chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑
This commit is contained in:
1 parent
5ef8329bd8
commit
4ec4e57005
183 files changed
+14653
-3936
No files matched your search
@@ -27,6 +27,7 @@ from app.services.shipping_notice import order_document_profile_lease_service as
|
||||
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
|
||||
from app.services.shipping_notice import order_document_profile_xfa_preview_service as xfa_preview_service
|
||||
from app.services.shipping_notice import order_document_profile_xfa_automark_service as xfa_automark_service
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as pdf_automark_service
|
||||
from app.services.shipping_notice import order_document_profile_revision_service as revision_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
from app.services.shipping_notice import order_document_profile_service as service
|
||||
@@ -533,6 +534,56 @@ def get_order_document_profile_preview_page(profile_id: int, page_no: int):
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/xfa-pdf-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_xfa_pdf_preview(profile_id: int):
|
||||
"""兼容旧 XFA 路由:签发统一编辑画布的单用途原 PDF 令牌。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(service.authorize_pdf_preview(
|
||||
profile_id, document_id=data.get('document_id'), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/xfa-pdf-preview', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_xfa_pdf_preview(profile_id: int):
|
||||
"""兼容旧 XFA 路由:消费短时令牌返回原 PDF,仅供 PDF.js 内存渲染。"""
|
||||
pdf = service.read_pdf_preview(
|
||||
token=str(request.args.get('preview_token') or ''), actor_id=_actor_id(),
|
||||
)
|
||||
response = send_file(io.BytesIO(pdf), mimetype='application/pdf', as_attachment=False, max_age=0)
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
response.headers['Content-Disposition'] = 'inline'
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/pdf-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_pdf_preview(profile_id: int):
|
||||
"""签发坐标 PDF 与 XFA 共用的单用途原 PDF 画布令牌。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(service.authorize_pdf_preview(
|
||||
profile_id, document_id=data.get('document_id'), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/pdf-preview', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_pdf_preview(profile_id: int):
|
||||
"""消费统一画布令牌返回原 PDF 字节,禁止缓存、下载和重放。"""
|
||||
pdf = service.read_pdf_preview(
|
||||
token=str(request.args.get('preview_token') or ''), actor_id=_actor_id(),
|
||||
)
|
||||
response = send_file(io.BytesIO(pdf), mimetype='application/pdf', as_attachment=False, max_age=0)
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
response.headers['Content-Disposition'] = 'inline'
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/samples/<int:sample_binding_id>/preview-pages', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_frozen_sample_preview_pages(profile_id: int, sample_binding_id: int):
|
||||
@@ -1048,6 +1099,38 @@ def reject_order_document_profile_xfa_visual_binding(profile_id: int, binding_id
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/pdf-automark',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def enqueue_order_document_profile_pdf_automark(profile_id: int):
|
||||
"""入队统一 PDF 自动标记;客户端不得按 XFA/普通 PDF 选择接口。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
document_id = data.get('document_id')
|
||||
if document_id in (None, ''):
|
||||
raise ValidationError('document_id is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
return _private_ok(pdf_automark_service.enqueue_pdf_automark(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
table_id=str(data.get('table_id') or '').strip() or None,
|
||||
schema_version_id=int(data['schema_version_id']) if data.get('schema_version_id') not in (None, '') else None,
|
||||
page_no=int(data['page_no']) if data.get('page_no') not in (None, '') else None,
|
||||
actor_id=_actor_id(),
|
||||
force=bool(data.get('force')),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/pdf-automark/jobs/<int:job_id>',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_pdf_automark_job(profile_id: int, job_id: int):
|
||||
"""轮询统一 PDF 自动标记 Job 的 candidates/diagnostics 契约。"""
|
||||
return _private_ok(pdf_automark_service.get_pdf_automark_job(job_id, profile_id=profile_id))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/automark',
|
||||
methods=['POST'],
|
||||
|
||||
@@ -704,7 +704,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
raise NotFoundError('Not found')
|
||||
return _ok({
|
||||
**serialize_task_detail(task, viewer_user_id=user.id, is_admin=is_admin),
|
||||
'ui_state': build_task_ui_state(task),
|
||||
'ui_state': build_task_ui_state(task, include_stage_context=True),
|
||||
})
|
||||
|
||||
|
||||
@@ -752,7 +752,7 @@ def workspace_shipping_task_ui_state(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task))
|
||||
return _ok(build_task_ui_state(task, include_stage_context=True))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
@@ -1239,6 +1239,32 @@ def workspace_shipping_task_export(task_no: str):
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/inventory-file', methods=['GET'])
|
||||
def workspace_shipping_task_inventory_file(task_no: str):
|
||||
"""下载当前任务实际关联的库存快照;无 active link 或托管文件时 fail-closed。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||||
|
||||
resolved = resolve_task_inventory_download(task)
|
||||
if resolved is None:
|
||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
||||
path, download_name = resolved
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
record_access_audit(
|
||||
action='download_task_inventory_file',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
actor_id=user.id,
|
||||
task_no=str(task.task_no),
|
||||
reason_code='inventory_file_downloaded',
|
||||
metadata={'inventory_file': download_name},
|
||||
)
|
||||
return send_file(path, as_attachment=True, download_name=download_name)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||
def workspace_list_shipping_order_intakes():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
@@ -1545,6 +1571,29 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-queue/<run_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_queue(run_no: str):
|
||||
"""读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_queue
|
||||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
||||
|
||||
runs = get_review_queue_visible_to_user(run_no, user.id, is_admin=is_admin)
|
||||
payload = serialize_review_queue(runs)
|
||||
record_access_audit(
|
||||
action='view_order_review_queue',
|
||||
aggregate_type='conversation',
|
||||
aggregate_id=str(payload.get('conversation_id') or ''),
|
||||
actor_id=user.id,
|
||||
conversation_id=str(payload.get('conversation_id') or '') or None,
|
||||
run_no=str(run_no),
|
||||
metadata={'item_count': len(payload.get('items') or [])},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_case(case_no: str):
|
||||
"""读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。"""
|
||||
@@ -2838,6 +2887,39 @@ def workspace_preview_shipping_order_review_document(case_no: str):
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/intake-parse-context', methods=['GET'],
|
||||
)
|
||||
def workspace_get_shipping_order_review_intake_parse_context(case_no: str):
|
||||
"""
|
||||
返回当前 Case 所属 Intake 的受控解析上下文,并记录敏感读取访问审计。
|
||||
|
||||
核心逻辑:只委托 Case 边界服务构造附件/同 Intake 邮件正文 DTO;PDF 二进制仍必须通过
|
||||
document-preview 代理读取,禁止把对象存储地址或资产内部定位下发至浏览器。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_intake_parse_context
|
||||
|
||||
payload = get_case_intake_parse_context(user_id=user.id, case_no=case_no)
|
||||
attachment = payload['attachment']
|
||||
record_access_audit(
|
||||
action='view_order_review_intake_parse_context',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case_no),
|
||||
actor_id=user.id,
|
||||
document_id=attachment['document_id'],
|
||||
review_case_no=str(case_no),
|
||||
metadata={
|
||||
'access_action': 'view_order_review_intake_parse_context',
|
||||
'workbench_event': 'intake_parse_context_viewed',
|
||||
'attachment_preview_kind': attachment['preview_kind'],
|
||||
'has_email_context': payload['email'] is not None,
|
||||
},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-evidence-preview/<int:document_id>', methods=['GET'])
|
||||
def workspace_preview_shipping_order_review_email_evidence(case_no: str, document_id: int):
|
||||
"""返回当前复核 Case 同 Intake 邮件正文的受控文本预览,不返回原始 EML 或附件。"""
|
||||
|
||||
@@ -59,8 +59,15 @@ class NotFoundError(AppError):
|
||||
message: str = "Resource not found",
|
||||
*,
|
||||
code: str = "RESOURCE.NOT_FOUND",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=404, retryable=False)
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=404,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
|
||||
@@ -12,6 +12,7 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
procurement_contract_review,
|
||||
schedule_run,
|
||||
shipping_document_layout,
|
||||
shipping_inventory_callback_process,
|
||||
shipping_notice_parse,
|
||||
shipping_notice_run,
|
||||
shipping_order_extraction,
|
||||
@@ -21,6 +22,7 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
shipping_line_auto_fulfill,
|
||||
shipping_post_ot_wave_progress,
|
||||
shipping_review_revalidate_progress,
|
||||
shipping_pdf_automark,
|
||||
shipping_xfa_ocr_automark,
|
||||
wecom_directory_sync,
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_inventory_callback_process.py
|
||||
|
||||
用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。
|
||||
依赖:Job 队列、inventory_rpa_workflow 的正式批量处理函数。
|
||||
逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS)
|
||||
def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None:
|
||||
"""处理一个已收件的库存 RPA 回调。
|
||||
|
||||
【AI 触发时机】:仅由 ``rpa_report_inventory_batch`` 在 HTTP 收件成功后入队;
|
||||
不得由浏览器 Worker 直接调用。
|
||||
"""
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
raise RuntimeError('missing_inventory_callback_process_job_id')
|
||||
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch
|
||||
|
||||
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'status': 'processed', 'callback_result': result},
|
||||
message='库存 RPA 回调已异步处理',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - queue must retain retryable receipt evidence
|
||||
db.session.rollback()
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc),
|
||||
result={'status': 'processing_failed', 'error': str(exc)[:1000]},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
app/jobs/handlers/shipping_pdf_automark.py
|
||||
|
||||
用途:执行统一 PDF 自动标记 Job,不向调用方暴露 XFA/普通 PDF 分流。
|
||||
依赖:Job 队列、order_document_profile_pdf_automark_service。
|
||||
逻辑:冻结 Job 载荷后委托统一证据管线;成功或受控失败均按通用 Job 契约终态化。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_PDF_AUTOMARK)
|
||||
def run_shipping_pdf_automark(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行统一 PDF 自动标记;任何 PDF 类型均复用同一 Job 生命周期。"""
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
return
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
frozen = dict(job.payload_json or {})
|
||||
frozen.setdefault('job_id', int(job.id))
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as automark_service
|
||||
try:
|
||||
result = automark_service.execute_pdf_automark_job(frozen)
|
||||
except automark_service.PdfAutomarkError as exc:
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc.message or exc)[:500],
|
||||
result={'status': 'failed', 'error_code': exc.error_code, 'details': dict(exc.details or {})},
|
||||
retryable=bool(exc.retryable),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed', 'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_FAILED'},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
finish_job(job.id, result=result, message='PDF automark completed', owned_attempt=owned_attempt)
|
||||
@@ -25,6 +25,7 @@ from app.services.shipping_notice.process_gate_job_service import (
|
||||
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
claim_and_run_gate_attempt,
|
||||
enqueue_gate_attempt_job,
|
||||
schedule_waiting_external_poll,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import complete_gate_attempt
|
||||
|
||||
@@ -127,4 +128,11 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
||||
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
finish_job(job.id, result=result if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt)
|
||||
# [STEP] 外部等待不是终态:Attempt 已正常执行完且 Gate 明确等待外部系统时,
|
||||
# 必须在当前 Job 成功收口后创建新的延迟 poll Attempt。此前只结束 Job,造成
|
||||
# Gate 永久停在 waiting_external,批次中心持续显示“处理中”。
|
||||
result_payload = result if isinstance(result, dict) else {'status': 'ok'}
|
||||
finish_job(job.id, result=result_payload, owned_attempt=owned_attempt)
|
||||
if str(result_payload.get('gate_status') or '').strip().lower() == 'waiting_external':
|
||||
schedule_waiting_external_poll(attempt_id=attempt_id)
|
||||
db.session.commit()
|
||||
@@ -20,9 +20,13 @@ class JobType(StrEnum):
|
||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
||||
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
||||
# RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
|
||||
SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process'
|
||||
# 历史 APX 兼容:Worker 仅终态化,不再执行 Gate。
|
||||
SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress'
|
||||
# XFA 合成预览就绪后的 OCR 自动标记(Job.job_type 为字符串列,无需 DB enum 迁移)
|
||||
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
||||
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
||||
# 旧 XFA 专用 Job 仅兼容已入队任务;新入口一律使用 SHIPPING_PDF_AUTOMARK。
|
||||
SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark'
|
||||
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
||||
SHIPPING_STP_AUTO_CREATE = 'shipping_stp_auto_create'
|
||||
@@ -68,7 +72,8 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({
|
||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_xfa_ocr_automark',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark', 'shipping_xfa_ocr_automark',
|
||||
'shipping_inventory_callback_process',
|
||||
'shipping_auto_progress',
|
||||
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||
|
||||
@@ -386,6 +386,7 @@ def submit_auto_progress(
|
||||
# ProcessGate Job/Attempt 通道;不得在此同步执行或退回 APX 六 Gate Job。
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_contract import is_technical_gate_party
|
||||
from app.services.shipping_notice.process_gate_executor import is_navigation_action
|
||||
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
@@ -428,7 +429,15 @@ def submit_auto_progress(
|
||||
action_code = str(getattr(gate, 'next_action_code', '') or '').strip()
|
||||
# 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的
|
||||
# system/worker Gate 才可自动创建 Attempt 并入队。
|
||||
if gate is not None and action_code and is_technical_gate_party(execution.responsible_party):
|
||||
# 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。
|
||||
# upload_inventory_file 等导航动作必须保留给用户;否则成功回调已同步
|
||||
# 的库存事实会被旧人工阻断动作再次覆盖。
|
||||
if (
|
||||
gate is not None
|
||||
and action_code
|
||||
and not is_navigation_action(action_code)
|
||||
and is_technical_gate_party(execution.responsible_party)
|
||||
):
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=str(gate.gate_code),
|
||||
|
||||
@@ -23,6 +23,22 @@ from app.services.shipping_notice.intake_service import can_force_create_shippin
|
||||
|
||||
_ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
|
||||
_STP_DUPLICATE_OK = frozenset({'none', 'unchecked'})
|
||||
_LIFECYCLE_ELIGIBLE_STATUSES = frozenset({'provisional', 'accepted'})
|
||||
|
||||
|
||||
def is_current_reviewable_candidate(candidate: ShippingOrderCandidate | None) -> bool:
|
||||
"""判断 Candidate 是否可作为订单生命周期的当前准入事实。
|
||||
|
||||
触发时机:Case、批次投影和 Gate 收口需要决定是否可以从接收解析进入订单复核时。
|
||||
仅当前版本且仍可复核/已接受的 Candidate 可以开放生命周期;已拒绝、过期、被替代
|
||||
或空 Candidate 只能保留审计,不能影响实时阶段或前端入口。
|
||||
"""
|
||||
return bool(
|
||||
candidate is not None
|
||||
and bool(getattr(candidate, 'is_current_version', False))
|
||||
and str(getattr(candidate, 'candidate_status', '') or '').strip().lower()
|
||||
in _LIFECYCLE_ELIGIBLE_STATUSES
|
||||
)
|
||||
|
||||
|
||||
def evaluate_candidate_stp_gate(candidate: ShippingOrderCandidate) -> tuple[bool, list[str]]:
|
||||
|
||||
@@ -18,7 +18,12 @@ from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.services.shipping_notice.query_service import get_batch_for_user, get_task_for_user, list_sorted_batch_tasks
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_batch_for_user,
|
||||
get_task_for_user,
|
||||
list_sorted_batch_tasks,
|
||||
resolve_task_export_download,
|
||||
)
|
||||
|
||||
MAX_ARCHIVE_TASKS = 100
|
||||
|
||||
@@ -54,14 +59,18 @@ def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | N
|
||||
|
||||
|
||||
def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExportArtifact]]:
|
||||
"""批量查询每票全部可下载 Artifact,滚动履约不得遗漏前一轮 Excel。"""
|
||||
task_ids = [int(task.id) for task in tasks if task.id is not None]
|
||||
rows = ShippingExportArtifact.query.join(ShippingNotice, ShippingNotice.id == ShippingExportArtifact.task_id).filter(
|
||||
ShippingExportArtifact.task_id.in_(task_ids), ShippingExportArtifact.status == 'ready',
|
||||
).order_by(ShippingExportArtifact.created_at, ShippingExportArtifact.id).all()
|
||||
"""批量解析每票当前正式 Artifact,与单文件下载使用同一授权事实。"""
|
||||
result: dict[int, list[ShippingExportArtifact]] = {}
|
||||
for item in rows:
|
||||
result.setdefault(int(item.task_id), []).append(item)
|
||||
for task in tasks:
|
||||
if task.id is None or resolve_task_export_download(task) is None:
|
||||
continue
|
||||
artifact = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploaded'}),
|
||||
ShippingExportArtifact.file_path == task.export_file_path,
|
||||
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first()
|
||||
if artifact is not None:
|
||||
result[int(task.id)] = [artifact]
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -142,6 +142,28 @@ def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFil
|
||||
return link.inventory_file if link else None
|
||||
|
||||
|
||||
def resolve_task_inventory_download(task: ShippingNotice) -> tuple[Path, str] | None:
|
||||
"""解析当前任务可下载的活动库存快照,禁止按库存源或订单反查猜测文件。
|
||||
|
||||
Args:
|
||||
task: 已完成用户归属鉴权的正式发货任务。
|
||||
|
||||
Returns:
|
||||
托管文件绝对路径与下载文件名;没有 active link、文件失效或缺失时返回 None。
|
||||
"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file is None:
|
||||
return None
|
||||
storage_path = str(inv_file.storage_path or '').strip()
|
||||
if not storage_path or storage_path.startswith('failed://'):
|
||||
return None
|
||||
path = Path(storage_path).resolve()
|
||||
if not path.is_file():
|
||||
return None
|
||||
filename = str(inv_file.source_file_name or f'{inv_file.inventory_file_no}{path.suffix or ".xlsx"}').strip()
|
||||
return path, filename
|
||||
|
||||
|
||||
def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
"""读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
|
||||
@@ -174,4 +174,23 @@ def sync_preparation_source_from_rpa_attempt(
|
||||
elif rows and all(row.status in {'ready', 'reusable', 'skipped'} for row in rows):
|
||||
preparation.status = 'succeeded'
|
||||
preparation.completed_at = datetime.utcnow()
|
||||
# RPA 回调是跨阶段「从库存准备恢复」的异步终点。Gate Attempt 已在
|
||||
# 发出 Trigger 时正确记录 waiting_external;此处聚合到终态后必须同步收口
|
||||
# 对应 RecoveryPlan,避免已完成的计划继续占用 active-plan 互斥位。
|
||||
if (
|
||||
preparation.status in {'succeeded', 'failed'}
|
||||
and preparation.recovery_plan_id
|
||||
):
|
||||
from app.models import ShippingProcessRecoveryPlan
|
||||
|
||||
plan = db.session.get(ShippingProcessRecoveryPlan, int(preparation.recovery_plan_id))
|
||||
if plan is not None and plan.status in {
|
||||
'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual',
|
||||
}:
|
||||
plan.status = 'succeeded' if preparation.status == 'succeeded' else 'failed'
|
||||
plan.started_at = plan.started_at or datetime.utcnow()
|
||||
plan.completed_at = datetime.utcnow()
|
||||
if preparation.status == 'failed':
|
||||
plan.failure_code = 'inventory_preparation_failed'
|
||||
plan.failure_detail_json = {'message': '库存准备 RPA 回调失败'}
|
||||
db.session.flush()
|
||||
@@ -67,6 +67,7 @@ from app.services.shipping_notice.query_service import (
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.rpa import (
|
||||
inventory_drop_dir,
|
||||
inventory_processed_dir,
|
||||
write_inventory_export_trigger_for_task,
|
||||
)
|
||||
@@ -2080,6 +2081,184 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""快速收件库存 RPA batch 回调,并将业务处理交给 shipping worker。
|
||||
|
||||
【AI 触发时机】:freight_rpa_worker 已完成库存文件导出、需要确认 HXOPS 已接收回调时调用。
|
||||
本函数只验证回调信封并持久化 Job;禁止在 HTTP 请求内解析 Excel、关联任务或推进 Gate。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
batch_run_no = str(payload.get('batch_run_no') or '').strip()
|
||||
results = payload.get('results') or []
|
||||
if not callback_id or not batch_run_no or not isinstance(results, list):
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
|
||||
# Worker 的 HTTP 超时可能在平台已收件后才发生。相同 callback 重放必须先复用活动 Job,
|
||||
# 不得再次依赖可能已被 Worker 清理的 shared drop 源文件。
|
||||
from app.models import Job
|
||||
|
||||
existing_job = (
|
||||
Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == 'shipping_inventory_callback_process',
|
||||
Job.business_ref == f'inventory-callback:{callback_id}',
|
||||
Job.status.in_(('queued', 'running')),
|
||||
)
|
||||
.order_by(Job.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing_job is not None:
|
||||
return tool_response(
|
||||
status='ok',
|
||||
message='库存 RPA 回调已收件,正在异步处理库存文件。',
|
||||
data={
|
||||
'job_id': int(existing_job.id),
|
||||
'batch_run_no': batch_run_no,
|
||||
'result_status': 'accepted',
|
||||
'callback_result_status': 'accepted',
|
||||
},
|
||||
extra={'result_status': 'accepted'},
|
||||
)
|
||||
|
||||
receipt_payload = _persist_batch_callback_receipt(
|
||||
payload,
|
||||
callback_id=callback_id,
|
||||
)
|
||||
if receipt_payload is None:
|
||||
return tool_response(status='failed', message='callback_file_receipt_failed', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_file_receipt_failed',
|
||||
})
|
||||
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS,
|
||||
receipt_payload,
|
||||
domain='shipping_notice',
|
||||
business_ref=f'inventory-callback:{callback_id}',
|
||||
message='库存 RPA 回调已收件,等待异步处理',
|
||||
max_attempts=3,
|
||||
commit=True,
|
||||
)
|
||||
return tool_response(
|
||||
status='ok',
|
||||
message='库存 RPA 回调已收件,正在异步处理库存文件。',
|
||||
data={
|
||||
'job_id': int(job_id),
|
||||
'batch_run_no': batch_run_no,
|
||||
'result_status': 'accepted',
|
||||
'callback_result_status': 'accepted',
|
||||
},
|
||||
extra={'result_status': 'accepted'},
|
||||
)
|
||||
|
||||
|
||||
def _persist_batch_callback_receipt(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
callback_id: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""将成功回调的 Excel 快速复制到 HXOPS 受控收件区。
|
||||
|
||||
【AI 触发时机】:仅由 batch HTTP 回调在入队前调用。它只做共享 drop 目录白名单校验
|
||||
和文件复制,绝不读取 Excel 内容、校验结构或更新任务状态;因此 Worker 可在短超时内
|
||||
得到“已收件”的确定响应,后台 Job 不依赖 RPA 随后可能清理的共享目录。
|
||||
|
||||
Returns:
|
||||
用受控副本路径替换成功项 ``file_path`` 后的 payload;无法安全收件时返回 None。
|
||||
"""
|
||||
allowed_root = inventory_drop_dir()
|
||||
if allowed_root is None:
|
||||
return None
|
||||
try:
|
||||
allowed_root = allowed_root.resolve()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
|
||||
safe_callback_id = ''.join(
|
||||
char if char.isalnum() or char in {'-', '_'} else '_'
|
||||
for char in callback_id
|
||||
).strip('_') or 'unknown'
|
||||
receipt_dir = _storage_root() / 'rpa_callback_receipts' / safe_callback_id
|
||||
receipt_payload = dict(payload)
|
||||
receipt_results: list[dict[str, Any]] = []
|
||||
copied_paths: list[Path] = []
|
||||
try:
|
||||
for index, raw_item in enumerate(payload.get('results') or []):
|
||||
item = dict(raw_item) if isinstance(raw_item, dict) else raw_item
|
||||
if not isinstance(item, dict) or str(item.get('status') or '').strip().lower() != 'success':
|
||||
receipt_results.append(item)
|
||||
continue
|
||||
|
||||
raw_path = str(item.get('file_path') or '').strip()
|
||||
source_path = Path(raw_path).resolve() if raw_path else None
|
||||
if source_path is None or not source_path.is_file():
|
||||
return None
|
||||
try:
|
||||
source_path.relative_to(allowed_root)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
suffix = source_path.suffix.lower()
|
||||
if suffix not in {'.xls', '.xlsx', '.csv'}:
|
||||
return None
|
||||
receipt_path = receipt_dir / f'{index:03d}_{source_path.name}'
|
||||
if not receipt_path.is_file():
|
||||
receipt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source_path, receipt_path)
|
||||
copied_paths.append(receipt_path)
|
||||
item['file_path'] = str(receipt_path)
|
||||
receipt_results.append(item)
|
||||
except (OSError, ValueError):
|
||||
for copied_path in copied_paths:
|
||||
try:
|
||||
copied_path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
receipt_payload['results'] = receipt_results
|
||||
return receipt_payload
|
||||
|
||||
|
||||
def _received_batch_callback_file_path(
|
||||
file_path: str,
|
||||
*,
|
||||
callback_id: str,
|
||||
) -> Path | None:
|
||||
"""验证 batch 处理可读取的文件仅来自 RPA drop 或本回调受控收件区。"""
|
||||
candidate = Path(file_path).resolve() if file_path else None
|
||||
if candidate is None or not candidate.is_file():
|
||||
return None
|
||||
allowed_roots: list[Path] = []
|
||||
drop_dir = inventory_drop_dir()
|
||||
if drop_dir is not None:
|
||||
allowed_roots.append(drop_dir.resolve())
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
|
||||
safe_callback_id = ''.join(
|
||||
char if char.isalnum() or char in {'-', '_'} else '_'
|
||||
for char in callback_id
|
||||
).strip('_') or 'unknown'
|
||||
allowed_roots.append((_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve())
|
||||
for allowed_root in allowed_roots:
|
||||
try:
|
||||
candidate.relative_to(allowed_root)
|
||||
return candidate
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
RPA 批量库存导出回调:为每个 Warehouse 创建库存快照,可选关联发货任务。
|
||||
【AI 触发时机】:freight_rpa_worker 完成 inventory_export_batch 后 POST 本接口。
|
||||
@@ -2153,6 +2332,9 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
skipped.append({"source_code": source_code, "task_no": task_no or None, "source_run_no": source_run_no_item, "callback_id": item_callback_id, "reason": "replayed", "original_business_status": replay_attempt.transaction_status or replay_attempt.status, "replayed": True})
|
||||
continue
|
||||
task: ShippingNotice | None = None
|
||||
# 仅正式三元组 Attempt 走延后确认;历史事件兼容回调及缺字段回调均不能
|
||||
# 读取未初始化变量,后者会在后续身份/来源校验中按业务错误拒绝。
|
||||
structured_attempt = False
|
||||
if task_no:
|
||||
task = resolve_task_from_payload({"task_id": task_no, "task_no": task_no})
|
||||
if task is None:
|
||||
@@ -2170,8 +2352,12 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
source_code=source_code,
|
||||
run_no=source_run_no_item,
|
||||
callback_payload=dict(merged_item),
|
||||
callback_payload={**dict(merged_item), '_defer_success_confirmation': True},
|
||||
)
|
||||
# 历史任务可能只有 inventory_rpa_triggered 审计事件,没有结构化
|
||||
# Attempt。此类回调继续走兼容入库链;新链路只对明确定位到 Attempt
|
||||
# 的结果启用“入库完成后再确认”约束。
|
||||
structured_attempt = _a is not None
|
||||
if per_source_code == 'idempotent_ok':
|
||||
skipped.append({
|
||||
"source_code": source_code,
|
||||
@@ -2234,6 +2420,14 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'error': 'RPA callback identity does not match the active preparation attempt.',
|
||||
})
|
||||
continue
|
||||
if per_source_code not in {'validated', 'not_found'}:
|
||||
failed.append({
|
||||
'source_code': source_code,
|
||||
'warehouse_id': warehouse_id,
|
||||
'task_no': task_no,
|
||||
'error_code': f'per_source_callback_{per_source_code}',
|
||||
})
|
||||
continue
|
||||
task = _lock_task_for_rpa_callback(task)
|
||||
|
||||
if task and raw_status in {"skipped", "failed"}:
|
||||
@@ -2278,7 +2472,13 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
ShippingProcessExecution,
|
||||
int(task.active_process_execution_id),
|
||||
)
|
||||
if execution is not None:
|
||||
# CandidateSet 已重冻结时,Task 指针可能尚未被下一轮提交
|
||||
# 覆写;迟到回调只能保留原始审计,不得回写旧 Gate。
|
||||
if (
|
||||
execution is not None
|
||||
and int(getattr(execution, 'task_id', 0) or 0) == int(task.id)
|
||||
and str(getattr(execution, 'status', '') or '').strip().lower() != 'superseded'
|
||||
):
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
actor_type='system',
|
||||
@@ -2339,14 +2539,10 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
})
|
||||
continue
|
||||
file_path = str(merged_item.get("file_path") or "").strip()
|
||||
path = Path(file_path).resolve() if file_path else None
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir
|
||||
allowed_root = inventory_drop_dir()
|
||||
if path and allowed_root:
|
||||
try:
|
||||
path.relative_to(allowed_root.resolve())
|
||||
except ValueError:
|
||||
path = None
|
||||
path = _received_batch_callback_file_path(
|
||||
file_path,
|
||||
callback_id=callback_id,
|
||||
)
|
||||
if not path or not path.is_file():
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
@@ -2455,14 +2651,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"difference": structure_check["difference"],
|
||||
},
|
||||
}
|
||||
if task_no and source_run_no_item:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
_att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
|
||||
if _att:
|
||||
# 成功回调是该 Attempt 的最终事实;清理旧失败态,避免投影继续显示 failed/retry。
|
||||
_att.status = 'succeeded'
|
||||
_att.callback_id = item_callback_id or callback_id; _att.callback_received_at = datetime.utcnow(); _att.file_generated = True; _att.file_path = str(path); _att.file_sha256 = server_hash; _att.file_size = server_size; _att.file_exists_at_callback = True; _att.execution_phase = 'callback_received'; _att.transaction_status = 'succeeded'
|
||||
_att.error_code = None; _att.error_message = None; _att.transaction_error_code = None
|
||||
created.append(created_entry)
|
||||
if item_orphan_path:
|
||||
batch_new_storage_paths.append(item_orphan_path)
|
||||
@@ -2505,8 +2693,35 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
_resolve_effective_callback_run_no(task, merged_item),
|
||||
)
|
||||
# 只有快照创建/复用、结构校验、库存行解析、任务关联都已完成,
|
||||
# 才确认逐源 Attempt 并触发 AutoProgress。该调用在单项保存点内,
|
||||
# 任一后续异常都会一并回滚,防止成功状态先于库存事实落库。
|
||||
if source_run_no_item and structured_attempt:
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
|
||||
if path.is_file():
|
||||
final_code, _ = per_source_callback_handler(
|
||||
task,
|
||||
source_code=source_code,
|
||||
run_no=source_run_no_item,
|
||||
callback_payload={
|
||||
**dict(merged_item),
|
||||
'inventory_file_no': inv_file.inventory_file_no,
|
||||
},
|
||||
)
|
||||
if final_code != 'succeeded':
|
||||
raise _RpaCallbackItemAbort(
|
||||
f'per_source_callback_confirmation_failed:{final_code}'
|
||||
)
|
||||
|
||||
drop_dir = inventory_drop_dir()
|
||||
is_drop_file = False
|
||||
if drop_dir is not None:
|
||||
try:
|
||||
path.relative_to(drop_dir.resolve())
|
||||
is_drop_file = True
|
||||
except ValueError:
|
||||
pass
|
||||
if is_drop_file and path.is_file():
|
||||
pending_callback_moves.append({
|
||||
"path": path,
|
||||
"run_no": run_no or None,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
services/shipping_notice/lifecycle_projection.py
|
||||
|
||||
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份四阶段业务生命周期。
|
||||
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。
|
||||
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。
|
||||
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_REASON_OWNING_GATE
|
||||
|
||||
|
||||
LIFECYCLE_STAGES: tuple[dict[str, str], ...] = (
|
||||
{'code': 'intake_parse', 'label': '接收解析'},
|
||||
{'code': 'order_review', 'label': '订单复核'},
|
||||
{'code': 'fulfillment_prep', 'label': '通知准备'},
|
||||
{'code': 'upload_complete', 'label': '通知完成'},
|
||||
)
|
||||
|
||||
LIFECYCLE_STAGE_CODES: tuple[str, ...] = tuple(stage['code'] for stage in LIFECYCLE_STAGES)
|
||||
|
||||
# 正式 Gate 到用户生命周期的唯一映射。任何页面均不得维护第二份 Gate 映射。
|
||||
LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
|
||||
'document_materialization': 'intake_parse',
|
||||
'layout_parsing': 'intake_parse',
|
||||
'document_profile_routing': 'intake_parse',
|
||||
'order_field_extraction': 'intake_parse',
|
||||
'field_completeness': 'order_review',
|
||||
'reservation_validation': 'order_review',
|
||||
'customer_resolution': 'order_review',
|
||||
'duplicate_detection': 'order_review',
|
||||
'field_conflict_resolution': 'order_review',
|
||||
'order_freeze_readiness': 'order_review',
|
||||
'task_creation': 'order_review',
|
||||
'inventory_source_routing': 'fulfillment_prep',
|
||||
'inventory_preparation': 'fulfillment_prep',
|
||||
'inventory_field_mapping': 'fulfillment_prep',
|
||||
'inventory_matching': 'fulfillment_prep',
|
||||
'inventory_sufficiency': 'fulfillment_prep',
|
||||
'excel_readiness': 'fulfillment_prep',
|
||||
'artifact_generation': 'fulfillment_prep',
|
||||
'freight_upload_rpa': 'upload_complete',
|
||||
'manual_upload_handoff': 'upload_complete',
|
||||
}
|
||||
|
||||
# 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。
|
||||
LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = (
|
||||
('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}),
|
||||
('order_review', {
|
||||
'customer_resolving', 'duplicate_checking', 'order_creating', 'review_required',
|
||||
'waiting_review', 'waiting_human_review', 'waiting_human', 'pre_ot_stp', 'order_review',
|
||||
}),
|
||||
('fulfillment_prep', {
|
||||
'inventory_source_resolving', 'inventory_fetching', 'inventory_fetch', 'inventory_preparation',
|
||||
'inventory_candidates_calculated', 'inventory_candidates_frozen', 'inventory_snapshots_ready',
|
||||
'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating',
|
||||
'excel_generate', 'excel_generated',
|
||||
}),
|
||||
('upload_complete', {'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'completed'}),
|
||||
)
|
||||
|
||||
|
||||
def lifecycle_entries(*, lifecycle_stage: str | None, has_candidate_context: bool) -> list[dict[str, str]]:
|
||||
"""返回只读生命周期入口;无有效 Candidate/正式任务时不开放任何订单生命周期面。"""
|
||||
if not has_candidate_context or lifecycle_stage not in LIFECYCLE_STAGE_CODES:
|
||||
return []
|
||||
current_index = LIFECYCLE_STAGE_CODES.index(str(lifecycle_stage))
|
||||
return [
|
||||
{
|
||||
'code': code,
|
||||
'state': 'current' if index == current_index else ('available' if index < current_index else 'unavailable'),
|
||||
'target_surface': 'order_lifecycle_workbench',
|
||||
}
|
||||
for index, code in enumerate(LIFECYCLE_STAGE_CODES)
|
||||
]
|
||||
|
||||
|
||||
def project_lifecycle(
|
||||
*,
|
||||
current_gate: dict[str, Any] | None,
|
||||
blocking_reason: dict[str, Any] | None,
|
||||
legacy_stage: str | None,
|
||||
has_candidate_context: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。
|
||||
|
||||
``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。
|
||||
"""
|
||||
gate = current_gate if isinstance(current_gate, dict) else {}
|
||||
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower()
|
||||
if gate_code in LIFECYCLE_STAGE_BY_GATE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
|
||||
authority = 'process_gate'
|
||||
else:
|
||||
reason = blocking_reason if isinstance(blocking_reason, dict) else {}
|
||||
reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip()
|
||||
owning_gate = PROCESS_GATE_REASON_OWNING_GATE.get(reason_code)
|
||||
if owning_gate in LIFECYCLE_STAGE_BY_GATE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[owning_gate]
|
||||
authority = 'blocking_reason'
|
||||
else:
|
||||
normalized_legacy = str(legacy_stage or '').strip().lower()
|
||||
lifecycle_stage = next(
|
||||
(code for code, aliases in LIFECYCLE_STAGE_RANGES if normalized_legacy in aliases),
|
||||
normalized_legacy if normalized_legacy in LIFECYCLE_STAGE_CODES else None,
|
||||
)
|
||||
authority = 'legacy_fallback' if lifecycle_stage else 'unclassified'
|
||||
return {
|
||||
'lifecycle_stage': lifecycle_stage,
|
||||
'lifecycle_entries': lifecycle_entries(
|
||||
lifecycle_stage=lifecycle_stage,
|
||||
has_candidate_context=has_candidate_context,
|
||||
),
|
||||
'lifecycle_authority': authority,
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
services/shipping_notice/order_document_profile_pdf_automark_service.py
|
||||
|
||||
用途:统一 PDF 自动标记任务的入队、执行与查询契约。
|
||||
依赖:Job 队列、坐标重建服务、XFA 多源视觉服务、Profile 模型。
|
||||
逻辑:入口只接受 PDF/profile/sample,上层不传 XFA 类型;执行期读取 Profile 实际
|
||||
template_mode,普通 PDF 复用冻结坐标重建,XFA 复用 PDFium + Widget + OCR +
|
||||
datasets 对照。两者输出同一个 {kind, candidates, diagnostics} Job 结果结构。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
|
||||
|
||||
|
||||
class PdfAutomarkError(Exception):
|
||||
"""统一 PDF 自动标记的受控 Job 失败。"""
|
||||
|
||||
def __init__(self, message: str, *, error_code: str, details: dict[str, Any] | None = None, retryable: bool = False) -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.error_code = error_code
|
||||
self.details = dict(details or {})
|
||||
self.retryable = retryable
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取模板 Profile;缺失时拒绝创建无归属自动标注任务。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return profile
|
||||
|
||||
|
||||
def _is_xfa_profile(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""由 Profile 已持久化能力识别 datasets,而不是由浏览器传递文档类型。"""
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
return str(profile.template_mode or definition.get('template_mode') or '') == 'xfa_dataset'
|
||||
|
||||
|
||||
def enqueue_pdf_automark(
|
||||
profile_id: int, *, document_id: int, table_id: str | None, schema_version_id: int | None,
|
||||
page_no: int | None, actor_id: int | None, force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""入队统一 PDF 自动标记;调用方无须也不得传入 XFA 类型开关。"""
|
||||
if actor_id is None:
|
||||
raise ValidationError('Actor is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
profile = _profile(profile_id)
|
||||
if str(profile.status or '') != 'draft':
|
||||
raise ValidationError('Only draft profiles support automark', code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE')
|
||||
if not document_id:
|
||||
raise ValidationError('document_id is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
if not _is_xfa_profile(profile) and not str(table_id or '').strip():
|
||||
raise ValidationError('table_id is required for coordinate profiles', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
capability = 'xfa_datasets' if _is_xfa_profile(profile) else 'coordinate'
|
||||
payload = {
|
||||
'profile_id': int(profile_id), 'document_id': int(document_id), 'table_id': str(table_id or '').strip() or None,
|
||||
'schema_version_id': int(schema_version_id) if schema_version_id else None,
|
||||
'page_no': int(page_no) if page_no else 1, 'actor_id': int(actor_id), 'capability': capability,
|
||||
}
|
||||
ref = f'pdf-automark:{int(profile_id)}:{int(document_id)}:{payload["table_id"] or "page"}:{payload["page_no"]}'
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_PDF_AUTOMARK, payload, domain=SHIPPING_NOTICE_JOB_DOMAIN, business_ref=ref,
|
||||
created_by_id=int(actor_id), message='Waiting for PDF automark', max_attempts=2,
|
||||
dedupe_active=not force, commit=True,
|
||||
)
|
||||
job = db.session.get(Job, int(job_id))
|
||||
return {'job_id': int(job_id), 'status': str(job.status if job else 'queued'), 'profile_id': int(profile_id), 'document_id': int(document_id)}
|
||||
|
||||
|
||||
def execute_pdf_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""执行统一证据管线;仅在这里按 Profile 的实际能力选择已有适配实现。"""
|
||||
profile_id = int(payload.get('profile_id') or 0)
|
||||
document_id = int(payload.get('document_id') or 0)
|
||||
if profile_id <= 0 or document_id <= 0:
|
||||
raise PdfAutomarkError('profile_id and document_id are required', error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
profile = _profile(profile_id)
|
||||
if _is_xfa_profile(profile):
|
||||
from app.services.shipping_notice import order_document_profile_xfa_automark_service as xfa
|
||||
try:
|
||||
result = xfa.execute_xfa_ocr_automark_job(payload)
|
||||
except xfa.XfaOcrAutomarkError as exc:
|
||||
raise PdfAutomarkError(exc.message, error_code=exc.error_code, details=exc.details, retryable=exc.retryable) from exc
|
||||
return {**result, 'kind': 'visual_binding', 'candidates': list(result.get('suggestions') or []), 'diagnostics': {'evidence': ['pdfium', 'acroform_widget', 'ocr', 'xfa_datasets']}}
|
||||
table_id = str(payload.get('table_id') or '').strip()
|
||||
if not table_id:
|
||||
raise PdfAutomarkError('table_id is required for coordinate profiles', error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
from app.core.errors import ValidationError as AppValidationError
|
||||
from app.services.shipping_notice import order_document_profile_service as coordinate
|
||||
request = {'document_id': document_id, 'table_id': table_id, 'schema_version_id': payload.get('schema_version_id')}
|
||||
try:
|
||||
reconstruction = coordinate.suggest_coordinate_reconstruction(request, actor_id=payload.get('actor_id'))
|
||||
except AppValidationError as exc:
|
||||
if exc.code != 'SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE':
|
||||
raise PdfAutomarkError(str(exc), error_code=exc.code, details=dict(exc.details or {})) from exc
|
||||
try:
|
||||
coordinate.generate_ocr_coordinate_evidence(document_id=document_id, table_id=table_id, actor_id=payload.get('actor_id'))
|
||||
reconstruction = coordinate.suggest_coordinate_reconstruction(request, actor_id=payload.get('actor_id'))
|
||||
except Exception as retry_exc: # noqa: BLE001
|
||||
raise PdfAutomarkError('PDF coordinate evidence is unavailable', error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from retry_exc
|
||||
fields = coordinate.suggest_order_field_layouts({
|
||||
'document_id': document_id, 'schema_version_id': payload.get('schema_version_id'), 'page_no': int(payload.get('page_no') or 1),
|
||||
}, actor_id=payload.get('actor_id'))
|
||||
return {
|
||||
'status': 'success', 'profile_id': profile_id, 'document_id': document_id, 'kind': 'coordinate_regions',
|
||||
'candidates': [{'candidate_kind': 'coordinate_reconstruction', 'payload': reconstruction}, {'candidate_kind': 'order_fields', 'payload': fields}],
|
||||
'diagnostics': {'evidence': ['pdfium_native_coordinates', 'ocr_if_needed'], 'table_id': table_id}, 'error_code': None,
|
||||
}
|
||||
|
||||
|
||||
def get_pdf_automark_job(job_id: int, *, profile_id: int) -> dict[str, Any]:
|
||||
"""按统一 DTO 查询 PDF 自动标记任务,拒绝跨 Profile 读取。"""
|
||||
job = db.session.get(Job, int(job_id))
|
||||
if job is None or str(job.job_type or '') != JobType.SHIPPING_PDF_AUTOMARK.value:
|
||||
raise NotFoundError('PDF automark job not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_JOB_NOT_FOUND')
|
||||
payload = dict(job.payload_json or {})
|
||||
if int(payload.get('profile_id') or 0) != int(profile_id):
|
||||
raise NotFoundError('PDF automark job not found for profile', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_JOB_NOT_FOUND')
|
||||
result = dict(job.result_json or {}) if isinstance(job.result_json, dict) else {}
|
||||
return {
|
||||
'job_id': int(job.id), 'status': str(job.status or ''), 'kind': result.get('kind'),
|
||||
'candidates': list(result.get('candidates') or []), 'diagnostics': dict(result.get('diagnostics') or {}),
|
||||
'preview_render_checksum': result.get('preview_render_checksum'),
|
||||
'renderer_version': result.get('renderer_version'),
|
||||
'error_code': result.get('error_code'), 'message': job.message,
|
||||
}
|
||||
@@ -64,6 +64,7 @@ from app.services.shipping_notice.preview_grant_store import preview_grant_store
|
||||
PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
PREVIEW_GRANT_TTL_SECONDS = 120
|
||||
PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-preview:'
|
||||
XFA_PDF_PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-xfa-pdf-preview:'
|
||||
|
||||
|
||||
def _definition_hash(definition: dict[str, Any]) -> str:
|
||||
@@ -1409,6 +1410,76 @@ def render_preview_page(*, token: str, page_no: int, actor_id: int | None) -> by
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
def authorize_pdf_preview(profile_id: int, *, document_id: int, actor_id: int | None) -> dict[str, Any]:
|
||||
"""签发绑定样本原 PDF 的单次内存预览令牌,不暴露对象存储定位信息。
|
||||
|
||||
编辑画布对坐标 PDF 与 XFA PDF 共用该通道和 PDF.js 渲染;授权范围仍严格限定为
|
||||
管理员、当前 Profile 已绑定的 PDF 样本、短时且单次消费的令牌。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
try:
|
||||
safe_document_id = int(document_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('document_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None:
|
||||
raise NotFoundError('Order profile PDF preview not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND')
|
||||
document = _bound_sample_document(profile_id, safe_document_id)
|
||||
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
|
||||
raise ValidationError('Only PDF samples support PDF preview', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE')
|
||||
asset = db.session.get(FileAsset, document.asset_id)
|
||||
if asset is None:
|
||||
raise ValidationError('Sample file is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE')
|
||||
grant_token = secrets.token_urlsafe(24)
|
||||
_preview_grant_store().setex(
|
||||
f'{XFA_PDF_PREVIEW_GRANT_KEY_PREFIX}{grant_token}', PREVIEW_GRANT_TTL_SECONDS,
|
||||
json.dumps({
|
||||
'profile_id': int(profile_id), 'document_id': document.id, 'actor_id': int(actor_id),
|
||||
'asset_id': int(asset.id), 'content_hash': str(asset.content_hash or ''),
|
||||
}, separators=(',', ':')),
|
||||
)
|
||||
_audit(profile_id=int(profile_id), document_id=document.id, event_type='pdf_preview_authorized', actor_id=actor_id, detail={
|
||||
'ttl_seconds': PREVIEW_GRANT_TTL_SECONDS,
|
||||
})
|
||||
db.session.commit()
|
||||
return {'document_id': document.id, 'preview_token': grant_token, 'expires_in_seconds': PREVIEW_GRANT_TTL_SECONDS}
|
||||
|
||||
|
||||
def read_pdf_preview(*, token: str, actor_id: int | None) -> bytes:
|
||||
"""原子消费原 PDF 预览令牌并读取绑定样本;失败不保留可重放凭据。"""
|
||||
raw_grant = _preview_grant_store().getdel(f'{XFA_PDF_PREVIEW_GRANT_KEY_PREFIX}{str(token)}')
|
||||
try:
|
||||
grant = json.loads(raw_grant) if raw_grant else None
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
grant = None
|
||||
if not isinstance(grant, dict) or actor_id is None or grant.get('actor_id') != int(actor_id):
|
||||
raise NotFoundError('Order profile PDF preview not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND')
|
||||
document = _bound_sample_document(grant['profile_id'], grant['document_id'])
|
||||
asset = db.session.get(FileAsset, document.asset_id)
|
||||
if asset is None or int(asset.id) != int(grant.get('asset_id') or 0) or str(asset.content_hash or '') != str(grant.get('content_hash') or ''):
|
||||
raise NotFoundError('Order profile PDF preview not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND')
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
try:
|
||||
payload = read_asset_bytes(asset)
|
||||
except Exception as exc:
|
||||
raise ValidationError('PDF preview is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE') from exc
|
||||
_audit(profile_id=grant['profile_id'], document_id=document.id, event_type='pdf_preview_viewed', actor_id=actor_id, detail={})
|
||||
db.session.commit()
|
||||
return payload
|
||||
|
||||
|
||||
def authorize_xfa_pdf_preview(profile_id: int, *, document_id: int, actor_id: int | None) -> dict[str, Any]:
|
||||
"""兼容旧 XFA 路由;统一画布授权已迁移至 authorize_pdf_preview。"""
|
||||
return authorize_pdf_preview(profile_id, document_id=document_id, actor_id=actor_id)
|
||||
|
||||
|
||||
def read_xfa_pdf_preview(*, token: str, actor_id: int | None) -> bytes:
|
||||
"""兼容旧 XFA 原 PDF 路由;令牌仍按统一单次消费语义读取。"""
|
||||
return read_pdf_preview(token=token, actor_id=actor_id)
|
||||
|
||||
|
||||
def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, actor_id: int | None) -> dict[str, Any]:
|
||||
"""???????????????? bbox?token ID?HTML ????????"""
|
||||
if actor_id is None:
|
||||
|
||||
+22
-14
@@ -6,6 +6,7 @@ services/shipping_notice/order_document_profile_xfa_automark_service.py
|
||||
visual_binding_service(确认)、lease_service、audit helpers、Job 模型。
|
||||
逻辑:Admin API 调用 enqueue/get/accept/reject;Worker Handler 调用
|
||||
execute_xfa_ocr_automark_job。编辑图源为原生 PDF 页,不再依赖 /xfa/preview。
|
||||
datasets 是正式值,Widget 与 OCR 是独立采集的视觉证据,成功后统一融合;
|
||||
high 且无 mismatch 才可接受为 confirmed;medium/low 仅写 suggested;
|
||||
mismatch 硬阻断。永不自动 confirmed。空白壳 OCR 无内容 → 空建议成功。
|
||||
"""
|
||||
@@ -398,13 +399,13 @@ def _normalize_suggestion(item: dict[str, Any], *, page_no: int) -> dict[str, An
|
||||
|
||||
def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
Worker 执行体:OCR 原生 PDF 页并合并 Widget/OCR 建议。
|
||||
Worker 执行体:采集原生 PDF 页的 Widget/OCR 证据并合并视觉建议。
|
||||
|
||||
核心逻辑:
|
||||
1. 加载 PDFium 原生页 PNG(与编辑画布同源);
|
||||
2. 无页/空白壳 → 空建议成功(不报 XFA_PREVIEW_UNAVAILABLE);
|
||||
3. 逐页 recognize_preview_page;无 OCR 行时不生成 datasets stub 建议;
|
||||
4. merge_visual_binding_suggestions(按 field_key 跨页去重);
|
||||
3. 每页先独立收集 AcroForm Widget,再执行强制 OCR;两者不互为前置条件;
|
||||
4. OCR 成功后 merge_visual_binding_suggestions(按 field_key 跨页去重);
|
||||
5. 回写 Profile.definition.xfa_ocr_automark。
|
||||
|
||||
Args:
|
||||
@@ -414,7 +415,7 @@ def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
写入 Job.result_json 的字典。
|
||||
|
||||
Raises:
|
||||
XfaOcrAutomarkError: 受控失败(样本缺失 / OCR 引擎不可用等)。
|
||||
XfaOcrAutomarkError: 受控失败(样本缺失 / 强制 OCR 不可用等)。
|
||||
"""
|
||||
profile_id = int(payload.get('profile_id') or 0)
|
||||
document_id = int(payload.get('document_id') or 0)
|
||||
@@ -503,6 +504,17 @@ def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
png = page.get('png_bytes')
|
||||
if not isinstance(png, (bytes, bytearray)) or not png:
|
||||
continue
|
||||
pending_targets = [
|
||||
item for item in flat_targets
|
||||
if str(item.get('field_key') or '') not in suggestions_by_key
|
||||
]
|
||||
# Widget 与 OCR 是独立证据:先采集 Widget,OCR 失败仍留下可审计的诊断,
|
||||
# 但不能把缺少强制 OCR 交叉校验的候选误标为成功。
|
||||
widgets = _widget_candidates_for_page(
|
||||
document_id=document_id,
|
||||
page_no=page_no,
|
||||
targets=pending_targets,
|
||||
)
|
||||
try:
|
||||
ocr_lines = recognize_preview_page(bytes(png))
|
||||
except ServiceUnavailableError as exc:
|
||||
@@ -513,7 +525,12 @@ def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
actor_id=int(actor_id) if actor_id is not None else None,
|
||||
result='failure',
|
||||
error_code=str(getattr(exc, 'code', None) or AUTOMARK_OCR_UNAVAILABLE),
|
||||
detail={'page_no': page_no, 'job_id': payload.get('job_id')},
|
||||
detail={
|
||||
'page_no': page_no,
|
||||
'job_id': payload.get('job_id'),
|
||||
'widget_candidate_count': len(widgets),
|
||||
'dataset_target_count': len(pending_targets),
|
||||
},
|
||||
)
|
||||
raise XfaOcrAutomarkError(
|
||||
'XFA native PDF OCR is unavailable',
|
||||
@@ -522,17 +539,8 @@ def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
retryable=False,
|
||||
) from exc
|
||||
|
||||
pending_targets = [
|
||||
item for item in flat_targets
|
||||
if str(item.get('field_key') or '') not in suggestions_by_key
|
||||
]
|
||||
# 无 OCR 行时不向 matcher 传 datasets 目标,避免空白壳刷出 needs_review stub。
|
||||
ocr_targets = pending_targets if ocr_lines else []
|
||||
widgets = _widget_candidates_for_page(
|
||||
document_id=document_id,
|
||||
page_no=page_no,
|
||||
targets=pending_targets,
|
||||
)
|
||||
if not ocr_lines and not widgets:
|
||||
continue
|
||||
|
||||
|
||||
@@ -596,6 +596,7 @@ def _trim_pending_order_item(item: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
|
||||
'po_number': str(item.get('po_number') or '').strip() or None,
|
||||
'document_id': int(item.get('document_id') or 0) or None,
|
||||
'reasons': _trim_reason_codes(item.get('reasons')),
|
||||
'missing_fields': [str(field).strip() for field in missing if str(field or '').strip()][:20],
|
||||
'duplicate_status': str(item.get('duplicate_status') or '').strip() or None,
|
||||
@@ -611,11 +612,26 @@ def _pending_order_facts(run: ShippingOrderProcessingRun) -> list[dict[str, Any]
|
||||
result = run.result_json if isinstance(getattr(run, 'result_json', None), dict) else {}
|
||||
stored = result.get('pending_orders')
|
||||
if isinstance(stored, list) and stored:
|
||||
return [
|
||||
pending = [
|
||||
_trim_pending_order_item(item)
|
||||
for item in stored
|
||||
if isinstance(item, dict)
|
||||
][:50]
|
||||
# 历史 Worker 快照没有 document_id;实时投影必须补齐同 Run 的 Candidate 归属,
|
||||
# 否则无法保证一个 PDF 不会被多个处理类别重复计数。
|
||||
if getattr(run, 'id', None) is not None:
|
||||
documents_by_candidate = {
|
||||
str(row.candidate_no): int(row.primary_document_id)
|
||||
for row in ShippingOrderCandidate.query.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
).all()
|
||||
if row.candidate_no and row.primary_document_id
|
||||
}
|
||||
for item in pending:
|
||||
if item.get('document_id') is None:
|
||||
item['document_id'] = documents_by_candidate.get(str(item.get('candidate_no') or ''))
|
||||
return pending
|
||||
|
||||
if getattr(run, 'id', None) is None:
|
||||
return []
|
||||
@@ -649,6 +665,7 @@ def _pending_order_facts(run: ShippingOrderProcessingRun) -> list[dict[str, Any]
|
||||
pending.append(_trim_pending_order_item({
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'po_number': candidate.po_number,
|
||||
'document_id': candidate.primary_document_id,
|
||||
'reasons': reasons,
|
||||
'missing_fields': missing,
|
||||
'duplicate_status': candidate.duplicate_status,
|
||||
@@ -674,6 +691,19 @@ def _auto_freeze_block_facts(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
})
|
||||
if code:
|
||||
blocked_codes.append(code)
|
||||
if blocked_tasks and getattr(run, 'id', None) is not None:
|
||||
document_by_candidate = {
|
||||
str(candidate.candidate_no): int(candidate.primary_document_id)
|
||||
for candidate in ShippingOrderCandidate.query.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
).all()
|
||||
if candidate.candidate_no and candidate.primary_document_id
|
||||
}
|
||||
for item in blocked_tasks:
|
||||
document_id = document_by_candidate.get(str(item.get('candidate_no') or ''))
|
||||
if document_id:
|
||||
item['document_id'] = document_id
|
||||
policy_raw = getattr(run, 'auto_freeze_policy_json', None)
|
||||
policy = policy_raw if isinstance(policy_raw, dict) else {}
|
||||
policy_codes = _trim_reason_codes(policy.get('blocking_reason_codes'))
|
||||
@@ -781,23 +811,77 @@ def build_handling_items(
|
||||
)
|
||||
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else _open_existing_document_ids(run)
|
||||
items: list[dict[str, Any]] = []
|
||||
# 处理事项的统计实体是业务文件,不是来源行。预算快照、Candidate、Unit 分别
|
||||
# 可能只带 content_hash、document_id 或 root_document_id;只按 document_id
|
||||
# 认领会让同一 PDF 落入多个类别并被相加。
|
||||
claimed_file_keys: set[str] = set()
|
||||
aliases_by_document_id: dict[int, set[str]] = {}
|
||||
for unit in unit_rows:
|
||||
document_id = int(getattr(unit, 'document_id', None) or 0)
|
||||
if document_id <= 0:
|
||||
continue
|
||||
aliases = aliases_by_document_id.setdefault(document_id, {f'document:{document_id}'})
|
||||
content_hash = str(getattr(unit, 'content_hash', None) or '').strip().lower()
|
||||
if content_hash:
|
||||
aliases.add(f'content-hash:{content_hash}')
|
||||
|
||||
def claim(refs: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""按 content_hash → root_document_id → document_id 互斥认领业务文件。"""
|
||||
kept: list[dict[str, Any]] = []
|
||||
for ref in refs:
|
||||
document_id = int(ref.get('document_id') or 0)
|
||||
keys: set[str] = set()
|
||||
# _identity_content_hash 仅用于本次互斥认领,不能改变既有 affected_refs 契约。
|
||||
content_hash = str(
|
||||
ref.get('_identity_content_hash') or ref.get('content_hash') or '',
|
||||
).strip().lower()
|
||||
root_document_id = int(ref.get('root_document_id') or 0)
|
||||
if content_hash:
|
||||
keys.add(f'content-hash:{content_hash}')
|
||||
if root_document_id > 0:
|
||||
keys.add(f'root-document:{root_document_id}')
|
||||
if document_id > 0:
|
||||
keys.update(aliases_by_document_id.get(document_id, set()))
|
||||
keys.add(f'document:{document_id}')
|
||||
# 无稳定文件身份的历史行不得相互误合并,仍保留其自身可审计定位。
|
||||
if not keys:
|
||||
candidate_no = str(ref.get('candidate_no') or '').strip()
|
||||
task_no = str(ref.get('task_no') or '').strip()
|
||||
keys.add(f'legacy:{candidate_no or task_no or id(ref)}')
|
||||
if keys & claimed_file_keys:
|
||||
continue
|
||||
claimed_file_keys.update(keys)
|
||||
# 身份别名是投影内部实现细节,不能泄漏到 affected_refs API。
|
||||
kept.append({
|
||||
key: value
|
||||
for key, value in ref.items()
|
||||
if not str(key).startswith('_identity_')
|
||||
})
|
||||
return kept
|
||||
|
||||
# [STEP 1] PDF 技术失败与人工复核(排除已 open_existing)。
|
||||
failed_units = [unit for unit in unit_rows if str(unit.status or '') == 'failed']
|
||||
if failed_units:
|
||||
# 先对全量事实认领,再由 _handling_item 截断 affected_refs 的展示长度。
|
||||
# 若在认领前截断,排在第 11 份之后的同一 PDF 可能再次落入低优先级类别,
|
||||
# 既破坏互斥统计,也会把真实数量错误压成 10。
|
||||
failed_refs = claim([
|
||||
{
|
||||
'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id),
|
||||
'_identity_content_hash': str(getattr(unit, 'content_hash', None) or '').strip().lower() or None,
|
||||
}
|
||||
for unit in failed_units
|
||||
if getattr(unit, 'document_id', None) is not None
|
||||
])
|
||||
if failed_refs:
|
||||
codes = _trim_reason_codes([
|
||||
getattr(unit, 'technical_failure_reason_code', None) or getattr(unit, 'reason_code', None)
|
||||
for unit in failed_units
|
||||
])
|
||||
items.append(_handling_item(
|
||||
category='technical_failure',
|
||||
count=len(failed_units),
|
||||
count=len(failed_refs),
|
||||
reason_codes=codes or ['technical_failure'],
|
||||
affected_refs=[
|
||||
{'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id)}
|
||||
for unit in failed_units[:10]
|
||||
if getattr(unit, 'document_id', None) is not None
|
||||
],
|
||||
affected_refs=failed_refs,
|
||||
primary_action='retry_failed_attachments',
|
||||
))
|
||||
|
||||
@@ -805,24 +889,34 @@ def build_handling_items(
|
||||
unit for unit in unit_rows
|
||||
if str(unit.status or '') == 'review_required' and int(unit.document_id or 0) not in open_ids
|
||||
]
|
||||
review_count = max(
|
||||
len(review_units),
|
||||
_unresolved_review_document_count(run, open_existing_doc_ids=open_ids),
|
||||
)
|
||||
if review_count > 0:
|
||||
review_refs = claim([
|
||||
{
|
||||
'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id),
|
||||
'_identity_content_hash': str(getattr(unit, 'content_hash', None) or '').strip().lower() or None,
|
||||
}
|
||||
for unit in review_units
|
||||
if getattr(unit, 'document_id', None) is not None
|
||||
])
|
||||
if not review_refs:
|
||||
review_refs = claim([
|
||||
{'type': 'document', 'document_id': int(case.document_id), 'case_no': case.case_no}
|
||||
for case in getattr(run, 'review_cases', []) or []
|
||||
if (
|
||||
str(case.status or '') not in {'confirmed', 'non_order', 'superseded'}
|
||||
and int(case.document_id or 0) not in open_ids
|
||||
and int(case.document_id or 0) > 0
|
||||
)
|
||||
])
|
||||
if review_refs:
|
||||
codes = _trim_reason_codes([
|
||||
getattr(unit, 'reason_code', None)
|
||||
for unit in review_units
|
||||
])
|
||||
items.append(_handling_item(
|
||||
category='document_review',
|
||||
count=review_count,
|
||||
count=len(review_refs),
|
||||
reason_codes=codes,
|
||||
affected_refs=[
|
||||
{'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id)}
|
||||
for unit in review_units[:10]
|
||||
if getattr(unit, 'document_id', None) is not None
|
||||
],
|
||||
affected_refs=review_refs,
|
||||
primary_action='enter_manual_review',
|
||||
))
|
||||
|
||||
@@ -832,6 +926,9 @@ def build_handling_items(
|
||||
missing_orders: list[dict[str, Any]] = []
|
||||
confirmation_only: list[dict[str, Any]] = []
|
||||
for item in pending_orders:
|
||||
document_id = int(item.get('document_id') or 0)
|
||||
if document_id > 0 and aliases_by_document_id.get(document_id, {f'document:{document_id}'}) & claimed_file_keys:
|
||||
continue
|
||||
reasons = {str(code) for code in item.get('reasons') or []}
|
||||
missing_fields = item.get('missing_fields') or []
|
||||
has_conflict = bool(reasons & _CANDIDATE_CONFLICT_REASON_CODES)
|
||||
@@ -844,103 +941,121 @@ def build_handling_items(
|
||||
confirmation_only.append(item)
|
||||
|
||||
if conflict_orders:
|
||||
conflict_refs = claim([
|
||||
{'type': 'candidate', 'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'), 'document_id': item.get('document_id')}
|
||||
for item in conflict_orders if item.get('candidate_no')
|
||||
])
|
||||
else:
|
||||
conflict_refs = []
|
||||
if conflict_refs:
|
||||
items.append(_handling_item(
|
||||
category='candidate_conflict',
|
||||
count=len(conflict_orders),
|
||||
count=len(conflict_refs),
|
||||
reason_codes=[code for item in conflict_orders for code in (item.get('reasons') or [])],
|
||||
affected_refs=[
|
||||
{
|
||||
'type': 'candidate',
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'),
|
||||
}
|
||||
for item in conflict_orders[:10]
|
||||
if item.get('candidate_no')
|
||||
],
|
||||
affected_refs=conflict_refs,
|
||||
primary_action='review_candidate',
|
||||
))
|
||||
if missing_orders:
|
||||
missing_refs = claim([
|
||||
{'type': 'candidate', 'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'), 'document_id': item.get('document_id'),
|
||||
'missing_fields': item.get('missing_fields') or []}
|
||||
for item in missing_orders if item.get('candidate_no')
|
||||
])
|
||||
else:
|
||||
missing_refs = []
|
||||
if missing_refs:
|
||||
items.append(_handling_item(
|
||||
category='candidate_missing_info',
|
||||
count=len(missing_orders),
|
||||
count=len(missing_refs),
|
||||
reason_codes=[code for item in missing_orders for code in (item.get('reasons') or [])]
|
||||
or ['required_field_missing'],
|
||||
affected_refs=[
|
||||
{
|
||||
'type': 'candidate',
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'),
|
||||
'missing_fields': item.get('missing_fields') or [],
|
||||
}
|
||||
for item in missing_orders[:10]
|
||||
if item.get('candidate_no')
|
||||
],
|
||||
affected_refs=missing_refs,
|
||||
primary_action='review_candidate',
|
||||
))
|
||||
|
||||
# [STEP 3] 自动冻结受阻与预算停扩。
|
||||
freeze = _auto_freeze_block_facts(run)
|
||||
if freeze['blocked']:
|
||||
freeze_refs = claim([
|
||||
{'type': 'task', 'task_no': item.get('task_no'),
|
||||
'candidate_no': item.get('candidate_no'), 'document_id': item.get('document_id')}
|
||||
for item in freeze['blocked_tasks']
|
||||
if item.get('task_no') or item.get('candidate_no')
|
||||
])
|
||||
else:
|
||||
freeze_refs = []
|
||||
if freeze_refs:
|
||||
items.append(_handling_item(
|
||||
category='auto_freeze_blocked',
|
||||
count=max(int(freeze['blocked_task_count'] or 0), 1),
|
||||
count=len(freeze_refs),
|
||||
reason_codes=list(freeze['reason_codes'] or []),
|
||||
affected_refs=[
|
||||
{
|
||||
'type': 'task',
|
||||
'task_no': item.get('task_no'),
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
}
|
||||
for item in freeze['blocked_tasks'][:10]
|
||||
if item.get('task_no') or item.get('candidate_no')
|
||||
],
|
||||
affected_refs=freeze_refs,
|
||||
primary_action='view_details',
|
||||
))
|
||||
|
||||
if _budget_stopped_for_run(run):
|
||||
budget_refs = _budget_limited_attachment_refs(run)
|
||||
items.append(_handling_item(
|
||||
category='budget_stopped',
|
||||
count=max(len(budget_refs), 1),
|
||||
reason_codes=['budget_initial_limit'],
|
||||
affected_refs=budget_refs,
|
||||
primary_action='view_details',
|
||||
))
|
||||
|
||||
# [STEP 4] 仅候选确认(无缺失/冲突);已有缺失/冲突事项时不再叠加笼统「待确认」。
|
||||
has_candidate_issue = any(
|
||||
item['category'] in {'candidate_conflict', 'candidate_missing_info'} for item in items
|
||||
)
|
||||
if not has_candidate_issue:
|
||||
confirmation_count = len(confirmation_only)
|
||||
if confirmation_count == 0:
|
||||
candidate_ready_units = [
|
||||
unit for unit in unit_rows
|
||||
if str(unit.status or '') == 'candidate_ready' and int(unit.document_id or 0) not in open_ids
|
||||
]
|
||||
result = run.result_json if isinstance(run.result_json, dict) else {}
|
||||
pending_count = max(0, int(result.get('pending_count') or 0))
|
||||
if candidate_ready_units and run.status in {'review_required', 'partially_completed'} and (
|
||||
pending_count > 0 or not items
|
||||
):
|
||||
confirmation_count = max(pending_count, len(candidate_ready_units))
|
||||
if confirmation_count > 0:
|
||||
budget_refs = claim(budget_refs)
|
||||
if budget_refs:
|
||||
items.append(_handling_item(
|
||||
category='candidate_confirmation',
|
||||
count=confirmation_count,
|
||||
reason_codes=['auto_create_disabled'] if confirmation_only else [],
|
||||
affected_refs=[
|
||||
{
|
||||
'type': 'candidate',
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'),
|
||||
}
|
||||
for item in confirmation_only[:10]
|
||||
if item.get('candidate_no')
|
||||
],
|
||||
primary_action='review_candidate',
|
||||
category='budget_stopped',
|
||||
count=len(budget_refs),
|
||||
reason_codes=['budget_initial_limit'],
|
||||
affected_refs=budget_refs,
|
||||
primary_action='view_details',
|
||||
))
|
||||
|
||||
# [STEP 4] 仅候选确认。每份 PDF 只保留一个最高优先级事项,但不能因为
|
||||
# 另一份 PDF 有冲突/缺字段,就把本文件的「待确认」整体吞掉。
|
||||
# 待确认候选同样必须先按文件认领:同一 PDF 可能产出多个候选行,
|
||||
# 但批次中心的「处理事项」统计口径是待处理文件而不是候选记录数。
|
||||
# 没有 document_id 的历史候选保留 candidate_no 作为兼容定位键,不能
|
||||
# 与任何已知文件行混合相加。
|
||||
confirmation_refs = claim([
|
||||
{
|
||||
'type': 'candidate',
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'),
|
||||
'document_id': item.get('document_id'),
|
||||
}
|
||||
for item in confirmation_only
|
||||
if item.get('candidate_no')
|
||||
])
|
||||
if not confirmation_refs:
|
||||
candidate_ready_refs = claim([
|
||||
{
|
||||
'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id),
|
||||
'_identity_content_hash': str(getattr(unit, 'content_hash', None) or '').strip().lower() or None,
|
||||
}
|
||||
for unit in unit_rows
|
||||
if (
|
||||
str(unit.status or '') == 'candidate_ready'
|
||||
and int(unit.document_id or 0) not in open_ids
|
||||
and not (
|
||||
aliases_by_document_id.get(
|
||||
int(unit.document_id or 0),
|
||||
{f'document:{int(unit.document_id or 0)}'},
|
||||
) & claimed_file_keys
|
||||
)
|
||||
)
|
||||
])
|
||||
result = run.result_json if isinstance(run.result_json, dict) else {}
|
||||
pending_count = max(0, int(result.get('pending_count') or 0))
|
||||
if candidate_ready_refs and run.status in {'review_required', 'partially_completed'} and (
|
||||
pending_count > 0 or not items
|
||||
):
|
||||
confirmation_refs = candidate_ready_refs
|
||||
if confirmation_refs:
|
||||
items.append(_handling_item(
|
||||
category='candidate_confirmation',
|
||||
count=len(confirmation_refs),
|
||||
reason_codes=['auto_create_disabled'] if confirmation_only else [],
|
||||
affected_refs=confirmation_refs,
|
||||
primary_action='review_candidate',
|
||||
))
|
||||
|
||||
priority = {name: index for index, name in enumerate(_HANDLING_ITEM_PRIORITY)}
|
||||
items.sort(key=lambda row: priority.get(str(row.get('category') or ''), 99))
|
||||
return items
|
||||
|
||||
@@ -241,15 +241,23 @@ def reconcile_single_case_for_auto_progress(
|
||||
# [STEP 3] Draft validate(refresh_validation=True 且有 current_draft)
|
||||
if refresh_validation and loaded_case.current_draft is not None:
|
||||
try:
|
||||
from app.services.shipping_notice.order_review_draft_service import validate_draft
|
||||
validate_out = validate_draft(
|
||||
user_id=int(loaded_case.owner_user_id),
|
||||
case_no=str(loaded_case.case_no),
|
||||
expected_draft_version=int(loaded_case.current_draft.draft_version),
|
||||
)
|
||||
result['validate_status'] = (
|
||||
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
draft_has_manual_values,
|
||||
validate_draft,
|
||||
)
|
||||
if draft_has_manual_values(loaded_case.current_draft):
|
||||
# 自动协调不消费人工编辑;显式保存 API 会先执行 validate_draft,
|
||||
# 再以 skip_validate=True 进入后续推进。
|
||||
result['validate_status'] = 'waiting_manual_validation'
|
||||
else:
|
||||
validate_out = validate_draft(
|
||||
user_id=int(loaded_case.owner_user_id),
|
||||
case_no=str(loaded_case.case_no),
|
||||
expected_draft_version=int(loaded_case.current_draft.draft_version),
|
||||
)
|
||||
result['validate_status'] = (
|
||||
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_LOGGER.warning(
|
||||
'validate_draft failed case_no=%s err=%s',
|
||||
@@ -347,15 +355,24 @@ def reconcile_run_review_cases_for_auto_progress(
|
||||
validate_status = 'skipped'
|
||||
if case.current_draft is not None:
|
||||
try:
|
||||
from app.services.shipping_notice.order_review_draft_service import validate_draft
|
||||
validate_out = validate_draft(
|
||||
user_id=int(case.owner_user_id),
|
||||
case_no=str(case.case_no),
|
||||
expected_draft_version=int(case.current_draft.draft_version),
|
||||
)
|
||||
validate_status = (
|
||||
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
draft_has_manual_values,
|
||||
validate_draft,
|
||||
)
|
||||
if draft_has_manual_values(case.current_draft):
|
||||
# 与单 Case 协调器及 Recovery Sweeper 保持同一语义:
|
||||
# 后台批量协调不得代替用户确认人工修改,否则每次扫描都会
|
||||
# 写入新的 validation 快照并使前端 CAS 版本持续过期。
|
||||
validate_status = 'waiting_manual_validation'
|
||||
else:
|
||||
validate_out = validate_draft(
|
||||
user_id=int(case.owner_user_id),
|
||||
case_no=str(case.case_no),
|
||||
expected_draft_version=int(case.current_draft.draft_version),
|
||||
)
|
||||
validate_status = (
|
||||
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_LOGGER.warning(
|
||||
'validate_draft failed case_no=%s err=%s',
|
||||
|
||||
@@ -13,7 +13,7 @@ services/shipping_notice/order_review_draft_service.py
|
||||
履约波次确认经 build_confirmable_draft_summary(line_keys) 仅对选中行重算 validation;
|
||||
库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定;
|
||||
路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放;
|
||||
显式校验后同步客户/Reservation/重复订单/库存路由 Gate(findings.details)。
|
||||
显式校验后同步字段完整性、字段冲突、客户/Reservation/重复订单/库存路由 Gate(findings.details)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -60,6 +60,52 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
|
||||
_EDITABLE_STATUSES = frozenset({'unreviewed', 'draft', 'ready'})
|
||||
|
||||
|
||||
def draft_has_manual_values(draft: ShippingOrderReviewDraft | Any | None) -> bool:
|
||||
"""
|
||||
判断草稿是否含需由用户显式提交的人工值。
|
||||
|
||||
核心逻辑:仅 ``source=manual`` 和 ``source=manual_override`` 表示用户改写了
|
||||
机器草稿;后台恢复不得替用户重复校验或推进。该判断同时供 STP 与 Recovery 使用,
|
||||
防止两条链路对“人工编辑”给出相反结论。
|
||||
"""
|
||||
if draft is None:
|
||||
return False
|
||||
|
||||
containers: list[dict[str, Any]] = []
|
||||
header = getattr(draft, 'header_values_json', None)
|
||||
if isinstance(header, dict):
|
||||
containers.append(header)
|
||||
for line in (getattr(draft, 'lines_json', None) or []):
|
||||
if isinstance(line, dict):
|
||||
containers.append(line)
|
||||
|
||||
for container in containers:
|
||||
values = container.get('values') if isinstance(container.get('values'), dict) else {}
|
||||
for item in values.values():
|
||||
if isinstance(item, dict) and str(item.get('source') or '') in {'manual', 'manual_override'}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def draft_requires_manual_validation(draft: ShippingOrderReviewDraft | Any | None) -> bool:
|
||||
"""
|
||||
判断人工值是否尚未被用户显式“保存订单并校验”确认。
|
||||
|
||||
核心逻辑:人工值存在本身不等于永久禁止建单;只要当前 Draft 版本已由显式
|
||||
校验生成 validation_version,即可由该次用户提交后的同步推进消费。后台恢复
|
||||
仍使用 ``draft_has_manual_values``,不会代替用户触发这个提交。
|
||||
"""
|
||||
if not draft_has_manual_values(draft):
|
||||
return False
|
||||
validation = getattr(draft, 'validation_result_json', None)
|
||||
if not isinstance(validation, dict):
|
||||
return True
|
||||
try:
|
||||
return int(validation.get('validation_version')) != int(getattr(draft, 'draft_version'))
|
||||
except (TypeError, ValueError):
|
||||
return True
|
||||
|
||||
|
||||
def soft_load_review_case_for_audit(*, user_id: int, case_no: str) -> ShippingOrderReviewCase | None:
|
||||
"""
|
||||
无行锁加载属主 Case(及 Draft),供路由层/早期门禁写拒绝审计。
|
||||
@@ -1376,10 +1422,46 @@ def _blocking_issues_for_gate(
|
||||
item for item in (validation.get('issues') or [])
|
||||
if isinstance(item, dict)
|
||||
and str(item.get('owning_gate_code') or '') == gate_code
|
||||
and str(item.get('severity') or '') == 'blocking'
|
||||
# auto_create_blocking 同样是当前复核必须解释的业务阻断:
|
||||
# 可人工建单不代表可自动建单,不能让它从 Gate 投影中消失。
|
||||
and str(item.get('severity') or '') in {'blocking', 'auto_create_blocking'}
|
||||
]
|
||||
|
||||
|
||||
def _candidate_conflict_locator(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""
|
||||
从 Candidate 原始冲突补齐字段定位,避免资格层的聚合 issue 丢失 field_code。
|
||||
|
||||
核心逻辑:资格评估可能将 ``evidence_missing`` 聚合为单条 field_conflict Finding;
|
||||
这里仅在 Finding 未附字段时读取首个阻断 Candidate conflict,供 Gate 和右栏说明。
|
||||
|
||||
Args:
|
||||
case: 当前复核 Case,可能未绑定 Candidate。
|
||||
|
||||
Returns:
|
||||
含 field_code / line_index 的定位字典;无可用事实时返回空字典。
|
||||
"""
|
||||
if not getattr(case, 'candidate_id', None):
|
||||
return {}
|
||||
from app.models import ShippingOrderCandidate
|
||||
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||||
for conflict in list(getattr(candidate, 'conflicts_json', None) or []):
|
||||
if not isinstance(conflict, dict):
|
||||
continue
|
||||
if str(conflict.get('severity') or '').lower() not in {'blocking', 'error'}:
|
||||
continue
|
||||
field_code = str(conflict.get('field') or '').strip()
|
||||
if not field_code:
|
||||
continue
|
||||
return {
|
||||
'field_code': field_code,
|
||||
'line_index': conflict.get('line_index'),
|
||||
'line_key': conflict.get('line_key'),
|
||||
}
|
||||
return {}
|
||||
|
||||
|
||||
def _sync_review_gates_safe(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
@@ -1388,7 +1470,7 @@ def _sync_review_gates_safe(
|
||||
details: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将客户/Reservation/重复订单/库存路由校验结果同步到统一 Gate。
|
||||
将字段完整性、字段冲突、客户/Reservation/重复订单/库存路由校验结果同步到统一 Gate。
|
||||
|
||||
核心逻辑:按 owning_gate 折叠阻断;原因码经 canonicalize;库存门禁附带
|
||||
unavailable_reasons 等业务事实。失败向上抛出,与 Draft 同事务回滚。
|
||||
@@ -1408,6 +1490,62 @@ def _sync_review_gates_safe(
|
||||
result = validation if isinstance(validation, dict) else _validation(case)
|
||||
base_details = dict(details or {})
|
||||
|
||||
assessment = result.get('assessment') if isinstance(result.get('assessment'), dict) else {}
|
||||
missing_fields = list(assessment.get('missing_required_fields') or [])
|
||||
invalid_lines = list(assessment.get('invalid_lines') or [])
|
||||
# [STEP 1] 字段完整性直接以当前 Draft 的 assessment 为准,主动覆盖旧 Gate 快照。
|
||||
# 不能只同步 issues:当缺字段已补齐时,旧 required_field_missing 会永久误导用户。
|
||||
sync_review_gate_for_case(
|
||||
case=case,
|
||||
gate_code='field_completeness',
|
||||
passed=not missing_fields and not invalid_lines,
|
||||
actor_id=int(user_id),
|
||||
blocking_reason_code='required_field_missing' if (missing_fields or invalid_lines) else None,
|
||||
default_reason_code='required_field_missing',
|
||||
details={
|
||||
**base_details,
|
||||
'missing_required_fields': missing_fields,
|
||||
'invalid_lines': invalid_lines,
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP 2] 自动建单冲突必须同步为字段冲突 Gate;否则右栏会保留已过期的缺字段提示。
|
||||
conflict_issues = _blocking_issues_for_gate(result, 'field_conflict_resolution')
|
||||
if not conflict_issues:
|
||||
sync_review_gate_for_case(
|
||||
case=case,
|
||||
gate_code='field_conflict_resolution',
|
||||
passed=True,
|
||||
actor_id=int(user_id),
|
||||
details=base_details,
|
||||
)
|
||||
else:
|
||||
primary_conflict = conflict_issues[0]
|
||||
conflict_locator = _candidate_conflict_locator(case)
|
||||
sync_review_gate_for_case(
|
||||
case=case,
|
||||
gate_code='field_conflict_resolution',
|
||||
passed=False,
|
||||
actor_id=int(user_id),
|
||||
blocking_reason_code=canonicalize_reason_code(
|
||||
str(primary_conflict.get('reason_code') or primary_conflict.get('code') or 'field_conflict')
|
||||
) or 'field_conflict',
|
||||
default_reason_code='field_conflict',
|
||||
details={
|
||||
**base_details,
|
||||
'line_key': primary_conflict.get('line_key') or conflict_locator.get('line_key'),
|
||||
'line_index': primary_conflict.get('line_index')
|
||||
if primary_conflict.get('line_index') is not None else conflict_locator.get('line_index'),
|
||||
'field_code': primary_conflict.get('field_code') or conflict_locator.get('field_code'),
|
||||
'issue_codes': [
|
||||
canonicalize_reason_code(str(item.get('reason_code') or item.get('code') or ''))
|
||||
for item in conflict_issues
|
||||
if canonicalize_reason_code(str(item.get('reason_code') or item.get('code') or ''))
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP 3] 其余复核 Gate 继续按 owning_gate 同步。
|
||||
for gate_code, default_reason in (
|
||||
('customer_resolution', 'customer_unresolved'),
|
||||
('reservation_validation', 'reservation_missing'),
|
||||
|
||||
@@ -17,7 +17,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderReviewCase
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderReviewCase
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.field_highlight_contract import build_field_highlight_projection
|
||||
from app.services.shipping_notice.order_review_service import get_user_review_case
|
||||
@@ -591,6 +591,61 @@ def get_case_pdf_bytes(*, user_id: int, case_no: str) -> tuple[bytes, str]:
|
||||
return read_asset_bytes(asset), str(document.filename or 'document.pdf').replace('\n', '').replace('\r', '')[:255]
|
||||
|
||||
|
||||
def get_case_intake_parse_context(*, user_id: int, case_no: str) -> dict[str, Any]:
|
||||
"""
|
||||
返回当前复核 Case 所属 Intake 的受控解析上下文,供工作台关联 PDF 与邮件正文。
|
||||
|
||||
核心逻辑:先经 Case owner 鉴权,读取 Case 主 Document 所属 Intake;direct_pdf
|
||||
强制不投影正文,其余来源再以 intake_id 查询唯一 email_body。严禁按 document_id
|
||||
或会话跨 Intake 回读正文,且不返回 FileAsset 存储位置或原始 EML。
|
||||
|
||||
Args:
|
||||
user_id: 当前登录用户,仅允许读取其拥有的 Case。
|
||||
case_no: 复核 Case 编号。
|
||||
|
||||
Returns:
|
||||
含主附件安全元数据与可选同 Intake 邮件正文的 DTO。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Case 主文档不存在时拒绝返回不完整或跨边界上下文。
|
||||
"""
|
||||
case = get_user_review_case(user_id=user_id, case_no=case_no)
|
||||
attachment = db.session.get(ShippingOrderDocument, int(case.document_id))
|
||||
if attachment is None:
|
||||
raise NotFoundError(
|
||||
'Intake parse context is unavailable',
|
||||
code='SHIPPING.REVIEW_INTAKE_CONTEXT_NOT_FOUND',
|
||||
)
|
||||
asset = db.session.get(FileAsset, int(attachment.asset_id)) if attachment.asset_id else None
|
||||
is_pdf = bool(
|
||||
asset and (
|
||||
str(asset.mime_type or '').lower() == 'application/pdf'
|
||||
or str(attachment.filename or '').lower().endswith('.pdf')
|
||||
)
|
||||
)
|
||||
intake = db.session.get(ShippingOrderIntake, int(attachment.intake_id))
|
||||
body = None if intake is not None and intake.source_type == 'direct_pdf' else (
|
||||
ShippingOrderDocument.query.filter_by(
|
||||
intake_id=attachment.intake_id,
|
||||
document_type='email_body',
|
||||
).one_or_none()
|
||||
)
|
||||
return {
|
||||
'case_no': case.case_no,
|
||||
'attachment': {
|
||||
'document_id': int(attachment.id),
|
||||
'filename': str(attachment.filename or '')[:255],
|
||||
'mime_type': str(asset.mime_type or '') if asset else None,
|
||||
'preview_kind': 'pdf' if is_pdf else 'unsupported',
|
||||
},
|
||||
'email': None if body is None else {
|
||||
'document_id': int(body.id),
|
||||
'filename': str(body.filename or 'email.eml')[:255],
|
||||
'text': str(body.extracted_text or '')[:20_000],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_case_email_evidence_text(*, user_id: int, case_no: str, document_id: int) -> dict[str, Any]:
|
||||
"""返回同一 Intake 邮件正文的已解析文本,禁止读取原始 EML、附件或存储地址。"""
|
||||
case = get_user_review_case(user_id=user_id, case_no=case_no)
|
||||
|
||||
@@ -319,7 +319,10 @@ def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[d
|
||||
except (TypeError, ValueError):
|
||||
line_index = -1
|
||||
value_keys = [str(v) for v in (item.get('values') or []) if v not in (None, '')]
|
||||
if len(value_keys) < 2:
|
||||
reason = str(item.get('reason') or 'field_conflict')
|
||||
# 证据缺失/单值冲突没有可供二选一的 values,但仍会阻断自动建单。
|
||||
# 必须投影给工作台,避免资格摘要与字段裁决区同时丢失定位事实。
|
||||
if len(value_keys) < 2 and reason not in {'evidence_missing', 'pdf_evidence_missing'}:
|
||||
continue
|
||||
observation_ids = [str(oid) for oid in (item.get('observation_ids') or []) if oid]
|
||||
options = [
|
||||
@@ -338,7 +341,7 @@ def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[d
|
||||
'line_index': line_index if line_index >= 0 else None,
|
||||
'line_key': line_key,
|
||||
'severity': str(item.get('severity') or 'blocking'),
|
||||
'reason': str(item.get('reason') or 'field_conflict'),
|
||||
'reason': reason,
|
||||
'options': options,
|
||||
'observation_ids': observation_ids,
|
||||
})
|
||||
|
||||
@@ -562,9 +562,11 @@ def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
|
||||
return actions
|
||||
if case.status == 'reparse_pending':
|
||||
return ['view']
|
||||
# 替代 PDF 的写入资格与质量异常标记不同:前者在服务层允许质量异常和普通待复核
|
||||
# Case 使用,必须作为独立动作下发,避免前端借用 mark_quality_issue 猜测权限。
|
||||
if case.status == 'quality_issue':
|
||||
return ['view', 'mark_quality_issue', 'reparse']
|
||||
actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'validate']
|
||||
return ['view', 'mark_quality_issue', 'reparse', 'upload_replacement']
|
||||
actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'upload_replacement', 'validate']
|
||||
if case.candidate_id is None and case.disposition != 'manual_order':
|
||||
actions.append('create_draft')
|
||||
else:
|
||||
@@ -729,6 +731,7 @@ def serialize_review_case(
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -739,6 +742,7 @@ def serialize_review_case(
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(formal_ot['task_id']))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -1016,6 +1020,63 @@ def serialize_review_case(
|
||||
}
|
||||
|
||||
|
||||
def _serialize_review_case_summary(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
run: ShippingOrderProcessingRun,
|
||||
) -> dict[str, Any]:
|
||||
"""为工作台文件队列投影单 Case 的只读识别与生命周期摘要。"""
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None
|
||||
# 空 Review Case 只是解析异常/人工处置容器,不能显示为已进入订单复核。
|
||||
# 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。
|
||||
lifecycle_stage = 'intake_parse'
|
||||
lifecycle_entries: list[dict[str, str]] = []
|
||||
# 接收解析是无 Candidate Case 的独立处置面,不属于订单生命周期入口;
|
||||
# 前端只能以此显式授权读取当前 Case 的解析上下文,不能据此开放订单复核。
|
||||
intake_parse_authorized = False
|
||||
candidate_is_reviewable = False
|
||||
if case.confirmed_task_id:
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
if formal_ot.get('has_formal_ot'):
|
||||
task_ui_state = build_task_ui_state(formal_ot['task'])
|
||||
lifecycle_stage = str(task_ui_state.get('lifecycle_stage') or lifecycle_stage)
|
||||
lifecycle_entries = list(task_ui_state.get('lifecycle_entries') or [])
|
||||
else:
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
candidate_is_reviewable = is_current_reviewable_candidate(candidate)
|
||||
if not case.confirmed_task_id and candidate_is_reviewable:
|
||||
# [AUTHORITY] 建单前的有效 Candidate 已由 Case 一对一绑定;后端明确授权
|
||||
# 接收解析回看与订单复核,后续履约阶段保持不可用。
|
||||
from app.services.shipping_notice.lifecycle_projection import lifecycle_entries as project_lifecycle_entries
|
||||
|
||||
lifecycle_entries = project_lifecycle_entries(
|
||||
lifecycle_stage='order_review',
|
||||
has_candidate_context=True,
|
||||
)
|
||||
lifecycle_stage = 'order_review'
|
||||
elif not case.confirmed_task_id:
|
||||
intake_parse_authorized = True
|
||||
return {
|
||||
'case_no': case.case_no,
|
||||
'document_id': int(case.document_id),
|
||||
'file_name': _document_filename(run, int(case.document_id)),
|
||||
'status': case.status,
|
||||
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
|
||||
'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0,
|
||||
'available_actions': _allowed_actions(case),
|
||||
# 后端按 Case/正式任务裁决,禁止工作台仅为当前项从草稿拼接 PO 或阶段。
|
||||
'po_number': str(candidate.po_number or '').strip() or None if candidate is not None else None,
|
||||
'lifecycle_stage': lifecycle_stage,
|
||||
# 与批次中心 / 任务中心同义;前端不得再根据 Case status 或 stage 推断入口。
|
||||
'lifecycle_entries': lifecycle_entries,
|
||||
'intake_parse_authorized': intake_parse_authorized,
|
||||
}
|
||||
|
||||
|
||||
def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
"""返回 Run 的 Case 汇总和轻量列表,避免 N+1 查询及泄露机器原始结果。"""
|
||||
cases = list(run.review_cases or [])
|
||||
@@ -1023,18 +1084,28 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
items = []
|
||||
for case in cases:
|
||||
counts[case.status] = counts.get(case.status, 0) + 1
|
||||
items.append({
|
||||
'case_no': case.case_no,
|
||||
'document_id': int(case.document_id),
|
||||
'file_name': _document_filename(run, int(case.document_id)),
|
||||
'status': case.status,
|
||||
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
|
||||
'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0,
|
||||
'available_actions': _allowed_actions(case),
|
||||
})
|
||||
items.append(_serialize_review_case_summary(case, run=run))
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
'superseded_by_run_no': run.superseding_run.run_no if run.superseding_run is not None else None,
|
||||
'summary': counts,
|
||||
'items': items,
|
||||
}
|
||||
|
||||
|
||||
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
|
||||
"""返回会话级订单队列;保留来源 Run,避免混淆单次 Run 摘要。"""
|
||||
items: list[dict[str, Any]] = []
|
||||
for run in runs:
|
||||
for case in run.review_cases or []:
|
||||
items.append({
|
||||
**_serialize_review_case_summary(case, run=run),
|
||||
'source_run_no': run.run_no,
|
||||
})
|
||||
counts = {
|
||||
'total': len(items),
|
||||
'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')),
|
||||
'processing': sum(1 for item in items if item['status'] in ('confirming', 'reparse_pending')),
|
||||
'completed': sum(1 for item in items if item['status'] in ('confirmed', 'non_order', 'quality_issue')),
|
||||
}
|
||||
return {'conversation_id': runs[0].conversation_id if runs else None, 'summary': counts, 'items': items}
|
||||
@@ -25,17 +25,52 @@ _RESERVATION_ISSUE_CODES = frozenset({
|
||||
|
||||
|
||||
def _reservation_field_id(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""从 Run 冻结 Schema 解析 reservation_id 的 field_id。"""
|
||||
"""
|
||||
从 Run 冻结 Schema 解析明细 reservation_id 的 field_id。
|
||||
|
||||
核心逻辑:字段身份由 field_code 与 scope 共同决定;同名表头 Reservation
|
||||
不能作为明细预约号投影的读取键,否则合法的明细值会被误判为缺失。
|
||||
"""
|
||||
from app.services.shipping_notice.order_review_projection import _schema_fields
|
||||
|
||||
for item in _schema_fields(case.run):
|
||||
if str(item.get('field_code') or '').strip() == 'reservation_id':
|
||||
if (
|
||||
str(item.get('field_code') or '').strip() == 'reservation_id'
|
||||
and str(item.get('scope') or '').strip() == 'line'
|
||||
):
|
||||
fid = str(item.get('field_id') or '').strip()
|
||||
if fid:
|
||||
return fid
|
||||
return None
|
||||
|
||||
|
||||
def _current_line_reservation_id(raw_line: dict[str, Any], reservation_field_id: str | None) -> str | None:
|
||||
"""
|
||||
读取 Draft 当前行的有效 Reservation。
|
||||
|
||||
核心逻辑:读取优先级与编辑工作面一致:人工 values[field_id].value → 冻结 machine_fields
|
||||
→ 顶层兼容字段。校验 Job 尚未回写 line_projections 时,摘要必须读取同一份 Draft 真源。
|
||||
"""
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
values = raw_line.get('values') if isinstance(raw_line.get('values'), dict) else {}
|
||||
entry = values.get(reservation_field_id) if reservation_field_id else None
|
||||
if isinstance(entry, dict) and 'value' in entry:
|
||||
value = entry.get('value')
|
||||
else:
|
||||
value = None
|
||||
for field in list(raw_line.get('machine_fields') or []):
|
||||
if not isinstance(field, dict) or str(field.get('field_id') or '') != reservation_field_id:
|
||||
continue
|
||||
observations = field.get('observations') if isinstance(field.get('observations'), list) else []
|
||||
if observations and isinstance(observations[0], dict):
|
||||
value = observations[0].get('value')
|
||||
break
|
||||
if value is None:
|
||||
value = raw_line.get('reservation_id')
|
||||
return validated_reservation_id(value) or None
|
||||
|
||||
|
||||
def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""
|
||||
投影建单前 Reservation 校验摘要。
|
||||
@@ -61,6 +96,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
|
||||
|
||||
validation = dict(draft.validation_result_json or {})
|
||||
line_projections = list(validation.get('line_projections') or [])
|
||||
reservation_field_id = _reservation_field_id(case)
|
||||
issues = [
|
||||
item for item in list(validation.get('issues') or [])
|
||||
if isinstance(item, dict)
|
||||
@@ -102,7 +138,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
|
||||
for idx, line in enumerate(raw_lines):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
rid = str(line.get('reservation_id') or '').strip() or None
|
||||
rid = _current_line_reservation_id(line, reservation_field_id)
|
||||
lines_out.append({
|
||||
'line_index': idx,
|
||||
'line_key': str(line.get('line_key') or '').strip() or None,
|
||||
@@ -117,7 +153,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
|
||||
return {
|
||||
'needs_attention': needs_attention,
|
||||
'status': status,
|
||||
'reservation_field_id': _reservation_field_id(case),
|
||||
'reservation_field_id': reservation_field_id,
|
||||
'lines': lines_out,
|
||||
'issues': [
|
||||
{
|
||||
|
||||
@@ -106,6 +106,7 @@ def _invalidate_downstream_if_needed(
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -277,6 +277,11 @@ def _backfill_existing_case_from_ready_unit(
|
||||
operation_json={'document_id': int(unit.document_id)},
|
||||
))
|
||||
_ensure_order_task_for_case_candidate(run, candidate_id=case.candidate_id)
|
||||
# Candidate/Case 物化后收口初始解析 Gate,确保实时阶段进入订单复核。
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
reconcile_extraction_gates_for_review_case,
|
||||
)
|
||||
reconcile_extraction_gates_for_review_case(case=case, actor_type='system')
|
||||
|
||||
|
||||
def ensure_review_case_for_unit(
|
||||
@@ -334,6 +339,10 @@ def ensure_review_case_for_unit(
|
||||
operation_json={'candidate_linked': candidate_id is not None, 'issue_count': len(issues)},
|
||||
))
|
||||
_ensure_order_task_for_case_candidate(run, candidate_id=candidate_id)
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
reconcile_extraction_gates_for_review_case,
|
||||
)
|
||||
reconcile_extraction_gates_for_review_case(case=case, actor_type='system')
|
||||
db.session.flush()
|
||||
return case
|
||||
|
||||
@@ -409,6 +418,26 @@ def get_review_run_visible_to_user(
|
||||
return run
|
||||
|
||||
|
||||
def get_review_queue_visible_to_user(
|
||||
run_no: str,
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool = False,
|
||||
) -> list[ShippingOrderProcessingRun]:
|
||||
"""按当前 Run 定位会话,并返回该用户会话内未被替代的 Review Run。"""
|
||||
anchor = get_review_run_visible_to_user(run_no, user_id, is_admin=is_admin)
|
||||
query = ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.conversation_id == anchor.conversation_id,
|
||||
)
|
||||
if not is_admin:
|
||||
query = query.filter(ShippingOrderProcessingRun.user_id == int(user_id))
|
||||
query = query.filter(ShippingOrderProcessingRun.superseded_by_run_id.is_(None))
|
||||
return query.order_by(
|
||||
ShippingOrderProcessingRun.created_at.asc(),
|
||||
ShippingOrderProcessingRun.id.asc(),
|
||||
).all()
|
||||
|
||||
|
||||
def get_review_case_visible_to_user(
|
||||
case_no: str,
|
||||
user_id: int,
|
||||
|
||||
@@ -38,7 +38,10 @@ from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
finalize_sync_auto_progress_after_commit,
|
||||
schedule_auto_progress_after_review_confirm,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import _validation
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
_validation,
|
||||
draft_requires_manual_validation,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
extraction_emergency_stop_enabled,
|
||||
xfa_shadow_mode_enabled,
|
||||
@@ -93,22 +96,41 @@ def _draft_has_manual_edits(case: ShippingOrderReviewCase) -> bool:
|
||||
|
||||
核心逻辑:header/line values 中任一 source=manual 即视为需显式确认。
|
||||
"""
|
||||
return case.current_draft is None or draft_requires_manual_validation(case.current_draft)
|
||||
|
||||
|
||||
def _refresh_validation_preserving_manual_confirmation(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
重算 STP 资格事实,同时保留当前 Draft 已完成的显式人工校验身份。
|
||||
|
||||
核心逻辑:Worker 必须在执行前重验配置、证据与门禁,但 ``validation_version``
|
||||
代表用户已对当前 Draft 版本点击“保存订单并校验”。若该值恰好等于当前版本,
|
||||
重验不能撤销该确认;草稿版本变化时绝不继承,仍会被 manual-validation 门禁拦截。
|
||||
|
||||
Args:
|
||||
case: 含当前 Draft 的复核 Case。
|
||||
|
||||
Returns:
|
||||
最新资格事实,必要时附带当前版本的 validation_version。
|
||||
"""
|
||||
draft = case.current_draft
|
||||
if draft is None:
|
||||
return True
|
||||
header = draft.header_values_json if isinstance(draft.header_values_json, dict) else {}
|
||||
values = header.get('values') if isinstance(header.get('values'), dict) else {}
|
||||
for item in values.values():
|
||||
if isinstance(item, dict) and str(item.get('source') or '') == 'manual':
|
||||
return True
|
||||
for raw_line in draft.lines_json or []:
|
||||
if not isinstance(raw_line, dict):
|
||||
continue
|
||||
line_values = raw_line.get('values') if isinstance(raw_line.get('values'), dict) else {}
|
||||
for item in line_values.values():
|
||||
if isinstance(item, dict) and str(item.get('source') or '') == 'manual':
|
||||
return True
|
||||
return False
|
||||
validation = _validation(case)
|
||||
prior = draft.validation_result_json if isinstance(draft.validation_result_json, dict) else {}
|
||||
try:
|
||||
confirmed_version = int(prior.get('validation_version'))
|
||||
except (TypeError, ValueError):
|
||||
confirmed_version = None
|
||||
if confirmed_version == int(draft.draft_version):
|
||||
validation['validation_version'] = confirmed_version
|
||||
for key in ('validation_checksum', 'validated_at', 'validated_case_no', 'validated_document_id'):
|
||||
if key in prior:
|
||||
validation[key] = prior[key]
|
||||
draft.validation_result_json = validation
|
||||
draft.issue_summary_json = list(validation.get('issues') or [])
|
||||
return validation
|
||||
|
||||
|
||||
def _is_xfa_case(*, candidate: ShippingOrderCandidate | None, validation: dict[str, Any]) -> bool:
|
||||
@@ -554,9 +576,7 @@ def ensure_stp_auto_create_for_case(
|
||||
|
||||
candidate = _persist_case_candidate_qualification(case=case, run=resolved_run)
|
||||
if refresh_validation:
|
||||
validation = _validation(case)
|
||||
case.current_draft.validation_result_json = validation
|
||||
case.current_draft.issue_summary_json = list(validation.get('issues') or [])
|
||||
validation = _refresh_validation_preserving_manual_confirmation(case=case)
|
||||
else:
|
||||
validation = (
|
||||
dict(case.current_draft.validation_result_json)
|
||||
|
||||
@@ -62,6 +62,20 @@ _PROGRESS_EVENT_TO_PROCESSING_STAGE: dict[str, str] = {
|
||||
'run_completed': 'candidate_creating',
|
||||
}
|
||||
|
||||
# 正式 Process Gate 的库存履约阶段 → 统一 15 阶投影阶段。
|
||||
# Gate 码不是 15 阶成员,必须在写路径转换后再回写 OT,避免已建单任务残留建单前 stage。
|
||||
_PROCESS_GATE_TO_PROCESSING_STAGE: dict[str, str] = {
|
||||
'inventory_source_routing': 'inventory_source_resolving',
|
||||
'inventory_preparation': 'inventory_fetching',
|
||||
'inventory_field_mapping': 'inventory_fetching',
|
||||
'inventory_matching': 'inventory_matching',
|
||||
'inventory_sufficiency': 'inventory_matching',
|
||||
'excel_readiness': 'excel_generating',
|
||||
'artifact_generation': 'excel_generating',
|
||||
'freight_upload_rpa': 'freight_uploading',
|
||||
'manual_upload_handoff': 'freight_uploading',
|
||||
}
|
||||
|
||||
|
||||
def _clamp_early_stage(stage: str, *, source_type: str | None) -> str:
|
||||
"""
|
||||
@@ -335,6 +349,19 @@ def sync_order_task_stage_for_notice(
|
||||
if ot is None:
|
||||
return None
|
||||
status, stage = map_notice_to_processing_status_stage(notice)
|
||||
# [STEP] Execution.current_gate_code 是正式履约事实,优先于尚未来得及写入 Notice
|
||||
# 领域字段的默认映射;只接受 active/waiting_external/blocked 执行,避免旧 Execution 回退 OT。
|
||||
active_execution_id = getattr(notice, 'active_process_execution_id', None)
|
||||
if active_execution_id is not None:
|
||||
from app.models import ShippingProcessExecution
|
||||
|
||||
execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
|
||||
execution_status = str(getattr(execution, 'status', None) or '').strip().lower()
|
||||
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
|
||||
gate_stage = _PROCESS_GATE_TO_PROCESSING_STAGE.get(gate_code)
|
||||
if execution_status in {'active', 'waiting_external', 'blocked'} and gate_stage:
|
||||
stage = gate_stage
|
||||
status = 'automating' if execution_status in {'active', 'waiting_external'} else 'blocked'
|
||||
if stage not in SHIPPING_PROCESSING_STAGES:
|
||||
stage = 'inventory_matching'
|
||||
return sync_order_task_processing_state(
|
||||
|
||||
@@ -263,6 +263,9 @@ def _attempts_summary(
|
||||
for code in source_codes:
|
||||
att = _latest_attempt(task_no, code, session=session)
|
||||
result[code] = {
|
||||
# PreparationSourceAttempt 必须持有不可变 RPA Attempt 主键;回调据此
|
||||
# 回写准备轮次及关联 RecoveryPlan,不能仅靠 task/source 猜测最新记录。
|
||||
'attempt_id': int(att.id) if att else None,
|
||||
'attempt_no': att.attempt_no if att else 0,
|
||||
'status': att.status if att else 'not_started',
|
||||
'run_no': att.run_no if att else None,
|
||||
@@ -407,7 +410,12 @@ def ensure_all_required_sources_prepared(
|
||||
gate_id = None
|
||||
if execution_id:
|
||||
execution_row = sess.get(ShippingProcessExecution, int(execution_id))
|
||||
if execution_row is not None and execution_row.current_gate_code:
|
||||
if (
|
||||
execution_row is not None
|
||||
and int(getattr(execution_row, 'task_id', 0) or 0) == int(task.id)
|
||||
and str(getattr(execution_row, 'status', '') or '').strip().lower() != 'superseded'
|
||||
and execution_row.current_gate_code
|
||||
):
|
||||
gate_row = sess.query(ShippingProcessGate).filter_by(
|
||||
execution_id=int(execution_row.id),
|
||||
gate_code=str(execution_row.current_gate_code),
|
||||
@@ -504,7 +512,7 @@ def per_source_callback_handler(
|
||||
|
||||
Returns:
|
||||
(result_code: str, attempt: ShippingTaskInventoryRpaAttempt | None)
|
||||
result_code ∈ {not_found, idempotent_ok, superseded_late, task_terminal, succeeded, failed}
|
||||
result_code ∈ {not_found, idempotent_ok, superseded_late, task_terminal, validated, succeeded, failed}
|
||||
"""
|
||||
sess = session or db.session
|
||||
task_no = str(task.task_no or '').strip()
|
||||
@@ -596,6 +604,12 @@ def per_source_callback_handler(
|
||||
sess.flush([attempt])
|
||||
return 'task_terminal', attempt
|
||||
|
||||
# Batch Worker 必须先在不改变 Attempt 状态的条件下完成身份围栏校验;Excel
|
||||
# 入库、结构校验、任务关联都成功后,才会以同一三元组再次调用本函数写入
|
||||
# succeeded。否则单项保存点回滚时会留下“RPA 已成功、库存未就绪”的假事实。
|
||||
if bool(callback_payload.get('_defer_success_confirmation')):
|
||||
return 'validated', attempt
|
||||
|
||||
# [STEP 6] 写回调结果
|
||||
attempt.callback_payload_json = dict(callback_payload or {})
|
||||
attempt.callback_received_at = datetime.utcnow()
|
||||
|
||||
@@ -23,6 +23,7 @@ from typing import Any
|
||||
|
||||
from app.models import (
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderCandidate,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingNotice,
|
||||
@@ -31,6 +32,7 @@ from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
bind_execution_task,
|
||||
ensure_execution_for_workflow_version,
|
||||
skip_gate_as_superseded,
|
||||
sync_gate_from_business_result,
|
||||
)
|
||||
|
||||
@@ -227,6 +229,7 @@ def find_execution_for_case(case: ShippingOrderReviewCase) -> ShippingProcessExe
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -237,6 +240,7 @@ def find_execution_for_task(task: ShippingNotice) -> ShippingProcessExecution |
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -605,6 +609,7 @@ def sync_early_pipeline_gates(
|
||||
idempotency_key=f'early:layout:{execution.execution_no}:{layouts_ready}',
|
||||
force=True,
|
||||
)
|
||||
|
||||
if not layouts_ready:
|
||||
return
|
||||
apply_gate_outcome(
|
||||
@@ -660,6 +665,71 @@ def sync_early_pipeline_gates(
|
||||
)
|
||||
|
||||
|
||||
def reconcile_extraction_gates_for_review_case(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> ShippingProcessExecution | None:
|
||||
"""在当前 Candidate 已物化后收口旧解析 Gate,避免阶段回退到接收解析。
|
||||
|
||||
触发时机:Review Case 初建或补回 Candidate 后调用。Case 本身可能先于机器候选
|
||||
创建,不能把“已创建人工容器”误当作“文件已解析成功”;未关联当前 Candidate 时
|
||||
不创建 Execution、也不推进任何解析 Gate,仍由真实解析链路裁决。
|
||||
|
||||
Args:
|
||||
case: 已持久化的复核 Case;必须关联当前 Candidate 才可推进。
|
||||
actor_type: 审计操作主体。
|
||||
actor_id: 可选审计主体标识。
|
||||
|
||||
Returns:
|
||||
已同步的正式 Execution;Candidate 尚未物化或已失效时返回 ``None``。
|
||||
"""
|
||||
candidate = (
|
||||
ShippingOrderCandidate.query.get(int(case.candidate_id))
|
||||
if case.candidate_id is not None else None
|
||||
)
|
||||
# [STEP] Candidate 是“解析成功”的最小业务事实。禁止由空 Case 关闭旧 Gate,
|
||||
# 否则缺候选的 PDF 会被错误投影为可进入订单复核。
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
if not is_current_reviewable_candidate(candidate):
|
||||
return None
|
||||
execution = find_execution_for_case(case)
|
||||
if execution is None:
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=int(case.id), actor_type=actor_type, actor_id=actor_id,
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
for code in (
|
||||
'document_materialization', 'layout_parsing',
|
||||
'document_profile_routing', 'order_field_extraction',
|
||||
):
|
||||
skip_gate_as_superseded(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=code,
|
||||
disposition='superseded_by_candidate',
|
||||
effective_result_json={
|
||||
'source': 'candidate_ready',
|
||||
'candidate_id': int(candidate.id),
|
||||
'review_case_id': int(case.id),
|
||||
},
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
)
|
||||
missing = list(getattr(candidate, 'missing_fields_json', None) or [])
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='field_completeness', passed=not missing,
|
||||
effective_result={'findings': [], 'blocked_fields': missing, 'source': 'candidate_ready'},
|
||||
blocking_reason_code=None if not missing else 'required_field_missing',
|
||||
actor_type=actor_type, actor_id=actor_id,
|
||||
idempotency_key=f'candidate-ready:field-completeness:{case.id}:{",".join(sorted(map(str, missing)))}',
|
||||
force=True,
|
||||
)
|
||||
return execution
|
||||
|
||||
|
||||
def _fulfillment_blocking_finding(
|
||||
*,
|
||||
gate_code: str,
|
||||
@@ -793,10 +863,15 @@ def sync_fulfillment_gates_from_task(
|
||||
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
|
||||
status = _derived_fulfillment_status(task)
|
||||
match_status = str(task.match_status or '').strip()
|
||||
has_export = bool(str(task.export_file_path or '').strip())
|
||||
has_inventory_lines = isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0
|
||||
status = _derived_fulfillment_status(task)
|
||||
# [STEP 1A] 已验证并绑定的库存行是库存准备的正式成功事实。RPA 回调与
|
||||
# 旧失败/超时 Attempt 可以乱序到达;不能让遗留的 rpa_exhausted 把已成功
|
||||
# 入库的任务重新投影为 waiting_inventory,否则 Gate 会停在“手工上传”。
|
||||
if has_inventory_lines and status == 'waiting_inventory':
|
||||
status = 'inventory_ready'
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)))
|
||||
# [STEP 1] 优先读匹配/短缺实体;阶段由领域事实推导。
|
||||
|
||||
@@ -563,6 +563,7 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
|
||||
'extraction_incomplete': 'order_field_extraction',
|
||||
'order_extraction_failed': 'order_field_extraction',
|
||||
'order_extraction_cancelled': 'order_field_extraction',
|
||||
'generic_extraction_disabled': 'order_field_extraction',
|
||||
'evidence_missing': 'order_field_extraction',
|
||||
'required_field_missing': 'field_completeness',
|
||||
'final_required_field_missing': 'field_completeness',
|
||||
|
||||
@@ -827,9 +827,7 @@ def _handle_retry_inventory_preparation(
|
||||
# 用户触发的重新获取库存不能把“已提交但未确认”伪装成业务完成;
|
||||
# Gate 仍可记录 waiting_external,调用方可据此轮询,但测试/审计需区分
|
||||
# 人工重试动作本身与系统自动轮询动作。
|
||||
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'}
|
||||
if payload.get('action_code') == 'poll_inventory_preparation'
|
||||
else {'waiting', 'waiting_external', 'pending'},
|
||||
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'},
|
||||
blocking_reason_code=prep_reason,
|
||||
)
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id)
|
||||
@@ -939,11 +937,14 @@ def _handle_retry_inventory_matching(
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
重试库存匹配;匹配已完成但仍有缺口时返回业务人工阻断。
|
||||
重试库存匹配;匹配已完成但仍有缺口时通过当前匹配 Gate,交由库存满足性 Gate
|
||||
保持业务人工阻断。
|
||||
|
||||
核心逻辑:``match_inventory`` 的 ``needs_human`` 同时覆盖“匹配失败”和
|
||||
“匹配成功但库存不足”。后者必须以库存满足性人工复核收口,不能误记为
|
||||
技术失败,否则 RecoveryPlan 会反复失败且页面看不到有效推进。
|
||||
“匹配成功但库存不足”。匹配成功但库存不足时,前置的
|
||||
``sync_fulfillment_gates_from_task`` 已将缺口写入 inventory_sufficiency;
|
||||
当前 inventory_matching Attempt 必须以 passed 收口,否则会覆盖正确的
|
||||
满足性 Gate 归属并再次显示“进入库存匹配处理”。
|
||||
"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_inventory
|
||||
@@ -958,16 +959,9 @@ def _handle_retry_inventory_matching(
|
||||
match_status in {'partial', 'unfulfillable'} or has_shortage
|
||||
):
|
||||
return {
|
||||
'outcome': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_shortage_review_required',
|
||||
'blocking_reason_json': {
|
||||
'message': '库存重新匹配已完成,仍存在库存缺口。',
|
||||
'match_status': match_status or None,
|
||||
},
|
||||
'recommendation_json': {
|
||||
'navigation_action': 'open_shortage_review',
|
||||
'dispatch_mode': 'navigate',
|
||||
},
|
||||
# 缺口归属由 sync_fulfillment_gates_from_task 写入
|
||||
# inventory_sufficiency;不能在这里再次阻断 inventory_matching。
|
||||
'outcome': 'passed',
|
||||
'effective_result_json': {
|
||||
'findings': [],
|
||||
'match_status': match_status or None,
|
||||
|
||||
@@ -198,10 +198,34 @@ def schedule_waiting_external_poll(
|
||||
60,
|
||||
)
|
||||
if (now - waiting_since).total_seconds() >= timeout_sec:
|
||||
# [STEP] 超时:创建 Attempt 将 Gate 转为人工阻断,停止无限轮询。
|
||||
# 回调与延迟 poll 可能交错:在把等待状态转为超时前,必须从当前任务事实
|
||||
# 重算 Gate。否则 RPA 已成功入库后,旧 poll 会用历史 waiting_since 覆盖成功结果。
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
return None
|
||||
if str(gate.gate_code or '').strip() == 'inventory_preparation' and execution.task_id:
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
task = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
has_inventory_lines = bool(
|
||||
isinstance(getattr(task, 'inventory_lines_json', None), list)
|
||||
and getattr(task, 'inventory_lines_json', None)
|
||||
)
|
||||
if task is not None and has_inventory_lines:
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system')
|
||||
db.session.flush()
|
||||
db.session.refresh(gate)
|
||||
if gate.status != 'waiting_external':
|
||||
return None
|
||||
# [STEP] 超时:创建 Attempt 将 Gate 转为人工阻断,停止无限轮询。
|
||||
# 外部轮询超时是新的、可恢复的业务事实;不能保留原来的
|
||||
# inventory_rpa_queued,否则页面会同时显示“等待外部”和“人工处理”。
|
||||
timeout_reason = (
|
||||
'inventory_rpa_timeout'
|
||||
if str(gate.gate_code or '').strip() == 'inventory_preparation'
|
||||
else (gate.blocking_reason_code or 'gate_invalidated')
|
||||
)
|
||||
poll_attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=gate.gate_code,
|
||||
@@ -221,7 +245,7 @@ def schedule_waiting_external_poll(
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(poll_attempt.id),
|
||||
outcome='blocked_manual',
|
||||
blocking_reason_code=gate.blocking_reason_code or 'gate_invalidated',
|
||||
blocking_reason_code=timeout_reason,
|
||||
blocking_reason_json={
|
||||
'message': '外部等待超时,请人工处理',
|
||||
'waiting_since': waiting_since.isoformat(),
|
||||
@@ -240,8 +264,29 @@ def schedule_waiting_external_poll(
|
||||
action = gate.next_action_code or primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status='waiting_external',
|
||||
)
|
||||
if not action:
|
||||
# ``poll_inventory_preparation`` 只能轮询库存准备 Gate。跨 Gate 恢复
|
||||
# (例如从 inventory_matching 回到 inventory_preparation)完成后,原 Gate
|
||||
# 可能短暂保留 waiting_external,但不能把准备阶段的轮询动作投递到该原 Gate;
|
||||
# 否则 executor 的归属校验会把过期 poll 误记为技术失败。
|
||||
if not action and str(gate.gate_code or '').strip() == 'inventory_preparation':
|
||||
action = 'poll_inventory_preparation'
|
||||
if (
|
||||
str(gate.gate_code or '').strip() != 'inventory_preparation'
|
||||
and str(action or '').strip() == 'poll_inventory_preparation'
|
||||
):
|
||||
_LOGGER.info(
|
||||
'skip stale inventory-preparation poll: gate_id=%s gate_code=%s',
|
||||
gate.id,
|
||||
gate.gate_code,
|
||||
)
|
||||
return None
|
||||
if not action:
|
||||
_LOGGER.info(
|
||||
'skip stale external-wait poll: gate_id=%s gate_code=%s has no waiting action',
|
||||
gate.id,
|
||||
gate.gate_code,
|
||||
)
|
||||
return None
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
return None
|
||||
|
||||
@@ -922,6 +922,7 @@ def find_execution_projection_for_case(case_id: int) -> dict[str, Any] | None:
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -935,6 +936,7 @@ def find_execution_projection_for_task(task_id: int) -> dict[str, Any] | None:
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -170,7 +170,7 @@ def request_gate_action(
|
||||
|
||||
execution = get_execution_by_no(execution_no)
|
||||
execution_status = str(execution.status or '').strip().lower()
|
||||
if execution_status in {'completed', 'cancelled'}:
|
||||
if execution_status in {'completed', 'cancelled', 'superseded'}:
|
||||
raise ValidationError(
|
||||
'Process execution is terminal; write actions are not allowed',
|
||||
code='SHIPPING.PROCESS_EXECUTION_TERMINAL',
|
||||
|
||||
@@ -290,6 +290,7 @@ def ensure_execution_for_workflow_version(
|
||||
existing = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(review_case_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.with_for_update()
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
@@ -298,6 +299,7 @@ def ensure_execution_for_workflow_version(
|
||||
existing = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.with_for_update()
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
@@ -641,6 +643,13 @@ def complete_gate_attempt(
|
||||
if execution is None:
|
||||
raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND')
|
||||
|
||||
if str(execution.status or '').strip().lower() == 'superseded':
|
||||
raise ConflictError(
|
||||
'Superseded process execution cannot complete gate attempts',
|
||||
code='SHIPPING.PROCESS_EXECUTION_SUPERSEDED',
|
||||
details={'execution_no': execution.execution_no},
|
||||
)
|
||||
|
||||
now = _utc_now()
|
||||
before = {
|
||||
'status': gate.status,
|
||||
@@ -749,6 +758,114 @@ def complete_gate_attempt(
|
||||
return gate
|
||||
|
||||
|
||||
def skip_gate_as_superseded(
|
||||
*,
|
||||
execution_no: str,
|
||||
gate_code: str,
|
||||
disposition: str,
|
||||
effective_result_json: dict[str, Any] | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> ShippingProcessGate:
|
||||
"""以明确替代语义关闭不再需要的 Gate,并终止活动 Attempt。
|
||||
|
||||
触发时机:更高层、可审计的业务事实(例如当前有效 Candidate)已形成,旧技术
|
||||
Gate 不应继续主导当前阶段时调用。已真实通过的 Gate 保持 ``passed``,不能被
|
||||
事后改写;其余 Gate 收口为 ``skipped``,且留下 disposition 供诊断和审计区分。
|
||||
|
||||
Args:
|
||||
execution_no: 正式 Execution 编号。
|
||||
gate_code: 需要收口的 Gate 编码。
|
||||
disposition: 稳定替代原因,例如 ``superseded_by_candidate``。
|
||||
effective_result_json: 受控业务证据,不得含原始文档或敏感内容。
|
||||
"""
|
||||
execution = _locked_execution(execution_no)
|
||||
if str(execution.status or '').strip().lower() == 'superseded':
|
||||
raise ConflictError(
|
||||
'Superseded process execution cannot skip gates',
|
||||
code='SHIPPING.PROCESS_EXECUTION_SUPERSEDED',
|
||||
details={'execution_no': execution.execution_no},
|
||||
)
|
||||
gate = _locked_gate(execution=execution, gate_code=gate_code)
|
||||
reason = str(disposition or '').strip() or 'superseded'
|
||||
previous_result = gate.effective_result_json if isinstance(gate.effective_result_json, dict) else {}
|
||||
# 候选收口可重复调用;同一替代事实已写入时不再制造新审计事件或版本。
|
||||
if gate.status == 'skipped' and str(previous_result.get('disposition') or '') == reason:
|
||||
return gate
|
||||
# 旧实现曾把 candidate_ready 收口伪记为 passed。它不是技术 Gate 的真实成功,
|
||||
# 因此可被安全纠正为 skipped;其他 passed 仍是不可改写的真实执行事实。
|
||||
candidate_ready_compatibility_pass = (
|
||||
gate.status == 'passed'
|
||||
and str(previous_result.get('source') or '') == 'candidate_ready'
|
||||
)
|
||||
if gate.status == 'passed' and not candidate_ready_compatibility_pass:
|
||||
return gate
|
||||
|
||||
now = _utc_now()
|
||||
active_attempts = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter(
|
||||
ShippingProcessGateAttempt.gate_id == int(gate.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
)
|
||||
.order_by(ShippingProcessGateAttempt.attempt_no.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
latest_attempt_id = gate.latest_attempt_id
|
||||
for attempt in active_attempts:
|
||||
attempt.status = 'superseded'
|
||||
attempt.finished_at = now
|
||||
attempt.lease_token = None
|
||||
attempt.lease_expires_at = None
|
||||
attempt.error_code = reason[:64]
|
||||
attempt.error_summary = 'Gate superseded by higher-level business fact.'
|
||||
latest_attempt_id = int(attempt.id)
|
||||
|
||||
before = {
|
||||
'status': gate.status,
|
||||
'gate_code': gate.gate_code,
|
||||
'blocking_reason_code': gate.blocking_reason_code,
|
||||
}
|
||||
result = dict(previous_result)
|
||||
result.update(dict(effective_result_json or {}))
|
||||
result['disposition'] = reason
|
||||
gate.status = 'skipped'
|
||||
gate.blocking_reason_code = None
|
||||
gate.blocking_reason_json = None
|
||||
gate.recommendation_json = None
|
||||
gate.effective_result_json = result
|
||||
gate.next_action_code = None
|
||||
gate.latest_attempt_id = latest_attempt_id
|
||||
gate.evaluation_version = int(gate.evaluation_version) + 1
|
||||
gate.lock_version = int(gate.lock_version) + 1
|
||||
gate.updated_at = now
|
||||
execution.lock_version = int(execution.lock_version) + 1
|
||||
execution.updated_at = now
|
||||
_refresh_execution_pointers(execution)
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_superseded',
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
action='skip',
|
||||
actor_type=actor_type if actor_type in {'user', 'system', 'rpa', 'chatflow', 'admin'} else 'system',
|
||||
actor_id=actor_id,
|
||||
result='success',
|
||||
reason_code=reason,
|
||||
before=before,
|
||||
after={
|
||||
'status': gate.status,
|
||||
'gate_code': gate.gate_code,
|
||||
'execution_no': execution.execution_no,
|
||||
'current_gate_code': execution.current_gate_code,
|
||||
},
|
||||
metadata={'disposition': reason},
|
||||
source='process_gate',
|
||||
)
|
||||
db.session.flush()
|
||||
return gate
|
||||
|
||||
|
||||
def _enqueue_auto_progress_after_gate_pass(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
@@ -776,6 +893,16 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
# 通过后必须继续进入库存匹配;关闭自动匹配时才保留人工恢复入口。
|
||||
if str(definition.get('responsible_party') or '') not in {'system', 'worker'}:
|
||||
return
|
||||
# 自动续跑只可投递真实执行动作。导航动作属于人工工作台入口,不能因
|
||||
# Gate 的默认责任方为 worker 而被 Job 执行后重新写回人工阻断状态。
|
||||
from app.services.shipping_notice.process_gate_executor import is_navigation_action
|
||||
|
||||
if is_navigation_action(str(next_gate.next_action_code)):
|
||||
return
|
||||
# retry_inventory_preparation 是用户显式恢复动作,会强制写新的 RPA Trigger。
|
||||
# 自动推进只能轮询 waiting_external,绝不能把失败恢复误当作下一步执行。
|
||||
if next_gate.next_action_code == 'retry_inventory_preparation':
|
||||
return
|
||||
if (
|
||||
(
|
||||
next_gate.next_action_code in {'retry_inventory_matching'}
|
||||
@@ -912,6 +1039,14 @@ def sync_gate_from_business_result(
|
||||
"""
|
||||
key = str(idempotency_key or '').strip() or f'sync:{execution_no}:{gate_code}:{uuid.uuid4().hex}'
|
||||
execution = _locked_execution(execution_no)
|
||||
# [STEP] CandidateSet 重冻结后旧 Execution 仅保留审计价值。任何迟到的
|
||||
# 回调、Worker 或业务同步都不能再写入其 Gate,否则历史链会重新覆盖实时阶段。
|
||||
if str(execution.status or '').strip().lower() == 'superseded':
|
||||
raise ConflictError(
|
||||
'Superseded process execution cannot accept business results',
|
||||
code='SHIPPING.PROCESS_EXECUTION_SUPERSEDED',
|
||||
details={'execution_no': execution.execution_no},
|
||||
)
|
||||
gate = _locked_gate(execution=execution, gate_code=gate_code)
|
||||
|
||||
# [STEP] Gate Worker 执行器可能在当前 Attempt 内同步最新业务事实。
|
||||
|
||||
@@ -51,7 +51,7 @@ def record_projection_inconsistency_audit(payload: dict[str, Any]) -> None:
|
||||
review_case_no=str(payload.get('case_no') or '').strip() or None,
|
||||
conversation_id=str(payload.get('conversation_id') or '').strip() or None,
|
||||
actor_type='system',
|
||||
result='blocked',
|
||||
result='failure',
|
||||
error_code=PROJECTION_INCONSISTENT_ERROR_CODE,
|
||||
reason_code=PROJECTION_INCONSISTENT_ERROR_CODE,
|
||||
reason='shipping_notice_no present with pre-create stage',
|
||||
@@ -165,7 +165,7 @@ def assert_notice_task_ownership(
|
||||
review_case_no=expect_case,
|
||||
actor_type='user' if actor_id is not None else 'system',
|
||||
actor_id=actor_id,
|
||||
result='blocked',
|
||||
result='failure',
|
||||
error_code=TASK_OWNERSHIP_MISMATCH_ERROR_CODE,
|
||||
reason_code=TASK_OWNERSHIP_MISMATCH_ERROR_CODE,
|
||||
reason='formal notice does not belong to current case/run/order task',
|
||||
|
||||
@@ -496,6 +496,13 @@ def reconcile_processing_projection_facts(
|
||||
# inventory_matching/running,但 Gate 已经进入 Excel 或上传节点;先把统一
|
||||
# 投影游标对齐 Gate,禁止旧 primary_action 继续生成 match_inventory。
|
||||
gate_stage = {
|
||||
# 正式 20-Gate 进入履约后,兼容 OT 字段可能尚未被旧写路径同步。
|
||||
# 读投影必须以 Gate 统一覆盖,避免历史 waiting_review 重新污染批次中心。
|
||||
'inventory_source_routing': 'inventory_source_resolving',
|
||||
'inventory_preparation': 'inventory_fetching',
|
||||
'inventory_field_mapping': 'inventory_fetching',
|
||||
'inventory_matching': 'inventory_matching',
|
||||
'inventory_sufficiency': 'inventory_matching',
|
||||
'excel_readiness': 'excel_generating',
|
||||
'artifact_generation': 'excel_generating',
|
||||
'freight_upload_rpa': 'freight_uploading',
|
||||
@@ -811,12 +818,19 @@ def apply_user_projection_fields(
|
||||
|
||||
# ===== [STEP 6] 计算 blocking_reason: {code, i18n_key, details} 或 None =====
|
||||
_REASON_TO_I18N_KEY: dict[str, str] = {
|
||||
# 批次中心与订单生命周期工作台共用 chat 文案域,避免把内部原因码裸露给用户。
|
||||
'generic_extraction_disabled': 'chat.shippingProcessing.reasonCode.generic_extraction_disabled',
|
||||
'inventory_file_missing': 'chat.shippingProcessing.reasonCode.inventory_file_missing',
|
||||
'inventory_match_failed': 'chat.shippingProcessing.reasonCode.inventory_match_failed',
|
||||
'inventory_preparation_failed': 'chat.shippingProcessing.reasonCode.inventory_preparation_failed',
|
||||
'manual_upload_pending': 'chat.shippingProcessing.reasonCode.manual_upload_pending',
|
||||
'inventory_source_unstable': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
|
||||
'inventory_snapshot_missing': 'workspace.shippingNotice.processGate.reasons.inventory_file_missing',
|
||||
'inventory_match_incomplete': 'workspace.shippingNotice.processGate.reasons.inventory_match_failed',
|
||||
'inventory_source_candidates_need_human': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
|
||||
'upload_rpa_failed': 'workspace.shippingNotice.processGate.reasons.upload_rpa_failed',
|
||||
'inventory_shortage': 'workspace.shippingNotice.processGate.reasons.inventory_insufficient',
|
||||
'inventory_shortage_review_required': 'workspace.shippingNotice.processGate.reasons.inventory_shortage_review_required',
|
||||
'inventory_source_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_source_conflicted',
|
||||
'inventory_source_unresolved': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
|
||||
'inventory_multi_file_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_multi_file_conflict',
|
||||
@@ -924,6 +938,7 @@ def apply_user_projection_fields(
|
||||
_ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = {
|
||||
'retry': 'workspace.shippingNotice.processGate.actionCodes.retry_with_latest_rules',
|
||||
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
'retry_inventory_matching': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_matching',
|
||||
'open_inventory_source_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_source_review',
|
||||
'open_inventory_match_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_match_review',
|
||||
'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review',
|
||||
|
||||
@@ -700,6 +700,7 @@ def _sync_process_gates_after_progress(task: Any, payload: dict[str, Any]) -> No
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -131,6 +131,27 @@ _REVIEW_CASE_STATUS_TODO: dict[str, str] = {
|
||||
}
|
||||
|
||||
|
||||
def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[str, str]]:
|
||||
"""裁决建单前 Review Case 的生命周期查看入口。
|
||||
|
||||
只有关联当前有效订单 Candidate 的 Case 才能进入订单生命周期工作台;空 Case、
|
||||
已替代 Candidate 与拒绝/过期 Candidate 仍是解析或处置对象,不能因待办列表存在
|
||||
而获得订单复核、库存准备或通知完成入口。
|
||||
"""
|
||||
candidate = (
|
||||
db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||||
if case.candidate_id is not None
|
||||
else None
|
||||
)
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
if not is_current_reviewable_candidate(candidate):
|
||||
return []
|
||||
from app.services.shipping_notice.lifecycle_projection import lifecycle_entries
|
||||
|
||||
return lifecycle_entries(lifecycle_stage='order_review', has_candidate_context=True)
|
||||
|
||||
|
||||
class TaskProjection(str, Enum):
|
||||
"""任务读模型投影:Tool / 工作台列表 / 工作台详情。"""
|
||||
|
||||
@@ -1318,6 +1339,7 @@ def serialize_review_case_todo(
|
||||
del is_admin
|
||||
run = db.session.get(ShippingOrderProcessingRun, case.run_id) if case.run_id else None
|
||||
document = db.session.get(ShippingOrderDocument, case.document_id) if case.document_id else None
|
||||
lifecycle_entries = _review_case_lifecycle_entries(case)
|
||||
source_name = None
|
||||
if document is not None:
|
||||
source_name = str(getattr(document, "filename", None) or "").strip() or None
|
||||
@@ -1376,6 +1398,10 @@ def serialize_review_case_todo(
|
||||
"created_at": case.created_at.isoformat() if case.created_at else None,
|
||||
"ui_state": {
|
||||
"stage": {"code": "order_review", "label": "订单复核", "index": 2, "total": 4},
|
||||
# [AUTHORITY] 任务中心、批次中心和工作台均消费该入口;禁止前端按 Case
|
||||
# 状态或待办类别补造订单复核权限。
|
||||
"lifecycle_stage": "order_review" if lifecycle_entries else None,
|
||||
"lifecycle_entries": lifecycle_entries,
|
||||
"checkpoint": {"code": "order_review", "kind": str(CheckpointKind.MUST_HUMAN), "label": "订单复核"},
|
||||
"todo": {"title": current_todo, "message": current_todo},
|
||||
"actions": {"primary": ({"code": action_buttons[0], "label": "重试自动建单", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if action_buttons else None), "secondary": []},
|
||||
@@ -1539,6 +1565,9 @@ def serialize_intake_todo(
|
||||
"created_at": intake.created_at.isoformat() if intake.created_at else None,
|
||||
"ui_state": {
|
||||
"stage": {"code": "intake_parse", "label": "接收解析", "index": 1, "total": 4},
|
||||
# Intake 尚未有当前有效订单 Candidate;只能进入对话查看解析,不能进入生命周期工作台。
|
||||
"lifecycle_stage": "intake_parse",
|
||||
"lifecycle_entries": [],
|
||||
"checkpoint": {"code": "order_field_extraction", "kind": str(
|
||||
CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE
|
||||
), "label": "订单解析"},
|
||||
|
||||
@@ -224,7 +224,9 @@ def claim_next_shipping_notice_job() -> Job | None:
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
JobType.SHIPPING_DOCUMENT_LAYOUT,
|
||||
JobType.SHIPPING_PROCESS_GATE,
|
||||
JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS,
|
||||
JobType.SHIPPING_AUTO_PROGRESS,
|
||||
JobType.SHIPPING_PDF_AUTOMARK,
|
||||
JobType.SHIPPING_XFA_OCR_AUTOMARK,
|
||||
JobType.SHIPPING_STP_AUTO_CREATE,
|
||||
JobType.SHIPPING_LINE_AUTO_FULFILL,
|
||||
|
||||
@@ -39,6 +39,7 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Literal, TypedDict
|
||||
|
||||
from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingOrderReviewCase,
|
||||
User,
|
||||
)
|
||||
@@ -85,7 +86,7 @@ REVIEW_DOMAIN_ACTION_CODES: frozenset[str] = frozenset({
|
||||
'create_draft', 'edit_draft', 'validate',
|
||||
'retry_stp_auto_create',
|
||||
'reconcile_and_progress',
|
||||
'adjudicate_duplicate',
|
||||
'resolve_field_conflicts', 'adjudicate_duplicate',
|
||||
'create_revision', 'force_create', 'reuse_existing', 'adjudicate',
|
||||
'open_order_review', 'open_profile_review',
|
||||
'mark_non_order', 'mark_quality_issue', 'reparse',
|
||||
@@ -404,9 +405,11 @@ def project_case_allowed_actions(
|
||||
return actions
|
||||
if case.status == 'reparse_pending':
|
||||
return ['view']
|
||||
# 替代 PDF 的写入资格由 disposition service 的 Case 状态裁决,独立于
|
||||
# mark_quality_issue;统一投影必须下发独立动作,供各页面一致消费。
|
||||
if case.status == 'quality_issue':
|
||||
return ['view', 'mark_quality_issue', 'reparse']
|
||||
actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'validate']
|
||||
return ['view', 'mark_quality_issue', 'reparse', 'upload_replacement']
|
||||
actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'upload_replacement', 'validate']
|
||||
if case.candidate_id is None and case.disposition != 'manual_order':
|
||||
actions.append('create_draft')
|
||||
else:
|
||||
@@ -555,6 +558,103 @@ def project_case_current_gate(
|
||||
)
|
||||
|
||||
|
||||
def _project_case_formal_gate_summary(
|
||||
case: ShippingOrderReviewCase,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
读取 Case 绑定的正式 ProcessExecution 用户态摘要。
|
||||
|
||||
Case 草稿、STP Job 仅描述复核上下文;当前业务阶段、人工阻断与恢复动作
|
||||
必须由 ProcessExecution Gate 裁决。本函数让所有 Case bundle 消费方使用
|
||||
与批次中心完全相同的正式 Gate 读模型,而不是在各投影端重建状态。
|
||||
"""
|
||||
case_id = getattr(case, 'id', None)
|
||||
if case_id is None:
|
||||
return None
|
||||
from flask import has_app_context
|
||||
|
||||
if not has_app_context():
|
||||
# 纯投影契约测试与离线诊断没有 Flask application context;此时没有可读
|
||||
# 的持久化 Execution,保持原有 Case 派生事实即可。
|
||||
return None
|
||||
execution = (
|
||||
ShippingProcessExecution.query.filter_by(review_case_id=int(case_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
summary = project_user_gate_summary(execution)
|
||||
current = summary.get('current_blocking_gate') or summary.get('current_gate')
|
||||
return summary if isinstance(current, dict) and current.get('gate_code') else None
|
||||
|
||||
|
||||
def _project_case_formal_gate_facts(
|
||||
summary: dict[str, Any] | None,
|
||||
) -> tuple[CurrentGate, BlockingReason, UserStatus] | None:
|
||||
"""
|
||||
将正式 Gate 摘要归一化为 Case bundle 的三项用户事实。
|
||||
|
||||
正式 Execution 存在时,Gate 事实必须覆盖 Case 的历史阻断:
|
||||
只有已入队/运行或等待外部回执才表示系统正在推进;建单前的订单冻结
|
||||
校验仍需用户从编辑区提交,不能因 ``pending`` 误显示为系统处理中。
|
||||
"""
|
||||
if not isinstance(summary, dict):
|
||||
return None
|
||||
current = summary.get('current_blocking_gate') or summary.get('current_gate')
|
||||
if not isinstance(current, dict):
|
||||
return None
|
||||
gate_code = str(current.get('gate_code') or '').strip()
|
||||
if not gate_code:
|
||||
return None
|
||||
gate_status = str(current.get('status') or '').strip().lower()
|
||||
reason_code = str(
|
||||
summary.get('blocking_reason_code')
|
||||
or current.get('blocking_reason_code')
|
||||
or ''
|
||||
).strip() or None
|
||||
raw_details = (
|
||||
(summary.get('explainability') or {}).get('details')
|
||||
if isinstance(summary.get('explainability'), dict)
|
||||
else None
|
||||
)
|
||||
details = raw_details if isinstance(raw_details, dict) else None
|
||||
blocking_reason = BlockingReason(
|
||||
code=reason_code,
|
||||
i18n_key=_REASON_TO_I18N_KEY.get(reason_code, 'shipping.review.blocked_generic') if reason_code else None,
|
||||
details=details,
|
||||
)
|
||||
current_gate = CurrentGate(
|
||||
gate_code=gate_code,
|
||||
next_action_code=(
|
||||
str(summary.get('next_action_code') or current.get('next_action_code') or '').strip()
|
||||
or None
|
||||
),
|
||||
blocking_reason_code=reason_code,
|
||||
)
|
||||
if gate_code == 'order_freeze_readiness' and gate_status == 'pending':
|
||||
# 保存并校验是订单编辑区底栏唯一提交入口;这里仅输出交接状态,
|
||||
# 不创建右栏 CTA,也不把尚未提交的校验伪装为已开始的自动任务。
|
||||
blocking_reason = BlockingReason(code=None, i18n_key=None, details=None)
|
||||
user_status: UserStatus = 'waiting_human'
|
||||
elif gate_status in {'pending', 'queued', 'running', 'waiting_external'}:
|
||||
# 没有人工阻断时仅投影系统推进态;下一步文案由前端状态映射给出。
|
||||
blocking_reason = BlockingReason(code=None, i18n_key=None, details=None)
|
||||
user_status: UserStatus = 'running'
|
||||
elif gate_status == 'blocked_manual':
|
||||
user_status: UserStatus = 'waiting_human'
|
||||
elif gate_status in {'blocked_retryable', 'invalidated'}:
|
||||
user_status = 'retryable'
|
||||
elif gate_status == 'failed_terminal':
|
||||
user_status = 'failed'
|
||||
else:
|
||||
return None
|
||||
return current_gate, blocking_reason, user_status
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [4] blocking_reason(code/i18n_key/details)
|
||||
# ============================================================
|
||||
@@ -711,31 +811,25 @@ def project_case_primary_action(
|
||||
return {'code': 'open_order_review', 'variant': 'warning',
|
||||
'label_key': 'shipping.actions.open_order_review'}
|
||||
|
||||
# 1f: waiting_human → edit_draft / validate
|
||||
# 1f: 草稿编辑和保存校验分别属于主编辑区与底栏,不得升级为当前任务 CTA。
|
||||
if user_status == 'waiting_human':
|
||||
if 'edit_draft' in actions:
|
||||
return {'code': 'edit_draft', 'variant': 'primary',
|
||||
'label_key': 'shipping.actions.edit_draft'}
|
||||
if 'validate' in actions:
|
||||
return {'code': 'validate', 'variant': 'primary',
|
||||
'label_key': 'shipping.actions.validate'}
|
||||
return None
|
||||
|
||||
# 1g: idle → 有 create_draft 优先(首次打开草稿面板 CTA)
|
||||
if user_status == 'idle':
|
||||
if 'create_draft' in actions:
|
||||
return {'code': 'create_draft', 'variant': 'primary',
|
||||
'label_key': 'shipping.actions.create_draft'}
|
||||
return None
|
||||
if 'edit_draft' in actions:
|
||||
return {'code': 'edit_draft', 'variant': 'primary',
|
||||
'label_key': 'shipping.actions.edit_draft'}
|
||||
return None
|
||||
|
||||
# 1h: running/queued → 次优先 view(但 edit_draft 仍然允许)
|
||||
if user_status == 'running' and 'edit_draft' in actions:
|
||||
return {'code': 'edit_draft', 'variant': 'default',
|
||||
'label_key': 'shipping.actions.edit_draft'}
|
||||
return None
|
||||
|
||||
# 1i: 兜底 — 按 _PRIMARY_ACTION_ORDER 优先级取第一个命中的动作码
|
||||
for code in _PRIMARY_ACTION_ORDER:
|
||||
if code in {'edit_draft', 'create_draft', 'validate'}:
|
||||
continue
|
||||
if code in actions:
|
||||
variant = 'default'
|
||||
if code in ('reconcile_and_progress', 'create_draft', 'retry_stp_auto_create'):
|
||||
@@ -1067,6 +1161,14 @@ def project_review_case_projection_bundle(
|
||||
blocking_reason = project_case_blocking_reason(automation)
|
||||
# [STEP 5] user_status
|
||||
user_status = project_case_user_status(case, automation)
|
||||
# [STEP 5.1] 已持久化的正式 Gate 是实时状态唯一裁决源。此前这里用 Case
|
||||
# 草稿状态重算 order_review_build/idle,会覆盖批次投影已读取的
|
||||
# field_completeness / required_field_missing,造成同一文件前后端状态冲突。
|
||||
formal_gate_facts = _project_case_formal_gate_facts(
|
||||
_project_case_formal_gate_summary(case),
|
||||
)
|
||||
if formal_gate_facts is not None:
|
||||
current_gate, blocking_reason, user_status = formal_gate_facts
|
||||
# [STEP 6] primary_action
|
||||
# 建单前 STP 已失败时,主操作的阶段必须随失败事实停在 pre_ot_stp;
|
||||
# 不能因 Case 仍为 ready 回退到 customer_resolution/order_review 的展示语义。
|
||||
|
||||
@@ -786,6 +786,19 @@ def reconcile_and_progress(
|
||||
# 用 case_after 替换引用,防止后续审计写入已失效对象。
|
||||
case = case_after
|
||||
user = db.session.get(User, int(user_id))
|
||||
# 归属 L3 歧义不是可继续处理的业务结果:调用方若收到普通 200 outcome,
|
||||
# 仍可能继续执行后续复用/推进。回滚与敏感审计完成后必须硬隔离,要求
|
||||
# 用户回到人工裁决面,而不是把不确定归属投影成可操作阶段。
|
||||
raise ValidationError(
|
||||
'Ambiguous task ownership requires manual adjudication',
|
||||
code='SHIPPING.RECONCILE_OWNERSHIP_ANOMALY',
|
||||
details={
|
||||
'hard_isolation': True,
|
||||
'case_no': str(case_after.case_no),
|
||||
'match': match_result,
|
||||
'user_action': user_action,
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP 5] 写审计 + 幂等持久化(CaseEvent 保证下一次同 operation_id 可回返)
|
||||
_write_reconcile_audit_and_event(
|
||||
|
||||
@@ -47,6 +47,11 @@ from app.services.shipping_notice.processing_projection_invariants import (
|
||||
from app.services.shipping_notice.processing_ownership import (
|
||||
record_projection_inconsistency_audit,
|
||||
)
|
||||
from app.services.shipping_notice.lifecycle_projection import (
|
||||
LIFECYCLE_STAGE_RANGES,
|
||||
project_lifecycle,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import resolve_task_export_download
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
DIRECT_PDF_ALLOWED_STAGES,
|
||||
ORDER_INTAKE_SOURCE_TYPES,
|
||||
@@ -441,7 +446,11 @@ def _intake_source_summary(
|
||||
|
||||
candidate_count = (
|
||||
db.session.query(ShippingOrderCandidate.id)
|
||||
.filter(ShippingOrderCandidate.intake_id == int(intake.id))
|
||||
.filter(
|
||||
ShippingOrderCandidate.intake_id == int(intake.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')),
|
||||
)
|
||||
.count()
|
||||
)
|
||||
subject = str(email.get('subject') or '').strip() or None
|
||||
@@ -629,11 +638,37 @@ def project_intake_work_item(
|
||||
}),
|
||||
'upload_states': sorted(set(upload_states)),
|
||||
}
|
||||
payload['user_group'] = (
|
||||
'failed' if status in {'failed', 'blocked'}
|
||||
else 'waiting_human' if status in {'waiting_human', 'waiting_review'}
|
||||
else 'processing'
|
||||
)
|
||||
# EML 根卡只汇总子文件的正式裁决;不能保留 Intake 的旧解析阶段,
|
||||
# 否则候选已落为 Review Case 仍会被父卡投影成“接收解析中”。
|
||||
if aggregate_states:
|
||||
if any(state in {'failed', 'retryable'} for state in aggregate_states):
|
||||
payload['user_status'] = 'failed'
|
||||
payload['user_group'] = 'failed'
|
||||
elif any(state in {'waiting_human', 'idle'} for state in aggregate_states):
|
||||
payload['user_status'] = 'waiting_human'
|
||||
payload['user_group'] = 'waiting_human'
|
||||
elif all(state == 'completed' for state in aggregate_states):
|
||||
payload['user_status'] = 'completed'
|
||||
payload['user_group'] = 'completed'
|
||||
else:
|
||||
payload['user_status'] = 'running'
|
||||
payload['user_group'] = 'processing'
|
||||
representative = next(
|
||||
(child for child in aggregate_children if str(child.get('user_status') or '') in {'failed', 'retryable', 'waiting_human', 'idle'}),
|
||||
aggregate_children[0],
|
||||
)
|
||||
payload['user_stage'] = str(representative.get('user_stage') or representative.get('stage') or payload.get('user_stage') or '')
|
||||
payload['stage'] = payload['user_stage']
|
||||
payload['current_gate'] = representative.get('current_gate')
|
||||
payload['blocking_reason'] = representative.get('blocking_reason')
|
||||
payload['primary_action'] = representative.get('primary_action')
|
||||
payload['available_actions'] = list(representative.get('available_actions') or [])
|
||||
if not (source_type == 'eml' and payload.get('aggregate_children')):
|
||||
payload['user_group'] = (
|
||||
'failed' if status in {'failed', 'blocked'}
|
||||
else 'waiting_human' if status in {'waiting_human', 'waiting_review'}
|
||||
else 'processing'
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
@@ -818,17 +853,28 @@ def _order_task_source_summary(
|
||||
"""
|
||||
run_candidate_count = (
|
||||
db.session.query(ShippingOrderCandidate.id)
|
||||
.filter(ShippingOrderCandidate.order_extraction_run_id == int(run.id))
|
||||
.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')),
|
||||
)
|
||||
.count()
|
||||
)
|
||||
candidate: ShippingOrderCandidate | None = None
|
||||
if order_task is not None and order_task.candidate_id:
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(order_task.candidate_id))
|
||||
if candidate is None:
|
||||
# 已替代 Candidate 仅供审计。旧 OT 不得借同 Run 的新候选重新获得另一 PDF
|
||||
# 的生命周期上下文或按钮。
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
if not is_current_reviewable_candidate(candidate):
|
||||
candidate = None
|
||||
if candidate is None and (order_task is None or not order_task.candidate_id):
|
||||
candidate = (
|
||||
ShippingOrderCandidate.query.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')),
|
||||
)
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.first()
|
||||
@@ -870,6 +916,7 @@ def _order_task_source_summary(
|
||||
parsed_document_count = 1 if str(task_document.parse_status or '') == 'parsed' else 0
|
||||
candidate_count = 1
|
||||
document_id = int(task_document.id)
|
||||
content_hash = str(task_document.content_hash or '').strip().lower() or None
|
||||
else:
|
||||
parsed_document_count = 0
|
||||
if intake_ids:
|
||||
@@ -883,13 +930,17 @@ def _order_task_source_summary(
|
||||
.count()
|
||||
)
|
||||
task_document_count = int(document_count)
|
||||
candidate_count = int(run_candidate_count)
|
||||
# OT 已绑定但 Candidate 已被替代时,不能把同 Run 的当前候选借给它。
|
||||
# 该 OT 只保留历史审计信息;生命周期入口必须关闭。
|
||||
candidate_count = 0 if (order_task is not None and order_task.candidate_id) else int(run_candidate_count)
|
||||
document_id = None
|
||||
content_hash = None
|
||||
|
||||
return {
|
||||
'email_subject': None,
|
||||
'filename': filename,
|
||||
'document_id': document_id,
|
||||
'content_hash': content_hash,
|
||||
'document_count': task_document_count,
|
||||
'parsed_document_count': int(parsed_document_count),
|
||||
'candidate_count': int(candidate_count),
|
||||
@@ -928,29 +979,31 @@ def _order_task_current_gate(
|
||||
Returns:
|
||||
ProcessGateSummary 形状 dict;无需门禁时 None。
|
||||
"""
|
||||
# Child OT 必须先按自身 Candidate 找 Case;仅按 run_id 取最新 Case 会把
|
||||
# 多 PDF 的子订单阶段错误绑定到根 PDF。
|
||||
# 每个已绑定 Candidate 的 OT(包括根 OT)都必须先按自身 Candidate 找 Case;
|
||||
# 仅按 run_id 取最新 Case 会把多 PDF 或已替代根 OT 的阶段错误绑定到另一份 PDF。
|
||||
# 只有尚未绑定 Candidate 的兼容 OT 才能按 Run 回退查找。
|
||||
open_case = None
|
||||
is_child_order_task = bool(
|
||||
order_task is not None
|
||||
and getattr(order_task, 'candidate_id', None)
|
||||
and str(getattr(order_task, 'task_no', '') or '').strip()
|
||||
!= str(getattr(run, 'user_task_no', '') or '').strip()
|
||||
)
|
||||
if is_child_order_task:
|
||||
if order_task is not None and getattr(order_task, 'candidate_id', None):
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.query.join(
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCandidate.id == ShippingOrderReviewCase.candidate_id,
|
||||
).filter(
|
||||
ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_case is None:
|
||||
if open_case is None and not (
|
||||
order_task is not None and getattr(order_task, 'candidate_id', None)
|
||||
):
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.candidate_id.isnot(None),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
@@ -965,6 +1018,7 @@ def _order_task_current_gate(
|
||||
|
||||
execution = (
|
||||
ShippingProcessExecution.query.filter_by(review_case_id=int(open_case.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -1007,7 +1061,10 @@ def _order_task_current_gate(
|
||||
active_execution_id = getattr(notice, 'active_process_execution_id', None)
|
||||
if active_execution_id is not None:
|
||||
execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
|
||||
if execution is not None and int(getattr(execution, 'task_id', 0) or 0) != int(notice.id):
|
||||
if execution is not None and (
|
||||
int(getattr(execution, 'task_id', 0) or 0) != int(notice.id)
|
||||
or str(getattr(execution, 'status', '') or '').strip().lower() == 'superseded'
|
||||
):
|
||||
execution = None
|
||||
if execution is None:
|
||||
execution = (
|
||||
@@ -1196,7 +1253,8 @@ def _project_order_task_work_item(
|
||||
from app.models import ShippingProcessExecution
|
||||
active_execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
|
||||
active_gate = str(getattr(active_execution, 'current_gate_code', '') or '').strip().lower()
|
||||
if active_gate in SHIPPING_PROCESSING_STAGES:
|
||||
active_status = str(getattr(active_execution, 'status', '') or '').strip().lower()
|
||||
if active_status != 'superseded' and active_gate in SHIPPING_PROCESSING_STAGES:
|
||||
stage = active_gate
|
||||
stage_label_key = active_gate
|
||||
# order_creating 无共享投影时仍统一用户文案键。
|
||||
@@ -1262,18 +1320,27 @@ def _project_order_task_work_item(
|
||||
open_case = None
|
||||
if order_task is not None and getattr(order_task, 'candidate_id', None):
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.query.join(
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCandidate.id == ShippingOrderReviewCase.candidate_id,
|
||||
).filter(
|
||||
ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_case is None:
|
||||
# 已绑定 Candidate 的 OT 不得借同 Run 的另一 Case 补阶段;这会使历史根 OT
|
||||
# 重新获得当前 PDF 的 Gate、生命周期入口和操作权限。
|
||||
if open_case is None and not (
|
||||
order_task is not None and getattr(order_task, 'candidate_id', None)
|
||||
):
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.candidate_id.isnot(None),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
@@ -1394,20 +1461,39 @@ def _project_order_task_work_item(
|
||||
child['stage'] = 'order_creating'
|
||||
child['stage_label_key'] = 'order_creating'
|
||||
child['legacy_stage'] = 'order_creating'
|
||||
formal_gate_projection = isinstance(payload.get('current_gate'), dict) and bool(
|
||||
str((payload.get('current_gate') or {}).get('gate_code') or '').strip()
|
||||
)
|
||||
# 六字段覆盖:user_status / blocking_reason / primary_action / current_gate / available_actions / retryable
|
||||
if isinstance(bundle.get('user_status'), str):
|
||||
payload['user_status'] = bundle['user_status']
|
||||
if isinstance(bundle.get('blocking_reason'), dict):
|
||||
payload['blocking_reason'] = dict(bundle['blocking_reason'])
|
||||
if isinstance(bundle.get('primary_action'), dict) and (pre_ot_stp or not formal_gate_projection):
|
||||
payload['primary_action'] = dict(bundle['primary_action'])
|
||||
if isinstance(bundle.get('current_gate'), dict) and (pre_ot_stp or not formal_gate_projection):
|
||||
current_gate = dict(payload.get('current_gate') or {})
|
||||
current_gate.update(bundle['current_gate'])
|
||||
payload['current_gate'] = current_gate
|
||||
if isinstance(bundle.get('user_stage'), str):
|
||||
# 未确认 Case 的正式阶段只能由 Review bundle 给出;旧 OT.stage
|
||||
# 仍可能是 document_parsing/customer_resolving,不能在读路径回退阶段。
|
||||
payload['user_stage'] = bundle['user_stage']
|
||||
if isinstance(bundle.get('user_current_gate_code'), str):
|
||||
payload['user_current_gate_code'] = bundle['user_current_gate_code']
|
||||
# Case bundle 必须能够显式清空旧阻断,不能仅在有新 reason 时覆盖;
|
||||
# 否则字段冲突已裁决后,右栏仍会显示“字段存在冲突”。
|
||||
bundle_blocking_reason = bundle.get('blocking_reason')
|
||||
payload['blocking_reason'] = (
|
||||
dict(bundle_blocking_reason)
|
||||
if isinstance(bundle_blocking_reason, dict)
|
||||
else None
|
||||
)
|
||||
# 未确认 Review Case 是建单前用户动作的唯一事实源。即使旧 OT 留有正式 Gate,
|
||||
# 也必须用最新 bundle 显式覆盖(包括 None),否则已解决字段冲突仍会显示旧裁决按钮。
|
||||
bundle_primary_action = bundle.get('primary_action')
|
||||
payload['primary_action'] = (
|
||||
dict(bundle_primary_action)
|
||||
if isinstance(bundle_primary_action, dict)
|
||||
else None
|
||||
)
|
||||
# 同一 Case 的 Gate 也是完整展示事实;禁止与 OT 历史 Gate 合并,
|
||||
# 以免残留 field_conflict_resolution / resolve_field_conflicts。
|
||||
bundle_current_gate = bundle.get('current_gate')
|
||||
payload['current_gate'] = (
|
||||
dict(bundle_current_gate)
|
||||
if isinstance(bundle_current_gate, dict)
|
||||
else None
|
||||
)
|
||||
if isinstance(bundle.get('available_actions'), list):
|
||||
old_actions = list(payload.get('available_actions') or [])
|
||||
keep_notice_side = [a for a in old_actions if a not in REVIEW_DOMAIN_ACTION_CODES]
|
||||
@@ -1679,7 +1765,7 @@ def _eml_aggregate_user_group(
|
||||
"""按用户关注优先级确定一张 EML Intake 卡的唯一分组。"""
|
||||
if any(state in {'failed', 'retryable'} for state in states):
|
||||
return 'failed'
|
||||
if any(state == 'waiting_human' for state in states):
|
||||
if any(state in {'waiting_human', 'idle'} for state in states):
|
||||
return 'waiting_human'
|
||||
if any(state not in {'completed', 'cancelled'} for state in states):
|
||||
return 'processing'
|
||||
@@ -1717,7 +1803,7 @@ def _eml_aggregate_document_children(
|
||||
"""
|
||||
if intake is None:
|
||||
return [
|
||||
{**child, 'ui_state': _processing_ui_state_from_item(child)}
|
||||
_with_processing_ui_state(child)
|
||||
for child in order_task_children
|
||||
]
|
||||
|
||||
@@ -1731,7 +1817,7 @@ def _eml_aggregate_document_children(
|
||||
)
|
||||
if not documents:
|
||||
return [
|
||||
{**child, 'ui_state': _processing_ui_state_from_item(child)}
|
||||
_with_processing_ui_state(child)
|
||||
for child in order_task_children
|
||||
]
|
||||
|
||||
@@ -1764,10 +1850,60 @@ def _eml_aggregate_document_children(
|
||||
str(unit.reason_code or unit.error_code or 'unit_review_required').strip()
|
||||
if review_required and unit is not None else None
|
||||
)
|
||||
# Case 是候选落库后的正式人工阶段事实;Unit 保留 candidate_ready 不能让
|
||||
# EML 聚合退回「接收解析」。终态 Case 不再提供复核入口。
|
||||
review_case = (
|
||||
ShippingOrderReviewCase.query.filter_by(unit_id=int(unit.id)).one_or_none()
|
||||
if review_required and unit is not None else None
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.unit_id == int(unit.id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready', 'confirming')),
|
||||
).one_or_none()
|
||||
if unit is not None else None
|
||||
)
|
||||
review_required = review_required or review_case is not None
|
||||
review_bundle: dict[str, Any] | None = None
|
||||
if review_case is not None:
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
draft = getattr(review_case, 'current_draft', None)
|
||||
validation = (
|
||||
dict(draft.validation_result_json or {})
|
||||
if draft is not None and isinstance(draft.validation_result_json, dict)
|
||||
else None
|
||||
)
|
||||
review_bundle = project_review_case_projection_bundle(
|
||||
review_case, validation=validation, post_confirm=None, is_admin=False,
|
||||
)
|
||||
# Case 只是人工处置容器,不等于已生成订单候选。空 Candidate Case 必须
|
||||
# 保留解析链路的 Gate/阶段,禁止从 Review Bundle 继承旧的订单复核事实。
|
||||
review_candidate = (
|
||||
db.session.get(ShippingOrderCandidate, int(review_case.candidate_id))
|
||||
if review_case is not None and review_case.candidate_id is not None
|
||||
else None
|
||||
)
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
has_current_candidate = bool(
|
||||
is_current_reviewable_candidate(review_candidate)
|
||||
and int(getattr(review_candidate, 'primary_document_id', 0) or 0) == int(document.id)
|
||||
)
|
||||
review_status = str((review_bundle or {}).get('user_status') or 'waiting_human')
|
||||
review_stage = str((review_bundle or {}).get('user_stage') or 'order_review')
|
||||
review_gate = (review_bundle or {}).get('current_gate')
|
||||
review_reason = (review_bundle or {}).get('blocking_reason')
|
||||
review_primary = (review_bundle or {}).get('primary_action')
|
||||
review_actions = list((review_bundle or {}).get('available_actions') or [])
|
||||
if review_case is not None and not has_current_candidate:
|
||||
review_stage = 'intake_parse'
|
||||
review_gate = _intake_current_gate(intake)
|
||||
review_reason = None
|
||||
review_primary = {
|
||||
'code': 'open_order_review',
|
||||
'variant': 'primary',
|
||||
'label_key': 'shipping.actions.open_order_review',
|
||||
}
|
||||
review_actions = ['open_order_review']
|
||||
run = db.session.get(ShippingOrderProcessingRun, int(review_case.run_id)) if review_case is not None else None
|
||||
leaf = {
|
||||
'work_item_type': 'document',
|
||||
@@ -1784,35 +1920,66 @@ def _eml_aggregate_document_children(
|
||||
'submission_no': '',
|
||||
'intake_no': str(intake.intake_no),
|
||||
'status': 'failed' if (failed or unit_failed) else 'waiting_review' if review_required else 'processing',
|
||||
'stage': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
|
||||
'stage_label_key': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
|
||||
'stage': 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
|
||||
'stage_label_key': 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
|
||||
'progress_version': int(getattr(intake, 'progress_version', None) or 1),
|
||||
'last_activity_at': _iso(document.updated_at) or _iso(intake.updated_at) or '',
|
||||
'current_gate': None,
|
||||
'available_actions': ['open_order_review'] if review_case is not None else [],
|
||||
'current_gate': review_gate if review_case is not None else None,
|
||||
'available_actions': review_actions if review_case is not None else [],
|
||||
'blocking_reason': (
|
||||
{'code': failure_reason_code, 'details': {}}
|
||||
if unit_failed else
|
||||
{'code': review_reason_code, 'details': {}}
|
||||
if review_required else None
|
||||
review_reason if review_case is not None else
|
||||
{'code': review_reason_code, 'details': {}} if review_required else None
|
||||
),
|
||||
'primary_action': {'code': 'open_order_review'} if review_case is not None else None,
|
||||
'user_status': 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'running',
|
||||
'user_stage': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
|
||||
'primary_action': review_primary if review_case is not None else None,
|
||||
'user_status': 'failed' if (failed or unit_failed) else review_status if review_case is not None else 'waiting_human' if review_required else 'running',
|
||||
'user_stage': 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
|
||||
'user_group': 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'processing',
|
||||
'facts': {'upload_state': 'not_created'},
|
||||
# 与 Case summary 同义:无 Candidate 的解析处置可进入独立接收解析面,
|
||||
# 但 lifecycle_entries 仍保持空,绝不能视为订单生命周期授权。
|
||||
'intake_parse_authorized': bool(review_case is not None and not has_current_candidate),
|
||||
'child_order_tasks': [],
|
||||
}
|
||||
summary = {}
|
||||
summary.update({
|
||||
'document_id': int(document.id),
|
||||
# 跨 Run 重识别可能产生新 document_id;内容哈希是批次统计的稳定文件身份。
|
||||
'content_hash': str(document.content_hash or '').strip().lower() or None,
|
||||
'filename': str(document.filename or '').strip() or None,
|
||||
'document_count': 1,
|
||||
'parsed_document_count': 1 if str(document.parse_status or '').strip().lower() == 'parsed' else 0,
|
||||
})
|
||||
# [AUTHORITY] EML 建单前叶子没有 OT 摘要可回填 Candidate。只有 Review Case
|
||||
# 关联的当前有效 Candidate,且其主文档就是本 PDF,才能开放生命周期入口;
|
||||
# 同一邮件的兄弟附件绝不能借此获得订单复核权限。
|
||||
if existing is None:
|
||||
summary['candidate_count'] = int(
|
||||
has_current_candidate
|
||||
)
|
||||
leaf['source_summary'] = summary
|
||||
leaf['ui_state'] = _processing_ui_state_from_item(leaf)
|
||||
result.append(leaf)
|
||||
# 有/无预建 OT 的 EML 附件都在这里汇合。批次中心的文件级主动作只能
|
||||
# 是生命周期入口;create/edit/validate 是 Case 内部处置,必须在工作台内
|
||||
# 呈现。只保留正式 Process Gate 的主动作;Case 内部码(例如
|
||||
# order_review_build)即使带 next_action 也不能夺走批次入口。
|
||||
leaf_case_no = str(leaf.get('case_no') or '').strip()
|
||||
leaf_gate = leaf.get('current_gate') if isinstance(leaf.get('current_gate'), dict) else {}
|
||||
leaf_primary = leaf.get('primary_action') if isinstance(leaf.get('primary_action'), dict) else {}
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE_SET
|
||||
|
||||
has_formal_gate = str(leaf_gate.get('gate_code') or '').strip() in PROCESS_GATE_CODE_SET
|
||||
if (
|
||||
leaf_case_no
|
||||
and not has_formal_gate
|
||||
and str(leaf_primary.get('code') or '').strip() in {'create_draft', 'edit_draft', 'validate'}
|
||||
):
|
||||
leaf['primary_action'] = {
|
||||
'code': 'open_order_review',
|
||||
'variant': 'primary',
|
||||
'label_key': 'shipping.actions.open_order_review',
|
||||
}
|
||||
result.append(_with_processing_ui_state(leaf))
|
||||
return result
|
||||
|
||||
|
||||
@@ -1870,7 +2037,7 @@ def _aggregate_eml_order_task_work_items(
|
||||
states = [_state(item) for item in aggregate_children]
|
||||
upload_states = [_upload_state(item) for item in aggregate_children]
|
||||
failed_count = sum(state in {'failed', 'retryable'} for state in states)
|
||||
waiting_count = sum(state == 'waiting_human' for state in states)
|
||||
waiting_count = sum(state in {'waiting_human', 'idle'} for state in states)
|
||||
# 用户视角的完成必须同时满足任务完成和货代上传成功;候选已生成等中间态仍在处理中。
|
||||
completed_count = sum(
|
||||
state == 'completed' and upload_state == 'succeeded'
|
||||
@@ -1895,7 +2062,7 @@ def _aggregate_eml_order_task_work_items(
|
||||
'order_creating'
|
||||
if str(item.get('user_stage') or '').strip().lower() == 'pre_ot_stp'
|
||||
else str(item.get('user_stage') or item.get('stage') or '').strip()
|
||||
for item in children
|
||||
for item in aggregate_children
|
||||
if _state(item) != 'completed' or _upload_state(item) != 'succeeded'
|
||||
),
|
||||
'completed',
|
||||
@@ -1939,11 +2106,11 @@ def _aggregate_eml_order_task_work_items(
|
||||
# 待人工按钮”的矛盾组合。
|
||||
actionable_states = (
|
||||
{'failed', 'retryable'} if aggregate_group == 'failed'
|
||||
else {'waiting_human'} if aggregate_group == 'waiting_human'
|
||||
else {'waiting_human', 'idle'} if aggregate_group == 'waiting_human'
|
||||
else set()
|
||||
)
|
||||
actionable_child = next(
|
||||
(item for item in children if _state(item) in actionable_states),
|
||||
(item for item in aggregate_children if _state(item) in actionable_states),
|
||||
None,
|
||||
)
|
||||
if actionable_child is not None:
|
||||
@@ -1978,7 +2145,7 @@ def _aggregate_eml_order_task_work_items(
|
||||
'stages': sorted(summary_stages),
|
||||
'reason_codes': sorted({
|
||||
str(code).strip()
|
||||
for item in children
|
||||
for item in aggregate_children
|
||||
for code in (
|
||||
(item.get('blocking_reason') or {}).get('code')
|
||||
if isinstance(item.get('blocking_reason'), dict) else None,
|
||||
@@ -2179,16 +2346,52 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
primary_raw = item.get('primary_action')
|
||||
primary = dict(primary_raw) if isinstance(primary_raw, dict) else None
|
||||
source_summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
|
||||
lifecycle = project_lifecycle(
|
||||
current_gate=(
|
||||
item.get('current_gate')
|
||||
if isinstance(item.get('current_gate'), dict)
|
||||
else {'gate_code': item.get('user_current_gate_code')}
|
||||
),
|
||||
blocking_reason=item.get('blocking_reason') if isinstance(item.get('blocking_reason'), dict) else None,
|
||||
legacy_stage=str(item.get('user_stage') or item.get('stage') or ''),
|
||||
# root_order_task_no 只是导航身份;必须有当前 Candidate 或正式通知事实才开放入口。
|
||||
has_candidate_context=bool(
|
||||
int(source_summary.get('candidate_count') or 0) > 0
|
||||
or item.get('has_formal_ot')
|
||||
or item.get('shipping_notice_no')
|
||||
),
|
||||
)
|
||||
lifecycle_stage = lifecycle['lifecycle_stage']
|
||||
if primary is not None:
|
||||
action_target = _action_lifecycle_target(primary.get('code'), lifecycle_stage=lifecycle_stage)
|
||||
if action_target is not None:
|
||||
primary['execution_mode'] = 'navigate'
|
||||
primary['target_surface'] = 'order_lifecycle_workbench'
|
||||
primary['target_lifecycle_stage'] = action_target
|
||||
primary_code = str((primary or {}).get('code') or '').strip()
|
||||
secondary: list[dict[str, Any]] = []
|
||||
for raw_code in item.get('available_actions') or []:
|
||||
code = str(raw_code or '').strip()
|
||||
if not code or code == primary_code:
|
||||
continue
|
||||
secondary.append({'code': code, 'enabled': True})
|
||||
action_target = _action_lifecycle_target(code, lifecycle_stage=lifecycle_stage)
|
||||
action = {'code': code, 'enabled': True}
|
||||
if action_target is not None:
|
||||
action.update({
|
||||
'execution_mode': 'navigate',
|
||||
'target_surface': 'order_lifecycle_workbench',
|
||||
'target_lifecycle_stage': action_target,
|
||||
})
|
||||
secondary.append(action)
|
||||
return {
|
||||
'status': str(item.get('user_status') or item.get('status') or 'running'),
|
||||
'stage': str(item.get('user_stage') or item.get('stage') or ''),
|
||||
# 生命周期阶段是批次中心和工作台共享的业务语义;技术节点仍保留在 stage。
|
||||
'lifecycle_stage': lifecycle_stage,
|
||||
# 三阶段入口由后端一次性裁决;前端只按 state 投影,不得以候选数或阶段顺序二次判断。
|
||||
'lifecycle_entries': lifecycle['lifecycle_entries'],
|
||||
'lifecycle_authority': lifecycle['lifecycle_authority'],
|
||||
'blocking_reason': (
|
||||
dict(item['blocking_reason'])
|
||||
if isinstance(item.get('blocking_reason'), dict)
|
||||
@@ -2199,20 +2402,242 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _with_processing_ui_state(item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""一次裁决后同时下发 ui_state 与工作项顶层生命周期镜像。
|
||||
|
||||
``ui_state`` 是页面的完整权威 DTO;顶层镜像使批次叶子、Review Queue 与其它
|
||||
受控消费者无须依赖嵌套形状即可读取同一阶段和入口。该函数只复制既有裁决结果,
|
||||
禁止按旧状态、候选数或消费界面重新计算。
|
||||
"""
|
||||
projected = dict(item)
|
||||
ui_state = _processing_ui_state_from_item(projected)
|
||||
projected['ui_state'] = ui_state
|
||||
projected['lifecycle_stage'] = ui_state.get('lifecycle_stage')
|
||||
projected['lifecycle_entries'] = list(ui_state.get('lifecycle_entries') or [])
|
||||
projected['lifecycle_authority'] = ui_state.get('lifecycle_authority')
|
||||
return projected
|
||||
|
||||
|
||||
def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) -> str | None:
|
||||
"""将已授权动作映射到工作台展示面;未知动作不生成导航目标。"""
|
||||
code = str(action_code or '').strip().lower()
|
||||
if code in {
|
||||
'open_order_review', 'open_order_processing', 'edit_draft', 'create_draft',
|
||||
'reconcile_and_progress', 'confirm_customer', 'resolve_field_conflicts',
|
||||
'adjudicate_duplicate', 'open_profile_review',
|
||||
}:
|
||||
# 空 Candidate Case 的同一入口用于解析处置;不得借动作码跳到订单复核。
|
||||
return 'order_review' if lifecycle_stage == 'order_review' else 'intake_parse'
|
||||
if code in {
|
||||
'open_inventory_source_review', 'confirm_inventory_source', 'retry_resolve_inventory_source',
|
||||
'open_inventory_match_review', 'match_inventory', 'rematch', 'open_shortage_review',
|
||||
'upload_inventory_file', 'retry_inventory_preparation', 'regenerate_excel', 'generate_excel',
|
||||
}:
|
||||
return 'fulfillment_prep'
|
||||
if code in {
|
||||
'download_excel', 'open_manual_upload', 'wait_manual_upload', 'mark_manual_uploaded',
|
||||
'retry_freight_upload_rpa', 'retry_upload',
|
||||
}:
|
||||
return 'upload_complete'
|
||||
# 历史 Review 投影的 view 与 view_result 同为只读查看入口;必须由后端附带
|
||||
# 当前已裁决的工作台目标,前端不得因缺失目标误判为“前置阶段未完成”。
|
||||
return lifecycle_stage if code in {'view', 'view_result', 'view_record'} else None
|
||||
|
||||
|
||||
def _lifecycle_stage_from_item(item: dict[str, Any]) -> str | None:
|
||||
"""批次统计使用与任务详情相同的共享生命周期裁决,不维护独立映射。"""
|
||||
return project_lifecycle(
|
||||
current_gate=(
|
||||
item.get('current_gate')
|
||||
if isinstance(item.get('current_gate'), dict)
|
||||
else {'gate_code': item.get('user_current_gate_code')}
|
||||
),
|
||||
blocking_reason=item.get('blocking_reason') if isinstance(item.get('blocking_reason'), dict) else None,
|
||||
legacy_stage=str(item.get('user_stage') or item.get('stage') or ''),
|
||||
has_candidate_context=bool(item.get('has_formal_ot') or item.get('shipping_notice_no')),
|
||||
)['lifecycle_stage']
|
||||
|
||||
|
||||
def _current_file_representatives(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""为批次投影选择每个业务文件唯一的当前代表项。
|
||||
|
||||
核心逻辑:EML 聚合根不参与文件口径;同一文件的旧 Run、旧 OT 或历史失败
|
||||
投影只保留最新活动项。四阶段、文件统计、未分类统计必须共用本函数,避免一个
|
||||
PDF 同时被计入多个阶段或多个状态组。
|
||||
|
||||
Args:
|
||||
work_items: 已完成 EML 聚合和用户态投影的工作项。
|
||||
|
||||
Returns:
|
||||
按稳定业务文件身份去重后的当前代表项列表。
|
||||
"""
|
||||
file_items = [
|
||||
child
|
||||
for item in work_items
|
||||
for child in (item.get('aggregate_children') or [item])
|
||||
if isinstance(child, dict)
|
||||
]
|
||||
|
||||
def _file_key(item: dict[str, Any], index: int) -> str:
|
||||
"""优先用稳定文档身份;缺少正式标识时保守地不跨工作项合并。"""
|
||||
summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
|
||||
# 与跨 Run 聚合保持同一身份优先级:同内容重传可产生不同根文档,
|
||||
# 必须先以内容哈希归并,避免历史版本重新出现在当前状态组。
|
||||
content_hash = str(summary.get('content_hash') or '').strip().lower()
|
||||
if content_hash:
|
||||
return f'content-hash:{content_hash}'
|
||||
root_document_id = int(summary.get('root_document_id') or 0)
|
||||
if root_document_id > 0:
|
||||
return f'root-document:{root_document_id}'
|
||||
document_id = int(summary.get('document_id') or 0)
|
||||
if document_id > 0:
|
||||
return f'document:{document_id}'
|
||||
work_item_no = str(item.get('work_item_no') or '').strip()
|
||||
return f'item:{work_item_no or index}'
|
||||
|
||||
def _activity_key(item: dict[str, Any]) -> tuple[str, int]:
|
||||
"""最新活动优先;同一时刻以更需人工处理的状态稳定打破平局。"""
|
||||
status = str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
priority = {
|
||||
'failed': 0, 'retryable': 0, 'waiting_human': 1,
|
||||
'running': 2, 'completed': 3, 'cancelled': 4,
|
||||
}.get(status, 5)
|
||||
timestamp = str(item.get('last_activity_at') or item.get('updated_at') or item.get('created_at') or '')
|
||||
return timestamp, -priority
|
||||
|
||||
unique_by_file: dict[str, dict[str, Any]] = {}
|
||||
for index, item in enumerate(file_items):
|
||||
key = _file_key(item, index)
|
||||
current = unique_by_file.get(key)
|
||||
if current is None or _activity_key(item) > _activity_key(current):
|
||||
unique_by_file[key] = item
|
||||
return list(unique_by_file.values())
|
||||
|
||||
|
||||
def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""保留 EML 容器,同时仅展示每份文件的当前代表项。
|
||||
|
||||
核心逻辑:批次文件行不能直接以叶子代表项替换 EML 父卡,否则附件失去 intake
|
||||
归属并出现“汇总五份、列表只见三份”。本函数只替换父卡的子文件集合,并按该集合
|
||||
重算父卡用户态;非 EML 叶子直接保留当前代表项。
|
||||
|
||||
Args:
|
||||
work_items: 已完成 EML 聚合和用户态投影的完整工作项。
|
||||
|
||||
Returns:
|
||||
与互斥统计完全同源、且保留 EML 展开层级的展示工作项。
|
||||
"""
|
||||
representatives = _current_file_representatives(work_items)
|
||||
representative_ids = {id(item) for item in representatives}
|
||||
displayed: list[dict[str, Any]] = []
|
||||
|
||||
def _state(item: dict[str, Any]) -> str:
|
||||
return str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
|
||||
def _upload_state(item: dict[str, Any]) -> str:
|
||||
facts = item.get('facts') if isinstance(item.get('facts'), dict) else {}
|
||||
return str(facts.get('upload_state') or '').strip().lower()
|
||||
|
||||
for item in work_items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
children = item.get('aggregate_children')
|
||||
if not isinstance(children, list) or not children:
|
||||
if id(item) in representative_ids:
|
||||
displayed.append(item)
|
||||
continue
|
||||
|
||||
current_children = [child for child in children if id(child) in representative_ids]
|
||||
if not current_children:
|
||||
continue
|
||||
clone = dict(item)
|
||||
states = [_state(child) for child in current_children]
|
||||
upload_states = [_upload_state(child) for child in current_children]
|
||||
group = _eml_aggregate_user_group(
|
||||
states=states,
|
||||
upload_states=upload_states,
|
||||
children=current_children,
|
||||
)
|
||||
status = (
|
||||
'failed' if group == 'failed' else
|
||||
'waiting_human' if group == 'waiting_human' else
|
||||
'cancelled' if group == 'cancelled' else
|
||||
'completed' if group == 'completed' else
|
||||
'running'
|
||||
)
|
||||
actionable_states = (
|
||||
{'failed', 'retryable'} if group == 'failed' else
|
||||
{'waiting_human', 'idle'} if group == 'waiting_human' else set()
|
||||
)
|
||||
representative = next(
|
||||
(child for child in current_children if _state(child) in actionable_states),
|
||||
current_children[0],
|
||||
)
|
||||
source_summary = dict(clone.get('source_summary') or {})
|
||||
source_summary['document_count'] = len(current_children)
|
||||
clone.update({
|
||||
'aggregate_children': current_children,
|
||||
'user_group': group,
|
||||
'user_status': status,
|
||||
'status': status,
|
||||
'user_stage': str(representative.get('user_stage') or representative.get('stage') or ''),
|
||||
'stage': str(representative.get('user_stage') or representative.get('stage') or ''),
|
||||
'current_gate': representative.get('current_gate'),
|
||||
'blocking_reason': representative.get('blocking_reason') if actionable_states else None,
|
||||
'primary_action': representative.get('primary_action') if actionable_states else None,
|
||||
'available_actions': list(representative.get('available_actions') or []) if actionable_states else [],
|
||||
'source_summary': source_summary,
|
||||
'facts': {
|
||||
**dict(clone.get('facts') or {}),
|
||||
'upload_state': (
|
||||
'failed' if any(value == 'failed' for value in upload_states) else
|
||||
'succeeded' if upload_states and all(value == 'succeeded' for value in upload_states) else
|
||||
'uploading' if any(value in {'uploading', 'callback_received'} for value in upload_states) else
|
||||
'manual_upload_pending' if any(value == 'manual_upload_pending' for value in upload_states) else
|
||||
'not_created'
|
||||
),
|
||||
},
|
||||
'aggregate_summary': {
|
||||
'intake_no': clone.get('intake_no'),
|
||||
'total': len(current_children),
|
||||
'completed': sum(
|
||||
state == 'completed' and upload_state == 'succeeded'
|
||||
for state, upload_state in zip(states, upload_states)
|
||||
),
|
||||
'processing': sum(
|
||||
state not in {'failed', 'retryable', 'waiting_human', 'idle', 'completed'}
|
||||
or (state == 'completed' and upload_state != 'succeeded')
|
||||
for state, upload_state in zip(states, upload_states)
|
||||
),
|
||||
'needs_action': sum(state in {'waiting_human', 'idle'} for state in states),
|
||||
'failed': sum(state in {'failed', 'retryable'} for state in states),
|
||||
'stages': sorted({
|
||||
str(child.get('user_stage') or child.get('stage') or '').strip()
|
||||
for child in current_children
|
||||
if str(child.get('user_stage') or child.get('stage') or '').strip()
|
||||
}),
|
||||
'reason_codes': sorted({
|
||||
str((child.get('blocking_reason') or {}).get('code') or '').strip()
|
||||
for child in current_children
|
||||
if isinstance(child.get('blocking_reason'), dict)
|
||||
and str((child.get('blocking_reason') or {}).get('code') or '').strip()
|
||||
}),
|
||||
'upload_states': sorted(set(upload_states)),
|
||||
},
|
||||
})
|
||||
# 父卡的 ui_state 同样必须由当前附件集合重新封装;不能透传聚合前的旧按钮。
|
||||
displayed.append(_with_processing_ui_state(clone))
|
||||
return displayed
|
||||
|
||||
|
||||
def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""从最终用户态工作项构建批次四阶段主进度。
|
||||
|
||||
业务阶段映射和状态优先级只在后端维护;15 个技术节点仍附着在单项诊断字段,
|
||||
绝不要求前端通过 stage 索引再计算四阶段。
|
||||
"""
|
||||
ranges = (
|
||||
('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}),
|
||||
('order_review', {'order_creating', 'review_required', 'waiting_review', 'pre_ot_stp'}),
|
||||
('fulfillment_prep', {'inventory_fetching', 'inventory_matching', 'excel_generating'}),
|
||||
('upload_complete', {'freight_uploading', 'completed'}),
|
||||
)
|
||||
ranked_items = sorted(
|
||||
work_items,
|
||||
_current_file_representatives(work_items),
|
||||
key=lambda item: {
|
||||
'failed': 0,
|
||||
'retryable': 0,
|
||||
@@ -2222,33 +2647,75 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str,
|
||||
'cancelled': 4,
|
||||
}.get(str(item.get('user_status') or item.get('status') or '').strip().lower(), 5),
|
||||
)
|
||||
selected = ranked_items[0] if ranked_items else {}
|
||||
active_index = 0
|
||||
selected_status = str(selected.get('user_status') or selected.get('status') or '').strip().lower()
|
||||
stage = str(selected.get('user_stage') or selected.get('stage') or '').strip().lower()
|
||||
for index, (_, stage_codes) in enumerate(ranges):
|
||||
if stage in stage_codes:
|
||||
active_index = index
|
||||
break
|
||||
all_completed = bool(work_items) and all(
|
||||
str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
in {'completed', 'cancelled'}
|
||||
for item in work_items
|
||||
)
|
||||
for item in work_items:
|
||||
stage = str(item.get('user_stage') or item.get('stage') or '').strip().lower()
|
||||
for index, (_, stage_codes) in enumerate(ranges):
|
||||
if stage in stage_codes:
|
||||
break
|
||||
# 每一阶段的计数和首个阻断原因也在服务端统一裁决;前端不能从筛选后的
|
||||
# EML/文件行反算,否则聚合、历史项和权限裁剪会让摘要口径漂移。
|
||||
stage_summaries: dict[str, dict[str, Any]] = {
|
||||
code: {
|
||||
'total': 0,
|
||||
'completed': 0,
|
||||
'needs_action': 0,
|
||||
'processing': 0,
|
||||
'failed': 0,
|
||||
'blocking_reason': None,
|
||||
}
|
||||
for code, _ in LIFECYCLE_STAGE_RANGES
|
||||
}
|
||||
for item in ranked_items:
|
||||
lifecycle_stage = _lifecycle_stage_from_item(item)
|
||||
if lifecycle_stage is None:
|
||||
continue
|
||||
summary = stage_summaries[lifecycle_stage]
|
||||
summary['total'] += 1
|
||||
# 四阶段与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run
|
||||
# 兼容投影中残留为 running,不能把后端已裁决为“待处理”的文件再显示为处理中。
|
||||
item_group = _batch_user_group(item)
|
||||
if item_group == 'completed':
|
||||
summary['completed'] += 1
|
||||
continue
|
||||
if item_group == 'failed':
|
||||
summary['failed'] += 1
|
||||
summary['needs_action'] += 1
|
||||
elif item_group == 'waiting_human':
|
||||
summary['needs_action'] += 1
|
||||
else:
|
||||
summary['processing'] += 1
|
||||
if summary['blocking_reason'] is None and isinstance(item.get('blocking_reason'), dict):
|
||||
reason = item['blocking_reason']
|
||||
summary['blocking_reason'] = {
|
||||
key: reason[key]
|
||||
for key in ('code', 'i18n_key')
|
||||
if reason.get(key)
|
||||
} or None
|
||||
|
||||
nodes: list[dict[str, Any]] = []
|
||||
for index, (code, _) in enumerate(ranges):
|
||||
status = 'passed' if all_completed or index < active_index else 'pending'
|
||||
if not all_completed and index == active_index:
|
||||
status = 'blocked' if selected_status in {'failed', 'retryable', 'waiting_human'} else 'running'
|
||||
nodes.append({'code': code, 'label_key': code, 'status': status})
|
||||
for code, _ in LIFECYCLE_STAGE_RANGES:
|
||||
summary = stage_summaries[code]
|
||||
# 卡片状态只由本阶段聚合事实计算,禁止由其他阶段的优先文件反向影响。
|
||||
status = (
|
||||
'blocked' if summary['failed'] or summary['needs_action']
|
||||
else 'running' if summary['processing']
|
||||
else 'passed' if summary['completed']
|
||||
else 'pending'
|
||||
)
|
||||
nodes.append({
|
||||
'code': code,
|
||||
'label_key': code,
|
||||
'status': status,
|
||||
'summary': stage_summaries[code],
|
||||
})
|
||||
return nodes
|
||||
|
||||
|
||||
def _unclassified_summary(work_items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""统计无法归入四阶段的业务文件,避免批次摘要与文件清单口径不一致。"""
|
||||
return {
|
||||
'count': sum(
|
||||
1 for item in _current_file_representatives(work_items)
|
||||
if _lifecycle_stage_from_item(item) is None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""投影本次已就绪产出物;只暴露后端确认可下载的正式 Excel。"""
|
||||
artifacts: list[dict[str, Any]] = []
|
||||
@@ -2260,10 +2727,10 @@ def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str,
|
||||
task = ShippingOrderTask.query.filter_by(task_no=task_no).first()
|
||||
notice_id = getattr(task, 'shipping_notice_id', None) if task is not None else None
|
||||
notice = db.session.get(ShippingNotice, int(notice_id)) if notice_id else None
|
||||
filename = str(getattr(notice, 'export_file_name', None) or '').strip() if notice else ''
|
||||
path = str(getattr(notice, 'export_file_path', None) or '').strip() if notice else ''
|
||||
if not filename or not path:
|
||||
resolved = resolve_task_export_download(notice)
|
||||
if resolved is None:
|
||||
continue
|
||||
_, filename = resolved
|
||||
seen.add(task_no)
|
||||
artifacts.append({
|
||||
'order_task_no': task_no,
|
||||
@@ -2281,8 +2748,11 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An
|
||||
优先级与 EML 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造
|
||||
人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。
|
||||
"""
|
||||
# 批次主状态与文件计数、四阶段必须消费同一份“每文件唯一当前代表项”。
|
||||
# 否则历史 Run 的失败/待办虽然不再计数,仍可能抢走批次 CTA,形成
|
||||
# “数字是当前、按钮却指向历史”的第二裁决源。
|
||||
ranked = sorted(
|
||||
work_items,
|
||||
_current_file_representatives(work_items),
|
||||
key=lambda item: {
|
||||
'failed': 0,
|
||||
'retryable': 0,
|
||||
@@ -2315,35 +2785,36 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An
|
||||
}
|
||||
|
||||
|
||||
def _batch_user_group(item: dict[str, Any]) -> str:
|
||||
"""归一批次统计使用的互斥用户分组,优先消费领域投影已裁决的 user_group。"""
|
||||
group = str(item.get('user_group') or '').strip().lower()
|
||||
if group in {'failed', 'waiting_human', 'processing', 'completed'}:
|
||||
return group
|
||||
status = str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
if status in {'failed', 'retryable'}:
|
||||
return 'failed'
|
||||
if status in {'waiting_human', 'waiting_review', 'idle'}:
|
||||
return 'waiting_human'
|
||||
if status in {'completed', 'cancelled'}:
|
||||
return 'completed'
|
||||
return 'processing'
|
||||
|
||||
|
||||
def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""按后端最终 EML 聚合结果统计业务文件,EML 容器永不计数。"""
|
||||
groups = {'failed': set(), 'waiting_human': set(), 'processing': set(), 'completed': set()}
|
||||
for item in work_items:
|
||||
group = str(item.get('user_group') or '').strip().lower()
|
||||
if group not in groups:
|
||||
status = str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
group = 'failed' if status in {'failed', 'retryable'} else (
|
||||
'waiting_human' if status in {'waiting_human', 'waiting_review'} else (
|
||||
'completed' if status == 'completed' else 'processing'
|
||||
)
|
||||
)
|
||||
for child in item.get('aggregate_children') or [item]:
|
||||
if not isinstance(child, dict):
|
||||
continue
|
||||
summary = child.get('source_summary') if isinstance(child.get('source_summary'), dict) else {}
|
||||
filename = str(summary.get('filename') or '').strip().lower()
|
||||
if filename.endswith('.eml'):
|
||||
continue
|
||||
document_id = int(summary.get('document_id') or 0)
|
||||
key = f'document:{document_id}' if document_id else f'filename:{filename}'
|
||||
if filename or document_id:
|
||||
groups[group].add(key)
|
||||
"""按唯一当前业务文件统计互斥状态组,EML 容器永不计数。"""
|
||||
groups = {'failed': 0, 'waiting_human': 0, 'processing': 0, 'completed': 0}
|
||||
for item in _current_file_representatives(work_items):
|
||||
group = _batch_user_group(item)
|
||||
summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
|
||||
filename = str(summary.get('filename') or '').strip().lower()
|
||||
if not filename.endswith('.eml') and (filename or int(summary.get('document_id') or 0)):
|
||||
groups[group] += 1
|
||||
return {
|
||||
'total_files': len(set().union(*groups.values())),
|
||||
'failed_files': len(groups['failed']),
|
||||
'waiting_human_files': len(groups['waiting_human']),
|
||||
'processing_files': len(groups['processing']),
|
||||
'completed_files': len(groups['completed']),
|
||||
'total_files': sum(groups.values()),
|
||||
'failed_files': groups['failed'],
|
||||
'waiting_human_files': groups['waiting_human'],
|
||||
'processing_files': groups['processing'],
|
||||
'completed_files': groups['completed'],
|
||||
}
|
||||
|
||||
|
||||
@@ -2368,6 +2839,9 @@ def _conversation_processing_from_work_items(
|
||||
Returns:
|
||||
与 project_conversation_processing 同形的 dict。
|
||||
"""
|
||||
# 文件清单必须与批次统计、四阶段和 CTA 使用相同的当前文件代表项,同时
|
||||
# 保留 EML 父卡,避免附件失去邮件归属或在多个状态组重复出现。
|
||||
display_work_items = _display_work_items_from_current_files(work_items)
|
||||
needs_action: list[dict[str, Any]] = []
|
||||
processing: list[dict[str, Any]] = []
|
||||
completed: list[dict[str, Any]] = []
|
||||
@@ -2375,7 +2849,7 @@ def _conversation_processing_from_work_items(
|
||||
focused = str(focused_task_no or '').strip() or None
|
||||
recent = str(recent_task_no or '').strip() or None
|
||||
|
||||
for item in work_items:
|
||||
for item in display_work_items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if str(item.get('work_item_type') or '') not in {'order_task', 'order_intake'}:
|
||||
@@ -2441,6 +2915,7 @@ def _conversation_processing_from_work_items(
|
||||
'archived': [row for row in all_rows if row.get('user_group') == 'archived'],
|
||||
},
|
||||
'four_stage_nodes': _batch_four_stage_nodes(work_items),
|
||||
'unclassified_summary': _unclassified_summary(work_items),
|
||||
'ui_state': _batch_ui_state_from_items(work_items),
|
||||
'output_artifacts': _batch_output_artifacts(work_items),
|
||||
}
|
||||
@@ -2773,12 +3248,11 @@ def project_conversation_processing_items(
|
||||
# 保证对话正文、右侧任务区和 API 消费同一 user_status/user_stage/upload_state 事实。
|
||||
work_items = _aggregate_eml_order_task_work_items(work_items)
|
||||
# [AUTHORITY] 顶层 work_items 与 conversation_processing.status_groups 必须使用
|
||||
# 相同的展示 DTO。否则 direct PDF / EML 聚合根会缺 ui_state,迫使前端从旧
|
||||
# gate 或 available_actions 重新裁决状态与按钮。
|
||||
work_items = [
|
||||
{**item, 'ui_state': _processing_ui_state_from_item(item)}
|
||||
for item in work_items
|
||||
]
|
||||
# 同一份“当前文件代表项”展示 DTO。否则前端兼容消费者若从顶层 work_items
|
||||
# 读取,会重新看到历史 Run/旧失败项,绕过批次统计已经完成的互斥裁决。
|
||||
# 该函数保留 EML 父容器,只裁掉其历史附件,不能以叶子项直接替换父卡。
|
||||
work_items = _display_work_items_from_current_files(work_items)
|
||||
work_items = [_with_processing_ui_state(item) for item in work_items]
|
||||
|
||||
recent_override = str(recent_task_no or '').strip() or None
|
||||
rebuilt = _conversation_processing_from_work_items(
|
||||
|
||||
@@ -287,6 +287,13 @@ def shipping_recovery_tick() -> int:
|
||||
nested.rollback()
|
||||
continue
|
||||
|
||||
# 人工改写后的草稿必须等待用户点击“保存订单并校验”。恢复扫描只补偿
|
||||
# 遗漏的系统任务,不能反复写入校验快照导致前端版本持续过期。
|
||||
from app.services.shipping_notice.order_review_draft_service import draft_has_manual_values
|
||||
if draft_has_manual_values(locked_case.current_draft):
|
||||
nested.rollback()
|
||||
continue
|
||||
|
||||
db.session.execute(text(
|
||||
"SELECT pg_advisory_xact_lock(hashtext('shipping_stp_sweeper'), :case_id)"
|
||||
), {"case_id": int(case_id)})
|
||||
|
||||
@@ -64,6 +64,8 @@ def _request_formal_gate_action(
|
||||
current_id = getattr(task, 'active_process_execution_id', None)
|
||||
if current_id:
|
||||
execution = ShippingProcessExecution.query.filter_by(id=int(current_id)).with_for_update().first()
|
||||
if execution is not None and str(execution.status or '').strip().lower() == 'superseded':
|
||||
execution = None
|
||||
if execution is None:
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=int(task.id), actor_type='user', actor_id=int(user_id),
|
||||
|
||||
@@ -32,6 +32,7 @@ def _task_has_process_execution(task: ShippingNotice | None) -> bool:
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.first()
|
||||
is not None
|
||||
)
|
||||
|
||||
@@ -49,9 +49,14 @@ from app.services.shipping_notice.constants import (
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
from app.services.shipping_notice.lifecycle_projection import (
|
||||
LIFECYCLE_STAGES,
|
||||
project_lifecycle,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import (
|
||||
compute_batch_process_summary,
|
||||
list_sorted_batch_tasks,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_summary,
|
||||
)
|
||||
@@ -66,8 +71,8 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta
|
||||
WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
|
||||
{"id": "shipping-stage-1", "code": "intake_parse", "label": "接收解析"},
|
||||
{"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"},
|
||||
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "发货准备"},
|
||||
{"id": "shipping-stage-4", "code": "upload_complete", "label": "上传完成"},
|
||||
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "通知准备"},
|
||||
{"id": "shipping-stage-4", "code": "upload_complete", "label": "通知完成"},
|
||||
)
|
||||
|
||||
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
|
||||
@@ -132,36 +137,6 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
|
||||
}
|
||||
|
||||
# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
|
||||
BUSINESS_STAGES: tuple[dict[str, Any], ...] = (
|
||||
{"code": "intake_parse", "label": "接收解析"},
|
||||
{"code": "order_review", "label": "订单复核"},
|
||||
{"code": "fulfillment_prep", "label": "发货准备"},
|
||||
{"code": "upload_complete", "label": "上传完成"},
|
||||
)
|
||||
|
||||
_STAGE_GATE_CODES: dict[str, str] = {
|
||||
"document_materialization": "intake_parse",
|
||||
"layout_parsing": "intake_parse",
|
||||
"document_profile_routing": "intake_parse",
|
||||
"order_field_extraction": "intake_parse",
|
||||
"field_completeness": "order_review",
|
||||
"reservation_validation": "order_review",
|
||||
"customer_resolution": "order_review",
|
||||
"duplicate_detection": "order_review",
|
||||
"field_conflict_resolution": "order_review",
|
||||
"order_freeze_readiness": "order_review",
|
||||
"task_creation": "order_review",
|
||||
"inventory_source_routing": "fulfillment_prep",
|
||||
"inventory_preparation": "fulfillment_prep",
|
||||
"inventory_field_mapping": "fulfillment_prep",
|
||||
"inventory_matching": "fulfillment_prep",
|
||||
"inventory_sufficiency": "fulfillment_prep",
|
||||
"excel_readiness": "fulfillment_prep",
|
||||
"artifact_generation": "fulfillment_prep",
|
||||
"freight_upload_rpa": "upload_complete",
|
||||
"manual_upload_handoff": "upload_complete",
|
||||
}
|
||||
|
||||
_STAGE_CHECKPOINT_CODES: dict[str, str] = {
|
||||
CP_PARSE_REVIEW: "order_review",
|
||||
CP_RSV_REQ: "order_review",
|
||||
@@ -184,17 +159,36 @@ _STAGE_CHECKPOINT_CODES: dict[str, str] = {
|
||||
}
|
||||
|
||||
|
||||
def _business_stage(
|
||||
def _task_lifecycle(
|
||||
*, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""将内部 Gate/checkpoint 投影为四阶段;不向前端暴露底层状态枚举。"""
|
||||
gate = (process_gate or {}).get("current_blocking_gate") or (process_gate or {}).get("current_gate") or {}
|
||||
gate_code = str(gate.get("gate_code") or "").strip()
|
||||
stage_code = _STAGE_GATE_CODES.get(gate_code) or _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ""))
|
||||
if not stage_code:
|
||||
stage_code = "upload_complete" if str(checkpoint or "") in {CP_UPLOADED, CP_COMPLETED} else "intake_parse"
|
||||
index = next((i for i, item in enumerate(BUSINESS_STAGES) if item["code"] == stage_code), 0)
|
||||
return {**BUSINESS_STAGES[index], "index": index + 1, "total": len(BUSINESS_STAGES)}
|
||||
"""以共享裁决器投影正式任务生命周期;旧 checkpoint 仅作无 Gate 的兼容兜底。"""
|
||||
gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate')
|
||||
legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ''))
|
||||
if legacy_stage is None:
|
||||
legacy_stage = 'upload_complete' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None
|
||||
if legacy_stage is None:
|
||||
# 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。
|
||||
legacy_index = _derive_current_step_index(task)
|
||||
legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete')[legacy_index]
|
||||
return project_lifecycle(
|
||||
current_gate=gate if isinstance(gate, dict) else None,
|
||||
blocking_reason=(
|
||||
{'code': process_gate.get('blocking_reason_code')}
|
||||
if isinstance(process_gate, dict) and process_gate.get('blocking_reason_code')
|
||||
else None
|
||||
),
|
||||
legacy_stage=legacy_stage,
|
||||
# ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。
|
||||
has_candidate_context=True,
|
||||
)
|
||||
|
||||
|
||||
def _business_stage(lifecycle: dict[str, Any]) -> dict[str, Any]:
|
||||
"""将共享生命周期结果包装为任务详情既有的阶段 DTO。"""
|
||||
stage_code = str(lifecycle.get('lifecycle_stage') or 'intake_parse')
|
||||
index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), 0)
|
||||
return {**LIFECYCLE_STAGES[index], 'index': index + 1, 'total': len(LIFECYCLE_STAGES)}
|
||||
|
||||
|
||||
def _unified_action(action: dict[str, Any], *, default_kind: str = "recovery") -> dict[str, Any]:
|
||||
@@ -289,14 +283,24 @@ def _derive_current_step_index(task: ShippingNotice) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def build_shipping_workflow_steps(task: ShippingNotice, checkpoint: str | None) -> list[dict[str, str]]:
|
||||
def build_shipping_workflow_steps(
|
||||
task: ShippingNotice,
|
||||
checkpoint: str | None,
|
||||
*,
|
||||
lifecycle_stage: str | None = None,
|
||||
) -> list[dict[str, str]]:
|
||||
"""
|
||||
构造四阶段流程状态。
|
||||
|
||||
Returns:
|
||||
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
|
||||
"""
|
||||
current_index = _derive_current_step_index(task)
|
||||
lifecycle_index = next(
|
||||
(index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage),
|
||||
None,
|
||||
)
|
||||
# 正式 Gate 已存在时,四阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。
|
||||
current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task)
|
||||
pending_reason = str(task.pending_human_reason or "").strip()
|
||||
checkpoint_value = str(checkpoint or "").strip()
|
||||
steps: list[dict[str, str]] = []
|
||||
@@ -359,7 +363,17 @@ def _action_buttons_for_task(task: ShippingNotice) -> list[dict[str, str]]:
|
||||
# 保留重试/重匹配/驳回,但把指定源放在首位作为主恢复入口。
|
||||
rest = [btn for btn in (ui.action_buttons or []) if str(btn.get('id') or '') != 'confirm_inventory_source']
|
||||
return [confirm_btn, *rest]
|
||||
return ui.action_buttons
|
||||
action_buttons = list(ui.action_buttons or [])
|
||||
# [AUTHORITY] ``export_file_name`` 只是历史字段,不能作为下载授权或文件存在的证据。
|
||||
# 只有任务当前 Artifact 已由后端解析为可下载文件时,才把 download_excel 下发给
|
||||
# 任一前端;下载 API 仍会在真正读取文件时再次校验,抵御页面快照过期。
|
||||
if any(str((button or {}).get('id') or '') == 'download_excel' for button in action_buttons):
|
||||
if resolve_task_export_download(task) is None:
|
||||
action_buttons = [
|
||||
button for button in action_buttons
|
||||
if str((button or {}).get('id') or '') != 'download_excel'
|
||||
]
|
||||
return action_buttons
|
||||
|
||||
_PARSE_STAGE_CHECKPOINTS = {
|
||||
CP_PARSE_REVIEW,
|
||||
@@ -690,7 +704,235 @@ def _build_task_summary(
|
||||
return summary
|
||||
|
||||
|
||||
def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
def _build_stage_context(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
lifecycle_stage: str,
|
||||
stp_facts: dict[str, Any] | None,
|
||||
process_gate: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造四阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。
|
||||
|
||||
通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成
|
||||
只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。
|
||||
"""
|
||||
from app.models.shipping_excel_template import ShippingExportArtifact
|
||||
from app.models.shipping_fulfillment import (
|
||||
ShippingInventoryVerification,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
|
||||
from app.models.shipping_notice_line import ShippingNoticeLine
|
||||
|
||||
facts = stp_facts if isinstance(stp_facts, dict) else {}
|
||||
raw_rows = task.line_results_json if isinstance(task.line_results_json, list) else []
|
||||
fact_rows = facts.get('line_resolutions') if isinstance(facts.get('line_resolutions'), list) else []
|
||||
fact_by_key = {
|
||||
str(row.get('line_key') or ''): row
|
||||
for row in fact_rows
|
||||
if isinstance(row, dict) and str(row.get('line_key') or '')
|
||||
}
|
||||
# 正式结构化匹配事实是通知准备的首要来源;旧 JSON/STP 仅作为历史任务兼容回退。
|
||||
current_match_rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=task.id, is_current=True)
|
||||
.order_by(ShippingNoticeLineInventoryMatch.line_index, ShippingNoticeLineInventoryMatch.id)
|
||||
.all()
|
||||
if getattr(task, 'id', None) is not None else []
|
||||
)
|
||||
match_by_key = {
|
||||
str(row.line_key or ''): row
|
||||
for row in current_match_rows
|
||||
if str(row.line_key or '')
|
||||
}
|
||||
match_by_index = {
|
||||
int(row.line_index): row
|
||||
for row in current_match_rows
|
||||
if row.line_index is not None
|
||||
}
|
||||
verification_rows: dict[str, dict[str, Any]] = {}
|
||||
latest_verification = (
|
||||
ShippingInventoryVerification.query
|
||||
.filter_by(task_id=task.id, status='completed')
|
||||
.order_by(ShippingInventoryVerification.created_at.desc(), ShippingInventoryVerification.id.desc())
|
||||
.first()
|
||||
if getattr(task, 'id', None) is not None else None
|
||||
)
|
||||
if latest_verification is not None:
|
||||
# 核验行没有 line_key,按冻结订单行/Reservation 顺序作为最后一级兼容回退。
|
||||
for position, verification_line in enumerate(latest_verification.lines):
|
||||
verification_rows[str(position)] = {
|
||||
'required_qty': verification_line.required_qty,
|
||||
'available_qty': verification_line.available_qty,
|
||||
'shortage_qty': (
|
||||
max(verification_line.required_qty - verification_line.available_qty, 0)
|
||||
if verification_line.required_qty is not None and verification_line.available_qty is not None
|
||||
else None
|
||||
),
|
||||
'status': verification_line.status,
|
||||
}
|
||||
# 冻结订单与库存匹配是不同事实:库存文件尚未准备好时,用户仍必须能核对
|
||||
# 已冻结的预约号、料号和需求数量。禁止用“是否有匹配结果”决定订单行是否展示。
|
||||
frozen_order_lines: list[dict[str, Any]] = []
|
||||
preparation_lines: list[dict[str, Any]] = []
|
||||
notice_lines = (
|
||||
ShippingNoticeLine.query.filter_by(notice_id=task.id).order_by(ShippingNoticeLine.position).all()
|
||||
if getattr(task, 'id', None) is not None else []
|
||||
)
|
||||
for line in notice_lines:
|
||||
frozen_order_lines.append({
|
||||
'line_key': getattr(line, 'line_key', None),
|
||||
'reservation_id': getattr(line, 'reservation_id', None),
|
||||
'part_number': getattr(line, 'part_number', None),
|
||||
'required_qty': str(getattr(line, 'required_qty', None)) if getattr(line, 'required_qty', None) is not None else None,
|
||||
})
|
||||
|
||||
# 匹配表只输出已经存在的匹配/核验事实。历史任务尚未双写正式行时可用旧 JSON
|
||||
# 兼容,但绝不能把未匹配的冻结订单行伪装为“库存匹配结果”。
|
||||
row_count = max(len(raw_rows), len(fact_rows), len(current_match_rows))
|
||||
for index in range(row_count):
|
||||
line = notice_lines[index] if index < len(notice_lines) else None
|
||||
match_row = match_by_key.get(str(getattr(line, 'line_key', '') or '')) or match_by_index.get(index)
|
||||
structured = ({
|
||||
'line_key': match_row.line_key,
|
||||
'reservation_id': match_row.reservation_id,
|
||||
'part_number': match_row.part_number,
|
||||
'required_qty': match_row.required_qty,
|
||||
'available_qty': match_row.matched_qty or match_row.available_qty,
|
||||
'shortage_qty': match_row.shortage_qty,
|
||||
'resolved_inventory_source_code': match_row.inventory_source_code,
|
||||
'disposition': match_row.match_result,
|
||||
} if match_row is not None else {})
|
||||
legacy_source = fact_by_key.get(
|
||||
str(getattr(line, 'line_key', '') or ''),
|
||||
fact_rows[index] if index < len(fact_rows) and isinstance(fact_rows[index], dict) else {},
|
||||
)
|
||||
# 结构化事实优先,但不以空值覆盖历史/STP 投影中仍有价值的证据字段。
|
||||
source = {
|
||||
**(legacy_source if isinstance(legacy_source, dict) else {}),
|
||||
**{
|
||||
key: value
|
||||
for key, value in structured.items()
|
||||
if value is not None and value != ''
|
||||
},
|
||||
}
|
||||
verification = verification_rows.get(str(index), {})
|
||||
result = raw_rows[index] if index < len(raw_rows) and isinstance(raw_rows[index], dict) else {}
|
||||
required_qty = result.get('required_qty', source.get('required_qty', verification.get('required_qty', getattr(line, 'required_qty', None))))
|
||||
available_qty = result.get('available_qty', source.get('available_qty', source.get('matched_qty', verification.get('available_qty'))))
|
||||
shortage_qty = result.get('shortage_qty', source.get('shortage_qty', verification.get('shortage_qty')))
|
||||
preparation_lines.append({
|
||||
'line_key': getattr(line, 'line_key', None) or source.get('line_key'),
|
||||
'reservation_id': result.get('reservation_id') or source.get('effective_reservation_id') or source.get('reservation_id') or getattr(line, 'reservation_id', None),
|
||||
'part_number': result.get('part_number') or source.get('part_number') or getattr(line, 'part_number', None),
|
||||
'required_qty': required_qty,
|
||||
'available_qty': available_qty,
|
||||
'shortage_qty': shortage_qty,
|
||||
'source_code': source.get('resolved_inventory_source_code') or source.get('inventory_source_code'),
|
||||
'status': result.get('line_status') or source.get('disposition') or verification.get('status') or None,
|
||||
})
|
||||
|
||||
has_match_result = bool(current_match_rows or raw_rows or any(
|
||||
row.get('matched_qty') is not None
|
||||
or row.get('shortage_qty') is not None
|
||||
or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage'}
|
||||
for row in fact_rows if isinstance(row, dict)
|
||||
))
|
||||
gate = process_gate if isinstance(process_gate, dict) else {}
|
||||
gate_code = str((gate.get('current_blocking_gate') or gate.get('current_gate') or {}).get('gate_code') or '')
|
||||
preparation_status = (
|
||||
'ready' if has_match_result else
|
||||
'blocked' if gate_code else
|
||||
'processing'
|
||||
)
|
||||
|
||||
inventory_sources: list[dict[str, Any]] = []
|
||||
latest_preparation = None
|
||||
if getattr(task, 'id', None):
|
||||
from app.models.shipping_inventory_preparation import ShippingInventoryPreparationAttempt
|
||||
|
||||
latest_preparation = (
|
||||
ShippingInventoryPreparationAttempt.query
|
||||
.filter_by(task_id=task.id)
|
||||
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
|
||||
.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||||
|
||||
downloadable_inventory = resolve_task_inventory_download(task)
|
||||
for source_attempt in (getattr(latest_preparation, 'source_attempts', None) or []):
|
||||
inventory_sources.append({
|
||||
'source_code': source_attempt.source_code,
|
||||
'status': source_attempt.status,
|
||||
'inventory_file_id': source_attempt.inventory_file_id,
|
||||
})
|
||||
|
||||
artifact = None
|
||||
attempts = []
|
||||
if getattr(task, 'id', None):
|
||||
artifact = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by(
|
||||
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
|
||||
).first()
|
||||
attempts = ShippingUploadAttempt.query.join(
|
||||
ShippingExportArtifact,
|
||||
ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id,
|
||||
).filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
).order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()).all()
|
||||
latest_attempt = attempts[0] if attempts else None
|
||||
latest_status = str(getattr(latest_attempt, 'status', '') or '').lower()
|
||||
upload_outcome = (
|
||||
'succeeded' if latest_status == 'succeeded' else
|
||||
'failed' if latest_status in {'failed', 'timed_out'} else
|
||||
'unknown' if latest_status == 'unknown' else
|
||||
'running' if latest_status in {'pending', 'running'} else
|
||||
'awaiting_manual' if lifecycle_stage == 'upload_complete' else
|
||||
'not_started'
|
||||
)
|
||||
return {
|
||||
'preparation': {
|
||||
'status': preparation_status,
|
||||
'reason_code': gate.get('blocking_reason_code') or None,
|
||||
'frozen_order': {
|
||||
'task_no': task.task_no,
|
||||
'snapshot_id': task.order_snapshot_id,
|
||||
},
|
||||
'inventory_source_code': facts.get('inventory_source_code'),
|
||||
'match_status': facts.get('match_status'),
|
||||
'frozen_order_lines': frozen_order_lines,
|
||||
'lines': preparation_lines,
|
||||
'has_match_result': has_match_result,
|
||||
# 任务级库存准备源只说明文件获取进度;实际匹配源必须从 lines[].source_code 读取。
|
||||
'inventory_sources': inventory_sources,
|
||||
'inventory_file': {
|
||||
'available': downloadable_inventory is not None,
|
||||
'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None,
|
||||
},
|
||||
'artifact': {
|
||||
'file_name': artifact.file_name if artifact is not None else None,
|
||||
'status': artifact.status if artifact is not None else 'not_generated',
|
||||
},
|
||||
},
|
||||
'upload': {
|
||||
'outcome': upload_outcome,
|
||||
'latest_attempt': ({
|
||||
'id': latest_attempt.id,
|
||||
'status': latest_attempt.status,
|
||||
'mode': latest_attempt.mode,
|
||||
'freight_ref_no': latest_attempt.freight_ref_no,
|
||||
'error_code': latest_attempt.error_code,
|
||||
'finished_at': latest_attempt.finished_at.isoformat() if latest_attempt.finished_at else None,
|
||||
} if latest_attempt is not None else None),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def build_task_ui_state(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
include_stage_context: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建单票任务 UI State。
|
||||
|
||||
@@ -712,8 +954,10 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
button for button in action_buttons
|
||||
if str((button or {}).get('id') or '') in _non_recovery_action_ids
|
||||
]
|
||||
steps = build_shipping_workflow_steps(task, ui.checkpoint)
|
||||
current_index = _derive_current_step_index(task)
|
||||
lifecycle = _task_lifecycle(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
|
||||
stage = _business_stage(lifecycle)
|
||||
steps = build_shipping_workflow_steps(task, ui.checkpoint, lifecycle_stage=stage['code'])
|
||||
current_index = int(stage['index']) - 1
|
||||
current_step = steps[current_index] if 0 <= current_index < len(steps) else None
|
||||
summary = _build_task_summary(
|
||||
task,
|
||||
@@ -732,8 +976,32 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
summary['diagnostic_hint'] = process_gate['diagnostic_hint']
|
||||
if process_gate.get('current_blocking_gate'):
|
||||
summary['allowed_actions'] = []
|
||||
stage = _business_stage(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
|
||||
actions = _unified_actions(process_gate=process_gate, action_buttons=action_buttons)
|
||||
# [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作,
|
||||
# 两者不能相互覆盖。即使当前 Gate 阻断并清空旧 checkpoint 动作,也只在
|
||||
# Artifact 已通过 resolve_task_export_download 校验时补入下载授权。
|
||||
if resolve_task_export_download(task) is not None:
|
||||
download_action = _unified_action({
|
||||
'id': 'download_excel',
|
||||
'label': '下载 Excel',
|
||||
'kind': 'view',
|
||||
'enabled': True,
|
||||
}, default_kind='view')
|
||||
action_codes = {
|
||||
str((action or {}).get('code') or '')
|
||||
for action in [actions.get('primary'), *(actions.get('secondary') or [])]
|
||||
}
|
||||
if download_action['code'] not in action_codes:
|
||||
actions['secondary'].append(download_action)
|
||||
stage_context = (
|
||||
_build_stage_context(
|
||||
task,
|
||||
lifecycle_stage=stage['code'],
|
||||
stp_facts=summary.get('stp_facts'),
|
||||
process_gate=process_gate,
|
||||
)
|
||||
if include_stage_context else None
|
||||
)
|
||||
checkpoint_payload = {
|
||||
"code": ui.checkpoint,
|
||||
"kind": str(ui.checkpoint_kind),
|
||||
@@ -749,6 +1017,9 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
"task_no": task.task_no,
|
||||
"batch_no": None,
|
||||
"stage": stage,
|
||||
"lifecycle_stage": stage["code"],
|
||||
"lifecycle_entries": lifecycle['lifecycle_entries'],
|
||||
"lifecycle_authority": lifecycle['lifecycle_authority'],
|
||||
"checkpoint": checkpoint_payload,
|
||||
"checkpoint_view": checkpoint_payload,
|
||||
"todo": {
|
||||
@@ -756,6 +1027,8 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
"message": summary.get("message"),
|
||||
},
|
||||
"actions": actions,
|
||||
# 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。
|
||||
**({'stage_context': stage_context} if stage_context is not None else {}),
|
||||
"reason": reason,
|
||||
"lifecycle_status": task.lifecycle_status,
|
||||
"checkpoint_code": ui.checkpoint,
|
||||
@@ -797,6 +1070,7 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=task_pk)
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -89,12 +89,19 @@ def _decode_png_to_ndarray(png_bytes: bytes) -> Any:
|
||||
|
||||
def is_ocr_engine_available() -> bool:
|
||||
"""
|
||||
探测 RapidOCR 是否可导入(不强制加载模型权重)。
|
||||
探测 XFA 自动标记所需 OCR 运行时是否完整(不强制加载模型权重)。
|
||||
|
||||
XFA 自动标记把 OCR 作为 datasets/Widget 的视觉交叉证据,因此 shipping
|
||||
Worker 必须在领取任务前通过此探测。仅检查 RapidOCR 本体不足以保证页图
|
||||
解码和 ONNX 推理可执行,故同时检查 OpenCV、NumPy 与 ONNX Runtime。
|
||||
|
||||
Returns:
|
||||
True 表示引擎模块可导入;False 表示本进程不可用。
|
||||
"""
|
||||
try:
|
||||
import cv2 # noqa: F401
|
||||
import numpy # noqa: F401
|
||||
import onnxruntime # noqa: F401
|
||||
import rapidocr_onnxruntime # noqa: F401
|
||||
|
||||
return True
|
||||
@@ -104,7 +111,7 @@ def is_ocr_engine_available() -> bool:
|
||||
|
||||
def recognize_preview_page(png_bytes: bytes) -> list[dict[str, Any]]:
|
||||
"""
|
||||
对 XFA 合成预览 PNG 页执行 OCR,返回归一化文本行。
|
||||
对 XFA 原生 PDF 渲染 PNG 页执行 OCR,返回归一化文本行。
|
||||
|
||||
核心逻辑:解码 PNG → 惰性调用 document_layout.ocr_pdf.extract_ocr_lines →
|
||||
将页面坐标映射为 0..1 normalized_bbox。引擎缺失或解码失败时抛 OCR_UNAVAILABLE,
|
||||
|
||||
@@ -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)
|
||||
@@ -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',
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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']
|
||||
@@ -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)
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
### 当前业务阶段基线(2026-08)
|
||||
|
||||
业务人员只看到四个阶段:`接收解析 → 订单复核 → 发货准备 → 上传完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于发货准备;上传或登记回执后进入上传完成。`ui_state` 是唯一前端读模型,按钮由后端统一返回。
|
||||
业务人员只看到四个阶段:`接收解析 → 订单复核 → 通知准备 → 通知完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于通知准备;上传或登记回执后进入通知完成。`ui_state` 是唯一前端读模型,按钮由后端统一返回。阶段四的进入不等于上传成功:必须有服务端确认的上传 Attempt 和回执事实;同一 Gate 的全局处理按钮只在右侧“当前处理”出现一次。
|
||||
|
||||
- **模式**:直通处理(STP)+ 例外工作台。可信 PDF 自动建 Task 并推进至「Excel 已生成,待人工上传」;解析不确定进入人工复核;建单后异常优先在对话侧 Process Gate 轻量处理,复杂数据进复核工作台。
|
||||
- **双工作台架构(2026-08-02 冻结)**:对话工作台 = 主入口/主状态/主进度/轻量操作;复核工作台 = 深度编辑与证据处理;Task 工作台 = 仅备用深链(非主导航)。后端工作流始终后台运行,前端只消费状态投影。权威线框见 [review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md) §0。
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
| 域 | 说明 | 入口 |
|
||||
| --- | --- | --- |
|
||||
| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [客户识别规则改造方案](shipping-notice/customer_identity_rules_plan.md) |
|
||||
| [in-transit-transfer](in-transit-transfer/) | 在途仓自动调拨 Agent | [PRD](in-transit-transfer/prd.md) · [路线图](in-transit-transfer/roadmap.md) · [场景化UI/UX原型说明](in-transit-transfer/ui-ux-scenario-prototype.md) · [完整规格](in-transit-transfer/minimum-implementation-spec.md) · [TDD](in-transit-transfer/in-transit-transfer-tdd.md) · [前端需求](in-transit-transfer/frontend-product-requirements.md) |
|
||||
| [in-transit-transfer](in-transit-transfer/) | 在途仓自动调拨 Agent | [Chat工作区MVP实施规格](in-transit-transfer/mvp-chat-workbench-implementation-spec.md) · [Chat工作区UI/UX](in-transit-transfer/mvp-chat-workbench-ui-ux.md) · [Chat工作区TDD](in-transit-transfer/mvp-chat-workbench-tdd.md) · [Chat工作区可点击原型](../platform/in-transit-transfer-chat-workbench-mvp.html) · [PRD](in-transit-transfer/prd.md) · [路线图](in-transit-transfer/roadmap.md) · [场景化UI/UX原型说明](in-transit-transfer/ui-ux-scenario-prototype.md) · [完整规格](in-transit-transfer/minimum-implementation-spec.md) |
|
||||
| [auth](auth/README.md) | Casdoor 登录与产品内平级服务无感登录 | [hxops-peer-service-sso.md](auth/hxops-peer-service-sso.md) |
|
||||
| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [原型](shipping-notice/shipping_notice_agent_prototype.md) |
|
||||
| [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) |
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
# 在途仓自动调拨 Agent MVP:Chat 工作区实施规格
|
||||
|
||||
> 状态:评审稿;本文件是当前“Chat 优先、右侧业务面板承接操作”MVP的实现权威。它不覆盖旧规格,仅在冲突时优先于旧规格的交互描述。
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
在既有 `/chat/:agentId` 中交付安全、可恢复、可审计的在途仓调拨闭环:仓管从新建对话选择 DBS、Crane 来源,完成只读预检,在右侧“本次调拨”面板勾选部分可执行 Invoice、一次确认后由后台 Worker 调用 ERP 原子建单/审核/过账。自动排程处理正常项,历史可恢复异常在新建对话欢迎页点击后进入右侧“待处理调拨”面板。
|
||||
|
||||
不新增 Workspace 调拨一级菜单,不建设独立集成中心,不支持部分调拨、数量容差、人工改数、手工 Invoice 搜索、多人占用锁或页面租约。Dify 仅识别意图、解释结果;HXOPS 服务与 Worker 唯一持有 ERP 写能力。
|
||||
|
||||
### 已冻结事实
|
||||
|
||||
- DBS 通过 RPA 获取累计全量收料文件;Crane 通过 HTTP Callback 获取累计全量文件。
|
||||
- 用户不能处理收料日期为当天的 Invoice:标记 `not_matured`,不查 ERP、不写 ERP。
|
||||
- 同一 Invoice 多行仅汇总收料数量,并保留原始 Sheet、行号;一个 Invoice 不跨来源。
|
||||
- 只有收料数量严格等于 ERP 账面库存才可写入。库存大于或小于收料数量均阻断。
|
||||
- 任务创建后固定文件版本/checksum、策略版本和映射版本;中途不能抓 RPA 或更新文件。新文件只能通过新预检取得。
|
||||
- ERP 接口原子完成新建、审核、过账;失败会回滚、不产生单据;同一 ERP 组织内 Invoice 是幂等键,重复 Invoice 返回原调拨单号且能确认原单已审核过账。
|
||||
- ERP 只可能给成功/失败;若请求超时而系统不能确认结果,落 `result_unknown`。该状态只读,绝不重试、关闭、恢复或再次执行。
|
||||
- 不做任何多人并发控制或占用提示。服务端仍须在每次提交时按当前状态、确认快照和 ERP 幂等结果裁决;后到请求只返回最新事实,不能绕过门禁。
|
||||
|
||||
## 2. 当前项目复用点
|
||||
|
||||
| 现有能力 | 复用方式 | 禁止改变的事实 |
|
||||
| --- | --- | --- |
|
||||
| `ChatViewContent.vue` | 增加 transfer 专用右侧面板状态;与货代 `batchWorkbenchOpen` 同样按需展开 | 普通 Agent 首屏不加载调拨数据 |
|
||||
| `ChatWelcomePanel.vue` | 当当前 Agent 具有 transfer UI profile 时插入欢迎摘要和来源选择 | 不修改其他 Agent 欢迎页行为 |
|
||||
| `ChatMessageList.vue` / `ChatMessageBubble.vue` | 渲染结构化 transfer 进度/结果卡,并抛出“打开面板”事件 | Chat 文本不是 ERP 写入授权 |
|
||||
| Vue Router `mode` query | `transfer-run`、`transfer-pending`、`transfer-unknown` 复用现有 `mode` 约定 | 深链必须校验 Agent 权限,不泄露对象 |
|
||||
| Job/Worker | 新增调拨 Job Handler,持久化 Run 后异步处理 | 页面关闭、SSE 断开不得取消 Run |
|
||||
| 现有 `requestJson` / `BusinessError` | 所有调拨 API 采用统一 envelope 和错误处理 | 不新建第二套 HTTP 客户端 |
|
||||
|
||||
## 3. 领域模型、状态与审计
|
||||
|
||||
### 3.1 最小实体
|
||||
|
||||
| 实体 | 关键字段 | 不可变规则 |
|
||||
| --- | --- | --- |
|
||||
| `TransferRun` | run_no、trigger(manual/automatic)、business_date、source_scope、status、conversation_id、config_version | 创建后来源范围、触发方式、版本快照不可改 |
|
||||
| `ReceiptFileVersion` | source_code、business_date、purpose、version、checksum、ready_at、object_key、parser_profile_version | 历史 Run 永远引用当时版本 |
|
||||
| `TransferPrecheck` | precheck_id、run_id、file snapshots、precheck_hash、expires_at、counts、total_quantity | 仅追加;过期或输入变化失效 |
|
||||
| `TransferInvoiceItem` | invoice_no、source、receipt_qty、erp_qty、status、erp_org、warehouse mapping、evidence refs | 数量、来源和映射不可由用户编辑 |
|
||||
| `TransferAttempt` | attempt_no、item_id、kind(precheck/requery/write)、before/after、result、operation_id | 每次重查/写入均新增,不覆盖 |
|
||||
| `TransferAuditEvent` | actor、time、action、object、before/after、diff、snapshot_hash、request_id、operation_id | 只追加;读取/下载同样记录访问审计 |
|
||||
|
||||
### 3.2 状态机
|
||||
|
||||
```text
|
||||
file_pending → prechecking → ready_to_confirm → executing → completed
|
||||
├→ blocked_recoverable → requerying → ready_to_confirm
|
||||
├→ not_matured (终态事实,不进入 ERP)
|
||||
├→ manually_closed → recoverable(仅恢复并记录原因)
|
||||
└→ result_unknown(只读终态)
|
||||
```
|
||||
|
||||
`ready_to_confirm` 必须持有未过期 `precheck_hash`。执行 Worker 写前重新查询 ERP;任何数量、映射、文件、状态或确认 Hash 不一致,都改为 `precheck_expired` / `blocked_recoverable`,ERP 写调用次数必须为 0。
|
||||
|
||||
## 4. 后端模块与 API 契约
|
||||
|
||||
### 4.1 建议模块边界
|
||||
|
||||
```text
|
||||
backend/app/services/in_transit_transfer/
|
||||
contracts.py # 请求/响应 DTO、快照 schema
|
||||
status_machine.py # 状态迁移及 fail-closed 门禁
|
||||
receipt_file_service.py # ensure_receipt_file_ready
|
||||
receipt_parser.py # 文件结构校验、原始行追溯
|
||||
precheck_service.py # 成熟过滤、汇总、ERP 查询、Hash
|
||||
execution_service.py # 写前复查、ERP 原子写入、结果投影
|
||||
backlog_service.py # 待处理/已关闭/结果未知投影
|
||||
recovery_service.py # 可恢复异常自动重新预检
|
||||
notification_service.py # 企业微信汇总与异常 Excel
|
||||
audit_service.py # 不可变审计、Diff、Hash
|
||||
erp_adapter.py # SOAP 边界;地址/凭据仅环境变量
|
||||
```
|
||||
|
||||
所有业务服务接收接口型 adapter、时钟和审计 sink;服务层不得解析聊天文本,不得把 SOAP XML 直接返回前端。
|
||||
|
||||
### 4.2 MVP API
|
||||
|
||||
所有 JSON 返回 `{ success, data | error, request_id }`。下列端点须 Agent 权限;仅配置端点额外需要管理员权限。
|
||||
|
||||
| 方法与路径 | 用途 | 核心门禁/响应 |
|
||||
| --- | --- | --- |
|
||||
| `GET /api/in-transit-transfer/summary` | 新对话欢迎摘要 | 待处理、结果未知、最近自动 Run;不返回敏感证据 |
|
||||
| `POST /api/in-transit-transfer/prechecks` | 创建手工预检 | 参数:业务日期、`source_codes[]`;无 Ready 文件时排队准备并立即返回 `run_id` |
|
||||
| `GET /api/in-transit-transfer/runs/{run_no}` | Chat/深链恢复 Run 投影 | 返回面板阶段、版本快照、汇总与授权动作 |
|
||||
| `GET /api/in-transit-transfer/runs/{run_no}/events` | 恢复进度 | 优先 SSE,失败时轮询同一 DTO;不创建第二个 Run |
|
||||
| `POST /api/in-transit-transfer/prechecks/{id}/confirm` | 保存用户选中范围和确认 | 校验 `precheck_hash`、过期时间、可执行项、ERP 组织;返回 execution run |
|
||||
| `POST /api/in-transit-transfer/runs/{run_no}/execute` | 投递执行 Job | 必须已有有效确认;重复点击无额外 ERP 副作用 |
|
||||
| `GET /api/in-transit-transfer/backlog` | 待处理侧栏 | `tab=recoverable|closed|unknown`,MVP 不支持 invoice 文本搜索 |
|
||||
| `POST /api/in-transit-transfer/items/requery` | 多选只读 ERP 重查 | 仅可恢复项;不更新文件、不写 ERP;匹配项返回新的确认集合 |
|
||||
| `POST /api/in-transit-transfer/items/{id}/close` | 无需继续处理 | 原因必填,转 `manually_closed` |
|
||||
| `POST /api/in-transit-transfer/items/{id}/restore` | 恢复已关闭项 | 原因必填,返回可恢复待处理状态 |
|
||||
| `GET /api/in-transit-transfer/items/{id}` | Invoice 证据抽屉 | 文件证据、Attempt、当前事实、允许动作 |
|
||||
| `GET /api/in-transit-transfer/runs/{run_no}/exception-file` | 下载固定异常 Excel | 下载审计;同一 Run 固定版本 |
|
||||
|
||||
错误至少包括:`TRANSFER_PERMISSION_DENIED`、`TRANSFER_FILE_NOT_READY`、`TRANSFER_RECEIPT_NOT_MATURED`、`TRANSFER_QUANTITY_MISMATCH`、`TRANSFER_PRECHECK_EXPIRED`、`TRANSFER_CONFIRMATION_REQUIRED`、`TRANSFER_RESULT_UNKNOWN`、`TRANSFER_MANUAL_REASON_REQUIRED`。
|
||||
|
||||
### 4.3 排程、文件与通知
|
||||
|
||||
- 08:00:每个来源独立准备收料文件;DBS RPA 失败不阻断 Crane Callback。
|
||||
- 09:00:每个来源独立自动预检;满足门禁的 Item 自动写 ERP;每个非空自动 Run 仅发一条企业微信汇总,并附固定七 Sheet 异常 Excel。
|
||||
- 调拨排程仅消费“当前业务日期最新 Ready 文件”;文件缺失才在 Run 创建前触发来源获取;Run 创建后冻结。
|
||||
- 历史 `blocked_recoverable` 每日建立新的预检 Attempt;`manually_closed` 跳过;`result_unknown` 永远跳过。
|
||||
- 通知失败记录 `notification_failed` 审计/运行事件,不改变任何 ERP 业务结果,不自动重试。
|
||||
|
||||
## 5. 前端模块与路由
|
||||
|
||||
### 5.1 路由
|
||||
|
||||
```text
|
||||
/chat/:agentId
|
||||
/chat/:agentId?mode=transfer-run&run_id=RUN-...
|
||||
/chat/:agentId?mode=transfer-pending
|
||||
/chat/:agentId?mode=transfer-unknown&item_id=...
|
||||
```
|
||||
|
||||
路由进入时只恢复既有 Run/侧栏投影。`mode` 不是授权;前端必须以 API 返回的 `actions` 决定按钮是否可见。关闭侧栏时只移除 query 中的 `mode/run_id/item_id`,保留 `conversation_id`、来源筛选、已选 Item、滚动位置。企业微信深链进入 `transfer-run`,不生成无内容的新会话。
|
||||
|
||||
### 5.2 前端文件规划
|
||||
|
||||
| 路径 | 内容 |
|
||||
| --- | --- |
|
||||
| `frontend/src/features/chat/transfer/api/transfer.api.ts` | `requestJson` API 封装 |
|
||||
| `frontend/src/features/chat/transfer/types/transfer.types.ts` | 后端 DTO、actions、状态联合类型 |
|
||||
| `frontend/src/features/chat/transfer/useChatTransfer.ts` | 路由同步、Run 轮询/SSE、面板开关、选择状态;不保存业务事实 |
|
||||
| `frontend/src/features/chat/transfer/components/TransferWelcomeSummary.vue` | 新会话摘要、来源卡和入口 |
|
||||
| `frontend/src/features/chat/transfer/components/TransferRunWorkbench.vue` | 右侧“本次调拨”,按阶段装配内容 |
|
||||
| `frontend/src/features/chat/transfer/components/TransferBacklogWorkbench.vue` | 待处理三 Tab、批量 ERP 重查 |
|
||||
| `frontend/src/features/chat/transfer/components/TransferUnknownWorkbench.vue` | 只读未知结果与 SOP |
|
||||
| `frontend/src/features/chat/transfer/components/TransferInvoiceDrawer.vue` | 证据、原始行、Attempt、审计 |
|
||||
| `frontend/src/features/chat/transfer/components/TransferConfirmPanel.vue` | 勾选确认、数量/单据数、过期处理 |
|
||||
| `frontend/src/features/chat/transfer/components/messages/*` | 对话内文件进度、预检、执行、结果的简洁卡片 |
|
||||
|
||||
修改 `ChatViewContent.vue` 仅增加一个 transfer 面板插槽和路由状态编排;不把调拨逻辑堆入该文件。修改 `ChatWelcomePanel.vue` 时只通过 profile/slot 对 transfer Agent 生效。四语言文案写入 `locales/{zh-CN,zh-TW,en,th}/chat.json` 和 `errors.json`。
|
||||
|
||||
## 6. 审计、权限与安全
|
||||
|
||||
| 节点 | 必留字段 |
|
||||
| --- | --- |
|
||||
| 创建预检/文件准备 | actor 或 schedule identity、来源、业务日期、文件版本/checksum、前后快照、request_id |
|
||||
| ERP 查询/重查 | item、收料数量、ERP 返回摘要、时间、Attempt、operation_id(如有) |
|
||||
| 确认与执行 | actor、选中范围、precheck_hash、确认有效期、映射快照、ERP 单号/结果 |
|
||||
| 关闭/恢复 | actor、必填原因、before/after、Diff、Hash |
|
||||
| 自动排程/通知/下载 | 排程身份、Run、接收人去重摘要、附件版本、通知结果、下载者 |
|
||||
|
||||
ERP/RPA URL、凭据、SOAP 原文敏感字段只能从环境变量/脱敏证据读取,绝不进聊天消息、前端 DTO、日志或审计明文。所有外部写失败关闭:未满足门禁不调用 ERP。
|
||||
|
||||
## 7. 分阶段交付与量化验收
|
||||
|
||||
| 阶段 | 交付目标 | 可验证验收 |
|
||||
| --- | --- | --- |
|
||||
| P0 契约与底座 | 模型、Alembic、状态机、审计、Fake ERP/RPA/WeCom | 非法迁移100%拒绝;写操作审计字段完整率100%;迁移升级/回滚通过 |
|
||||
| P1 Chat 预检 | 欢迎摘要、来源选择、文件进度、冻结预检与右侧面板 | 缺文件5秒内可见来源进度;当天项 ERP 查询次数0;多行汇总准确率100% |
|
||||
| P2 手动写 ERP | 部分勾选、确认、写前复查、执行/结果恢复 | 未确认/过期/变化预检 ERP 写次数0;成功与重复成功单号可追溯;关闭页面 Run 继续 |
|
||||
| P3 自动与异常 | 两个排程、待处理三 Tab、重查/关闭/恢复、Excel、企业微信深链 | 来源故障隔离;每非空自动 Run 通知1条;未知项自动写次数0;旧 Attempt 从不覆盖 |
|
||||
| P4 上线硬化 | 沙箱、故障恢复、归档、指标与 E2E | Worker 重启不重复成功;审计丢失率0;四语言/构建/专项测试/E2E全绿 |
|
||||
|
||||
## 8. 核心风险
|
||||
|
||||
**预检确认与 ERP 写入之间,ERP 库存或快照发生变化。** 即使不做多人控制,也必须靠冻结文件版本、10分钟确认有效期、写前 ERP 重查、服务端状态校验和 Invoice 幂等来保证变化项绝不写入。任何一层证据缺失均 fail-closed。
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# 在途仓自动调拨 Agent MVP:Chat 工作区 TDD 验证规范
|
||||
|
||||
> 本文件细化当前 MVP 的测试顺序。每个切片严格遵循 Red → Green → Refactor;先写失败测试,再写最小实现。旧版 TDD 中涉及独立 Workspace 调拨页、操作租约或人工 Invoice 搜索的内容不适用于本 MVP。
|
||||
|
||||
## 1. 不可突破的测试断言
|
||||
|
||||
- 当天收料、未确认、确认过期、文件/映射/数量变化、无权限:ERP 写调用次数均为 `0`。
|
||||
- ERP 库存只有严格相等才可执行;大于、小于、缺失均为 `0` 写入。
|
||||
- `result_unknown` 的自动/手工 ERP 重试、关闭、恢复和执行次数均为 `0`。
|
||||
- 每次 ERP 重查、自动预检、写入尝试新增 Attempt;历史 Attempt 的快照永不修改。
|
||||
- 所有业务操作与读取证据/下载均产生审计事件,包含 actor、时间、action、before、after、diff、hash、request_id。
|
||||
- 不实现多人占用/租约:并发请求不显示锁;仍必须断言服务端不会绕过状态门禁或 ERP Invoice 幂等。
|
||||
|
||||
## 2. 测试目录与固定 Fake
|
||||
|
||||
```text
|
||||
backend/tests/services/in_transit_transfer/
|
||||
conftest.py fakes.py factories.py
|
||||
test_receipt_file_service.py test_precheck_service.py
|
||||
test_execution_service.py test_backlog_service.py
|
||||
test_status_machine.py test_audit_service.py
|
||||
backend/tests/api/test_in_transit_transfer_api.py
|
||||
backend/tests/jobs/test_in_transit_transfer_jobs.py
|
||||
frontend/src/features/chat/transfer/**/*.spec.ts
|
||||
frontend/e2e/in-transit-transfer-chat-workbench.spec.ts
|
||||
```
|
||||
|
||||
`FakeERP` 记录 query/write 调用、Invoice、组织、数量、operation id,支持 `success`、`duplicate_success`、`business_failed(rolled_back)`、`timeout_unknown`。`FakeRPA` 分别模拟 DBS RPA 和 Crane Callback;`FakeWeCom` 记录一次汇总和附件。固定时钟为 Asia/Shanghai `2026-08-16 09:00`。
|
||||
|
||||
## 3. Red → Green 切片
|
||||
|
||||
| 切片 | 先写 Red 测试 | 最小 Green 实现 | Refactor 验收 |
|
||||
| --- | --- | --- | --- |
|
||||
| T1 文件准备 | 无 Ready 文件时 DBS 仅触发一次 RPA;Crane callback 不阻断 DBS;Run 后不允许替换文件 | `ensure_receipt_file_ready` 与来源级进度 | 提取共同 source adapter,不把 DBS/Crane 分支混入预检 |
|
||||
| T2 预检 | 当天不查 ERP;同 Invoice 多行汇总;数量不等阻断;快照 Hash 固定 | parser、aggregator、precheck service | Decimal 比较与日期策略变为纯函数 |
|
||||
| T3 Chat 投影 | 新会话显示摘要;预检在同一消息卡原位更新;右侧打开 Run | DTO、`useChatTransfer`、欢迎区/卡片 | 页面编排仅保留状态,不持久化事实 |
|
||||
| T4 确认与写入 | 可部分选择;未确认/过期/变化不写;写前重新查 ERP | confirm API、execution worker | 状态门禁集中在 service,不依赖按钮禁用 |
|
||||
| T5 结果恢复 | 页面关闭后 Run 继续;历史会话打开固定结果卡;重复 Invoice 显示原单号 | Run 投影 API、轮询/SSE 回退 | 统一 `mode=transfer-run` 路由恢复逻辑 |
|
||||
| T6 待处理 | 默认仅可恢复项;批量重查不抓文件/不写 ERP;关闭/恢复原因必填 | backlog API、三个 Tab、原因弹窗 | Attempt 时间线、筛选、动作授权解耦 |
|
||||
| T7 未知与自动 | 未知项无动作;自动 Run 每来源隔离;非空 Run 仅通知一次 | schedule handler、unknown panel、WeCom adapter | 通知与 ERP 结果状态分离 |
|
||||
|
||||
## 4. 前端组件测试
|
||||
|
||||
| 组件/Composable | 必测断言 |
|
||||
| --- | --- |
|
||||
| `TransferWelcomeSummary` | 显示待处理/未知/最近自动 Run;点击数字才请求并打开对应面板;无 Invoice 搜索输入 |
|
||||
| `TransferRunWorkbench` | 版本/checksum/数量/预计单据显示;`not_matured` 不显示 ERP 异常;关闭保留对话草稿 |
|
||||
| `TransferConfirmPanel` | 默认选中可执行项;阻断项不可选;取消部分后总数量和单据数同步;过期后只能重新预检 |
|
||||
| `TransferBacklogWorkbench` | 三 Tab;仅可恢复项可多选重查;重查后匹配项进入新确认区;不调用文件刷新 API |
|
||||
| `TransferUnknownWorkbench` | 无 requery/close/restore/execute DOM 元素;显示已知事实与 SOP |
|
||||
| `useChatTransfer` | `transfer-run` 深链展开面板;关闭时保留 conversation;权限失败不展示对象信息 |
|
||||
| Chat 消息卡 | 文件进度来源级显示;执行结果和 `notification_failed` 分离;同 Run 更新不新增历史卡 |
|
||||
|
||||
## 5. API、Worker 与审计测试
|
||||
|
||||
1. API:每端点覆盖成功、未授权、参数错误、过期快照、领域阻断、重复提交、审计写失败。统一断言 envelope 和 `request_id`。
|
||||
2. Worker:DBS 失败/Crane 成功;进程重启后按 ERP Invoice 幂等处理;超时未知时不再提交;停止只影响未开始项。
|
||||
3. 并发:同时提交同一确认的两个请求时,不使用锁提示;断言每个请求依据最新状态返回,ERP 的重复 Invoice 由 ERP 返回原单号,且系统不把它误投影为第二张成功单。
|
||||
4. 审计:对创建预检、文件选择、ERP 查询、确认、写入、关闭、恢复、通知、下载分别检查快照 Hash 可复算;敏感字段不出现在事件 payload。
|
||||
|
||||
## 6. E2E 场景
|
||||
|
||||
| 编号 | 场景 | 通过标准 |
|
||||
| --- | --- | --- |
|
||||
| E01 | 新会话选择 DBS+Crane,缺文件后看到来源级进度 | 同一对话卡原位完成,右侧预检显示冻结文件 |
|
||||
| E02 | 预检后只选择部分匹配 Invoice,确认并执行 | UI 数量正确;ERP fake 仅收到已选项;结果卡可重开 |
|
||||
| E03 | 当天收料和库存不等 | 不可选,ERP write=0 |
|
||||
| E04 | 欢迎页点击待处理,批量 ERP 重查 | 不发生 RPA/API 文件更新;匹配项进入确认,不自动写 ERP |
|
||||
| E05 | 关闭再恢复 | 原因必填、Attempt 追加、列表计数更新 |
|
||||
| E06 | 企业微信深链自动 Run | `mode=transfer-run` 打开指定 Run;无新对话、可下载固定 Excel |
|
||||
| E07 | 结果未知 | 只读 UI;所有禁用动作不存在;ERP write 不再发生 |
|
||||
|
||||
## 7. 命令与交付门槛
|
||||
|
||||
```powershell
|
||||
cd D:\Workspace\HxProjects\hxops\backend
|
||||
pytest tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py tests/jobs/test_in_transit_transfer_jobs.py
|
||||
|
||||
cd D:\Workspace\HxProjects\hxops\frontend
|
||||
npm run test:unit
|
||||
npm run build
|
||||
```
|
||||
|
||||
进入 UAT 前:上述专项测试、四语言校验、`git diff --check`、迁移升级/回滚、ERP 沙箱成功/重复/回滚/超时未知场景,以及全部 E2E 必须通过。任何 fail-closed 断言、审计完整性断言或 `result_unknown` 禁止动作断言失败,均不可上线。
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
# 在途仓自动调拨 Agent MVP:Chat 工作区 UI/UX 规格
|
||||
|
||||
> 范围:仓库管理人员。配置管理不属于本 MVP UI;它继续按现有库存来源管理/管理端规划。本文以当前 Chat 三栏布局、右侧 `ShippingWorkflowTimeline` 按需工作区和 `mode` 深链模式为实现基准。
|
||||
|
||||
配套可点击原型:[`in-transit-transfer-chat-workbench-mvp.html`](../../platform/in-transit-transfer-chat-workbench-mvp.html)。
|
||||
|
||||
## 1. 交互原则
|
||||
|
||||
1. 用户仍默认进入 Chat;不要求学习独立工作台导航。
|
||||
2. 对话用于意图、进度解释、结果摘要;选择、确认、ERP 写入和异常批处理只在右侧业务面板发生。
|
||||
3. 不让用户等待无反馈:没有 Ready 文件时,来源级阶段在同一条任务卡原位刷新。
|
||||
4. 右侧面板是同一业务对象的容器:当前 Run、待处理、结果未知各自独立,不能混写。
|
||||
5. 查看不阻塞任何人;不展示“被谁占用”。所有按钮都以服务端最新 `actions` 结果为准。
|
||||
|
||||
## 2. 页面与容器
|
||||
|
||||
| 编号 | 容器 | 触发 | 主要动作 |
|
||||
| --- | --- | --- | --- |
|
||||
| C0 | 新建对话欢迎页 | 无历史消息 | 来源选择、发起预检、打开待处理、打开结果未知、查看最近自动 Run |
|
||||
| C1 | 对话文件准备卡 | 创建预检且无 Ready 文件 | 查看来源进度;不可刷新文件 |
|
||||
| C2 | 对话预检结果卡 + 右侧本次调拨 | 预检完成 | 查看证据、部分勾选、确认执行 |
|
||||
| C3 | 对话执行卡 + 右侧本次调拨 | 确认后 | 查看逐项进度、停止未开始项 |
|
||||
| C4 | 固定结果卡 + 右侧结果 | Run 完成 | 单号、异常 Excel、证据、待处理跳转 |
|
||||
| B1 | 右侧待处理调拨 | 点击欢迎页待处理笔数 | Tab、批量 ERP 重查、关闭、恢复、查看证据 |
|
||||
| B2 | 右侧结果未知 | 点击欢迎页未知数或深链 | 只读事实、Operation ID、人工 SOP |
|
||||
| A1 | 指定自动 Run 详情 | 企业微信深链/最近自动 Run | 来源结果、固定 Excel、异常进入待处理 |
|
||||
|
||||
## 3. 线框与行为边界
|
||||
|
||||
### C0 新建对话欢迎页
|
||||
|
||||
```text
|
||||
┌──────────────────────────────── Chat 主区 ───────────────────────────────┐
|
||||
│ 在途仓自动调拨 │
|
||||
│ 今天:最近自动运行 AUTO-... 成功18 待处理6 结果未知1 [查看本次结果] │
|
||||
│ │
|
||||
│ 发起预检 │
|
||||
│ [✓ DBS 收料] [✓ Crane 收料] 可多选,但每来源独立处理 │
|
||||
│ [选择业务日期:昨天 ▼] [发起调拨预检] │
|
||||
│ │
|
||||
│ [待处理调拨 6 笔] [结果未知 1 笔] │
|
||||
│ 当天收料不可调拨;仅收料数量与 ERP 账面库存完全一致才可写入。 │
|
||||
├──────────────────────────────────────────────────────────────────────────┤
|
||||
│ 输入框:例如“说明 DBS 昨天为什么不能调拨” │
|
||||
└──────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 仅在 transfer Agent 的新会话显示;加载中用摘要骨架屏,失败显示“暂无法取得摘要”,仍允许用户发送普通查询。
|
||||
- DBS/Crane 不默认假定同一份文件;用户可选择一个或两个来源。业务日期默认昨天,但可选择更早日期;当天不可提交并说明原因。
|
||||
- “待处理调拨 N 笔”只有计数,不提供 Invoice 搜索框。点击后才拉取列表。
|
||||
|
||||
### C1 文件准备与 C2 预检
|
||||
|
||||
```text
|
||||
Chat 任务卡 右侧:本次调拨
|
||||
┌──────────────────────┐ ┌────────────────────────────┐
|
||||
│ 正在准备收料文件 │ │ PRE-... / 正在预检 │
|
||||
│ DBS ● RPA 导出完成 │──完成后原位更新──▶ │ 文件:DBS-v3 / checksum… │
|
||||
│ Crane ◌ 等待回调 │ │ 可执行24 阻断3 未成熟2 │
|
||||
│ 本任务文件一旦选定即冻结│ │ 总数量18,540 / ERP写入24 │
|
||||
└──────────────────────┘ │ [查看文件] [查看明细] │
|
||||
│ [进入确认] │
|
||||
└────────────────────────────┘
|
||||
```
|
||||
|
||||
- 不新建第二条聊天历史,原卡按 Run 投影更新。
|
||||
- DBS/Crane 进度分别显示,不伪造总百分比;一方失败时另一方继续。
|
||||
- 右侧预检中显示 `not_matured` 为灰黄“当天收料,未进入 ERP 查询”,不标为系统错误。
|
||||
|
||||
### C2 确认面板
|
||||
|
||||
```text
|
||||
┌────────────────────── 本次调拨 / 确认执行 ──────────────────────┐
|
||||
│ 文件 DBS-v3 · 业务日期 2026-08-15 · 预检有效至 10:32 │
|
||||
│ ERP组织 CN01 | 来源仓 DBS-TRANSIT | 目标仓 HUB-SZ(均只读) │
|
||||
├──────────────────────────────────────────────────────────────────┤
|
||||
│ ☑ INV-001 收料500 ERP500 可执行 │
|
||||
│ ☑ INV-002 收料1200 ERP1200 可执行 │
|
||||
│ ☐ INV-003 收料300 ERP280 数量不一致(不可选) │
|
||||
│ ☐ INV-004 收料400 - 当天收料(不可选) │
|
||||
├──────────────────────────────────────────────────────────────────┤
|
||||
│ 已选 2 张 | 预计调拨总数量 1,700 | 预计 ERP 写入 2 张 │
|
||||
│ [返回预检] [执行调拨] │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 默认全选全部可执行项,允许取消部分。选中项必须同一 ERP 组织;跨组织时按组织生成分别确认区,不可合并写入。
|
||||
- 点击执行前先展示面板内确认态,明确数量、单据数、仓库与过期时间;确认后才投递 Worker。
|
||||
- 确认过期或写前复查变化:按钮变为“重新预检”,不允许旧快照继续执行。
|
||||
|
||||
### C3 执行与 C4 结果
|
||||
|
||||
```text
|
||||
Chat:09:20 已开始写 ERP;关闭页面不会取消后台任务。
|
||||
右侧:RUN-...
|
||||
已处理18/24 成功16 失败1 处理中1
|
||||
INV-001 成功 TR-10001
|
||||
INV-003 数量不符 [查看证据]
|
||||
[停止未开始项]
|
||||
```
|
||||
|
||||
- Chat 每个阶段只追加简洁事件;右侧提供可验证的逐项结果。
|
||||
- 结果卡固定保留在历史会话中;再次打开该会话可按 `run_id` 恢复右侧详情。
|
||||
- `notification_failed` 只在通知一行显示,不改变“ERP 已完成/失败”的主结论。
|
||||
|
||||
### B1 待处理调拨
|
||||
|
||||
```text
|
||||
┌────────────────────────── 待处理调拨 ───────────────────────────┐
|
||||
│ [可恢复异常 6] [已人工关闭 2] [结果未知 1] │
|
||||
│ 来源:全部 ▼ 业务日期:全部 ▼ │
|
||||
├──────────────────────────────────────────────────────────────────┤
|
||||
│ □ DBS | 08-14 | 数量不一致 | 收料300 / ERP280 | 最近查 09:12 │
|
||||
│ □ Crane| 08-13 | 无库存 | 收料500 / ERP0 | 最近查 09:12 │
|
||||
├──────────────────────────────────────────────────────────────────┤
|
||||
│ [重新查询 ERP 库存(2)] [标记无需继续处理] │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 默认 Tab 为可恢复异常。已关闭仅提供“恢复处理”;结果未知 Tab 不提供任何更改业务状态的按钮。
|
||||
- 可恢复项可多选、统一重查 ERP;重查不抓 RPA、不改文件、不写 ERP。匹配项在右侧就地形成新的确认区;未匹配项仍留在列表,展示新的查询时间与 Attempt。
|
||||
- 关闭/恢复用原因对话框。原因为空,提交按钮禁用;成功后列表、徽标、审计原位更新。
|
||||
|
||||
### B2 结果未知与 A1 自动 Run
|
||||
|
||||
```text
|
||||
结果未知(只读)
|
||||
Invoice:INV-005 调用时间:09:17 Operation ID:OP-xxx
|
||||
已知:ERP 未返回确定成功或失败;系统无法确认是否已产生单据。
|
||||
[查看脱敏证据] [查看人工核实 SOP] 无重查/关闭/恢复/执行按钮
|
||||
|
||||
自动 Run 深链:/chat/:agentId?mode=transfer-run&run_id=AUTO-...
|
||||
进入后自动展开右侧本次运行详情,不创建会话,不落到泛化首页。
|
||||
```
|
||||
|
||||
## 4. 页面跳转矩阵
|
||||
|
||||
| ID | 起点 | 触发 | 终点 | 必传上下文 | 返回规则 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| N01 | C0 | 发起预检 | C1/C2 | `conversation_id, run_id, source_codes, business_date` | 同会话原位更新 |
|
||||
| N02 | C1 | 文件就绪 | C2 | `run_id, file_version, checksum, config_version` | 禁止刷新/替换文件 |
|
||||
| N03 | C2 | 进入确认 | C2确认态 | `precheck_id, precheck_hash, selected_item_ids` | 保留勾选与滚动位置 |
|
||||
| N04 | C2确认态 | 执行调拨 | C3 | `execution_run_id, confirmation_audit_id` | 重载后恢复同一 Run |
|
||||
| N05 | C3 | 完成 | C4 | `run_id, result_summary, exception_file_version` | 结果卡永久留历史会话 |
|
||||
| N06 | C0 | 点击待处理数 | B1 | `mode=transfer-pending, tab=recoverable` | 关闭面板回 C0,不清空草稿输入 |
|
||||
| N07 | B1 | 批量重查 | B1/确认区 | `item_ids, query_attempt_ids, frozen_file_refs` | 不得跳转至 RPA 抓取 |
|
||||
| N08 | B1 | 查看证据 | Invoice 抽屉 | `item_id, return_context` | 抽屉关闭精确恢复 Tab/筛选/滚动 |
|
||||
| N09 | C0/企业微信 | 查看自动 Run | A1 | `mode=transfer-run, run_id, notification_id` | 不创建新会话 |
|
||||
| N10 | 任意 | 查看未知项 | B2 | `mode=transfer-unknown, item_id` | 仅关闭返回;无业务动作跳转 |
|
||||
|
||||
禁止:运行中更新文件;异常 ERP 重查直接写 ERP;`result_unknown` 到关闭/恢复/确认;配置变化覆盖历史 Run;通过 URL 参数绕过权限或确认。
|
||||
|
||||
## 5. 响应式与可访问性
|
||||
|
||||
- 桌面端右侧面板宽度沿用当前可折叠工作区,最小 360px;聊天区始终保留。
|
||||
- 平板/移动端不双栏:打开面板后全屏覆盖 Chat,顶部有“返回对话”和当前 Run 名称;确认主按钮固定在底部安全区。
|
||||
- 所有状态均有文字和图标,不能只靠颜色;焦点顺序为摘要→来源→发起→面板表格→操作。
|
||||
- 长时间操作允许关闭页面,重新进入使用轮询恢复;明确显示“后台仍在处理”。
|
||||
@@ -76,6 +76,15 @@
|
||||
- 匹配结果有缺口时,缺货预约单继续等待补货;本轮已满足预约单仍可进入滚动制单
|
||||
- 至少一个预约单满足时,生成包含全部当前可用预约单的**本轮发货 Excel**,并完成该文件的货代上传
|
||||
|
||||
### 四阶段工作台速查(2026-08)
|
||||
|
||||
- **接收解析**:核对邮件正文、当前附件和解析异常;模板匹配只在这里查看。需要替换文件或重新识别时,按“当前处理”提示操作。
|
||||
- **订单复核**:核对订单字段、客户、冲突、重复和 Reservation;此阶段不处理库存数量或上传。
|
||||
- **通知准备**:查看已经冻结的订单、每行库存来源/需求/可用/缺口和通知 Excel 状态;尚未生成匹配结果时,以右侧“当前处理”的提示为准。
|
||||
- **通知完成**:下载 Excel、按右侧“当前处理”登记人工上传或重试,并查看最近上传尝试与货代回执。进入本阶段不表示已经上传成功;只有系统显示已确认的上传结果才可视为完成。
|
||||
|
||||
同一问题只在右侧 **“当前处理”** 提供一个主操作按钮;页面中其他区域用于查看明细或填写被该按钮打开的表单,避免重复点击不同入口。
|
||||
|
||||
**系统如何工作(便于理解)**:
|
||||
|
||||
- 上传 **发货通知 EML/PDF/Word** 后,系统先自动读取正文和附件;点击发送后完整订单识别在后台执行,不依赖聊天连接持续在线。进行中显示不确定进度,不展示虚假百分比;失败附件会回到可重试入口。每份 PDF 均须在复核工作台确认对应草稿版本后独立创建任务;识别可信不替代人工确认。
|
||||
|
||||
@@ -7,7 +7,20 @@
|
||||
|
||||
## 四阶段 UI 状态契约(2026-08)
|
||||
|
||||
业务人员只看到四个阶段:`intake_parse`(接收解析)→ `order_review`(订单复核)→ `fulfillment_prep`(发货准备)→ `upload_complete`(上传完成)。`ui_state` 是唯一前端读模型;Gate/Execution 是业务门禁真相;按钮统一由后端 `ui_state.actions.primary/secondary` 提供,前端不得根据领域字段自行推导阶段或按钮;`process_status` 已删除。
|
||||
业务人员只看到四个阶段:`intake_parse`(接收解析)→ `order_review`(订单复核)→ `fulfillment_prep`(通知准备)→ `upload_complete`(通知完成)。`ui_state` 是唯一前端读模型;Gate/Execution 是业务门禁真相。正式 Task 的操作使用 `ui_state.actions.primary/secondary`,批次 / 生命周期投影的操作使用 `ui_state.primary_action/secondary_actions`;两者均由后端下发,前端不得根据领域字段自行推导阶段或按钮;`process_status` 已删除。
|
||||
|
||||
### 四阶段工作面与动作宿主(2026-08)
|
||||
|
||||
- 接收解析只展示邮件/附件、解析证据和替换/重解析处置;模板匹配只在该阶段展示。
|
||||
- 订单复核只展示字段、客户、冲突、重复和 Reservation 人工裁决;不得展示库存数量、缺口或上传操作。
|
||||
- 通知准备只展示冻结订单、库存匹配行和 Excel 产物状态。任务详情的 `ui_state.stage_context.preparation` 是只读摘要;未生成匹配结果时必须明确显示当前 Gate,不能显示“处理结果已完成”。
|
||||
- 通知完成只展示 Excel、最新上传 Attempt 和回执。`upload_complete` 只是第四阶段工作面;只有可追溯 `ShippingUploadAttempt.status=succeeded` 才是上传成功。人工登记必须同时提交回执号和证据资产。
|
||||
- 桌面右栏 `ReviewCurrentProcessingCard` 是每个 Gate 唯一全局写入口;主区仅显示事实、行级局部操作或被右栏定位的裁决表单。`TaskTodoPanel` 在生命周期工作台仅作无界面动作执行宿主,禁止重复渲染 Gate 或主按钮。
|
||||
- `stage_context` 不落库、不驱动状态、不授权动作,仅由正式任务详情与单票 `/ui-state` 按需返回;任务列表、聊天轻量投影不加载它,以避免 N+1 查询。
|
||||
|
||||
### Dify 配置边界(2026-08)
|
||||
|
||||
本次四阶段工作面调整**无需修改 Dify**。Dify 不能创建/推进 Gate,不能确认客户、裁决订单、匹配库存、生成 Excel、上传货代或登记回执;这些写入只由 HXOPS 服务端 Gate 校验后的工作台动作执行。若管理员维护现有 `shipping_notice` Chatflow,仍只能保留只读 `get_task_status` Tool,并原样传递 HXOPS 注入的短效能力令牌;发现任何写 Tool 或由 Dify 推断“已完成”时,应停止发布并移除。
|
||||
|
||||
## 2026-07-31 订单解析增强最终实施方案(待实施)
|
||||
|
||||
@@ -1657,6 +1670,7 @@ GET /api/admin/shipping-order-schema/published-contract
|
||||
- 批量测试创建时各站点先处于 `awaiting_rpa / waiting_worker`。Windows Worker 实际领取某个站点前,会向 `POST /api/shipping-notice/rpa/inventory-configuration-test-batch-progress` 回调该站点的 `validation_run_no` 与受控阶段 `rpa_exporting`;后端仅允许将当前批次的非终态运行写为 `processing / rpa_exporting`。因此管理端可以区分“尚未被 Worker 领取”和“RPA 正在登录并导出”;最终成功、无库存或失败仍必须通过原有 `inventory-configuration-test-batch-ready` 回调确认,进度回调不得覆盖终态。同一 Profile 仍只登录一次,但每个 DSV 站点使用新的页面并复用同一 browser context 的登录 Cookie,避免上一站报表 iframe、下载菜单或等待状态污染下一站。
|
||||
- 测试运行超过 `SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS`(默认 900 秒)仍未完成时,服务端在读取或再次发起测试时将其收口为 `failed / failed`,提示“等待 RPA Worker 超时,请重新测试”。同一 Worker 队列中的批量站点按队列站点数线性扩展等待窗口,避免后排站点尚未领取就按单站时限误判超时;单站测试仍使用原始等待窗口。超时、版本不一致和重复/迟到回调都不能更新当前站点绑定或放行启用。**Dify 手动配置说明**:此恢复与轮询机制不要求修改 Dify 画布、Tool 或 Prompt;Dify 不读取此管理端状态接口。
|
||||
- **DSV SSO 回跳优化(2026-07)**:密码提交后,Worker 将 `auth.dbschenker.com` 的授权回跳与 Portal Reports 菜单加载分开计时。空白 `authorization.ping/oauth2` 中转页停留 `SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS`(默认 12000)后只刷新一次;超过 `SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS`(默认 90000)仍未回到 Portal 时,明确报 `DSV SSO authorization return timed out`,不再伪装为库存测试超时。Portal 壳层出现后仅轮询 Reports 导航,避免反复读取整页与 iframe。Dify 无需修改配置。
|
||||
- **DSV 性能证据与快速路径(2026-08)**:库存导出 Worker 以 `[dsv-chain]` 输出不含凭据和查询参数的 `session_prepare`、`report_navigation`、`report_parameter_fill`、`report_execute_and_download`,并将最后一段拆为 `report_result_ready` 与 `excel_export_and_download` 的 `start/end/error` 与 `elapsedMs`;登录内层继续输出 `auto_login.*` 子阶段,Warehouse option 等待继续输出 `waitedMs`。提交 View Report 后直接等待 SSRS 业务就绪条件,不以可能被长连接阻塞的 `networkidle` 作为前置条件。Reports 级联菜单先走一次精确文本的 hover/click 快速路径,只有未确认下一级已展开时才退回原多 selector、多动作兼容链;不得因优化删除回退逻辑。一次真实运行据此区分认证/首页、报表菜单/参数页、参数异步加载、SSRS 结果与 Excel 导出下载耗时。
|
||||
- 多个 Inventory Source 可绑定同一个 published Profile;同模板只维护一份。存在少量列差异时创建新 Profile 版本或新 Profile,不在 Source 中复制完整映射。
|
||||
- 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。
|
||||
- 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingInventoryExternalMapping`,绝不自动创建映射。
|
||||
@@ -1707,7 +1721,7 @@ GET /api/admin/shipping-order-schema/published-contract
|
||||
|
||||
### 发货任务处置生命周期
|
||||
|
||||
- 业务人员只看到四阶段:`订单解析 → 订单复核 → 通知准备 → 通知完成`;Gate/Execution 是业务判断真相,`ui_state` 是唯一前端读模型,任务处置使用独立的 `lifecycle_status=active|voided|archived`。
|
||||
- 业务人员只看到四阶段:`接收解析 → 订单复核 → 通知准备 → 通知完成`;Gate/Execution 是业务判断真相,`ui_state` 是唯一前端读模型,任务处置使用独立的 `lifecycle_status=active|voided|archived`。
|
||||
- 用户点击删除时,服务端以任务行锁重算资格并写入 `ShippingTaskEvent` 审计(操作者、请求 ID、原因和处置前后事实)。纯误建任务仅进入回收站;已有业务单、Candidate 消费、库存链接或导出 Artifact 的任务同时设为 `voided` 后进入回收站。存在修订后继的任务禁止 delete/void,只允许 archive,避免破坏版本链。
|
||||
- `upload_status` 为 queued/pending/running/uploading/uploaded/succeeded/success、存在货代参考号/回执时,平台禁止 delete/void,只允许 archive。异步编排、队列、RPA 回调和上传入口必须统一检查 `task_is_active`。
|
||||
- 回收站只允许恢复仍为 `active` 的纯误建任务;已作废或已归档任务不得恢复,必须走受控新建/修订业务流程。永久删除仅在第五阶段实现,并重新检查全部引用。
|
||||
@@ -2197,6 +2211,8 @@ volumes:
|
||||
|
||||
同一 Windows 用户通过两个独立计划任务同时运行 test/prod。每个任务调用 `start_rpa_worker.ps1`,只给对应 Worker 子进程注入环境变量;Secret 使用当前用户 DPAPI 文件保存,不写入用户级或机器级环境变量。
|
||||
|
||||
DSV 库存导出默认使用一次性浏览器 Profile。仅在一个对应环境 Worker 运行时,启动命令可显式追加 `-ReuseDsvSession`:Worker 只为 DSV 库存任务保留独立 `dsv360_session` Profile,后续任务会优先复用登录态;会话失效仍回落现有登录流程。Crane 与上传任务保持一次性 Profile,且不得并发启动两个共享同一 WorkerRoot 的 Worker。
|
||||
|
||||
Windows 如禁止运行 `.ps1`,仅对单次 Secret 创建使用临时 Bypass:
|
||||
|
||||
```powershell
|
||||
@@ -2437,7 +2453,7 @@ Task 工作台 = 非主界面,仅保留备用深链
|
||||
|
||||
- **对话工作台(`chat`)**:主上传入口、解析摘要 / Candidate / Task 进度 / Process Gate 业务卡片;会话右侧「**本次处理中**」为会话级状态投影(Run / Candidate / Task / Process Gate,支持多对象与当前 Task 聚焦)。轻量操作(客户确认、重试、人工接管、刷新)**只调用正式 Workspace API**,禁止前端本地改业务状态或推导进度百分比。纯 `open_existing` 显示「发现重复文件,已关联已有任务」。文档投影含 `duplicate_resolution` / `existing_task_no` / `opened_existing_documents`。**不**挂载顶部批次进度条与右侧批次履约抽屉作为主路径。
|
||||
- **人工复核工作台(`review`)**:复杂字段/明细/证据/冲突/LLM/库存异常的深度写入口;确认建单后优先**返回原对话并聚焦 Task**,走与直通相同的后台 `auto_progress` 链。资格摘要与对话卡片数据同源 Candidate Qualification。
|
||||
- **Task 备用深链(`task_deep_link`)**:路由 `/workspace/shipping-notice/tasks/:taskNo` **不进入主导航**;仅用于对话删除后恢复、外部深链、管理员排查、运维诊断。履约写操作仍以后端状态机与正式 API 为准;业务按钮只消费 `ui_state.actions.primary/secondary`。
|
||||
- **Task 备用深链(`task_deep_link`)**:路由 `/workspace/shipping-notice/tasks/:taskNo` **不进入主导航**;仅用于对话删除后恢复、外部深链、管理员排查、运维诊断。履约写操作仍以后端状态机与正式 API 为准;正式 Task 按钮只消费 `ui_state.actions.primary/secondary`,批次 / 生命周期按钮只消费同一投影的 `primary_action/secondary_actions`。
|
||||
- **我的待办**:跨会话聚合待复核 / 异常 / 待人工上传;徽标与列表同源后端 `todo_category`;打开后深链进入复核或对话聚焦,**不以 Task 工作台为默认主区**。
|
||||
- 服务端状态机(含 `checkpoint_kind`)、审计与乐观锁是唯一裁决;Chat Turn 履约写路径标记废弃,逐步拆除。
|
||||
- 对话侧所有写操作必须带 `request_id` / 幂等键并写入审计;自动推进节点顺序与重试上限由后端固定,前端只展示投影。
|
||||
@@ -2852,7 +2868,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui
|
||||
- 所有 Tool 接口均为 `POST`
|
||||
- 需要同时支持 `batch_id/batch_no` 与 `task_id/task_no`
|
||||
- `submit_decision`、`get_task_status` 允许用 `conversation_id` 辅助定位任务
|
||||
- 统一返回 `status/message/data`,可能附带 `checkpoint`、`human_options`;业务按钮统一由 `ui_state.actions.primary/secondary` 返回
|
||||
- 统一返回 `status/message/data`,可能附带 `checkpoint`、`human_options`;正式 Task 的业务按钮由 `ui_state.actions.primary/secondary` 返回,批次 / 生命周期投影的按钮由 `ui_state.primary_action/secondary_actions` 返回
|
||||
|
||||
当前 Dify 目标导出接口:
|
||||
|
||||
@@ -3017,7 +3033,7 @@ API 层
|
||||
- **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值)
|
||||
- Worker:`scripts/rpa/freight_rpa_worker.py` → `_handle_inventory_batch_trigger`
|
||||
- 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready`
|
||||
- **回调响应语义**(2026-07):`status` 恒为 `ok`(payload 合法且回调处理完成);**业务成败**看顶层 `result_status` 或 `data.result_status`(`success` / `partial_failed` / `failed`),全失败回调也是 `status=ok` + `result_status=failed`。**排程场景**(含 `schedule_run_id` 且 finalize 成功)时 `result_status` 与 `ScheduleRun.status` 一致;`data.callback_result_status` 保留仅按回调 results 计算的原始结果。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。
|
||||
- **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts/<callback_id>/`、创建 `shipping_inventory_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。
|
||||
- 定时排程:`schedule_type=platform_job`,`platform_api_path=shipping-inventory-rpa`,`data_source_type=null`;建议 cron `0 3 * * *`(Asia/Shanghai)
|
||||
- 排程语义:`data_source_type` 仅用于 `schedule_type=data_pipeline`(`database` | `external_api`);平台任务通过 Job Registry 注册,由 `platform_api_path` 引用 job key
|
||||
|
||||
@@ -3256,7 +3272,7 @@ Case 状态:`unreviewed`、`draft`、`ready`、`confirming`、`confirmed`、`n
|
||||
|
||||
- PDF 工具栏采用左侧编辑操作、中间上一页/页码/下一页、右侧缩放操作的固定布局;页码输入支持大页数文档直接跳转,页面标记只按精确页码渲染。
|
||||
- 历史 `all_pages` 草稿缺少原始页码时按第 1 页恢复,重新保存后统一写入 `exact_page + page_no`,避免第 1 页标记泄漏到第 2 页。
|
||||
- 自动标记优先从 PDF 原生文字层补齐字符坐标与页面尺寸,仅在原生文字层为空时调用 OCR;补证结果仍属于待人工复核证据。
|
||||
- 自动标记统一通过 `shipping_pdf_automark` Job 和 `/pdf-automark` API 执行:浏览器不按 XFA/普通 PDF 选择入口,统一轮询 `candidates[] / diagnostics / status` 并投影到同一画布候选状态。执行器读取已持久化 Profile 能力而非客户端类型:普通 PDF 优先从 PDF 原生文字层补齐字符坐标与页面尺寸,仅在原生文字层为空时调用 OCR;补证结果仍属于待人工复核证据。含 XFA datasets 的 PDF 以 `/XFA datasets` 为唯一正式值源,使用 PDFium 原生渲染页、AcroForm Widget 和 RapidOCR 三类独立视觉证据:Widget 与 OCR 必须分别采集后再融合,OCR 用于识别用户实际可见文字、校验 datasets/Widget 并补足无 Widget 字段。XFA shipping Worker 启动前必须验证 `RapidOCR + OpenCV + NumPy + ONNX Runtime`,不完整运行环境不得消费 `shipping` 队列;任何候选均保持 `suggested/needs_review`,仅人工确认后可成为视觉绑定,且绝不替代 datasets 正式解析。最终保存/正式解析时,只有含 datasets 的模板额外走 datasets + 拆分规则;普通模板保持既有坐标规则。
|
||||
- 订单级字段的 `anchor` 只用于定位字段、唯一性校验和停止标签上下文;管理员在画布确认的 `absolute_value_region`(归一化页面坐标)是唯一值读取边界,后端不得再按实际匹配到的标签 bbox 投影、缩放或偏移该值框。新草稿必须写入 `absolute_value_region`,不再写入锚点相对的 `value_region`;历史 Profile 的 `value_region` 仅在缺少绝对值框时兼容读取。删除后重新标注也必须直接持久化新的绝对值框,禁止从锚点 bbox 反算,避免零高度、非法偏移及画布与读取结果不一致。多行值仅在绝对值框内按视觉行读取,并在当前锚点后的首个停止标签前截断。
|
||||
- 模板当前样本验证与结果面板必须按 `order_field_layouts` 的页域读取全部订单头字段:`exact_page` 读取指定页,`all_pages` 展开冻结坐标证据中的全部页面。跨页同字段同值合并,不同值标记 `order_field_page_value_conflict`;必填订单头未得到 confirmed 值时当前样本验证失败。单页编辑器仍只读取当前页,不改变正式解析算法。
|
||||
- 明细删除文字不是全局硬编码删除规则。只有管理员用表区 `exclusion_regions` 显式圈定且区内文字精确匹配 `** Item deleted **` 时,该标记才授权把前一条逻辑明细设为 `deleted`;没有配置区或标记位于区外时忽略该文字,不删除有效明细。普通排除区内容仍仅从字段候选中剔除。
|
||||
|
||||
+2
-2
@@ -6,8 +6,8 @@
|
||||
|
||||
- 接收解析:接收、解析和抽取订单字段。
|
||||
- 订单复核:核对订单并确认正式建单。
|
||||
- 发货准备:库存处理、匹配和生成发货通知 Excel。
|
||||
- 上传完成:上传通知或登记上传回执。
|
||||
- 通知准备:库存处理、匹配和生成发货通知 Excel;展示冻结订单、行级库存/缺口和 Excel 状态。
|
||||
- 通知完成:上传通知或登记上传回执;仅服务端确认的上传 Attempt 成功后显示完成结果。
|
||||
|
||||
- 平台把文本提交给 Dify 后,会继续确认 Dify 的 `indexing_status`;只有 `completed` 才展示“同步:已完成”。
|
||||
- Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<!--
|
||||
用途:在途仓自动调拨 Agent MVP 的完整可点击 UI/UX 原型。
|
||||
依赖:独立 HTML、原生 CSS、原生 JavaScript;布局复用当前 HXOPS Chat 的左侧会话、中心对话、右侧按需工作区模式。
|
||||
逻辑:仅模拟前端页面状态与页面跳转;不调用 RPA、ERP、企业微信或任何真实接口。
|
||||
-->
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>HXOPS · 在途仓自动调拨 Agent MVP 原型</title>
|
||||
<style>
|
||||
:root { --page:#f7f9fc; --surface:#fff; --soft:#f4f7fb; --line:#e4e9f1; --ink:#172033; --text:#45536a; --muted:#8190a6; --brand:#1677d2; --brand-soft:#edf6ff; --good:#17834c; --good-soft:#eaf8f0; --warn:#b77910; --warn-soft:#fff7e8; --bad:#c43d55; --bad-soft:#fff0f2; --shadow:0 12px 28px rgba(20,42,70,.07); }
|
||||
* { box-sizing:border-box; } html,body,#app { width:100%; height:100%; margin:0; } body { min-width:1120px; font:13px/1.48 "Microsoft YaHei","PingFang SC",Arial,sans-serif; color:var(--text); background:var(--page); } button,input,select,textarea { font:inherit; } button { cursor:pointer; } button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible { outline:3px solid rgba(22,119,210,.2); outline-offset:2px; }
|
||||
.hidden { display:none!important; } .app { display:flex; height:100%; overflow:hidden; } .chat-nav { width:264px; flex:none; background:var(--surface); border-right:1px solid var(--line); display:flex; flex-direction:column; } .brand { height:66px; display:flex; align-items:center; gap:10px; padding:0 18px; border-bottom:1px solid var(--line); } .brand-mark { width:34px; height:34px; display:grid; place-items:center; border-radius:11px; background:linear-gradient(135deg,#1683db,#2366c9); color:#fff; font-weight:800; font-size:12px; } .brand b { display:block; color:var(--ink); font-size:15px; } .brand span { display:block; margin-top:1px; font-size:10px; color:var(--muted); } .new-chat { margin:14px; border:1px solid #b8d9f6; border-radius:9px; padding:9px 11px; color:#1265ad; background:var(--brand-soft); font-weight:700; text-align:left; } .nav-label { padding:9px 17px 5px; color:#9aa7b9; font-size:10px; font-weight:700; letter-spacing:.06em; } .history { padding:0 9px; overflow:auto; } .history-item { position:relative; width:100%; border:0; border-radius:9px; padding:9px 10px; color:var(--text); background:transparent; text-align:left; } .history-item:hover { background:var(--soft); } .history-item.active { background:var(--brand-soft); color:#1265ad; } .history-item b,.history-item span { display:block; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } .history-item b { font-size:12px; } .history-item span { margin-top:2px; color:var(--muted); font-size:10px; } .history-item i { position:absolute; right:10px; top:12px; width:7px; height:7px; border-radius:100%; background:#efa534; } .history-item i.bad { background:#d95165; } .nav-user { margin-top:auto; border-top:1px solid var(--line); padding:13px 16px; display:flex; align-items:center; gap:8px; } .avatar { width:30px; height:30px; display:grid; place-items:center; border-radius:50%; color:#1565ac; background:#def0ff; font-weight:800; } .nav-user b,.nav-user span { display:block; } .nav-user b { color:var(--ink); font-size:11px; } .nav-user span { color:var(--muted); font-size:10px; }
|
||||
.chat-shell { display:flex; flex:1; min-width:0; flex-direction:column; background:var(--surface); } .chat-top { height:66px; flex:none; display:flex; align-items:center; gap:10px; padding:0 24px; border-bottom:1px solid var(--line); } .agent-avatar { width:32px; height:32px; display:grid; place-items:center; border-radius:10px; background:#e9f5ff; color:var(--brand); font-weight:800; } .agent-info b { color:var(--ink); } .agent-info span { display:block; margin-top:1px; color:var(--muted); font-size:10px; } .top-right { margin-left:auto; display:flex; align-items:center; gap:8px; } .small-chip { border:1px solid var(--line); border-radius:999px; padding:4px 8px; background:#fff; color:var(--muted); font-size:10px; } .small-chip.active { border-color:#b9daf5; color:#1265ad; background:var(--brand-soft); } .chat-layout { display:grid; grid-template-columns:minmax(0,1fr) 0; flex:1; min-height:0; transition:grid-template-columns .22s ease; } .chat-layout.workbench-open { grid-template-columns:minmax(420px,38fr) minmax(620px,62fr); } .message-zone { display:flex; min-width:0; flex-direction:column; } .workbench-open .message-zone { border-right:2px solid #abd4f4; box-shadow:inset -12px 0 20px -22px rgba(20,79,128,.7); } .messages { flex:1; overflow:auto; padding:26px max(28px,7%); background:#fff; transition:padding .22s ease; } .workbench-open .messages { padding-left:20px; padding-right:20px; background:#fbfdff; } .message { max-width:700px; margin:0 0 16px; } .workbench-open .message { max-width:100%; } .message.user { margin-left:auto; max-width:500px; } .message-meta { margin:0 0 5px 2px; color:var(--muted); font-size:10px; } .bubble { padding:11px 13px; border:1px solid var(--line); border-radius:4px 13px 13px; background:#fff; box-shadow:0 5px 18px rgba(30,50,80,.04); } .user .bubble { color:#fff; border-color:var(--brand); border-radius:13px 4px 13px 13px; background:var(--brand); } .chat-card { overflow:hidden; border:1px solid #d9e9f7; border-radius:12px; background:#fff; box-shadow:var(--shadow); } .card-head { display:flex; justify-content:space-between; align-items:flex-start; gap:10px; padding:13px 14px; border-bottom:1px solid #e3edf7; background:linear-gradient(100deg,#f3f9ff,#fff); } .card-head h3 { margin:0; color:var(--ink); font-size:14px; } .card-head p { margin:3px 0 0; color:var(--muted); font-size:10px; } .card-body { padding:13px 14px; } .composer { display:flex; gap:9px; padding:14px 20px; border-top:1px solid var(--line); background:#fff; } .composer input { flex:1; min-width:0; border:1px solid #d7e0eb; border-radius:9px; padding:10px 12px; color:var(--text); } .btn { border:1px solid #cfd9e5; border-radius:8px; padding:7px 10px; background:#fff; color:#425268; font-size:11px; font-weight:700; } .btn:hover { background:var(--soft); } .btn.primary { border-color:var(--brand); background:var(--brand); color:#fff; } .btn.danger { border-color:#efb7c0; background:var(--bad-soft); color:#b33449; } .btn.text { border-color:transparent; color:#146fbe; background:transparent; } .actions { display:flex; flex-wrap:wrap; gap:7px; margin-top:12px; }
|
||||
.workbench { width:100%; min-width:0; overflow:hidden; border-left:0 solid var(--line); background:#fbfcfe; opacity:0; transform:translateX(18px); transition:opacity .16s ease,transform .22s ease,border .22s ease; } .workbench.open { border-left-width:1px; opacity:1; transform:translateX(0); } .wb-inner { width:100%; height:100%; display:flex; flex-direction:column; } .wb-head { flex:none; display:flex; align-items:flex-start; gap:10px; padding:16px 20px 13px; border-bottom:1px solid var(--line); background:#fff; } .wb-head h2 { margin:0; color:var(--ink); font-size:16px; } .wb-head p { margin:3px 0 0; color:var(--muted); font-size:10px; } .icon-close { margin-left:auto; border:0; background:transparent; color:#78879a; font-size:22px; line-height:20px; } .wb-content { min-height:0; flex:1; overflow:auto; padding:18px 20px; } .wb-footer { flex:none; padding:13px 20px; border-top:1px solid var(--line); background:#fff; }
|
||||
.metrics { display:grid; grid-template-columns:repeat(4,1fr); gap:8px; } .metric { padding:9px; border:1px solid var(--line); border-radius:9px; background:#fff; } .metric span { display:block; color:var(--muted); font-size:9px; } .metric b { display:block; margin-top:2px; color:var(--ink); font-size:17px; } .metric.warn b { color:var(--warn); } .metric.bad b { color:var(--bad); } .source-select { display:grid; grid-template-columns:1fr 1fr; gap:9px; margin-top:13px; } .source-card { position:relative; border:1px solid var(--line); border-radius:10px; padding:11px; background:#fff; } .source-card.active { border-color:#77b8e9; background:#f6fbff; } .source-card input { position:absolute; right:10px; top:11px; accent-color:var(--brand); } .source-card b { color:var(--ink); } .source-card p { margin:3px 0 0; color:var(--muted); font-size:10px; } .source-card small { display:block; margin-top:8px; color:#61809d; font-size:10px; } .rule { margin-top:11px; padding:9px 10px; border:1px solid #f3dda7; border-radius:8px; background:var(--warn-soft); color:#8a621a; font-size:10px; } .tag { display:inline-flex; align-items:center; white-space:nowrap; border:1px solid transparent; border-radius:999px; padding:3px 7px; font-size:10px; font-weight:700; } .tag.good { color:var(--good); background:var(--good-soft); border-color:#bce8ce; } .tag.info { color:#1768ac; background:var(--brand-soft); border-color:#c3e1fa; } .tag.warn { color:#9b690b; background:var(--warn-soft); border-color:#f3dda7; } .tag.bad { color:#b5364b; background:var(--bad-soft); border-color:#f1c3cb; } .tag.gray { color:#627188; background:#f5f7fa; border-color:#dce3eb; }
|
||||
.stage { position:relative; padding:8px 0 8px 27px; border-bottom:1px solid var(--line); font-size:11px; } .stage:last-child { border:0; } .stage:before { content:""; position:absolute; top:11px; left:3px; width:14px; height:14px; border-radius:50%; background:#e2e8f0; } .stage.done:before { content:"✓"; display:grid; place-items:center; color:var(--good); background:#dcf5e6; font-size:9px; font-weight:900; } .stage.now:before { background:#d9efff; box-shadow:0 0 0 4px #eff8ff; } .stage.bad:before { content:"!"; display:grid; place-items:center; color:var(--bad); background:#ffe2e7; font-size:10px; font-weight:900; } .stage b { color:var(--ink); } .stage span { display:block; margin-top:1px; color:var(--muted); font-size:10px; } .context-box { margin-bottom:11px; border:1px solid var(--line); border-radius:9px; background:#fff; padding:10px; } .context-row { display:flex; justify-content:space-between; gap:8px; padding:3px 0; color:var(--muted); font-size:10px; } .context-row b { color:var(--text); text-align:right; }
|
||||
.table { width:100%; border-collapse:collapse; font-size:10px; } .table th,.table td { padding:8px 5px; border-bottom:1px solid var(--line); text-align:left; vertical-align:middle; } .table th { color:#73839a; background:#f7f9fc; font-weight:700; } .table tr:last-child td { border-bottom:0; } .table input { accent-color:var(--brand); } .table .disabled { color:#91a0b4; background:#fffbf2; } .link { border:0; padding:0; color:#166db7; background:transparent; font-size:10px; font-weight:700; } .notice { margin:11px 0 0; border:1px solid #cce6fa; border-radius:8px; padding:9px; color:#2d6b99; background:#f2f9ff; font-size:10px; } .notice.warn { border-color:#f1d9a2; color:#946513; background:var(--warn-soft); } .notice.bad { border-color:#efc1c9; color:#aa3447; background:var(--bad-soft); } .tabs { display:flex; gap:3px; margin-bottom:11px; border-bottom:1px solid var(--line); } .tab { border:0; border-bottom:2px solid transparent; padding:8px 7px; color:#73839a; background:transparent; font-size:10px; font-weight:700; } .tab.active { border-bottom-color:var(--brand); color:#156bab; } .filter-row { display:flex; gap:7px; margin-bottom:10px; } .filter-row select { flex:1; min-width:0; border:1px solid #d7e0eb; border-radius:7px; padding:6px; color:#65748a; background:#fff; font-size:10px; }
|
||||
.drawer-mask,.modal-mask { position:fixed; z-index:20; inset:0; display:none; background:rgba(18,34,56,.25); } .drawer-mask.open,.modal-mask.open { display:block; } .drawer { position:absolute; top:0; right:0; width:480px; height:100%; display:flex; flex-direction:column; background:#fff; box-shadow:-12px 0 34px rgba(20,40,70,.18); } .drawer-head { display:flex; align-items:flex-start; padding:16px; border-bottom:1px solid var(--line); } .drawer-head h2 { margin:0; color:var(--ink); font-size:15px; } .drawer-head p { margin:3px 0 0; color:var(--muted); font-size:10px; } .drawer-body { overflow:auto; padding:16px; } .fact { display:grid; grid-template-columns:130px 1fr; gap:12px; padding:8px 0; border-bottom:1px solid var(--line); font-size:11px; } .fact span { color:var(--muted); } .fact b { color:var(--ink); text-align:right; } .timeline { margin-top:15px; } .timeline h3 { margin:0 0 9px; color:var(--ink); font-size:12px; } .event { position:relative; padding:0 0 13px 22px; font-size:10px; } .event:before { content:""; position:absolute; left:2px; top:3px; width:10px; height:10px; border-radius:50%; background:#4aabeb; } .event:after { content:""; position:absolute; left:6px; top:14px; bottom:0; width:1px; background:#d9eafb; } .event:last-child:after { display:none; } .event time { display:block; color:var(--muted); } .event b { display:block; color:var(--ink); margin-top:2px; } .event span { display:block; color:var(--muted); }
|
||||
.modal-mask { display:none; align-items:center; justify-content:center; } .modal-mask.open { display:flex; } .modal { width:460px; overflow:hidden; border-radius:12px; background:#fff; box-shadow:0 25px 65px rgba(16,36,60,.25); } .modal header { padding:16px; border-bottom:1px solid var(--line); } .modal h2 { margin:0; color:var(--ink); font-size:15px; } .modal header p { margin:3px 0 0; color:var(--muted); font-size:10px; } .modal main { padding:15px 16px; } .modal textarea { width:100%; height:78px; border:1px solid #d2dce8; border-radius:8px; padding:9px; resize:none; } .modal footer { display:flex; justify-content:flex-end; gap:8px; padding:12px 16px; border-top:1px solid var(--line); } .toast { position:fixed; z-index:30; right:24px; bottom:23px; display:none; max-width:440px; border-radius:8px; padding:10px 13px; color:#fff; background:#243b55; box-shadow:var(--shadow); font-size:11px; }
|
||||
@media (max-width:1450px) { .chat-nav { width:74px; } .brand { justify-content:center; padding:0; } .brand>div:last-child,.new-chat,.nav-label,.history-item span,.history-item b,.nav-user>div:last-child { display:none; } .new-chat { margin:10px; } .history { padding:0 8px; } .history-item { height:38px; } .history-item:before { content:"◌"; display:block; color:#73839a; text-align:center; } .history-item.active:before { color:#1265ad; } .history-item i { right:9px; top:8px; } .nav-user { justify-content:center; padding:12px 0; } } @media (max-width:1240px) { body { min-width:980px; } .chat-layout.workbench-open { grid-template-columns:minmax(390px,38fr) minmax(560px,62fr); } .messages,.workbench-open .messages { padding-left:18px; padding-right:18px; } } @media (prefers-reduced-motion:reduce) { .chat-layout,.workbench { transition:none; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" class="app">
|
||||
<aside class="chat-nav">
|
||||
<div class="brand"><div class="brand-mark">HX</div><div><b>HXOPS</b><span>Enterprise AI Gateway</span></div></div>
|
||||
<button class="new-chat" data-action="new-chat">+ 新建对话</button>
|
||||
<div class="nav-label">在途仓自动调拨 Agent</div>
|
||||
<div id="history" class="history"></div>
|
||||
<div class="nav-user"><div class="avatar">仓</div><div><b>仓库管理人员</b><span>具备 Agent 使用权限</span></div></div>
|
||||
</aside>
|
||||
<main class="chat-shell">
|
||||
<header class="chat-top"><div class="agent-avatar">调</div><div class="agent-info"><b>在途仓自动调拨 Agent</b><span id="top-subtitle">新建对话 · 可查询、预检和执行调拨</span></div><div class="top-right"><span class="small-chip">Asia/Shanghai</span><span id="run-chip" class="small-chip">未创建任务</span><span id="layout-chip" class="small-chip">对话视图</span></div></header>
|
||||
<section id="chat-layout" class="chat-layout"><div class="message-zone"><div id="messages" class="messages"></div><div class="composer"><input id="input" placeholder="例如:查询 DBS 昨天可调拨情况" /><button class="btn primary" data-action="send">发送</button></div></div><aside id="workbench" class="workbench"><div class="wb-inner"><header class="wb-head"><div><h2 id="wb-title">本次调拨</h2><p id="wb-subtitle">当前业务对象与状态</p></div><button class="icon-close" data-action="close-workbench">×</button></header><div id="wb-content" class="wb-content"></div><footer id="wb-footer" class="wb-footer"></footer></div></aside></section>
|
||||
</main>
|
||||
</div>
|
||||
<div id="drawer-mask" class="drawer-mask"><aside class="drawer"><header class="drawer-head"><div><h2 id="drawer-title">详情</h2><p id="drawer-subtitle">返回后保留当前 Tab、筛选和滚动位置</p></div><button class="icon-close" data-action="close-drawer">×</button></header><div id="drawer-body" class="drawer-body"></div></aside></div>
|
||||
<div id="modal-mask" class="modal-mask"><section class="modal"><header><h2 id="modal-title">确认操作</h2><p id="modal-desc"></p></header><main><label style="display:block;margin-bottom:6px;color:var(--ink);font-size:11px;font-weight:700">原因(必填)</label><textarea id="reason" placeholder="请填写业务原因"></textarea></main><footer><button class="btn" data-action="modal-cancel">取消</button><button class="btn primary" data-action="modal-confirm">确认</button></footer></section></div>
|
||||
<div id="toast" class="toast"></div>
|
||||
<script>
|
||||
// 默认打开待处理工作区,便于评审者第一眼观察“Chat 被压缩 + 右侧业务面板”的目标布局;关闭后回到纯对话视图。
|
||||
const S = { view:'welcome', wb:'backlog', stage:'welcome', backlogTab:'recoverable', selected:new Set(['INV-031','INV-042']), modal:null, transferSources:new Set(['DBS']), run:'', chatHistory:'new' };
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const button = (label, action, kind='') => `<button class="btn ${kind}" data-action="${action}">${label}</button>`;
|
||||
const tag = (label, kind='gray') => `<span class="tag ${kind}">${label}</span>`;
|
||||
const facts = (rows) => rows.map(([a,b]) => `<div class="fact"><span>${a}</span><b>${b}</b></div>`).join('');
|
||||
const events = (rows) => rows.map(([a,b,c]) => `<div class="event"><time>${a}</time><b>${b}</b><span>${c}</span></div>`).join('');
|
||||
function toast(text) { const e=$('toast'); e.textContent=text; e.style.display='block'; clearTimeout(window._toast); window._toast=setTimeout(()=>e.style.display='none',2600); }
|
||||
function renderHistory() { const rows=[['new','新建对话','今日摘要与调拨入口',''],['precheck','昨天 DBS 调拨预检','PRE-20260816-001 · 已完成',''],['running','手动调拨任务','RUN-20260816-002 · 执行中','warn'],['result','今天自动调拨结果','AUTO-20260816-0900 · 18成功',''],['exception','历史异常处理','待处理 6 笔','bad']]; $('history').innerHTML=rows.map(([id,title,sub,dot])=>`<button class="history-item ${S.chatHistory===id?'active':''}" data-action="history-${id}"><b>${title}</b><span>${sub}</span>${dot?`<i class="${dot}"></i>`:''}</button>`).join(''); }
|
||||
function welcome() { return `<div class="message"><div class="message-meta">在途仓自动调拨 Agent</div><div class="bubble">你好。你可以先选择收料来源并发起预检;系统会在写入 ERP 前展示可执行范围、预计调拨数量和预计单据数。</div></div><div class="message"><section class="chat-card"><header class="card-head"><div><h3>今日业务摘要</h3><p>自动处理结果与历史异常均来自后端统一 Run 投影。</p></div>${tag('2026-08-16','info')}</header><div class="card-body"><div class="metrics"><div class="metric"><span>最近自动 Run</span><b>1</b></div><div class="metric"><span>已成功过账</span><b>18</b></div><div class="metric warn"><span>待处理调拨</span><b>6</b></div><div class="metric bad"><span>结果未知</span><b>1</b></div></div><div class="source-select"><label class="source-card ${S.transferSources.has('DBS')?'active':''}"><input type="checkbox" data-source="DBS" ${S.transferSources.has('DBS')?'checked':''}/><b>DBS 收料</b><p>通过 RPA 获取累计全量收料文件</p><small>来源仓:DBS-TRANSIT</small></label><label class="source-card ${S.transferSources.has('Crane')?'active':''}"><input type="checkbox" data-source="Crane" ${S.transferSources.has('Crane')?'checked':''}/><b>Crane 收料</b><p>通过 HTTP Callback 获取累计全量文件</p><small>来源仓:CRANE-TRANSIT</small></label></div><div class="actions">${button('发起调拨预检','start-precheck','primary')}${button('查看最近自动 Run','auto-run')}${button('待处理调拨 6 笔','open-backlog')}${button('结果未知 1 笔','open-unknown')}</div><div class="rule">默认业务日期为昨天。当天收料不会进入 ERP 查询或调拨;数量必须与 ERP 账面库存完全相等。</div></div></section></div>`; }
|
||||
function fileProgress() { return `<div class="message"><div class="message-meta">在途仓自动调拨 Agent · RUN-MAN-20260816-001</div><section class="chat-card"><header class="card-head"><div><h3>正在准备收料文件</h3><p>没有有效 Ready 文件时,系统在任务创建前按来源独立获取。</p></div>${tag('处理中','info')}</header><div class="card-body"><div class="stage done"><b>DBS · RPA 导出完成</b><span>DBS-receipt-20260815-v3.xlsx 已 Ready</span></div><div class="stage now"><b>Crane · 等待 HTTP Callback</b><span>已创建来源任务;正在等待累计全量文件</span></div><div class="stage"><b>冻结文件版本</b><span>选择 Ready 文件后,当前 Run 不允许重新抓取或替换文件</span></div><div class="notice">页面关闭或聊天流断开不会取消该任务。文件就绪后,本消息卡原位更新为预检结果。</div></div></section></div>`; }
|
||||
function precheckMessage() { return `<div class="message"><div class="message-meta">在途仓自动调拨 Agent · PRE-20260816-001</div><section class="chat-card"><header class="card-head"><div><h3>预检完成,尚未写入 ERP</h3><p>文件版本、checksum、策略与映射版本已冻结。</p></div>${tag('等待确认','warn')}</header><div class="card-body"><div class="metrics"><div class="metric"><span>可执行</span><b>3</b></div><div class="metric warn"><span>业务阻断</span><b>2</b></div><div class="metric"><span>当天未成熟</span><b>1</b></div><div class="metric"><span>预计写入</span><b>3</b></div></div><div class="actions">${button('打开本次调拨','open-run','primary')}${button('查看冻结文件','file-drawer')}${button('查看异常证据','invoice-drawer')}</div><div class="notice">右侧面板中可选择部分可执行 Invoice。阻断项和当天收料项不可选择。</div></div></section></div>`; }
|
||||
function runningMessage() { return `<div class="message"><div class="message-meta">在途仓自动调拨 Agent · RUN-MAN-20260816-002</div><section class="chat-card"><header class="card-head"><div><h3>正在执行 ERP 调拨</h3><p>后台 Worker 将在每项写入前再次查询 ERP 库存。</p></div>${tag('执行中','info')}</header><div class="card-body"><div class="stage done"><b>09:20:03 · INV-001 已完成</b><span>ERP 调拨单:TRF-10001</span></div><div class="stage done"><b>09:20:11 · INV-002 已完成</b><span>ERP 调拨单:TRF-10002</span></div><div class="stage now"><b>09:20:18 · INV-008 正在写入</b><span>执行中,不能从前端推断最终结果</span></div><div class="actions">${button('查看执行详情','open-run','primary')}${button('停止未开始项','stop-run','danger')}</div><div class="notice">关闭页面不会取消后台 Run;重新进入该历史对话可恢复同一 Run 的右侧投影。</div></div></section></div>`; }
|
||||
function resultMessage() { return `<div class="message"><div class="message-meta">在途仓自动调拨 Agent · RUN-MAN-20260816-002</div><section class="chat-card"><header class="card-head"><div><h3>调拨完成</h3><p>ERP 业务结果与企业微信通知结果分别呈现。</p></div>${tag('已完成','good')}</header><div class="card-body"><div class="metrics"><div class="metric"><span>成功</span><b>2</b></div><div class="metric"><span>重复成功</span><b>1</b></div><div class="metric warn"><span>业务阻断</span><b>1</b></div><div class="metric"><span>通知</span><b>已发送</b></div></div><div class="actions">${button('打开结果详情','open-run','primary')}${button('下载固定异常 Excel','download-excel')}${button('查看待处理','open-backlog')}</div><div class="notice">此结果卡固定保留在历史对话中。后续处理异常不会改写本次 Run 的固定异常 Excel。</div></div></section></div>`; }
|
||||
function currentMessages() { if(S.stage==='welcome') return welcome(); if(S.stage==='file') return fileProgress(); if(S.stage==='precheck') return precheckMessage(); if(S.stage==='running') return runningMessage(); return resultMessage(); }
|
||||
function runWorkbench() { const stage=S.stage; const header={file:['本次调拨','RUN-MAN-20260816-001 · 文件准备'],precheck:['本次调拨','PRE-20260816-001 · 只读预检'],confirm:['确认执行调拨','PRE-20260816-001 · 确认快照有效至 10:32'],running:['本次调拨','RUN-MAN-20260816-002 · 后台执行中'],result:['本次调拨结果','RUN-MAN-20260816-002 · 已完成']}[stage] || ['本次调拨','当前任务']; $('wb-title').textContent=header[0]; $('wb-subtitle').textContent=header[1]; if(stage==='file') return `<div class="context-box">${facts([['业务日期','2026-08-15'],['来源','DBS、Crane'],['文件状态','DBS Ready / Crane 等待']])}</div><div class="stage done"><b>确定预检范围</b><span>昨天 · DBS、Crane</span></div><div class="stage now"><b>准备收料文件</b><span>Crane 正在等待 Callback</span></div><div class="stage"><b>汇总 Invoice 并查询 ERP</b><span>文件 Ready 后开始</span></div>`; if(stage==='running') return `<div class="context-box">${facts([['已处理','2 / 3'],['成功','2'],['失败','0'],['正在执行','1']])}</div><table class="table"><thead><tr><th>Invoice</th><th>状态</th><th>ERP 单号</th></tr></thead><tbody><tr><td>INV-001</td><td>${tag('成功','good')}</td><td>TRF-10001</td></tr><tr><td>INV-002</td><td>${tag('成功','good')}</td><td>TRF-10002</td></tr><tr><td>INV-008</td><td>${tag('写入中','info')}</td><td>—</td></tr></tbody></table>`; if(stage==='result') return `<div class="context-box">${facts([['业务日期','2026-08-15'],['冻结文件','DBS-v3 / Crane-v2'],['ERP 写入','3 张'],['通知','已发送'],['异常 Excel','固定版本 v1']])}</div><table class="table"><thead><tr><th>Invoice</th><th>结果</th><th>单号 / 事实</th></tr></thead><tbody><tr><td>INV-001</td><td>${tag('成功','good')}</td><td>TRF-10001</td></tr><tr><td>INV-002</td><td>${tag('重复成功','good')}</td><td>TRF-98220</td></tr><tr><td>INV-003</td><td>${tag('数量不一致','warn')}</td><td>收料300 / ERP280</td></tr></tbody></table>`; const isConfirm=stage==='confirm'; return `<div class="context-box">${facts([['业务日期','2026-08-15'],['文件','DBS-v3 / checksum 7A4E…'],['ERP 组织','CN01'],['来源仓 / HUB','DBS-TRANSIT / HUB-SZ'],['预检有效期','10:32']])}</div><table class="table"><thead><tr><th></th><th>Invoice</th><th>收料 / ERP</th><th>状态</th></tr></thead><tbody><tr><td><input type="checkbox" checked data-item="INV-001" /></td><td>INV-001</td><td>500 / 500</td><td>${tag('可执行','good')}</td></tr><tr><td><input type="checkbox" checked data-item="INV-002" /></td><td>INV-002</td><td>1,200 / 1,200</td><td>${tag('可执行','good')}</td></tr><tr><td><input type="checkbox" checked data-item="INV-008" /></td><td>INV-008</td><td>600 / 600</td><td>${tag('可执行','good')}</td></tr><tr class="disabled"><td><input type="checkbox" disabled /></td><td>INV-031</td><td>300 / 280</td><td>${tag('数量不一致','warn')}</td></tr><tr class="disabled"><td><input type="checkbox" disabled /></td><td>INV-041</td><td>400 / —</td><td>${tag('当天收料','gray')}</td></tr></tbody></table><div class="notice ${isConfirm?'warn':''}">${isConfirm?'将写入已选 3 张 Invoice,预计调拨总数量 2,300,预计 ERP 单据 3 张。':'可执行项默认全选,允许只选择部分。点击进入确认前,ERP 尚未写入。'}</div>`; }
|
||||
function runFooter() { if(S.stage==='file') return ''; if(S.stage==='precheck') return `${button('查看证据','invoice-drawer')}${button('进入确认','enter-confirm','primary')}`; if(S.stage==='confirm') return `${button('返回预检','back-precheck')}${button('执行调拨','execute','primary')}`; if(S.stage==='running') return `${button('停止未开始项','stop-run','danger')}`; return `${button('下载固定异常 Excel','download-excel')}${button('查看审计','invoice-drawer')}`; }
|
||||
function backlogWorkbench() { $('wb-title').textContent='待处理调拨'; $('wb-subtitle').textContent='跨 Run 可恢复异常;不更新 RPA 文件'; const tab=S.backlogTab; const content=tab==='unknown'?`<div class="notice bad">结果未知只能展示事实和人工核实 SOP,不提供重查、关闭、恢复或执行按钮。</div><table class="table"><thead><tr><th>Invoice</th><th>已知事实</th><th></th></tr></thead><tbody><tr><td>INV-052</td><td>ERP 未返回确定成功/失败</td><td><button class="link" data-action="unknown-drawer">查看</button></td></tr></tbody></table>`:tab==='closed'?`<table class="table"><thead><tr><th>Invoice</th><th>关闭原因</th><th></th></tr></thead><tbody><tr><td>INV-061</td><td>货代确认无需调拨</td><td><button class="link" data-action="restore-item">恢复处理</button></td></tr><tr><td>INV-068</td><td>业务已线下完成</td><td><button class="link" data-action="restore-item">恢复处理</button></td></tr></tbody></table>`:`<div class="filter-row"><select><option>来源:全部</option><option>DBS</option><option>Crane</option></select><select><option>日期:全部</option><option>最近 3 天</option><option>更早</option></select></div><table class="table"><thead><tr><th></th><th>来源 / 日期</th><th>事实</th><th></th></tr></thead><tbody><tr><td><input type="checkbox" checked data-backlog="INV-031" /></td><td>DBS<br><span style="color:var(--muted)">08-14</span></td><td>数量不一致<br><span style="color:var(--muted)">收料300 / ERP280</span></td><td><button class="link" data-action="invoice-drawer">详情</button></td></tr><tr><td><input type="checkbox" checked data-backlog="INV-042" /></td><td>Crane<br><span style="color:var(--muted)">08-13</span></td><td>ERP 无库存<br><span style="color:var(--muted)">收料800 / ERP0</span></td><td><button class="link" data-action="invoice-drawer">详情</button></td></tr><tr><td><input type="checkbox" data-backlog="INV-073" /></td><td>DBS<br><span style="color:var(--muted)">08-12</span></td><td>明确技术失败</td><td><button class="link" data-action="invoice-drawer">详情</button></td></tr></tbody></table><div class="notice">批量重查仅重新读取 ERP 库存,不抓 RPA、不替换文件、不写 ERP。匹配项随后进入新的确认区。</div>`; return `<div class="tabs"><button class="tab ${tab==='recoverable'?'active':''}" data-action="tab-recoverable">可恢复异常 6</button><button class="tab ${tab==='closed'?'active':''}" data-action="tab-closed">已关闭 2</button><button class="tab ${tab==='unknown'?'active':''}" data-action="tab-unknown">结果未知 1</button></div>${content}`; }
|
||||
function backlogFooter() { if(S.backlogTab==='recoverable') return `${button('重新查询 ERP 库存(2)','requery','primary')}${button('标记无需继续处理','close-item','danger')}`; return ''; }
|
||||
function unknownWorkbench() { $('wb-title').textContent='结果未知'; $('wb-subtitle').textContent='只读隔离区 · 禁止推断 ERP 最终状态'; return `<div class="notice bad">此 Invoice 的 ERP 请求没有返回确定成功或失败。系统不能声明已建单或未建单。</div>${facts([['Invoice','INV-052'],['所属 Run','AUTO-20260816-0900'],['请求时间','2026-08-16 09:17:21'],['Operation ID','OP-20260816-8891'],['ERP 结果','未知'],['允许操作','查看证据与人工核实 SOP']])}<div class="timeline"><h3>人工核实 SOP</h3>${events([['1','记录 Operation ID','不要重新发起 ERP 写入'],['2','由 ERP 管理员核实 Invoice','核实是否存在且审核、过账'],['3','仅记录核实证据','系统状态不由前端主观改写']])}</div><div class="actions">${button('查看脱敏证据','unknown-drawer')}${button('复制 Operation ID','copy-operation')}</div>`; }
|
||||
function autoRunWorkbench() { $('wb-title').textContent='自动 Run 详情'; $('wb-subtitle').textContent='AUTO-20260816-0900 · 企业微信深链打开'; return `<div class="context-box">${facts([['触发方式','每日自动调拨'],['业务日期','2026-08-15'],['通知','已发送'],['深链模式','mode=transfer-run'],['异常 Excel','固定版本 v1']])}</div><div class="stage done"><b>DBS 文件与预检</b><span>20 项预检;18 项自动过账</span></div><div class="stage bad"><b>Crane 文件获取超时</b><span>Callback 超过 60 分钟;不影响 DBS</span></div><div class="stage done"><b>企业微信汇总</b><span>本非空 Run 已发送一条通知</span></div><table class="table" style="margin-top:10px"><thead><tr><th>结果</th><th>数量</th></tr></thead><tbody><tr><td>ERP 成功</td><td>18</td></tr><tr><td>业务阻断</td><td>2</td></tr><tr><td>来源异常</td><td>1</td></tr></tbody></table>`; }
|
||||
function renderWorkbench() { const w=$('workbench'), layout=$('chat-layout'), layoutChip=$('layout-chip'); if(!S.wb) { w.classList.remove('open'); layout.classList.remove('workbench-open'); layoutChip.textContent='对话视图'; layoutChip.classList.remove('active'); return; } w.classList.add('open'); layout.classList.add('workbench-open'); layoutChip.textContent='调拨工作区已展开'; layoutChip.classList.add('active'); let html='',footer=''; if(S.wb==='run') { html=runWorkbench(); footer=runFooter(); } if(S.wb==='backlog') { html=backlogWorkbench(); footer=backlogFooter(); } if(S.wb==='unknown') { html=unknownWorkbench(); footer=''; } if(S.wb==='auto') { html=autoRunWorkbench(); footer=`${button('下载固定异常 Excel','download-excel')}${button('进入待处理','open-backlog','primary')}`; } $('wb-content').innerHTML=html; $('wb-footer').innerHTML=footer; }
|
||||
function render() { renderHistory(); $('messages').innerHTML=currentMessages(); $('top-subtitle').textContent=S.stage==='welcome'?'新建对话 · 可查询、预检和执行调拨':S.stage==='running'?'后台 Run 持续执行中':S.stage==='result'?'历史结果可随时恢复':'当前 Run 的聊天投影'; $('run-chip').textContent=S.run|| (S.stage==='welcome'?'未创建任务':'RUN-MAN-20260816-001'); renderWorkbench(); bind(); }
|
||||
function openDrawer(kind) { const d=$('drawer-mask'); d.classList.add('open'); if(kind==='unknown') { $('drawer-title').textContent='INV-052 · ERP 结果未知'; $('drawer-subtitle').textContent='系统展示未知事实;不提供任何业务状态变更'; $('drawer-body').innerHTML=`<div class="notice bad">ERP 未返回确定成功或失败。不得通过“重试”“关闭”或“恢复”猜测处理结果。</div>${facts([['Operation ID','OP-20260816-8891'],['请求时间','2026-08-16 09:17:21'],['保存证据','脱敏请求摘要、request_id'],['可核实人','ERP 管理员'],['结论','未知']])}<div class="timeline"><h3>核实记录要求</h3>${events([['人工核实前','保持状态不变','系统不生成第二次 ERP 写入'],['人工核实后','记录证据','仅追加审计,不篡改原始 ERP 结果']])}</div>`; } else if(kind==='file') { $('drawer-title').textContent='冻结的收料文件版本'; $('drawer-subtitle').textContent='Run 创建后不可替换;历史 Run 永久指向此版本'; $('drawer-body').innerHTML=`${facts([['文件名','DBS-receipt-20260815-v3.xlsx'],['用途','receipt'],['Ready 时间','2026-08-16 08:03'],['checksum','7A4E…91B2'],['解析 Profile','DBS-RECEIPT-v4'],['原始行','Receipt Sheet 第 77、78 行']])}<div class="timeline"><h3>版本链路</h3>${events([['08:03','文件进入 Ready','RPA 获取累计全量文件'],['09:12','预检 Run 固定版本','写入 file_version 与 checksum 快照'],['09:15','预检完成','Invoice 汇总仍可追溯原始行']])}</div><div class="actions">${button('下载文件(记录访问审计)','download-excel')}</div>`; } else { $('drawer-title').textContent='INV-031 · 调拨证据'; $('drawer-subtitle').textContent='关闭抽屉后返回原 Tab、筛选和滚动位置'; $('drawer-body').innerHTML=`${facts([['来源','DBS'],['收料数量','300 PCS'],['ERP 账面库存','280 PCS'],['当前结论','数量不一致,不能调拨'],['文件版本','DBS-v3 / checksum 7A4E…'],['原始行','Receipt / 77、78'],['当前 Attempt','AT-20260816-003']])}<div class="actions">${button('重新查询 ERP 库存','requery-one','primary')}${button('标记无需继续处理','close-item','danger')}${button('查看文件版本','file-drawer')}</div><div class="timeline"><h3>Attempt 与审计</h3>${events([['08-14 09:00','自动预检','ERP280;创建 Attempt 1'],['08-15 09:00','自动预检','ERP280;创建 Attempt 2'],['08-16 09:12','当前预检','ERP280;创建 Attempt 3;快照 Hash 已保存']])}</div>`; } bind(); }
|
||||
function openModal(type) { S.modal=type; const x={close:['标记“无需继续处理”','该 Invoice 将变为 manually_closed,自动排程不再处理;历史与审计永久保留。'],restore:['恢复处理','恢复后进入可恢复待处理池,可立即重新查询 ERP 库存。'],stop:['停止未开始项','仅取消尚未开始的 Invoice;已成功或正在调用 ERP 的项不撤销。']}[type]; $('modal-title').textContent=x[0]; $('modal-desc').textContent=x[1]; $('reason').value=''; $('modal-mask').classList.add('open'); }
|
||||
function action(a) { if(a.startsWith('history-')) { const id=a.slice(8); S.chatHistory=id; if(id==='new'){S.stage='welcome';S.wb=null;} if(id==='precheck'){S.stage='precheck';S.wb='run';S.run='PRE-20260816-001';} if(id==='running'){S.stage='running';S.wb='run';S.run='RUN-MAN-20260816-002';} if(id==='result'){S.stage='result';S.wb='auto';S.run='AUTO-20260816-0900';} if(id==='exception'){S.stage='welcome';S.wb='backlog';} render(); return; } if(a==='new-chat'){S.stage='welcome';S.wb=null;S.run='';S.chatHistory='new';render();return;} if(a==='start-precheck'||a==='send'){ if(!S.transferSources.size){toast('至少选择一个收料来源后才能发起预检。');return;} S.stage='file';S.wb='run';S.run='RUN-MAN-20260816-001';S.chatHistory='precheck';render();setTimeout(()=>{S.stage='precheck';S.run='PRE-20260816-001';render();toast('原型:来源文件已就绪,任务卡原位更新为预检结果。');},900);return; } if(a==='open-run'){S.wb='run';render();return;} if(a==='enter-confirm'){S.stage='confirm';render();return;} if(a==='back-precheck'){S.stage='precheck';render();return;} if(a==='execute'){S.stage='running';S.run='RUN-MAN-20260816-002';render();setTimeout(()=>{S.stage='result';render();toast('原型:Worker 执行已完成,结果卡固定在历史会话中。');},1100);return;} if(a==='open-backlog'){S.wb='backlog';S.backlogTab='recoverable';render();return;} if(a==='open-unknown'){S.wb='unknown';render();return;} if(a==='auto-run'){S.wb='auto';S.run='AUTO-20260816-0900';render();toast('原型:模拟企业微信深链进入指定自动 Run。');return;} if(a==='close-workbench'){S.wb=null;render();return;} if(a==='invoice-drawer'){openDrawer('invoice');return;} if(a==='unknown-drawer'){openDrawer('unknown');return;} if(a==='file-drawer'){openDrawer('file');return;} if(a==='close-drawer'){$('drawer-mask').classList.remove('open');return;} if(a==='tab-recoverable'||a==='tab-closed'||a==='tab-unknown'){S.backlogTab=a.replace('tab-','');render();return;} if(a==='requery'||a==='requery-one'){toast('原型:仅重新查询所选异常的 ERP 库存。文件版本不变,未写入 ERP。');setTimeout(()=>{S.wb='run';S.stage='confirm';S.run='PRE-REQUERY-20260816-001';render();},600);return;} if(a==='close-item'){openModal('close');return;} if(a==='restore-item'){openModal('restore');return;} if(a==='stop-run'){openModal('stop');return;} if(a==='modal-cancel'){$('modal-mask').classList.remove('open');return;} if(a==='modal-confirm'){if(!$('reason').value.trim()){toast('请填写原因。');return;} $('modal-mask').classList.remove('open'); if(S.modal==='restore'){S.backlogTab='recoverable';S.wb='backlog';} toast('原型:操作已追加审计,页面已按新状态更新。');render();return;} if(a==='download-excel'){toast('原型:下载该 Run 创建时的固定异常 Excel,并写入下载访问审计。');return;} if(a==='copy-operation'){toast('已复制 Operation ID(原型)。');return;} }
|
||||
function bind(){document.querySelectorAll('[data-action]').forEach(el=>el.onclick=()=>action(el.dataset.action));document.querySelectorAll('[data-source]').forEach(el=>el.onchange=()=>{el.checked?S.transferSources.add(el.dataset.source):S.transferSources.delete(el.dataset.source);render();});}
|
||||
render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,189 +0,0 @@
|
||||
# 货代通用报表 RPA API 接口文档
|
||||
|
||||
## 1. 接口范围与通用约定
|
||||
|
||||
本文定义方案新增 API。现有库存接口 `/api/shipping-notice/rpa/inventory-*` 不改路径、不改 `shipping_inventory_rpa.v2` 请求和响应语义;通用报表使用独立 schema 与回调 API。
|
||||
|
||||
浏览器管理端 API 使用标准 JSON Envelope:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {},
|
||||
"request_id": "req_abc",
|
||||
"timestamp": "2026-08-12T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
失败统一为 `success=false`,`error.code` 使用 `<DOMAIN>.<SEMANTIC>`,前端通过 `requestJson` 处理。RPA Tool 回调沿用 `shipping_notice_tools` 的历史工具契约,返回 `ok/error_code/message`,不改为浏览器 Envelope。
|
||||
|
||||
认证约定:管理端使用现有登录会话/RBAC;Worker 使用机器身份认证、共享 scope 和能力声明;不得在 URL、日志或响应中返回明文凭据、Cookie、对象存储签名 URL。
|
||||
|
||||
## 2. 管理端定义与 Driver 模板 API
|
||||
|
||||
前缀:`/api/admin/freight-reports`。以下接口均要求管理员权限。
|
||||
|
||||
| 方法 | 路径 | 用途 | 请求要点 |
|
||||
| --- | --- | --- | --- |
|
||||
| GET | `/definitions` | 分页查询报表定义 | `source_code`、`file_purpose`、`status`、`page`、`page_size` |
|
||||
| POST | `/definitions` | 新建定义草稿 | `source_code`、`file_purpose`、路径、参数、Warehouse 策略 |
|
||||
| GET | `/definitions/{definition_id}` | 查看定义、当前版本和审计摘要 | 不返回密文凭据 |
|
||||
| PATCH | `/definitions/{definition_id}` | 修改草稿 | 仅 draft;要求 `expected_version_no`,避免覆盖他人修改 |
|
||||
| POST | `/definitions/{definition_id}/versions` | 从当前定义创建新草稿版本 | 发布版本不可原地修改 |
|
||||
| POST | `/definitions/{definition_id}/test` | 启动一次管理员真实配置测试 | `definition_version_id`、单个 `warehouse_id`(Crane 为来源执行单位) |
|
||||
| POST | `/definitions/{definition_id}/publish` | 发布定义版本 | 要求同 hash 成功测试、模板版本已发布 |
|
||||
| POST | `/definitions/{definition_id}/retire` | 退役定义 | 已被启用排程引用时拒绝或先停排程 |
|
||||
| GET | `/definitions/{definition_id}/versions` | 查询版本历史 | 支持按状态筛选 |
|
||||
| GET | `/definitions/{definition_id}/audit` | 查询定义审计 | 返回脱敏 before/after、diff、事件 hash |
|
||||
| GET | `/driver-templates` | 查询模板 | `connector_type`、`file_purpose`、`status` |
|
||||
| POST | `/driver-templates` | 新建模板草稿 | 名称、连接器、受控 selector/等待/下载规则 |
|
||||
| GET | `/driver-templates/{template_id}` | 查看模板与版本 | selector 仅管理员可见 |
|
||||
| PATCH | `/driver-templates/{template_id}` | 修改草稿模板 | 服务端白名单校验 |
|
||||
| POST | `/driver-templates/{template_id}/versions` | 创建新模板版本 | 发布版本只读 |
|
||||
| POST | `/driver-templates/{template_id}/test` | 启动模板配置测试 | 绑定定义版本和执行单位 |
|
||||
| POST | `/driver-templates/{template_id}/publish` | 发布模板版本 | 必须有成功测试且 hash 一致 |
|
||||
| POST | `/driver-templates/{template_id}/retire` | 退役模板 | 被已发布定义引用时禁止直接删除 |
|
||||
|
||||
### 2.1 定义草稿请求示例
|
||||
|
||||
```json
|
||||
{
|
||||
"source_code": "AWSBI",
|
||||
"file_purpose": "receipt",
|
||||
"report_path": {
|
||||
"customer": "AWS",
|
||||
"program": "Bison",
|
||||
"program_label": "AWSBI",
|
||||
"report_group": "Inbound",
|
||||
"report_name": "Receipt Detail"
|
||||
},
|
||||
"parameters": {
|
||||
"report_date": null,
|
||||
"owner": {"mode": "portal_default"},
|
||||
"type": {"mode": "portal_default"}
|
||||
},
|
||||
"warehouse_policy": {
|
||||
"mode": "fixed",
|
||||
"warehouse_ids": ["WH-A", "WH-B"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
服务端拒绝:空用途、未配置固定 Warehouse 的 DBS、日期被设置为非 NULL 筛选、未知参数、任意脚本、selector 非白名单或普通用户写请求。
|
||||
|
||||
## 3. 配置测试 API
|
||||
|
||||
测试只允许管理员调用,使用 `mode=test`,产物进入 test 前缀,三年保留,不推送企微、不写正式库存。
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/admin/freight-reports/tests` | 创建测试运行 |
|
||||
| GET | `/api/admin/freight-reports/tests/{test_run_no}` | 查询测试状态、步骤、文件 hash |
|
||||
| POST | `/api/admin/freight-reports/tests/{test_run_no}/cancel` | 取消尚未领取的测试 |
|
||||
|
||||
创建请求必须指定一条 definition/template 草稿版本和一个执行单位。成功响应返回 `test_run_no`、`unit_run_no`、`status=queued`、`content_hash`;服务端不接受管理员直接上传测试结果。
|
||||
|
||||
## 4. 通用报表排程与运行 API
|
||||
|
||||
排程定义复用现有 Schedule API;`platform_api_path` 固定为 `freight-general-report-rpa`,`job_params` 至少包含 `source_codes`、`file_purposes`,Cron、时区和接收人使用现有字段。
|
||||
|
||||
| 方法 | 路径 | 用途 | 权限 |
|
||||
| --- | --- | --- | --- |
|
||||
| GET | `/api/schedules/options?job=freight-general-report-rpa` | 返回满足已发布定义条件的来源/用途选项 | 登录用户只读 |
|
||||
| POST/PATCH | 现有 Schedule Task 接口 | 新建/编辑排程 | 管理员 |
|
||||
| POST | 现有 Schedule Task 启停接口 | 启停排程 | 管理员 |
|
||||
| GET | `/api/freight-reports/runs` | 查询父运行分页列表 | 管理员/授权业务用户 |
|
||||
| GET | `/api/freight-reports/runs/{parent_run_no}` | 查看父运行和单元明细 | 管理员/授权业务用户 |
|
||||
| GET | `/api/freight-reports/units/{unit_run_no}` | 查看单元、Artifact、通知和脱敏审计 | 管理员/授权业务用户 |
|
||||
| POST | `/api/admin/freight-reports/units/{unit_run_no}/retry` | 手工重试一个失败单元 | 管理员 |
|
||||
| GET | `/api/freight-reports/artifacts/{artifact_no}/download` | 授权下载原始文件 | 管理员/授权接收人 |
|
||||
| GET | `/api/freight-reports/runs/{parent_run_no}/audit` | 查询运行审计摘要 | 管理员完整,业务用户脱敏 |
|
||||
|
||||
重试请求:`{"reason":"Crane 页面超时,已确认配置正常"}`。响应返回新 `parent_run_no/unit_run_no`,原失败单元保持不变。
|
||||
|
||||
下载接口不把下载 URL 写入审计;审计记录 artifact、操作者、时间、授权结果和 `request_id`。文件过期后返回 `FREIGHT_REPORT.ARTIFACT_EXPIRED`。
|
||||
|
||||
## 5. Worker 心跳与通用回调 API
|
||||
|
||||
### 5.1 心跳
|
||||
|
||||
保留 `POST /api/shipping-notice/rpa/heartbeat`,新增能力字段,不改变旧字段语义:
|
||||
|
||||
```json
|
||||
{
|
||||
"worker_id": "freight-v2-01",
|
||||
"worker_version": "2.0.0",
|
||||
"capabilities": ["inventory_v2", "freight_general_report_v1"],
|
||||
"shared_scope_id": "scope-test-01",
|
||||
"runtime_status": "idle",
|
||||
"sent_at": "2026-08-12T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
后端就绪检查仅将声明 `inventory_v2` 或 `freight_general_report_v1` 且 scope、环境、TTL 合法的 Worker 视为可用。
|
||||
|
||||
### 5.2 通用报表领取回调
|
||||
|
||||
`POST /api/shipping-notice/rpa/general-report-claimed`
|
||||
|
||||
请求包含 `schema_version`、`callback_id`、`unit_run_no`、`worker_execution_id`、`claimed_at`、`worker_id`。该回调只记录领取事实,不推进成功终态。
|
||||
|
||||
### 5.3 通用报表结果回调
|
||||
|
||||
`POST /api/shipping-notice/rpa/general-report-ready`
|
||||
|
||||
成功示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": "freight_general_report.v1",
|
||||
"callback_id": "GRU-20260812-001:C1",
|
||||
"unit_run_no": "GRU-20260812-001-U01",
|
||||
"worker_execution_id": "WEX-9f2",
|
||||
"status": "succeeded",
|
||||
"artifact": {
|
||||
"file_path": "drop/GRU-20260812-001-U01.xlsx",
|
||||
"original_name": "Receipt_Detail_WH-A.xlsx",
|
||||
"size_bytes": 18342,
|
||||
"sha256": "<64 hex chars>",
|
||||
"content_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
},
|
||||
"diagnostics": {"trace_ref": "trace-hash", "steps": ["login", "navigate", "download"]}
|
||||
}
|
||||
```
|
||||
|
||||
失败示例:`status=failed`,包含 `error_code`、脱敏 `error_message` 和 `failed_step`,不得携带页面 HTML、Cookie 或凭据。
|
||||
|
||||
处理规则:认证、UnitRun 归属、版本 hash、文件存在性、大小/扩展名/SHA-256、状态机和 callback 唯一性全部通过后才归档;重复 callback 返回 `ok=true`、`result=ignored`,不重复副作用。
|
||||
|
||||
### 5.4 通用测试回调
|
||||
|
||||
`POST /api/shipping-notice/rpa/general-report-test-ready` 与正式回调字段一致,但必须 `mode=test`,只写测试 Artifact 和测试审计,不允许正式通知或库存入库。
|
||||
|
||||
## 6. 响应与错误码
|
||||
|
||||
标准管理 API 错误码:
|
||||
|
||||
| HTTP | code | 场景 |
|
||||
| --- | --- | --- |
|
||||
| 400 | `FREIGHT_REPORT.INVALID_PARAM` | 用途、路径、参数或 selector 不合法 |
|
||||
| 401 | `AUTH.UNAUTHORIZED` | 未登录或 Worker 认证失败 |
|
||||
| 403 | `AUTH.FORBIDDEN` | 普通用户调用管理/重试或未授权下载 |
|
||||
| 404 | `RESOURCE.NOT_FOUND` | 定义、运行或 Artifact 不存在 |
|
||||
| 409 | `FREIGHT_REPORT.VERSION_CONFLICT` | 草稿版本并发编辑或发布 hash 不一致 |
|
||||
| 409 | `FREIGHT_REPORT.INVALID_STATE` | 非法状态迁移、已发布版本修改 |
|
||||
| 409 | `FREIGHT_REPORT.DUPLICATE_CALLBACK` | callback 已被其他单元使用 |
|
||||
| 410 | `FREIGHT_REPORT.ARTIFACT_EXPIRED` | 文件超过三年保留期 |
|
||||
| 422 | `FREIGHT_REPORT.PUBLISH_GATE_FAILED` | 未通过同 hash 配置测试 |
|
||||
| 503 | `RPA.WORKER_OFFLINE` | 无可用 v2 Worker 或共享目录不可用 |
|
||||
| 503 | `RPA.CALLBACK_UNAVAILABLE` | 回调处理依赖不可用 |
|
||||
|
||||
新增错误码必须同步 `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json`。所有接口响应包含 `request_id`,Worker 日志按该 ID 与 `correlation_id` 关联。
|
||||
|
||||
## 7. 接口验收标准
|
||||
|
||||
- 管理员可完成定义/模板草稿、测试、发布、退役闭环;普通用户所有写接口返回 403。
|
||||
- 相同 callback 重放只产生一条 Artifact、一组通知投递和一条 `ignored` 审计,不重复副作用。
|
||||
- 非法 selector、明文凭据、非 NULL 日期筛选、未发布版本和过期下载均被服务端拒绝。
|
||||
- 既有库存 callback API 回归测试通过;通用回调不会写入 `shipping_inventory_files`,库存桥接仅处理 `file_purpose=inventory`。
|
||||
- OpenAPI/接口契约测试覆盖成功 Envelope、错误 Envelope、Tool 回调契约、权限、幂等和下载审计。
|
||||
@@ -1,168 +0,0 @@
|
||||
# 货代通用报表 RPA 数据库设计文档
|
||||
|
||||
## 1. 设计原则
|
||||
|
||||
数据库使用 PostgreSQL + SQLAlchemy 2.0 + Alembic。新增模型集中于 `backend/app/models/freight_report.py`,迁移只新增通用报表表,不修改 `shipping_inventory_files`。所有时间使用 UTC `DateTime`;JSON 仅存结构化快照和脱敏证据,凭据始终沿用 `shipping_rpa_profiles` 的密文配置。
|
||||
|
||||
复用表:`schedule_tasks`(排程)、`schedule_runs`(平台调度事实)、`shipping_inventory_sources`(站点/仓库身份)、`shipping_rpa_profiles`(登录连接)、`users`(操作者/接收人)、`shipping_audit_events`(不可变审计)。
|
||||
|
||||
## 2. ER 关系
|
||||
|
||||
```text
|
||||
ShippingInventorySource 1--* FreightReportDefinition 1--* FreightReportDefinitionVersion
|
||||
FreightReportDriverTemplate 1--* FreightReportDriverTemplateVersion
|
||||
ScheduleTask 1--* ScheduleRun 1--1 FreightReportParentRun 1--* FreightReportUnitRun
|
||||
FreightReportDefinitionVersion 1--* FreightReportUnitRun
|
||||
FreightReportDriverTemplateVersion 1--* FreightReportUnitRun
|
||||
FreightReportUnitRun 1--* FreightReportArtifact
|
||||
FreightReportUnitRun/ParentRun 1--* FreightReportNotificationDelivery
|
||||
所有聚合对象 --soft reference--> ShippingAuditEvent
|
||||
```
|
||||
|
||||
## 3. 新增表
|
||||
|
||||
### 3.1 `freight_report_driver_templates`
|
||||
|
||||
| 字段 | 类型 | 约束/说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | bigint PK | 自增 |
|
||||
| `template_code` | varchar(64) | `UNIQUE NOT NULL`,稳定业务编号 |
|
||||
| `name` | varchar(128) | `NOT NULL` |
|
||||
| `connector_type` | varchar(32) | `CHECK IN ('dbs','crane')` |
|
||||
| `status` | varchar(16) | `draft/tested/published/retired` |
|
||||
| `current_published_version_id` | bigint nullable | 发布版本指针,迁移后补 FK |
|
||||
| `created_by/updated_by` | bigint nullable | FK `users.id` |
|
||||
| `created_at/updated_at` | timestamp | `NOT NULL` |
|
||||
|
||||
索引:`(connector_type,status)`;引用中的模板不得物理删除。
|
||||
|
||||
### 3.2 `freight_report_driver_template_versions`
|
||||
|
||||
| 字段 | 类型 | 约束/说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | bigint PK | 自增 |
|
||||
| `template_id` | bigint | FK 到模板,`NOT NULL` |
|
||||
| `version_no` | integer | `UNIQUE(template_id,version_no)` |
|
||||
| `status` | varchar(16) | 同生命周期;发布/退役版本不可更新 |
|
||||
| `selector_json` | jsonb | 仅 allowlist key/locator,禁止脚本 |
|
||||
| `timeout_json` | jsonb | 正整数超时/轮询配置 |
|
||||
| `download_rule_json` | jsonb | 文件名、扩展名、最小大小、校验规则 |
|
||||
| `content_hash` | varchar(64) | SHA-256,`NOT NULL` |
|
||||
| `tested_at/published_at/retired_at` | timestamp nullable | 生命周期事实 |
|
||||
| `created_by/created_at` | bigint/timestamp | 创建事实 |
|
||||
|
||||
索引:`(template_id,status,version_no DESC)`、`content_hash`。服务和 ORM 禁止更新发布版本;数据库迁移加入触发器或 rule,阻断 UPDATE/DELETE。
|
||||
|
||||
### 3.3 `freight_report_definitions`
|
||||
|
||||
| 字段 | 类型 | 约束/说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | bigint PK | 自增 |
|
||||
| `definition_code` | varchar(64) | `UNIQUE NOT NULL` |
|
||||
| `inventory_source_id` | bigint | FK `shipping_inventory_sources.id` |
|
||||
| `file_purpose` | varchar(16) | `inventory/receipt/shipment` |
|
||||
| `status` | varchar(16) | 生命周期状态 |
|
||||
| `current_published_version_id` | bigint nullable | 发布版本指针 |
|
||||
| `created_by/updated_by/created_at/updated_at` | 审计字段 | 与现有模型一致 |
|
||||
|
||||
约束:`UNIQUE(inventory_source_id,file_purpose)`,保证一个来源+用途只有一个定义实体;启用条件由已发布版本判断,不额外创建可漂移的 enabled 字段。
|
||||
|
||||
### 3.4 `freight_report_definition_versions`
|
||||
|
||||
| 字段 | 类型 | 约束/说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | bigint PK | 自增 |
|
||||
| `definition_id` | bigint | FK 定义 |
|
||||
| `version_no` | integer | `UNIQUE(definition_id,version_no)` |
|
||||
| `template_version_id` | bigint | FK 模板版本,`NOT NULL` |
|
||||
| `report_path_json` | jsonb | DBS/Crane 路径或报表名 |
|
||||
| `parameters_json` | jsonb | 业务参数;日期 NULL/default 表示不覆盖页面默认值 |
|
||||
| `warehouse_policy_json` | jsonb | DBS 固定 Warehouse 列表;Crane 为空/来源粒度 |
|
||||
| `content_hash` | varchar(64) | `NOT NULL` |
|
||||
| `status/tested_at/published_at/retired_at` | 生命周期字段 | 同模板版本 |
|
||||
| `created_by/created_at` | 审计字段 | |
|
||||
|
||||
索引:`(definition_id,status,version_no DESC)`、`(template_version_id)`;发布时模板版本必须是 published,成功测试 hash 必须相同。
|
||||
|
||||
### 3.5 `freight_report_parent_runs`
|
||||
|
||||
| 字段 | 类型 | 约束/说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | bigint PK | 自增 |
|
||||
| `parent_run_no` | varchar(64) | `UNIQUE NOT NULL` |
|
||||
| `schedule_run_id` | bigint | `UNIQUE FK schedule_runs.id` |
|
||||
| `mode` | varchar(16) | `production/test/retry` |
|
||||
| `status` | varchar(32) | `queued/running/success/partial_failed/failed` |
|
||||
| `definition_selection_snapshot_json` | jsonb | 来源/用途/版本冻结快照 |
|
||||
| `notify_snapshot_json` | jsonb | 接收人 ID 快照,不存通讯录敏感字段 |
|
||||
| `started_at/finished_at` | timestamp nullable | |
|
||||
| `created_by/created_at` | 审计字段 | |
|
||||
|
||||
索引:`(status,created_at DESC)`、`(schedule_run_id)`。
|
||||
|
||||
### 3.6 `freight_report_unit_runs`
|
||||
|
||||
| 字段 | 类型 | 约束/说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | bigint PK | 自增 |
|
||||
| `parent_run_id` | bigint | FK 父运行 |
|
||||
| `unit_run_no` | varchar(64) | `UNIQUE NOT NULL` |
|
||||
| `source_code` | varchar(64) | 来源快照,避免历史配置改写事实 |
|
||||
| `file_purpose` | varchar(16) | 枚举约束 |
|
||||
| `warehouse_id` | varchar(64) nullable | DBS 必填,Crane 可空 |
|
||||
| `definition_version_id/template_version_id` | bigint | FK 已发布版本 |
|
||||
| `definition_snapshot_json/driver_snapshot_json` | jsonb | 完整发布快照、脱敏 |
|
||||
| `status` | varchar(16) | `queued/dispatched/running/succeeded/failed/cancelled` |
|
||||
| `callback_id` | varchar(128) | `UNIQUE NOT NULL` |
|
||||
| `worker_execution_id` | varchar(64) nullable | Worker 执行事实 |
|
||||
| `retry_of_id` | bigint nullable | 自引用 FK,只能指向 failed 单元 |
|
||||
| `error_code/error_message` | varchar(64)/text nullable | 脱敏错误 |
|
||||
| `dispatched_at/claimed_at/finished_at/created_at` | timestamp | 生命周期时间 |
|
||||
|
||||
约束:`UNIQUE(parent_run_id,definition_version_id,warehouse_id)`;PostgreSQL 对 NULL 不相等,因此 Crane 使用空字符串规范化值,或采用 `UNIQUE NULLS NOT DISTINCT`(按目标 PostgreSQL 版本确定)。索引:`(parent_run_id,status)`、`(source_code,file_purpose,created_at DESC)`、`(callback_id)`、`(retry_of_id)`。
|
||||
|
||||
### 3.7 `freight_report_artifacts`
|
||||
|
||||
| 字段 | 类型 | 约束/说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | bigint PK | 自增 |
|
||||
| `artifact_no` | varchar(64) | `UNIQUE NOT NULL` |
|
||||
| `unit_run_id` | bigint | FK 单元运行 |
|
||||
| `storage_key` | varchar(500) | `UNIQUE NOT NULL`,仅内部对象定位 |
|
||||
| `original_name` | varchar(255) | 原始文件名 |
|
||||
| `content_type` | varchar(128) | |
|
||||
| `size_bytes` | bigint | `CHECK > 0` |
|
||||
| `sha256` | char(64) | `NOT NULL` |
|
||||
| `retention_expires_at` | timestamp | `NOT NULL`,创建后约三年 |
|
||||
| `deleted_at/deleted_reason` | timestamp/varchar(64) nullable | 到期删除对象事实 |
|
||||
| `created_at` | timestamp | |
|
||||
|
||||
约束:`UNIQUE(unit_run_id,sha256)`,防重复归档;索引 `(retention_expires_at,deleted_at)`、`(unit_run_id,created_at)`、`sha256`。不存完整下载 URL;到期后 `storage_key` 可保留摘要或按数据治理规则脱敏,Artifact 行不得删除。
|
||||
|
||||
### 3.8 `freight_report_notification_deliveries`
|
||||
|
||||
| 字段 | 类型 | 约束/说明 |
|
||||
| --- | --- | --- |
|
||||
| `id` | bigint PK | 自增 |
|
||||
| `parent_run_id/unit_run_id/artifact_id` | bigint nullable | 至少一个关联对象;文件消息关联 artifact,汇总关联 parent |
|
||||
| `recipient_user_id` | bigint | FK `users.id` |
|
||||
| `message_type` | varchar(16) | `file/summary` |
|
||||
| `idempotency_key` | varchar(160) | `UNIQUE NOT NULL` |
|
||||
| `media_id_hash` | varchar(64) nullable | 不保存媒体 ID 明文 |
|
||||
| `status` | varchar(16) | `pending/sent/failed` |
|
||||
| `provider_response_redacted_json` | jsonb | 企微响应脱敏摘要 |
|
||||
| `sent_at/created_at` | timestamp nullable | |
|
||||
|
||||
索引:`(parent_run_id,status)`、`(recipient_user_id,created_at DESC)`。服务端按唯一幂等键防重复推送。
|
||||
|
||||
## 4. 完整性、审计与迁移
|
||||
|
||||
1. 所有 FK 默认 `RESTRICT` 或不设级联删除;运行、版本和 Artifact 历史不可由上游配置删除抹去。
|
||||
2. `file_purpose`、连接器、状态、模式均使用 PostgreSQL `CHECK`,不创建数据库 Enum,降低多环境迁移耦合。
|
||||
3. 版本发布后应用层与数据库层双重拒绝 UPDATE/DELETE;草稿修改通过新增修订或允许更新并留下 `ShippingAuditEvent` 前后快照,最终实现以不可变版本新建为准。
|
||||
4. 审计不新增平行审计表,复用 `shipping_audit_events` 的 append-only trigger、哈希链、IP/UA hash 与永久保留。`aggregate_type` 取 `freight_report_definition`、`freight_report_template`、`freight_report_parent_run`、`freight_report_unit_run`、`freight_report_artifact`。
|
||||
5. Alembic 迁移顺序:建模板/定义主表 -> 建版本表 -> 回填发布指针 FK -> 建运行/Artifact/通知表 -> 建索引/检查约束/不可变触发器。迁移必须在空库和现有库升级验证。
|
||||
|
||||
## 5. 数据生命周期与容量
|
||||
|
||||
运行、版本、通知投递和审计永久保留。Artifact 文件对象及测试文件保留三年;定时清理仅对 `retention_expires_at <= now()` 且 `deleted_at IS NULL` 的对象执行,成功后写 `deleted_at/deleted_reason` 和审计。对象删除失败保留待重试状态,禁止删除数据库记录。
|
||||
@@ -1,484 +0,0 @@
|
||||
# 货代通用报表 RPA 分阶段实施设计
|
||||
|
||||
## 1. 文档状态
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 状态 | 已确认设计,待实施计划评审 |
|
||||
| 日期 | 2026-08-12 |
|
||||
| 范围 | DBS / Crane 的库存、收料、出货报表定时导出、快照归档、企微推送、审计和新 Worker 切换 |
|
||||
| 明确不做 | 报表内容解析、库存自动匹配、ERP 写入、自动重试、节假日规则、旧 Worker 并行消费 |
|
||||
| 实施原则 | 不修改现有 `scripts/rpa/freight_rpa_worker.py`;允许新增或调整后端的 v2 适配、能力识别和切换配置,但冻结既有库存 trigger、callback 与入库业务契约;先新建 Worker 并完成真实测试,再停旧 Worker 并切换 |
|
||||
|
||||
## 1.1 配套详细设计与数据库设计
|
||||
|
||||
本文件说明范围、决策、线框与分阶段验收;实施细节和数据库物理设计以下列文档为准:
|
||||
|
||||
- [详细设计说明](2026-08-12-freight-general-report-rpa-detailed-design.md):组件边界、请求/回调协议、状态机、幂等、权限、异常、切换与回退。
|
||||
- [数据库设计文档](2026-08-12-freight-general-report-rpa-database-design.md):表、字段、外键、约束、索引、审计与保留策略。
|
||||
- [API 接口文档](2026-08-12-freight-general-report-rpa-api.md):管理端、运行中心、文件下载、Worker 回调、权限、幂等和错误码。
|
||||
|
||||
## 2. 已确认业务规则
|
||||
|
||||
1. 新建一个平台排程:`freight-general-report-rpa`(货代通用报表 RPA)。现有 `shipping-inventory-rpa` 排程保留不动,直至新 Worker 准入通过后由管理员停用。
|
||||
2. 一条排程可选择 `inventory`、`receipt`、`shipment` 任意组合;所有选中类型共享同一 Cron、同一时区、同一接收人和同一启停状态。
|
||||
3. 排程选择既有库存源,不重复填写站点、登录、路径、仓库或技术 selector。
|
||||
4. DBS:每个固定 Warehouse 分别导出一份文件;收料路径为 `AWS / Bison / AWSBI / Inbound / Receipt Detail`,出货路径为 `AWS / Bison / AWSBI / Outbound / Shipment Order Detail`;日期字段保持页面 `NULL`,Owner、Type 等不覆盖页面默认值。
|
||||
5. Crane:库存源本身承担 Warehouse 区分;每个库存源分别新建 `On Hand Details`、`Inbound Details`、`Outbound Details` 报表,使用本次运行唯一 Description 轮询完成后下载,禁止下载历史列表中的最新文件。
|
||||
6. 三类文件均写入通用报表快照,原样归档并推送企微。仅 `inventory` 在完成通用快照后,调用既有库存快照入库回调;排程本身不触发库存匹配、锁定、订单推进或 ERP 操作。
|
||||
7. 收料、出货绝不写入 `ShippingInventoryFile`,也不进入库存匹配链路。
|
||||
8. 成功的每个文件均向当前排程接收人单独发送企微文件消息;所有执行单元结束后发送一条汇总卡片。部分失败仍推送成功文件和失败明细;全部失败只推送汇总失败卡片。
|
||||
9. 排程不自动重试。管理员可手动重试失败的单个执行单元;重试创建新的运行、快照、文件和审计,不覆盖历史。
|
||||
10. 原始正式和测试 Excel 都保留 3 年;文件到期后删除对象。审计永久保留,包含删除事件、SHA-256、关联运行和存储定位摘要。
|
||||
11. 普通业务用户只有运行、文件和审计摘要的查看权限,以及作为企微接收人;无配置、发布、启停、测试、重试或恢复权限。管理员拥有全部治理权限。
|
||||
12. 报表定义和 Driver 模板均采用 `draft -> tested -> published -> retired`。正式运行只读取不可变的已发布版本。
|
||||
13. 配置测试仅管理员可执行,对一条草稿定义和一个执行单位运行真实 RPA;结果进入测试快照,不推送企微、不写正式快照、不进入库存业务。
|
||||
14. 新 Worker 与旧 Worker 不并行运行。上线前新 Worker 必须在测试环境完成 DBS 与 Crane 的三类报表真实导出,并连续 5 个工作日成功处理既有库存 RPA;准入后可修改后端的 Worker 能力识别、版本校验或切换配置,停旧 Worker 后再启动新 Worker 处理生产目录。失败时停新 Worker 并回退旧 Worker。
|
||||
15. “库存导出无感切换”仅指既有库存排程、`shipping_inventory_rpa.v2` trigger、既有 inventory callback API、库存快照入库及下游业务行为保持兼容;不表示后端零改动。切换所需后端改动只能用于 v2 Worker 识别、能力校验、路由/开关和新增通用报表能力,不得改变上述既有库存业务契约。
|
||||
|
||||
## 3. 设计目标与边界
|
||||
|
||||
### 3.1 目标
|
||||
|
||||
```text
|
||||
管理员发布配置和排程
|
||||
-> 排程按 Cron 创建父运行
|
||||
-> 对 (库存源 x 勾选报表类型 x DBS Warehouse) 展开执行单元
|
||||
-> 新 Worker 执行并回调
|
||||
-> 通用文件快照、三年归档、文件级企微推送
|
||||
-> 父运行汇总通知、可追溯审计、可定点人工重试
|
||||
```
|
||||
|
||||
### 3.2 不可突破的领域边界
|
||||
|
||||
| 对象 | 责任 | 不允许承担 |
|
||||
| --- | --- | --- |
|
||||
| Inventory Source | 既有业务站点、RPA Profile、固定 Warehouse、库存领域身份 | 收料/出货文件的生命周期或 selector |
|
||||
| Freight Report Definition | 每个库存源的报表用途、路径、业务参数、已发布模板引用 | 明文凭据、任意脚本 |
|
||||
| Driver Template | 受控 selector、等待、下载与验证规则 | 业务仓库选择、接收人、任意 JavaScript |
|
||||
| General Report Snapshot | 原始文件、校验值、归档、下载及其运行事实 | Excel 字段解析、库存匹配、ERP 写入 |
|
||||
| Inventory callback bridge | 将 `inventory` 通用成功结果送入既有库存入库协议 | 驱动 receipt/shipment 的库存业务 |
|
||||
| Windows Worker | 消费已发布快照、浏览器操作、文件回传 | 修改配置、直接访问数据库、发送企微 |
|
||||
|
||||
## 4. 行业实践与选型结论
|
||||
|
||||
本方案吸收 Playwright、Temporal、n8n 的成熟思路,但不引入它们作为新增运行时依赖。
|
||||
|
||||
| 可借鉴实践 | 行业来源 | 本项目落地方式 |
|
||||
| --- | --- | --- |
|
||||
| 浏览器上下文隔离、可诊断 trace、稳定 locator 优先、下载回读 | [microsoft/playwright](https://github.com/microsoft/playwright),约 94k Stars(2026-08-12 查询) | 新 Worker 每个执行单元隔离 Page/Context;保存脱敏 trace/截图索引;下载后 SHA-256、扩展名、最小大小及文件名规则校验 |
|
||||
| 持久运行状态、幂等回调、不可变历史、人工重试 | Temporal 的 durable execution 模式 | 不新建 Temporal 集群;复用 `ScheduleRun + Job`,新增父运行/单元运行与 callback idempotency key,显式状态机收口 |
|
||||
| 已发布版本、凭据与执行节点分离、失败可观测 | [n8n-io/n8n](https://github.com/n8n-io/n8n),约 200k Stars(2026-08-12 查询) | 定义、Driver 模板、RPA Profile 三层分离;发布版本快照下发 Worker;配置测试与正式运行隔离 |
|
||||
| 企业 RPA 的受控资产、机器人身份、日志证据 | Robocorp 等 RPA 平台通用实践 | Worker 使用机器身份和受控密钥;后端拥有审计与通知;不允许浏览器脚本承载业务决策 |
|
||||
|
||||
选择理由:当前项目已有 Flask、SQLAlchemy、PostgreSQL、Redis、Windows Playwright Worker、目录触发和 Job/Schedule 基础。新增独立 Worker 和领域模型的风险、运维成本均小于引入新的工作流引擎;同时通过不可变版本、幂等回调、审计链和人工重试获得可接受的可靠性。
|
||||
|
||||
## 5. 总体架构与协议
|
||||
|
||||
```text
|
||||
Admin Vue
|
||||
| 定义/模板/测试/发布/排程/重试
|
||||
v
|
||||
Flask API -- PostgreSQL
|
||||
| |- published definition/template snapshots
|
||||
| |- parent run / unit run / artifact / audit events
|
||||
v
|
||||
Schedule Worker -- Job queue -- General report trigger JSON
|
||||
|
|
||||
v
|
||||
Windows freight_report_worker_v2.py
|
||||
|- legacy inventory trigger: existing protocol/callback
|
||||
|- general report trigger: v1 protocol/new callback
|
||||
|- DBS driver / Crane driver
|
||||
|
|
||||
v
|
||||
Shared drop directory -> callback API -> archive + WeCom
|
||||
```
|
||||
|
||||
### 5.1 新协议
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": "freight_general_report.v1",
|
||||
"action": "general_report_export",
|
||||
"callback_id": "GRU-...:C1",
|
||||
"worker_execution_id": "WEX-...",
|
||||
"mode": "production",
|
||||
"unit_run_no": "GRU-...",
|
||||
"definition_snapshot": {
|
||||
"definition_version_no": 3,
|
||||
"template_version_no": 5,
|
||||
"connector_type": "dbs",
|
||||
"source_code": "AWSBI",
|
||||
"file_purpose": "receipt",
|
||||
"warehouse_id": "...",
|
||||
"report_path": { "customer": "AWS", "program": "Bison", "program_label": "AWSBI", "report_group": "Inbound", "report_name": "Receipt Detail" },
|
||||
"parameters": []
|
||||
},
|
||||
"driver_snapshot": { "selector_profile": "published and allowlisted", "timeouts": {} },
|
||||
"credential_envelope": { "encrypted": true }
|
||||
}
|
||||
```
|
||||
|
||||
规则:Worker 只能读取其中的发布快照;不接收明文密码、不接收 JavaScript、不接收对象存储签名 URL;`callback_id` 全局唯一并且 callback 只能首次改变单元终态。
|
||||
|
||||
### 5.2 执行状态机
|
||||
|
||||
```text
|
||||
draft definition -> tested -> published -> retired
|
||||
|
||||
parent run: queued -> running -> success | partial_failed | failed
|
||||
unit run: queued -> dispatched -> running -> succeeded | failed | cancelled
|
||||
test unit: queued -> dispatched -> running -> succeeded | failed
|
||||
|
||||
failed --管理员手动重试--> 新 unit run(queued)
|
||||
```
|
||||
|
||||
状态只允许向终态推进。Worker 回调、文件归档、企微发送各有 idempotency key。任何重复 callback 只记录 `ignored` 审计事件,不重复存档或发消息。
|
||||
|
||||
## 6. 数据与审计设计
|
||||
|
||||
### 6.1 新实体
|
||||
|
||||
| 表/实体 | 核心字段 | 约束 |
|
||||
| --- | --- | --- |
|
||||
| `freight_report_driver_templates` | connector_type、name、status、current_published_version_id | 管理员维护;删除受引用对象被拒绝 |
|
||||
| `freight_report_driver_template_versions` | template_id、version_no、status、selector_json、timeout_json、download_rule_json、content_hash、tested_at、published_at | 发布后不可更新;selector key 必须白名单 |
|
||||
| `freight_report_definitions` | inventory_source_id、file_purpose、status、current_published_version_id | 每 Source + purpose 仅一个活动定义 |
|
||||
| `freight_report_definition_versions` | definition_id、version_no、template_version_id、report_path_json、parameters_json、warehouse_policy_json、content_hash、tested_at、published_at | 发布后不可更新;业务参数与技术 selector 分离 |
|
||||
| `freight_report_parent_runs` | schedule_run_id、run_no、mode、status、definition_selection_snapshot_json、notify_snapshot_json | 一次排程一个父运行 |
|
||||
| `freight_report_unit_runs` | parent_run_id、unit_run_no、source_code、file_purpose、warehouse_id、definition_version_id、template_version_id、status、callback_id、retry_of_id | 唯一键:父运行+定义版本+Warehouse;callback id 全局唯一 |
|
||||
| `freight_report_artifacts` | unit_run_id、artifact_no、storage_key、original_name、size_bytes、sha256、retention_expires_at、deleted_at、deleted_reason | 文件到期后只删除对象,行永久保留 |
|
||||
| `freight_report_notification_deliveries` | unit_run_id/parent_run_id、user_id、message_type、media_id、status、provider_response_redacted_json | 每用户+文件/汇总幂等 |
|
||||
|
||||
`file_purpose` 只能为 `inventory`、`receipt`、`shipment`。所有运行和 artifact 使用独立编号,不复用库存快照编号。
|
||||
|
||||
### 6.2 审计硬约束
|
||||
|
||||
复用 `ShippingAuditEvent` 的 append-only ORM/数据库保护及哈希链,不创建可改写的第二套审计表。事件的 `aggregate_type` 取 `freight_report_definition`、`freight_report_template`、`freight_report_parent_run`、`freight_report_unit_run` 或 `freight_report_artifact`。
|
||||
|
||||
每个业务动作必须写审计:
|
||||
|
||||
| 节点 | actor | 必填快照/证据 |
|
||||
| --- | --- | --- |
|
||||
| 新建、编辑、删除草稿 | admin | before/after 白名单快照、diff、请求人、时间、IP/UA 哈希 |
|
||||
| 配置测试开始/结束 | admin / worker | 测试定义和模板版本、选定 Warehouse、callback id、脱敏诊断证据 |
|
||||
| 发布/退役 | admin | 已测版本、内容 hash、前后状态、理由 |
|
||||
| 排程创建、编辑、启停 | admin | Cron、报表类型、库存源、接收人快照前后对比 |
|
||||
| 计划触发与单元展开 | system | parent/unit 编号、定义/模板/接收人发布快照 |
|
||||
| Worker 领取、导航、参数应用、下载、回调 | worker | 机器 ID、版本、时间、步骤结果、脱敏 trace 引用、错误码 |
|
||||
| 文件写入、校验、归档、到期删除 | system | 原始名、大小、SHA-256、对象 key 摘要、保留到期日、删除理由 |
|
||||
| 企微文件/汇总发送 | system | 接收人、消息类型、媒体 ID 摘要、响应脱敏摘要、发送结果 |
|
||||
| 手动重试 | admin | 原失败单元、失败原因、新旧运行关联、管理员理由 |
|
||||
| 查看和下载 | user/admin | 读取人、对象、时间、授权结果;不把下载 URL 写入审计 |
|
||||
|
||||
敏感信息规则:绝不写明文凭据、完整对象 URL、cookie、HTML 全量内容、原始 IP 或 UA。selector 可存于受限模板版本;审计中只存 selector/version/hash 和最少的失败证据。
|
||||
|
||||
## 7. 核心页面 MD 线框
|
||||
|
||||
### 7.1 报表定义管理(管理员)
|
||||
|
||||
```text
|
||||
+--------------------------------------------------------------------------------+
|
||||
| 货代报表定义 [配置测试] [新建定义] |
|
||||
+--------------------+-----------------------------------------------------------+
|
||||
| 库存源筛选 | Source | 类型 | 已发布版本 | 模板 | 状态 | 最近测试 | 操作 |
|
||||
| [DBS/Crane v] | AWSBI | 库存 | v3 | DBS v5| 已发布| 08-12 | 编辑 |
|
||||
| 用途 [全部 v] | AWSBI | 收料 | v2 | DBS v5| 草稿 | -- | 编辑 |
|
||||
| 状态 [全部 v] | AWSBI | 出货 | v2 | DBS v5| 已发布| 08-12 | 查看 |
|
||||
| [搜索_________] | ... |
|
||||
+--------------------+-----------------------------------------------------------+
|
||||
| 右侧详情 Drawer: 路径 / 固定 Warehouse / 参数覆盖 / 版本记录 / 审计时间线 |
|
||||
+--------------------------------------------------------------------------------+
|
||||
```
|
||||
|
||||
- 仅管理员可见新增、编辑、测试、发布、退役;普通用户无该路由权限。
|
||||
- 路径、固定 Warehouse 与参数属于定义版本;selector、超时、下载规则不可在此页编辑,只展示绑定模板版本。
|
||||
- 草稿编辑先写 before/after 审计;发布必须存在与内容 hash 匹配的成功配置测试。
|
||||
|
||||
### 7.2 Driver 模板编辑与发布(管理员)
|
||||
|
||||
```text
|
||||
+--------------------------------------------------------------------------------+
|
||||
| Driver 模板 / DBS Receipt v5 [保存草稿] [配置测试] [发布]|
|
||||
+----------------------+---------------------------------------------------------+
|
||||
| 左: 版本列表 | 右: 受控编辑表单 |
|
||||
| v5 草稿 | Connector: DBS Purpose: Receipt |
|
||||
| v4 已发布 | [导航 selector 组] [参数控件 selector 组] |
|
||||
| v3 已退役 | [创建/下载 selector 组] [超时/轮询] [文件验证规则] |
|
||||
| | 允许键仅白名单,CSS 长度/字符集校验,无脚本输入 |
|
||||
+----------------------+---------------------------------------------------------+
|
||||
| 测试证据:测试运行号、时间、Worker 版本、下载 SHA-256、失败步骤、审计链接 |
|
||||
+--------------------------------------------------------------------------------+
|
||||
```
|
||||
|
||||
- 模板编辑权限仅管理员;不允许自由 JavaScript、URL 回调或 Secret 字段。
|
||||
- 发布后不可编辑,只能复制为新草稿版本;所有正式单元固化引用发布版本。
|
||||
|
||||
### 7.3 配置测试(管理员)
|
||||
|
||||
```text
|
||||
+------------------------------------------------------------------------+
|
||||
| 配置测试:AWSBI / Receipt Detail X |
|
||||
+------------------------------------------------------------------------+
|
||||
| 定义草稿版本 [v3 v] Driver 草稿版本 [v5 v] |
|
||||
| 执行单位 / Warehouse [AWSBI-01 v] |
|
||||
| 模式:真实 RPA;不推送企微、不进入正式库存、不影响正式排程 |
|
||||
| |
|
||||
| [取消] [开始测试] |
|
||||
+------------------------------------------------------------------------+
|
||||
| 结果:等待中 / 成功 / 失败 文件:name.xlsx SHA-256: ... |
|
||||
| 步骤:登录 -> 导航 -> 填参 -> 创建 -> 下载 -> 校验 -> 测试归档 |
|
||||
+------------------------------------------------------------------------+
|
||||
```
|
||||
|
||||
- 只能选择定义中已配置的一个 Warehouse;Crane 无 Warehouse 参数时选择对应库存源执行单位。
|
||||
- 成功测试对象进入 test 存储前缀、三年保留;发布时验证测试版本与内容 hash 完全相同。
|
||||
|
||||
### 7.4 通用报表 RPA 排程(管理员)
|
||||
|
||||
```text
|
||||
+--------------------------------------------------------------------------------+
|
||||
| 新建 / 编辑:货代通用报表 RPA |
|
||||
+--------------------------------------------------------------------------------+
|
||||
| 名称 [________________] Cron [0 8 * * *] [Cron 设计器] 时区 [Asia/Shanghai]|
|
||||
| 库存源 [多选:仅启用且三类定义均有已发布版本的来源____________________] |
|
||||
| 报表类型 [x] 库存 [x] 收料 [x] 出货 |
|
||||
| 企微接收人 [多选____________________________________________________] |
|
||||
| 启用 [开关] |
|
||||
| |
|
||||
| 预览:N 个库存源 x 选中类型 x DBS 固定 Warehouse = M 个执行单元 |
|
||||
| [取消] [保存] |
|
||||
+--------------------------------------------------------------------------------+
|
||||
```
|
||||
|
||||
- 新任务 key 固定为 `freight-general-report-rpa`;不改写旧 `shipping-inventory-rpa`。
|
||||
- 保存时拒绝:无报表类型、无接收人、无可用库存源、所选类型没有已发布定义或 DBS 固定 Warehouse 为空。
|
||||
- 普通用户只查看该排程与运行,不显示保存、启停、手动执行、重试控件。
|
||||
|
||||
### 7.5 运行中心与定点重试(管理员/业务用户只读)
|
||||
|
||||
```text
|
||||
+--------------------------------------------------------------------------------+
|
||||
| 通用报表运行中心 [状态 v] [类型 v] [库存源 v] [日期范围____] [查询] |
|
||||
+--------------------------------------------------------------------------------+
|
||||
| 父运行 | 计划 | 触发 | 状态 | 成功/失败 | 接收人 | 开始/结束 | 详情 |
|
||||
| GRP... | 08:00| cron | 部分失败 | 8 / 1 | 3 | ... | [查看] |
|
||||
+--------------------------------------------------------------------------------+
|
||||
| 展开单元:来源 | 类型 | Warehouse | 版本 | 状态 | 文件 | SHA-256 | 操作 |
|
||||
| AWSBI | 收料 | WH01 | D3/T5 | 成功 | [下载] | ... | 管理员: 审计 |
|
||||
| AWSBI | 出货 | WH01 | D2/T5 | 失败 | -- | -- | 管理员: [重试] [审计] |
|
||||
+--------------------------------------------------------------------------------+
|
||||
```
|
||||
|
||||
- 普通用户仅能下载其可见范围内的文件、查看运行详情和脱敏审计摘要;下载动作本身写审计。
|
||||
- `重试`仅在单元失败时展示给管理员,必须填写理由;不会重跑兄弟单元。
|
||||
|
||||
### 7.6 审计详情(管理员完整,业务用户脱敏)
|
||||
|
||||
```text
|
||||
+--------------------------------------------------------------------------------+
|
||||
| 审计事件 #... [哈希链验证: 通过] |
|
||||
+--------------------------------------------------------------------------------+
|
||||
| 操作:REPORT_UNIT_FAILED 结果:failure 时间:2026-... |
|
||||
| 操作人:RPA Worker v2 / machine | 关联:父运行 / 单元 / 文件 / callback |
|
||||
| 原因:CRANE_REPORT_WAIT_TIMEOUT | 请求/相关编号:... |
|
||||
+----------------------------------+---------------------------------------------+
|
||||
| Before 快照 | After 快照 |
|
||||
| 发布定义 v3/hash... | 状态 failed,错误码... |
|
||||
+----------------------------------+---------------------------------------------+
|
||||
| 证据:trace 摘要、截图索引、下载 SHA-256、企微响应脱敏摘要、前后事件哈希 |
|
||||
+--------------------------------------------------------------------------------+
|
||||
```
|
||||
|
||||
## 8. 分阶段实施计划
|
||||
|
||||
### 阶段 0:契约、模型和审计底座
|
||||
|
||||
**目标**:建立不影响旧库存运行的通用报表领域模型、迁移、不可变版本与审计约束。
|
||||
|
||||
| 文件 | 修改内容 |
|
||||
| --- | --- |
|
||||
| `backend/app/models/freight_report.py`(新增) | 定义模板、模板版本、报表定义、定义版本、父运行、单元运行、Artifact、通知投递模型及索引/唯一约束 |
|
||||
| `backend/app/models/__init__.py` | 导出新模型,供迁移和服务使用 |
|
||||
| `backend/migrations/versions/<revision>_add_freight_general_report_models.py`(新增) | 创建所有新表、枚举 CheckConstraint、callback/幂等唯一索引及 3 年保留字段;不修改 `ShippingInventoryFile` |
|
||||
| `backend/app/services/shipping_notice/freight_report_audit_service.py`(新增) | 复用 `ShippingAuditEvent` 追加事件、白名单快照、diff、hash/evidence 引用 |
|
||||
| `backend/app/services/shipping_notice/freight_report_contract.py`(新增) | 定义 purpose、状态机、schema、selector 白名单、快照脱敏和版本 hash |
|
||||
| `backend/tests/test_freight_report_models.py`(新增) | 约束、唯一性、发布后不可变、Artifact 保留事实测试 |
|
||||
| `backend/tests/test_freight_report_audit.py`(新增) | 全节点审计、前后快照、不可更新删除、hash 链测试 |
|
||||
|
||||
**验收标准**:
|
||||
|
||||
- 数据库迁移可在空库和当前 schema 升级;`flask db upgrade` 成功。
|
||||
- 发布版本 ORM/API 均无法更新或删除;草稿可编辑且每次编辑生成审计前后快照。
|
||||
- 重复 callback id、父运行重复单元、同一来源活动定义重复均被数据库约束拒绝。
|
||||
- 审计测试覆盖表 6.2 中全部事件,`pytest` 通过。
|
||||
|
||||
### 阶段 1:定义、模板、配置测试和后台治理
|
||||
|
||||
**目标**:管理员能独立维护、测试和发布每库存源三类定义及受控 Driver 模板。
|
||||
|
||||
| 文件 | 修改内容 |
|
||||
| --- | --- |
|
||||
| `backend/app/api/admin/freight_reports.py`(新增) | 管理员定义/模板 CRUD、版本、测试、发布、退役、审计查询 API |
|
||||
| `backend/app/api/admin/__init__.py` 或既有 blueprint 注册文件 | 注册新管理 API,统一 `require_admin` 和错误 envelope |
|
||||
| `backend/app/services/shipping_notice/freight_report_definition_service.py`(新增) | 定义草稿、版本 hash、发布门禁、库存源归属校验 |
|
||||
| `backend/app/services/shipping_notice/freight_report_driver_template_service.py`(新增) | selector 白名单、模板版本、发布门禁、受引用退役规则 |
|
||||
| `backend/app/services/shipping_notice/freight_report_test_service.py`(新增) | 创建 test 单元、写 trigger、接收 test callback、test artifact 归档 |
|
||||
| `frontend/src/features/admin/api/freight-reports.api.ts`(新增) | 全部新 API 的 typed client |
|
||||
| `frontend/src/features/admin/modules/freight-reports/FreightReportDefinitionsPage.vue`(新增) | 线框 7.1 对应页面 |
|
||||
| `frontend/src/features/admin/modules/freight-reports/FreightReportDriverTemplatesPage.vue`(新增) | 线框 7.2 对应页面 |
|
||||
| `frontend/src/features/admin/modules/freight-reports/components/FreightReportTestDialog.vue`(新增) | 线框 7.3 对应测试流程 |
|
||||
| `frontend/src/locales/{zh-CN,zh-TW,en,th}/freightReports.json`(新增) | 四语言文案和错误码 |
|
||||
| `frontend/src/app/router/routes/<admin-routes>.ts`(修改,先以实际文件定位) | 注册管理员路由与权限元数据 |
|
||||
| `backend/tests/test_admin_freight_reports.py`(新增) | 权限、发布门禁、定义/模板 API、测试隔离 |
|
||||
| `frontend/src/features/admin/modules/freight-reports/*.spec.ts`(新增) | 表单、测试、发布禁用态和权限态单测 |
|
||||
|
||||
**验收标准**:
|
||||
|
||||
- 普通用户请求任一管理 API 返回 403;管理员可完成草稿-测试-发布-退役闭环。
|
||||
- 未通过与当前内容 hash 一致的成功测试时不能发布。
|
||||
- selector/超时字段违反白名单、超长、含脚本或未识别 key 时被服务端拒绝并记录 rejected 审计。
|
||||
- 测试产物有 `test` 隔离前缀、3 年保留、无企微投递、无 `ShippingInventoryFile` 写入。
|
||||
- 前端四语言完整,`npm run test:unit` 和 `npm run build` 通过。
|
||||
|
||||
### 阶段 2:通用排程、运行和文件生命周期
|
||||
|
||||
**目标**:新增独立通用排程,按已发布定义展开执行单元、持久化运行并完成正式归档/企微通知。
|
||||
|
||||
| 文件 | 修改内容 |
|
||||
| --- | --- |
|
||||
| `backend/app/services/schedule/job_registry.py` | 注册 `freight-general-report-rpa`,schema 含 `source_codes`、`file_purposes`,不改旧库存任务 |
|
||||
| `backend/app/services/schedule/job_options.py` | 提供只返回满足已发布定义条件的库存源选项 |
|
||||
| `backend/app/services/schedule/freight_general_report_job.py`(新增) | 创建父运行/单元、冻结版本/接收人快照、写新 trigger、defer 父 ScheduleRun |
|
||||
| `backend/app/services/schedule/freight_general_report_finalize.py`(新增) | callback 后聚合单元终态、文件级通知、汇总通知、超时收口;不自动重试 |
|
||||
| `backend/app/services/shipping_notice/freight_report_trigger_service.py`(新增) | 生成 `freight_general_report.v1` trigger,注入密文凭据和发布快照 |
|
||||
| `backend/app/services/shipping_notice/freight_report_artifact_service.py`(新增) | SHA-256、命名、原样归档、三年到期、受权下载、删除审计 |
|
||||
| `backend/app/services/shipping_notice/freight_report_notification_service.py`(新增) | 调用既有 `wecom_notify`,文件级和汇总级幂等投递 |
|
||||
| `backend/app/jobs/handlers/freight_report_retention.py`(新增) | 到期删除对象、保留 Artifact 与永久审计事实 |
|
||||
| `backend/app/api/schedule/freight_reports.py`(新增) | 运行、单元、下载、管理员重试 API |
|
||||
| `backend/app/api/schedule/blueprint.py` | 注册运行及下载路由 |
|
||||
| `backend/app/services/schedule/scheduler_service.py` | 为新 Job 复用现有排程通知字段,但通知实际由新 finalize 处理 |
|
||||
| `backend/tests/test_freight_general_report_schedule.py`(新增) | 展开、快照冻结、无自动重试、超时、单元定点重试 |
|
||||
| `backend/tests/test_freight_report_artifact_retention.py`(新增) | SHA-256、下载授权、3 年删除和审计保留 |
|
||||
| `backend/tests/test_freight_report_wecom_notifications.py`(新增) | 每文件、汇总、部分失败、全失败、幂等投递 |
|
||||
|
||||
**验收标准**:
|
||||
|
||||
- 新排程可选多个已发布库存源和多个用途;`0 8 * * *` 等现有 Cron 原样复用。
|
||||
- DBS 每个固定 Warehouse 展开一个单元;Crane 每个库存源每用途展开一个单元,不做 Warehouse 拆分。
|
||||
- 排程、手动触发、重试均冻结定义/模板/接收人版本;后续配置变更不影响已创建单元。
|
||||
- 成功文件有通用快照、可授权下载、SHA-256、3 年到期日;receipt/shipment 不写入库存表。
|
||||
- 部分失败、全失败及重复 callback 的行为满足第 2 节规则。
|
||||
|
||||
### 阶段 3:新 Worker 与 DBS/Crane 驱动
|
||||
|
||||
**目标**:以新脚本完全接管现有库存 trigger,同时实现通用报表新协议。旧 Worker 在本阶段不改动。
|
||||
|
||||
| 文件 | 修改内容 |
|
||||
| --- | --- |
|
||||
| `scripts/rpa/freight_report_worker_v2.py`(新增) | 新进程入口、双协议路由、心跳版本/能力上报、目录轮询、错误隔离;复用既有 credential/heartbeat 工具 |
|
||||
| `scripts/rpa/freight_report_legacy_inventory_adapter.py`(新增) | 消费当前 `shipping_inventory_rpa.v2` trigger,调用既有库存 Driver/回调语义,确保库存行为不变 |
|
||||
| `scripts/rpa/freight_report_common.py`(新增) | 结构化日志、脱敏、原子文件落盘、SHA-256、trigger claim、trace/截图索引 |
|
||||
| `scripts/rpa/freight_report_dbs_driver.py`(新增) | DBS 三用途导航、固定 Warehouse、保留 NULL/default 参数、View Report、下载和回读 |
|
||||
| `scripts/rpa/freight_report_crane_driver.py`(新增) | Crane 三用途新建报表、运行、Schedule Description 唯一标识、轮询、下载和回读 |
|
||||
| `scripts/rpa/freight_report_selector_registry.py`(新增) | 把已发布模板 selector 映射为 allowlisted Playwright 定位器;禁止执行任意脚本 |
|
||||
| `scripts/rpa/freight_report_callback.py`(新增) | 对既有库存 callback 与新通用 callback 分别签名发送、超时重试、回调失败隔离 |
|
||||
| `scripts/rpa/start_freight_report_worker_v2.ps1`(新增) | 复用现有主机/密钥/浏览器 Profile 的新启动入口;打印版本、目录、能力,不输出秘密 |
|
||||
| `scripts/rpa/README.md` | 增加 v2 单独部署、切换、回退、运行诊断、环境变量和禁止并行运行说明 |
|
||||
| `backend/app/api/shipping_notice_tools.py` 或实际 RPA callback blueprint | 保留旧 inventory callback 不变;新增通用报表 callback API 和机器身份校验 |
|
||||
| `backend/app/services/shipping_notice/freight_report_callback_service.py`(新增) | 验证 callback id、文件 hash、模式、版本与单元状态后写 artifact/finalize |
|
||||
| `backend/tests/test_freight_report_worker_v2.py`(新增) | 双协议路由、DBS/Crane driver mock、callback、落盘、重复处理、脱敏日志 |
|
||||
| `backend/tests/test_freight_report_callback.py`(新增) | callback 授权、幂等、hash/文件名校验、非法状态拒绝 |
|
||||
|
||||
**验收标准**:
|
||||
|
||||
- `freight_report_worker_v2.py` 能处理既有库存 trigger,库存入库/回调测试与当前正式契约一致。
|
||||
- DBS 对已确认 Receipt/Shipment 路径按 Warehouse 独立生成文件,日期保持 NULL,未传 Owner/Type 覆盖值。
|
||||
- Crane 对 `Inbound Details`、`On Hand Details`、`Outbound Details` 均由本次唯一 Description 创建、轮询、下载;测试证明不会选择历史列表中相同文件名的条目。
|
||||
- Worker 对每个单元独立失败,不阻塞同一批其他单元;不直接连 PostgreSQL、不直接发送企微。
|
||||
- 生产日志、trace、截图与 callback 不包含明文凭据、cookie、完整对象 URL 或原始报表数据。
|
||||
|
||||
### 阶段 4:管理页面、运行可视化、审计中心和权限
|
||||
|
||||
**目标**:完成管理员操作面和普通用户只读体验,所有操作节点可定位、可验证、可审计。
|
||||
|
||||
| 文件 | 修改内容 |
|
||||
| --- | --- |
|
||||
| `frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue` | 为新任务渲染用途多选与发布可用库存源;复用通用动态表单而非任务硬编码 |
|
||||
| `frontend/src/features/admin/modules/schedules/SchedulesPage.vue` | 展示通用报表任务说明、执行单元预览和管理员操作 |
|
||||
| `frontend/src/features/admin/modules/freight-reports/FreightReportRunCenterPage.vue`(新增) | 实现线框 7.5 运行中心、文件下载、失败单元重试入口 |
|
||||
| `frontend/src/features/admin/modules/freight-reports/FreightReportAuditDrawer.vue`(新增) | 实现线框 7.6、前后快照、证据、哈希链结果和权限脱敏 |
|
||||
| `frontend/src/features/workspace/.../FreightReportReadOnlyPage.vue`(新增,实际归属以现有 workspace 路由确认) | 普通用户只读运行、文件和审计摘要页面 |
|
||||
| `frontend/src/features/admin/api/schedule.api.ts` | 新任务、运行与重试类型 |
|
||||
| `frontend/src/locales/{zh-CN,zh-TW,en,th}/scheduleRuns.json` | 新运行状态、类型、审计与权限文案 |
|
||||
| `backend/app/services/shipping_notice/freight_report_query_service.py`(新增) | 管理员完整视图与普通用户脱敏只读视图、下载授权 |
|
||||
| `backend/tests/test_freight_report_permissions.py`(新增) | 普通用户无写入/重试/启停权限,仅能读取授权范围 |
|
||||
| `frontend/src/features/admin/modules/freight-reports/*.spec.ts`(新增) | 线框交互、权限隐藏、失败重试、状态展示 |
|
||||
|
||||
**验收标准**:
|
||||
|
||||
- 所有新增文案四语言齐全,无硬编码中文。
|
||||
- 普通用户 UI 和 API 均无法绕过权限修改/重试/启停;管理员可完成操作闭环。
|
||||
- 每个下载、查看、重试、发布、测试在审计页有可检索事件。
|
||||
- `npm run test:unit`、`npm run build`、后端针对性 pytest 与 `git diff --check` 均通过。
|
||||
|
||||
### 阶段 5:切换、真实验收和回退
|
||||
|
||||
**目标**:以不并行运行的方式安全替换现有 Worker;允许为 v2 接管更新后端的 Worker 能力识别、版本校验和切换配置,但不改变既有库存业务契约。
|
||||
|
||||
| 文件 | 修改内容 |
|
||||
| --- | --- |
|
||||
| `scripts/rpa/start_rpa_worker.ps1` | 本阶段不修改;保留为旧 Worker 回退入口 |
|
||||
| `scripts/rpa/start_freight_report_worker_v2.ps1` | 作为唯一新 Worker 启动入口,复用原主机、Profile、密钥和计划任务配置 |
|
||||
| `backend/app/services/shipping_notice/rpa_worker_heartbeat.py` 及实际 Worker 路由/配置文件(以实施时定位为准) | 识别 v2 Worker 的库存导出能力、版本和共享 scope;按受控配置将库存 trigger 消费者切至 v2,不修改 `shipping_inventory_rpa.v2` payload、既有 inventory callback API 或库存入库服务契约 |
|
||||
| `scripts/rpa/README.md` | 写入测试、停旧、启新、观察、回退的运维步骤 |
|
||||
| `docs/features/shipping-notice/technical.md` | 更新货代 RPA 架构、双协议、保留策略、审计和切换约束 |
|
||||
| `docs/funclist.md` | 标记通用报表 RPA 功能及状态 |
|
||||
| `docs/demand.md`、`docs/tec.md` | 仅在现有章节确有对应需求/架构描述时同步更新 |
|
||||
|
||||
**验收标准**:
|
||||
|
||||
- 测试环境 DBS 和 Crane 分别完成 inventory/receipt/shipment 共 6 类真实导出;文件、SHA-256、归档、企微和审计逐项核对。
|
||||
- 新 Worker 在测试环境连续 5 个工作日成功处理现有库存 RPA,且无库存 callback、快照入库、共享目录、心跳回归。
|
||||
- 切换窗口内先停止旧 Worker,确认旧进程已退出后才启动新 Worker;无双 Worker 消费。
|
||||
- 后端切换改动只改变 v2 Worker 的就绪/能力识别或受控路由;相同 `shipping_inventory_rpa.v2` 黄金 trigger 在切换前后产生等价的 callback、库存快照入库和终态语义。
|
||||
- 首个生产排程按预期完成;失败回退演练证明能停新 Worker、启动旧 Worker,且未重复处理已 claim 的 trigger。
|
||||
|
||||
## 9. 风险清单与控制
|
||||
|
||||
| 类别 | 风险 | 影响 | 控制措施 |
|
||||
| --- | --- | --- | --- |
|
||||
| 核心技术 | 新 Worker 对既有库存 trigger/callback 行为不完全等价,切换后库存无法入库 | 高 | 独立 legacy adapter、协议黄金测试、连续 5 工作日真实库存准入、保留旧启动入口 |
|
||||
| RPA 页面 | DBS/Crane DOM、文本或异步生成机制变更 | 高 | 发布模板版本、selector 白名单、配置测试、trace/截图索引、失败不自动重试 |
|
||||
| 业务数据 | 把 receipt/shipment 写入库存快照或触发匹配 | 高 | 表与 callback 分流、服务层断言、回归测试、审计检查 |
|
||||
| 并发 | callback 重放或 Worker 崩溃导致重复归档/重复推送 | 高 | callback 唯一键、状态机、通知投递幂等、原子文件落盘 |
|
||||
| 权限 | 普通用户绕过 UI 调用重试或读取未授权文件 | 高 | 服务端 RBAC、下载授权、访问审计、前端仅作体验控制 |
|
||||
| 凭据 | selector/日志/trigger 泄漏密码、cookie 或对象 URL | 高 | 密文 envelope、日志脱敏、字段白名单、禁止脚本、测试扫描 |
|
||||
| 存储 | 3 年文件积累超出磁盘/对象存储容量 | 中 | 容量预估、对象生命周期、归档监控、到期只删对象不删审计 |
|
||||
| 企微 | 部分投递失败造成用户误认为全部成功 | 中 | 每文件投递状态、汇总卡片、失败列表、通知审计;不重发成功文件 |
|
||||
| 进度 | Crane 三个页面 selector 和报表完成条件未完整验证 | 高 | 先以真实配置测试建立 selector 基线,再承诺生产切换日期 |
|
||||
| 资源 | 单 Windows 主机浏览器资源不足、8 点批次拥塞 | 中 | 单 Worker 串行/受控并发、单元超时、队列长度/耗时监控、按现有排程拆分 |
|
||||
| 变更治理 | 管理员直接修改生产 selector 导致全站失败 | 高 | draft-test-publish、发布不可变、强制回归测试与退役/回滚版本 |
|
||||
|
||||
### 核心关键风险项:新 Worker 接管既有库存 RPA 的等价性
|
||||
|
||||
这是上线阻断风险,不是普通缺陷。库存 RPA 已连接库存快照入库与下游业务;即使通用收料/出货功能正确,若新 Worker 在旧 trigger、callback、心跳、目录处理、文件落盘或失败语义上与旧 Worker 有差异,仍可能造成库存快照缺失或状态悬挂。
|
||||
|
||||
**必须满足的放行证据**:旧协议黄金样本回放全通过、测试环境 DBS/Crane 三类真实报表通过、新 Worker 连续 5 个工作日库存 RPA 成功、心跳/共享 scope/回调幂等回归通过、停旧启新及回退演练通过。任一项不满足,禁止生产切换。
|
||||
|
||||
## 10. 开发与验收顺序
|
||||
|
||||
1. 先完成阶段 0,再进行阶段 1;未有不可变定义和审计,不允许写新 trigger。
|
||||
2. 阶段 2 的通用排程仅消费已发布配置;不以草稿配置“先跑再说”。
|
||||
3. 阶段 3 完成新 Worker 前,不修改 `scripts/rpa/freight_rpa_worker.py`。
|
||||
4. 阶段 4 所有 UI 必须先调用受 RBAC 保护的 API,再实现权限隐藏。
|
||||
5. 阶段 5 是唯一允许接管生产目录的阶段;切换不得让旧、新 Worker 并行。
|
||||
|
||||
## 11. 非目标与待现场验证项
|
||||
|
||||
- 不实现 Excel 行级解析、内容预览、检索、库存匹配、ERP 写入或自动创建业务单据。
|
||||
- 不引入假日逻辑;管理员自行在现有排程中配置 Cron 和启停。
|
||||
- 不要求历史库存排程迁移到新排程;新通用排程独立创建。
|
||||
- DBS 当前只确认 AWS/Bison/AWSBI 示例路径;其他现有库存源由管理员按定义/模板配置、测试、发布后启用。
|
||||
- Crane 三类报表的真实 query route、参数控件、生成完成信号和下载 DOM 必须在测试环境配置测试中逐项固化;不可用截图推断替代真实验证。
|
||||
@@ -1,90 +0,0 @@
|
||||
# 货代通用报表 RPA 详细设计说明
|
||||
|
||||
## 1. 目的与范围
|
||||
|
||||
本文是 [主设计](2026-08-12-freight-general-report-rpa-design.md) 的实施级说明。系统新增 `freight-general-report-rpa` 排程,在 DBS 与 Crane 导出库存、收料、出货报表,原样归档并逐文件推送企业微信。库存成功文件额外进入既有库存快照入库桥接;收料和出货不解析、不匹配、不写 ERP。
|
||||
|
||||
旧 `shipping-inventory-rpa` 与 `scripts/rpa/freight_rpa_worker.py` 在准入完成前保持不变。v2 可修改后端的能力识别与路由配置,但不得修改 `shipping_inventory_rpa.v2` 的 payload、既有 inventory callback API、库存快照入库及下游语义。
|
||||
|
||||
## 2. 组件与职责
|
||||
|
||||
| 组件 | 位置 | 责任 | 禁止事项 |
|
||||
| --- | --- | --- | --- |
|
||||
| 定义服务 | `shipping_notice/freight_report_definition_service.py` | 草稿、版本 hash、测试、发布、退役 | 保存明文凭据、直接执行 RPA |
|
||||
| 模板服务 | `shipping_notice/freight_report_driver_template_service.py` | selector 白名单、等待/下载规则版本化 | 接受任意 JS/回调 URL |
|
||||
| 排程 Job | `schedule/freight_general_report_job.py` | 冻结快照、展开父/单元运行、投递 trigger | 等待浏览器操作、直接发企微 |
|
||||
| 回调服务 | `shipping_notice/freight_report_callback_service.py` | 认证、幂等、文件校验、归档、库存桥接 | 重新解释定义或选择历史报表 |
|
||||
| 收尾服务 | `schedule/freight_general_report_finalize.py` | 父运行汇总、文件/汇总通知、超时收口 | 自动重试失败单元 |
|
||||
| v2 Worker | `scripts/rpa/freight_report_worker_v2.py` | 双协议路由、浏览器导出、下载校验、回调 | 访问 PostgreSQL、发送企微、修改定义 |
|
||||
| legacy adapter | `scripts/rpa/freight_report_legacy_inventory_adapter.py` | 原样处理既有库存 v2 trigger/callback | 将 receipt/shipment 混入库存链路 |
|
||||
|
||||
## 3. 运行流程
|
||||
|
||||
```text
|
||||
管理员发布 Definition/Driver Template
|
||||
-> 创建/启用 freight-general-report-rpa 排程
|
||||
-> Cron 创建 ScheduleRun + ParentRun
|
||||
-> 按来源/用途/Warehouse 展开 UnitRun,冻结版本与接收人
|
||||
-> 投递 freight_general_report.v1 trigger
|
||||
-> v2 Worker 领取、导出、校验、回调
|
||||
-> Artifact 原样归档;inventory 进入既有入库桥接
|
||||
-> 每成功文件企微投递;所有单元结束后汇总投递
|
||||
-> ParentRun 成功/部分失败/失败
|
||||
```
|
||||
|
||||
### 3.1 单元展开
|
||||
|
||||
1. 排程只能选择启用库存源和每个已选用途均存在已发布定义的来源。
|
||||
2. DBS 按定义内固定 Warehouse 列表拆分:`source x purpose x warehouse` 一条 `UnitRun`;报告日期不传值,页面保持 `NULL`,Owner/Type 不覆盖默认值。
|
||||
3. Crane 按库存源拆分:`source x purpose` 一条 `UnitRun`;每次新建报表并写入唯一 Description,只等待该 Description 对应结果,禁止选择历史“最新”文件。
|
||||
4. 创建时冻结 definition/template 版本、定义/模板内容 hash、接收人、来源显示名、Warehouse 与排程参数;后续配置变更不影响已创建单元。
|
||||
|
||||
### 3.2 通用 trigger 与 callback
|
||||
|
||||
通用 trigger 使用 `schema_version=freight_general_report.v1`、`action=general_report_export` 和全局唯一 `callback_id`。包含已发布定义/模板快照、执行模式、单元编号和密文凭据 envelope;不包含明文密码、Cookie、签名下载 URL 或任意脚本。
|
||||
|
||||
Worker 必须先对 trigger 做原子 claim,再执行。成功 callback 必须带 `callback_id`、单元号、文件路径/受控共享定位、原始文件名、字节数、SHA-256、诊断摘要;失败 callback 必须带结构化错误码和脱敏错误信息。服务端以 `callback_id` 和 UnitRun 状态机校验:首次合法回调可推进终态,重复回调仅记录 `ignored` 审计,绝不再次归档或推送。
|
||||
|
||||
### 3.3 库存兼容桥接
|
||||
|
||||
v2 以独立 adapter 消费既有 `shipping_inventory_rpa.v2` trigger,保留旧批量领取、逐源身份字段、无库存 `skipped` 语义和 `/rpa/inventory-batch-ready` callback。新通用库存单元的成功 Artifact 在校验和归档完成后,调用既有库存快照入库服务;桥接失败使该库存 UnitRun 失败,但不影响 receipt/shipment 单元。新通用排程不触发库存匹配、锁定、订单推进或 ERP 写入。
|
||||
|
||||
## 4. 状态机与异常处理
|
||||
|
||||
```text
|
||||
Definition/Template: draft -> tested -> published -> retired
|
||||
ParentRun: queued -> running -> success | partial_failed | failed
|
||||
UnitRun: queued -> dispatched -> running -> succeeded | failed | cancelled
|
||||
failed UnitRun --admin reason--> new UnitRun(queued, retry_of_id=old)
|
||||
```
|
||||
|
||||
- 发布门禁:必须存在相同 definition/template `content_hash` 的成功测试;发布版本不可更新或删除,只能复制为新草稿。
|
||||
- 回调超时:未终态单元标为失败,父运行按成功/失败数收口;不自动重试。
|
||||
- 部分失败:成功文件照常归档并推送,汇总包含失败单元及错误码;全部失败仅推送失败汇总。
|
||||
- 手工重试:仅管理员、仅失败单元、必须填写原因;新建运行及 Artifact,不覆盖原记录。
|
||||
- 文件校验失败(缺失、大小不足、扩展名不符、SHA 不符):拒绝 callback,记录失败审计,不发送文件。
|
||||
|
||||
## 5. 权限、审计与保留
|
||||
|
||||
管理员拥有定义、模板、测试、发布、排程、重试、恢复与完整审计访问权。普通业务用户仅能查看获授权的运行、文件和脱敏审计摘要,并作为企业微信接收人;服务端 RBAC 必须拒绝其写操作。
|
||||
|
||||
所有创建、编辑、测试、发布、退役、排程变更、触发、领取、回调、归档、下载、通知、重试和到期删除均追加 `ShippingAuditEvent`。记录操作人、时间、白名单 before/after 快照、diff、关联编号、结果和脱敏证据引用;审计永久保留。正式及测试文件保留三年,到期只删除对象,不删除 Artifact 行或审计。
|
||||
|
||||
## 6. 切换与回退
|
||||
|
||||
1. v2 在测试环境完成 DBS/Crane 三用途真实导出,并通过旧库存协议黄金样本、心跳、共享目录、callback 幂等与库存入库回归。
|
||||
2. v2 连续五个工作日成功处理既有库存 RPA 后,才允许进入生产切换窗口。
|
||||
3. 后端可更新 Worker 能力识别、版本校验、受控路由/开关;相同库存 v2 trigger 必须产生等价 callback 和终态。
|
||||
4. 停止旧 Worker,确认进程退出且不再持有 trigger 目录后,启动 v2;两个 Worker 不得同时消费库存目录。
|
||||
5. 首个生产排程逐项核对。若失败,停 v2、恢复旧 Worker 和原路由;以 claim/callback 幂等键避免重复处理。
|
||||
|
||||
## 7. 实施验证矩阵
|
||||
|
||||
| 类别 | 必验事实 |
|
||||
| --- | --- |
|
||||
| 契约 | 新旧库存 v2 trigger 的 callback、入库、`success/failed/skipped` 终态等价 |
|
||||
| DBS | 每 Warehouse 单独文件;日期 NULL;默认 Owner/Type 未被覆盖 |
|
||||
| Crane | 三类报表均用本次唯一 Description 创建、轮询、下载,无历史文件误取 |
|
||||
| 幂等 | 重放 callback、重启 Worker、重复通知均不产生重复 Artifact/企微消息 |
|
||||
| 权限 | 普通用户 API/UI 无法配置、发布、启停或重试;下载/查看均留审计 |
|
||||
| 回退 | 停 v2、启旧 Worker 后未处理 trigger 可继续处理,已领取/回调单元不重复 |
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
### 阶段与状态职责基线(2026-08)
|
||||
|
||||
业务阶段固定为 `intake_parse`、`order_review`、`fulfillment_prep`、`upload_complete` 四项(接收解析、订单复核、发货准备、上传完成);Gate/Execution 负责业务判断,`ui_state` 负责前端投影,`lifecycle_status` 独立表示 active/voided/archived,`process_status` 已删除。
|
||||
业务阶段固定为 `intake_parse`、`order_review`、`fulfillment_prep`、`upload_complete` 四项(接收解析、订单复核、通知准备、通知完成);Gate/Execution 负责业务判断,`ui_state` 负责前端投影,`lifecycle_status` 独立表示 active/voided/archived,`process_status` 已删除。`ui_state.stage_context` 是正式任务详情按需返回的只读阶段事实,不是新的 State、数据库字段或动作权限来源;上传成功必须以 `ShippingUploadAttempt.status=succeeded` 为准。
|
||||
|
||||
### STP 阶段 0:字段契约与状态语义冻结(2026-07-30,项次派生 Phase 0 纠偏)
|
||||
|
||||
|
||||
@@ -315,6 +315,32 @@ export const listOrderProfileSampleXfaSyntheticPreviewPages = (documentId: numbe
|
||||
export const orderProfileSampleXfaSyntheticPreviewPagePath = (documentId: number, pageNo: number) =>
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview/pages/${pageNo}`;
|
||||
|
||||
/** 入队统一 PDF 自动标记;服务端按 Profile 能力选择坐标或 XFA 多源证据。 */
|
||||
export const enqueueOrderProfilePdfAutomark = (
|
||||
profileId: number,
|
||||
payload: { document_id: number; table_id?: string; schema_version_id?: number; page_no?: number; force?: boolean },
|
||||
) => requestJson<{ job_id: number; status: string }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/pdf-automark`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 轮询统一 PDF 自动标记 Job;候选格式不暴露模板类型。 */
|
||||
export const getOrderProfilePdfAutomarkJob = (profileId: number, jobId: number) =>
|
||||
requestJson<{
|
||||
job_id: number;
|
||||
status: string;
|
||||
kind?: 'coordinate_regions' | 'visual_binding' | null;
|
||||
candidates?: Array<Record<string, unknown>>;
|
||||
diagnostics?: Record<string, unknown>;
|
||||
preview_render_checksum?: string | null;
|
||||
renderer_version?: string | null;
|
||||
error_code?: string | null;
|
||||
message?: string | null;
|
||||
}>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/pdf-automark/jobs/${jobId}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 入队 XFA OCR 自动标记 Job(须合成预览 ready)。 */
|
||||
export const enqueueOrderProfileXfaOcrAutomark = (
|
||||
profileId: number,
|
||||
@@ -645,6 +671,17 @@ export const authorizeOrderProfilePreviewPages = (profileId: number, documentId:
|
||||
},
|
||||
);
|
||||
|
||||
/** 为统一编辑画布申请一次性原 PDF 内存读取令牌;响应绝不包含存储地址。 */
|
||||
export const authorizeOrderProfilePdfPreview = (profileId: number, documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').OrderProfilePdfPreviewGrant>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/pdf-preview`, {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId }), ...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** @deprecated 旧 XFA 调用方兼容别名;新代码使用 authorizeOrderProfilePdfPreview。 */
|
||||
export const authorizeOrderProfileXfaPdfPreview = authorizeOrderProfilePdfPreview;
|
||||
|
||||
/** 为冻结样本绑定申请只读详情页逐页预览授权,禁止回退到当前 document layout。 */
|
||||
export const authorizeOrderProfileFrozenSamplePreviewPages = (profileId: number, sampleBindingId: number) =>
|
||||
requestJson<OrderProfilePreviewPages>(
|
||||
|
||||
+70
-145
@@ -21,13 +21,15 @@ import { BusinessError } from "@/shared/api/client";
|
||||
import { useMessage } from "@/shared/composables/useMessage";
|
||||
import { getShippingOrderSchemaState } from "@/features/admin/api/shipping-order-schema.api";
|
||||
import {
|
||||
authorizeOrderProfilePreviewPages,
|
||||
authorizeOrderProfilePdfPreview,
|
||||
addOrderProfileTrainingSample,
|
||||
listOrderDocumentProfiles,
|
||||
acquireOrderDocumentProfileEditLease,
|
||||
decideOrderDocumentProfileSuggestion,
|
||||
enqueueOrderProfilePdfAutomark,
|
||||
generateOrderProfileOcrCoordinateEvidence,
|
||||
getOrderDocumentProfileDetail,
|
||||
getOrderProfilePdfAutomarkJob,
|
||||
getOrderProfileSampleTables,
|
||||
listOrderProfileBoundSamples,
|
||||
listOrderProfileSamples,
|
||||
@@ -37,9 +39,7 @@ import {
|
||||
renewOrderDocumentProfileEditLease,
|
||||
readOrderProfilePreviewPageRegionText,
|
||||
suggestOrderProfileHeader,
|
||||
suggestOrderProfileOrderFields,
|
||||
saveOrderDocumentProfileDraft,
|
||||
suggestOrderProfileCoordinateReconstruction,
|
||||
} from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import type {
|
||||
CoordinateReconstructionPreview,
|
||||
@@ -52,7 +52,6 @@ import type {
|
||||
OrderFieldLayoutSuggestion,
|
||||
OrderProfileRowReconstructionMode,
|
||||
ShippingOrderDocumentProfile,
|
||||
XfaValueBindingType,
|
||||
} from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
import {
|
||||
asCoordinateProfileDefinition,
|
||||
@@ -124,8 +123,9 @@ const samples = ref<
|
||||
const schemas = ref<ShippingOrderSchemaVersion[]>([]);
|
||||
const active = ref<ShippingOrderDocumentProfile | null>(null);
|
||||
const boundSamples = ref<OrderProfileBoundSample[]>([]);
|
||||
const pageGrant = ref<{ page_no: number; preview_token: string } | null>(null);
|
||||
const pageGrants = ref<Array<{ page_no: number; preview_token: string }>>([]);
|
||||
/** 坐标 PDF 与 XFA 共用原 PDF + PDF.js 画布;PDFium 页图仅留给后端证据生成。 */
|
||||
const pdfPreviewGrant = ref<{ document_id: number; preview_token: string; expires_in_seconds: number } | null>(null);
|
||||
const pdfPageCount = ref(1);
|
||||
const pageNo = ref(1);
|
||||
const sampleTables = ref<
|
||||
Array<{
|
||||
@@ -234,15 +234,13 @@ function onDeskAcceptXfaSuggestion(): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* 驳回首条 XFA OCR 建议,或关闭视觉候选(工具栏「拒绝建议」入口)。
|
||||
* 驳回首条 XFA OCR 建议(工具栏「拒绝建议」入口)。
|
||||
*/
|
||||
function onDeskRejectXfaSuggestion(): void {
|
||||
const next = xfaDesk.autoMarkSuggestions[0];
|
||||
if (next) {
|
||||
void xfaDesk.onRejectAutomark(next);
|
||||
return;
|
||||
}
|
||||
xfaDesk.dismissPendingSuggestion();
|
||||
}
|
||||
|
||||
|
||||
@@ -260,14 +258,6 @@ function assignXfaSplitRulePanel(el: unknown): void {
|
||||
xfaDesk.splitRulePanel = (el as typeof xfaDesk.splitRulePanel) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新选中绑定的正式取值模式。
|
||||
*/
|
||||
function onXfaReadingModeChange(event: Event): void {
|
||||
const value = (event.target as HTMLSelectElement).value as XfaValueBindingType;
|
||||
xfaDesk.updateSelectedReadingMode(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 共享画布是否只读:XFA 在页授权失败 / 页不可用时禁用标注工具;
|
||||
* 右侧非视觉字段(数据源/拆分等)不受此约束。
|
||||
@@ -345,28 +335,11 @@ const xfaTableRegionSetting = computed(() => {
|
||||
* XFA 后台仍可走 automark Job,但 UI 不再使用专用 OCR 底栏。
|
||||
*/
|
||||
async function onDeskCanvasSuggest(): Promise<void> {
|
||||
if (isXfaTemplate.value) {
|
||||
if (suggestingRegions.value || deskCanvasReadonly.value) return;
|
||||
suggestingRegions.value = true;
|
||||
suggestionProgress.value = t('admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing');
|
||||
try {
|
||||
await xfaDesk.startAutomarkJob(true);
|
||||
const count = xfaDesk.autoMarkSuggestions.length;
|
||||
suggestionProgress.value = count > 0
|
||||
? t('admin.shippingOrderProfiles.workbench.autoSuggestComplete')
|
||||
: t('admin.shippingOrderProfiles.workbench.autoSuggestNoRows');
|
||||
} catch {
|
||||
suggestionProgress.value = t('admin.shippingOrderProfiles.workbench.autoSuggestFailed');
|
||||
} finally {
|
||||
suggestingRegions.value = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
void suggestRegions();
|
||||
}
|
||||
|
||||
/**
|
||||
* 画布创建框:XFA 走统一 mapping;PDF 落本地区域。
|
||||
* 画布创建框:XFA/PDF 均立即落本地视觉框;XFA 正式 datasets 映射由右侧配置完成。
|
||||
*/
|
||||
function onDeskCanvasCreate(region: OrderProfileRelativeRegion): void {
|
||||
if (isXfaTemplate.value) {
|
||||
@@ -742,11 +715,7 @@ const selectedHeaderLayoutId = computed(() => {
|
||||
const selected = selectedRegion.value;
|
||||
return selected?.kind === "header_field" ? selected.parentId || null : null;
|
||||
});
|
||||
const pageCount = computed(() =>
|
||||
pageGrants.value.length
|
||||
? Math.max(...pageGrants.value.map((item) => item.page_no))
|
||||
: 1,
|
||||
);
|
||||
const pageCount = computed(() => pdfPageCount.value);
|
||||
/** 将任意订单字段编码转换为当前冻结 Schema 的业务名称,避免单头候选泄露内部编码。 */
|
||||
const schemaFieldLabel = (fieldCode: string) =>
|
||||
[...headerFields.value, ...lineFields.value].find(
|
||||
@@ -1548,51 +1517,56 @@ const save = async (automatic = false) => {
|
||||
/** 创建只含主行区域的最小草稿并自动绑定样本,之后才允许打开受控页面画布标注。 */
|
||||
/** 以启用的 Schema 字段规则和冻结坐标生成待复核标记,绝不自动发布模板。 */
|
||||
const suggestRegions = async () => {
|
||||
if (!form.documentId || !form.tableId || suggestingRegions.value) return;
|
||||
if (suggestingRegions.value || !active.value) return;
|
||||
// XFA desk owns the annotation sample lifecycle. The coordinate editor's
|
||||
// form.documentId can still be empty while the XFA desk has already loaded
|
||||
// its authoritative annotation sample, so do not silently drop the action.
|
||||
const documentId = isXfaTemplate.value
|
||||
? xfaDesk.annotationDocumentId
|
||||
: form.documentId;
|
||||
if (!documentId) {
|
||||
suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestFailed");
|
||||
message.error(t("admin.shippingOrderProfiles.workbench.autoSuggestFailed"));
|
||||
return;
|
||||
}
|
||||
if (!isXfaTemplate.value && !form.tableId) return;
|
||||
suggestingRegions.value = true;
|
||||
suggestionProgress.value = t(
|
||||
"admin.shippingOrderProfiles.workbench.autoSuggestCheckingCoordinates",
|
||||
);
|
||||
try {
|
||||
const orderFields = await suggestOrderProfileOrderFields(
|
||||
form.documentId,
|
||||
form.schemaId,
|
||||
pageNo.value,
|
||||
);
|
||||
let suggestion;
|
||||
try {
|
||||
suggestionProgress.value = t(
|
||||
"admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing",
|
||||
);
|
||||
suggestion = await suggestOrderProfileCoordinateReconstruction(
|
||||
form.documentId,
|
||||
form.tableId,
|
||||
undefined,
|
||||
form.schemaId,
|
||||
);
|
||||
} catch (error) {
|
||||
if (
|
||||
!(error instanceof BusinessError) ||
|
||||
error.code !==
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE"
|
||||
)
|
||||
throw error;
|
||||
suggestionProgress.value = t(
|
||||
"admin.shippingOrderProfiles.workbench.autoSuggestOcr",
|
||||
);
|
||||
await generateOrderProfileOcrCoordinateEvidence(
|
||||
form.documentId,
|
||||
form.tableId,
|
||||
);
|
||||
suggestionProgress.value = t(
|
||||
"admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing",
|
||||
);
|
||||
suggestion = await suggestOrderProfileCoordinateReconstruction(
|
||||
form.documentId,
|
||||
form.tableId,
|
||||
undefined,
|
||||
form.schemaId,
|
||||
);
|
||||
suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing");
|
||||
const queued = await enqueueOrderProfilePdfAutomark(active.value.id, {
|
||||
document_id: documentId,
|
||||
table_id: isXfaTemplate.value ? undefined : form.tableId,
|
||||
schema_version_id: form.schemaId,
|
||||
page_no: pageNo.value,
|
||||
force: true,
|
||||
});
|
||||
let job;
|
||||
for (;;) {
|
||||
job = await getOrderProfilePdfAutomarkJob(active.value.id, queued.job_id);
|
||||
if (!['queued', 'running', 'pending'].includes(String(job.status || ''))) break;
|
||||
await new Promise<void>((resolve) => { window.setTimeout(resolve, 500); });
|
||||
}
|
||||
if (String(job.status) !== 'success') {
|
||||
throw new Error(String(job.error_code || job.message || 'PDF automark failed'));
|
||||
}
|
||||
const candidates = Array.isArray(job.candidates) ? job.candidates : [];
|
||||
if (job.kind === 'visual_binding') {
|
||||
xfaDesk.applyPdfAutomarkCandidates(candidates);
|
||||
xfaDesk.applyPdfAutomarkRenderIdentity(job.preview_render_checksum);
|
||||
suggestionProgress.value = candidates.length
|
||||
? t("admin.shippingOrderProfiles.workbench.autoSuggestComplete")
|
||||
: t("admin.shippingOrderProfiles.workbench.autoSuggestNoRows");
|
||||
return;
|
||||
}
|
||||
const reconstructionCandidate = candidates.find((item) => item?.candidate_kind === 'coordinate_reconstruction');
|
||||
const orderFieldCandidate = candidates.find((item) => item?.candidate_kind === 'order_fields');
|
||||
const suggestion = reconstructionCandidate?.payload as import('@/features/admin/types/shipping-order-document-profile.types').CoordinateReconstructionSuggestion | undefined;
|
||||
const orderFields = orderFieldCandidate?.payload as { order_field_candidates: OrderFieldLayoutSuggestion[] } | undefined;
|
||||
if (!suggestion || !orderFields) {
|
||||
throw new Error('Unified PDF automark returned incomplete coordinate candidates');
|
||||
}
|
||||
if (!suggestion.subrow_layouts.length && !orderFields.order_field_candidates.some((item) => item.status === "suggested")) {
|
||||
suggestionProgress.value = t(
|
||||
@@ -1701,7 +1675,7 @@ const suggestRegions = async () => {
|
||||
});
|
||||
});
|
||||
}
|
||||
const summary = { algorithm_version: 'coordinate-suggest-v1', kind: 'page_regions', page_no: pageNo.value, document_id: form.documentId, table_id: form.tableId, region_count: suggestedRegions.length, region_kinds: suggestedRegions.map((item) => item.kind) };
|
||||
const summary = { algorithm_version: 'coordinate-suggest-v1', kind: 'page_regions', page_no: pageNo.value, document_id: documentId, table_id: form.tableId, region_count: suggestedRegions.length, region_kinds: suggestedRegions.map((item) => item.kind) };
|
||||
const serialized = canonicalSuggestionJson(summary);
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized));
|
||||
const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join('');
|
||||
@@ -1863,28 +1837,24 @@ const schedulePreview = () => {
|
||||
}
|
||||
}, 400);
|
||||
};
|
||||
/** 签发当前绑定样本的单用途画布令牌;令牌失败仅降级画布,不能掩盖草稿保存成功。 */
|
||||
/** 签发当前绑定样本的原 PDF 单用途画布令牌;坐标 PDF 与 XFA 共用 PDF.js 渲染。 */
|
||||
const loadPages = async () => {
|
||||
if (!active.value || !form.documentId) return;
|
||||
try {
|
||||
const grants = await authorizeOrderProfilePreviewPages(
|
||||
pdfPreviewGrant.value = await authorizeOrderProfilePdfPreview(
|
||||
active.value.id,
|
||||
form.documentId,
|
||||
);
|
||||
pageGrants.value = grants.pages;
|
||||
pageGrant.value =
|
||||
grants.pages.find((item) => item.page_no === pageNo.value) ||
|
||||
grants.pages[0] ||
|
||||
null;
|
||||
pageNo.value = pageGrant.value?.page_no || 1;
|
||||
pageNo.value = 1;
|
||||
pdfPageCount.value = 1;
|
||||
canvasUnavailable.value = false;
|
||||
} catch {
|
||||
pageGrant.value = null;
|
||||
pageGrants.value = [];
|
||||
pdfPreviewGrant.value = null;
|
||||
pdfPageCount.value = 1;
|
||||
canvasUnavailable.value = true;
|
||||
}
|
||||
};
|
||||
/** 切页时重新签发整个页面列表,避免已消费的单页令牌被重复使用。 */
|
||||
/** PDF.js 已在内存中持有原件,切页只切换页码,避免消费新的预览令牌。 */
|
||||
/** 切换 PDF 页时同步选择该页表格,使局部候选与当前标注页使用同一份坐标证据。 */
|
||||
const selectPage = async (nextPageNo: number) => {
|
||||
if (nextPageNo === pageNo.value) return;
|
||||
@@ -1894,7 +1864,6 @@ const selectPage = async (nextPageNo: number) => {
|
||||
(item) => item.page_no === nextPageNo,
|
||||
);
|
||||
form.tableId = pageTable?.table_id || "";
|
||||
await loadPages();
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
};
|
||||
/** 请求当前或全部表头的只读精确别名建议;结果不自动修改人工字段绑定。 */
|
||||
@@ -2371,8 +2340,8 @@ watch(
|
||||
() => form.documentId,
|
||||
() => {
|
||||
form.tableId = "";
|
||||
pageGrant.value = null;
|
||||
pageGrants.value = [];
|
||||
pdfPreviewGrant.value = null;
|
||||
pdfPageCount.value = 1;
|
||||
canvasUnavailable.value = false;
|
||||
if (restoringProfile) return;
|
||||
void loadSampleTables();
|
||||
@@ -2568,17 +2537,15 @@ onBeforeUnmount(() => {
|
||||
ref="documentCanvas"
|
||||
:profile-id="active?.id || null"
|
||||
:mode="deskCanvasReadonly ? 'readonly' : 'edit'"
|
||||
:grant="isXfaTemplate ? xfaDesk.activePageGrant : pageGrant"
|
||||
:preview-page-path="isXfaTemplate ? xfaDesk.activePreviewPagePath : undefined"
|
||||
:pdf-preview="isXfaTemplate ? xfaDesk.activeXfaPdfGrant : pdfPreviewGrant"
|
||||
:preview-page-path="isXfaTemplate ? xfaDesk.activePreviewPagePath : `/api/admin/shipping-notice/order-document-profiles/${active?.id || 0}/pdf-preview`"
|
||||
:regions="isXfaTemplate ? xfaDesk.canvasRegions : pageRegions"
|
||||
:selected-region-id="isXfaTemplate ? xfaDesk.selectedBindingId : selectedId"
|
||||
:creation-kind="isXfaTemplate ? xfaDesk.creationKind : creationKind"
|
||||
:annotation-tool-set="'full'"
|
||||
:auto-suggest-disabled="isXfaTemplate ? deskCanvasReadonly : (compactEditor || !form.documentId || !form.tableId)"
|
||||
:suggesting="suggestingRegions || (isXfaTemplate && xfaDesk.suggestingBinding)"
|
||||
:suggestion-progress="suggestionProgress || (isXfaTemplate && xfaDesk.suggestingBinding
|
||||
? t('admin.shippingOrderProfiles.xfaUnified.suggesting')
|
||||
: '')"
|
||||
:suggesting="suggestingRegions"
|
||||
:suggestion-progress="suggestionProgress"
|
||||
:undo-disabled="isXfaTemplate
|
||||
? (!xfaDesk.bindingHistory.length || deskCanvasReadonly)
|
||||
: !history.length"
|
||||
@@ -2596,7 +2563,7 @@ onBeforeUnmount(() => {
|
||||
:save-disabled="isXfaTemplate ? !xfaDesk.dirty : issues.length > 0"
|
||||
:saving="saving"
|
||||
:pending-suggestion-count="isXfaTemplate
|
||||
? (xfaDesk.autoMarkSuggestions.length || xfaDesk.pendingCandidateCount)
|
||||
? xfaDesk.autoMarkSuggestions.length
|
||||
: (pendingSuggestion?.regions.length || 0)"
|
||||
:order-field-values="isXfaTemplate ? undefined : orderFieldValues"
|
||||
:order-field-value-state="isXfaTemplate ? undefined : orderFieldValueState"
|
||||
@@ -2608,6 +2575,7 @@ onBeforeUnmount(() => {
|
||||
@delete="onDeskCanvasDelete"
|
||||
@save="() => void save()"
|
||||
@page="onDeskCanvasPage"
|
||||
@page-count="(count) => { if (isXfaTemplate) xfaDesk.setRenderedPageCount(count); else pdfPageCount = count; }"
|
||||
@draw="onDeskCanvasDraw"
|
||||
@suggest="() => void onDeskCanvasSuggest()"
|
||||
@create="onDeskCanvasCreate"
|
||||
@@ -2632,34 +2600,6 @@ onBeforeUnmount(() => {
|
||||
@load-failed="onDeskCanvasLoadFailed"
|
||||
@retry="onDeskCanvasRetry"
|
||||
/>
|
||||
<section
|
||||
v-if="isXfaTemplate && xfaDesk.pendingSuggestion?.visual_suggestion?.candidates?.length"
|
||||
class="suggestion-decision"
|
||||
role="status"
|
||||
:aria-label="t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision')"
|
||||
>
|
||||
<strong>{{ t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') }}</strong>
|
||||
<span>{{ xfaDesk.pendingCandidateCount }}</span>
|
||||
<button type="button" class="link" @click="xfaDesk.dismissPendingSuggestion()">{{ t('common.close') }}</button>
|
||||
<div
|
||||
v-for="candidate in xfaDesk.pendingSuggestion.visual_suggestion.candidates"
|
||||
:key="candidate.candidate_id"
|
||||
class="xfa-candidate-inline"
|
||||
>
|
||||
<span>{{ candidate.acroform_field_name_tail || candidate.widget_id }}</span>
|
||||
<span>{{ Math.round((candidate.confidence || 0) * 100) }}%</span>
|
||||
<template v-for="path in (candidate.path_candidates || [])" :key="`${candidate.candidate_id}-${path.path_id}`">
|
||||
<span>{{ path.dataset_value_masked || path.path_id }}</span>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="deskCanvasReadonly"
|
||||
@click="xfaDesk.applyVisualCandidate(candidate, path.path_id)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaUnified.acceptCandidate') }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
<section v-if="!isXfaTemplate && pendingSuggestion" class="suggestion-decision" role="status">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') }}</strong>
|
||||
<span>{{ pendingSuggestion.regions.length }}</span>
|
||||
@@ -2910,21 +2850,6 @@ onBeforeUnmount(() => {
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>{{ t('admin.shippingOrderProfiles.xfaDesk.readingMode') }}
|
||||
<select
|
||||
class="select-field"
|
||||
:value="xfaDesk.selectedReadingMode"
|
||||
:disabled="xfaConfigReadonly"
|
||||
@change="onXfaReadingModeChange"
|
||||
>
|
||||
<option value="pdf_coordinate">{{ t('admin.shippingOrderProfiles.xfaDesk.readingModes.pdf_coordinate') }}</option>
|
||||
<option value="ocr_coordinate">{{ t('admin.shippingOrderProfiles.xfaDesk.readingModes.ocr_coordinate') }}</option>
|
||||
<option value="xfa_dataset">{{ t('admin.shippingOrderProfiles.xfaDesk.readingModes.xfa_dataset') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="xfaDesk.readingModeWarning" class="schema-warning" role="status">
|
||||
{{ t('admin.shippingOrderProfiles.xfaDesk.readingModeWarning') }}
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<template v-if="xfaDesk.showDatasetsSection">
|
||||
|
||||
+341
-21
@@ -11,9 +11,15 @@ import { defineComponent, h, nextTick } from 'vue';
|
||||
import OrderProfileXfaWorkbench from './OrderProfileXfaWorkbench.vue';
|
||||
import { useOrderProfileXfaDesk } from './composables/useOrderProfileXfaDesk';
|
||||
|
||||
const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => ({
|
||||
const { authorizePreviewPagesMock, authorizePdfPreviewMock, saveDraftMock, splitPreviewMock, enqueueAutomarkMock, getAutomarkJobMock, suggestUnifiedMappingMock, messageErrorMock, detailDefinition } = vi.hoisted(() => ({
|
||||
authorizePreviewPagesMock: vi.fn(),
|
||||
authorizePdfPreviewMock: vi.fn(),
|
||||
saveDraftMock: vi.fn(),
|
||||
splitPreviewMock: vi.fn(),
|
||||
enqueueAutomarkMock: vi.fn(),
|
||||
getAutomarkJobMock: vi.fn(),
|
||||
suggestUnifiedMappingMock: vi.fn(),
|
||||
messageErrorMock: vi.fn(),
|
||||
detailDefinition: { value: null as Record<string, unknown> | null },
|
||||
}));
|
||||
|
||||
@@ -51,7 +57,7 @@ vi.mock('vue-router', () => ({
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }),
|
||||
useMessage: () => ({ success: vi.fn(), error: messageErrorMock, info: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
@@ -86,12 +92,8 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderProfileSampleXfaCollections: vi.fn(async () => ({
|
||||
collection_candidates: [{ path_id: 'items-data', collection_path_hash: 'h', row_count: 1 }],
|
||||
})),
|
||||
authorizeOrderProfilePreviewPages: vi.fn(async () => ({
|
||||
document_id: 85,
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
})),
|
||||
authorizeOrderProfilePreviewPages: (...args: unknown[]) => authorizePreviewPagesMock(...args),
|
||||
authorizeOrderProfilePdfPreview: (...args: unknown[]) => authorizePdfPreviewMock(...args),
|
||||
requestOrderProfileSampleXfaSyntheticPreview: vi.fn(async () => ({
|
||||
document_id: 85,
|
||||
identity: {
|
||||
@@ -117,16 +119,11 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
cache_hit: false,
|
||||
})),
|
||||
listOrderProfileSampleXfaSyntheticPreviewPages: vi.fn(),
|
||||
enqueueOrderProfileXfaOcrAutomark: vi.fn(async () => ({ job_id: 9, status: 'queued' })),
|
||||
getOrderProfileXfaOcrAutomarkJob: vi.fn(async () => ({
|
||||
job_id: 9,
|
||||
status: 'succeeded',
|
||||
suggestions: [],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
})),
|
||||
enqueueOrderProfilePdfAutomark: (...args: unknown[]) => enqueueAutomarkMock(...args),
|
||||
getOrderProfilePdfAutomarkJob: (...args: unknown[]) => getAutomarkJobMock(...args),
|
||||
acceptOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
rejectOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
suggestOrderProfileXfaUnifiedMapping: vi.fn(),
|
||||
suggestOrderProfileXfaUnifiedMapping: (...args: unknown[]) => suggestUnifiedMappingMock(...args),
|
||||
acquireOrderDocumentProfileEditLease: vi.fn(async () => ({ lease_token: 'lease', expires_at: new Date().toISOString() })),
|
||||
renewOrderDocumentProfileEditLease: vi.fn(),
|
||||
releaseOrderDocumentProfileEditLease: vi.fn(),
|
||||
@@ -162,6 +159,31 @@ describe('OrderProfileXfaWorkbench (deprecated thin wrapper)', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
enqueueAutomarkMock.mockReset();
|
||||
enqueueAutomarkMock.mockResolvedValue({ job_id: 9, status: 'queued' });
|
||||
getAutomarkJobMock.mockReset();
|
||||
getAutomarkJobMock.mockResolvedValue({
|
||||
job_id: 9,
|
||||
status: 'succeeded',
|
||||
kind: 'visual_binding',
|
||||
candidates: [],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
});
|
||||
messageErrorMock.mockReset();
|
||||
suggestUnifiedMappingMock.mockReset();
|
||||
authorizePreviewPagesMock.mockReset();
|
||||
authorizePreviewPagesMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
});
|
||||
authorizePdfPreviewMock.mockReset();
|
||||
authorizePdfPreviewMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
preview_token: 'xfa-pdf-token',
|
||||
expires_in_seconds: 120,
|
||||
});
|
||||
saveDraftMock.mockReset();
|
||||
splitPreviewMock.mockReset();
|
||||
// Canvas-related absolute URL safety: relative /api fetch must not throw in jsdom.
|
||||
@@ -213,6 +235,31 @@ describe('OrderProfileXfaWorkbench (deprecated thin wrapper)', () => {
|
||||
describe('useOrderProfileXfaDesk', () => {
|
||||
beforeEach(() => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
enqueueAutomarkMock.mockReset();
|
||||
enqueueAutomarkMock.mockResolvedValue({ job_id: 9, status: 'queued' });
|
||||
getAutomarkJobMock.mockReset();
|
||||
getAutomarkJobMock.mockResolvedValue({
|
||||
job_id: 9,
|
||||
status: 'succeeded',
|
||||
kind: 'visual_binding',
|
||||
candidates: [],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
});
|
||||
messageErrorMock.mockReset();
|
||||
suggestUnifiedMappingMock.mockReset();
|
||||
authorizePreviewPagesMock.mockReset();
|
||||
authorizePreviewPagesMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
});
|
||||
authorizePdfPreviewMock.mockReset();
|
||||
authorizePdfPreviewMock.mockResolvedValue({
|
||||
document_id: 85,
|
||||
preview_token: 'xfa-pdf-token',
|
||||
expires_in_seconds: 120,
|
||||
});
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({
|
||||
ok: true,
|
||||
blob: async () => new Blob(['png'], { type: 'image/png' }),
|
||||
@@ -360,15 +407,13 @@ describe('useOrderProfileXfaDesk', () => {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
// 原生页授权就绪后,synthetic 失败不应禁标注。
|
||||
desk.pageGrants.value = [{ page_no: 1, preview_token: 'token' }];
|
||||
desk.pageGrant.value = { page_no: 1, preview_token: 'token' };
|
||||
// 原 PDF 授权就绪后,合成预览失败不应禁标注。
|
||||
desk.xfaPdfGrant.value = { document_id: 85, preview_token: 'token', expires_in_seconds: 120 };
|
||||
desk.pageLoadError.value = null;
|
||||
desk.syntheticPreviewStatus.value = 'unavailable';
|
||||
expect(desk.annotationDisabled.value).toBe(false);
|
||||
|
||||
desk.pageGrant.value = null;
|
||||
desk.pageGrants.value = [];
|
||||
desk.xfaPdfGrant.value = null;
|
||||
expect(desk.annotationDisabled.value).toBe(true);
|
||||
|
||||
desk.definition.value = {
|
||||
@@ -391,4 +436,279 @@ describe('useOrderProfileXfaDesk', () => {
|
||||
desk.selectedBindingId.value = 'anchor-1';
|
||||
expect(desk.showDatasetsSection.value).toBe(false);
|
||||
}, 15000);
|
||||
|
||||
it('keeps XFA mapping ready but reports a native PDF page authorization failure', async () => {
|
||||
// 该 suite 保留多个 mounted desk;持续拒绝确保本用例的异步 loadPages 不会被旧实例抢先消费。
|
||||
authorizePdfPreviewMock.mockRejectedValue(new Error('PDF preview unavailable'));
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
// 断言:XFA 字段建模不依赖 synthetic preview;仅原生 PDF 页进入可重试失败态。
|
||||
expect(desk.definition.value).toBeTruthy();
|
||||
expect(desk.loadError.value).toBe(false);
|
||||
expect(desk.pageUnavailable.value).toBe(true);
|
||||
expect(desk.pageLoadError.value).toBe('native page unavailable');
|
||||
}, 15000);
|
||||
|
||||
it('uses the single-use XFA PDF grant instead of PDFium page grants', async () => {
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
workbench: { regionLabels: { order_field: '字段 {count}' } },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
expect(authorizePdfPreviewMock).toHaveBeenCalledWith(52, 85);
|
||||
expect(authorizePreviewPagesMock).not.toHaveBeenCalled();
|
||||
expect(desk.activeXfaPdfGrant.value?.preview_token).toBe('xfa-pdf-token');
|
||||
}, 15000);
|
||||
|
||||
it('creates a local XFA visual box immediately without requesting mapping suggestions', async () => {
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
workbench: { regionLabels: { order_field: '字段 {count}' } },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
await desk.onCanvasCreate({ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 });
|
||||
|
||||
expect(suggestUnifiedMappingMock).not.toHaveBeenCalled();
|
||||
expect(desk.selectedBindingId.value).toBeTruthy();
|
||||
expect(desk.creationKind.value).toBeNull();
|
||||
expect(desk.canvasRegions.value).toEqual(expect.arrayContaining([expect.objectContaining({
|
||||
id: desk.selectedBindingId.value,
|
||||
kind: 'xfa_visual',
|
||||
pageNo: 1,
|
||||
region: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
visualBindingStatus: 'suggested',
|
||||
})]));
|
||||
}, 15000);
|
||||
|
||||
it('blocks saving a drawn XFA box until Schema and datasets bindings are completed', async () => {
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: {
|
||||
loadFailed: 'fail', pageUnavailable: 'native page unavailable',
|
||||
blocker: { incomplete_visual_binding: '请先完成每个手工视觉框的 Schema 字段和 datasets 路径绑定' },
|
||||
},
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
workbench: { regionLabels: { order_field: '字段 {count}' } },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
await desk.onCanvasCreate({ x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 });
|
||||
|
||||
await expect(desk.saveDraft()).resolves.toBe(false);
|
||||
expect(saveDraftMock).not.toHaveBeenCalled();
|
||||
expect(messageErrorMock).toHaveBeenCalledWith('请先完成每个手工视觉框的 Schema 字段和 datasets 路径绑定');
|
||||
}, 15000);
|
||||
|
||||
it('shows the OCR worker error code when an automark job fails', async () => {
|
||||
getAutomarkJobMock.mockResolvedValueOnce({
|
||||
job_id: 9,
|
||||
status: 'failed',
|
||||
error_code: 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE',
|
||||
message: 'XFA native PDF OCR is unavailable',
|
||||
suggestions: [],
|
||||
});
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败', jobFailedWithCode: '自动标记不可用({code}):{message}' },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
await expect(desk.startAutomarkJob()).rejects.toThrow('SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE');
|
||||
expect(messageErrorMock).toHaveBeenCalledWith(
|
||||
'自动标记不可用(SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE):XFA native PDF OCR is unavailable',
|
||||
);
|
||||
}, 15000);
|
||||
|
||||
it('projects XFA automark suggestions onto the shared canvas without persisting bindings', async () => {
|
||||
getAutomarkJobMock.mockResolvedValueOnce({
|
||||
job_id: 9,
|
||||
status: 'success',
|
||||
kind: 'visual_binding',
|
||||
candidates: [{
|
||||
suggestion_id: 'sugg-1',
|
||||
field_key: 'invoiced-to-path',
|
||||
field_code: 'customer_po_no',
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
match_class: 'medium',
|
||||
suggestion_origin: 'ocr',
|
||||
confidence: 0.95,
|
||||
needs_review: false,
|
||||
}],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
});
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败' },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
expect(desk.activeXfaPdfGrant.value?.preview_token).toBe('xfa-pdf-token');
|
||||
await desk.startAutomarkJob();
|
||||
|
||||
// XFA 自动标注必须以 XFA desk 选定的 annotation sample 为输入,
|
||||
// 不允许退回到普通 PDF 表单的 documentId。
|
||||
expect(enqueueAutomarkMock).toHaveBeenCalledWith(52, expect.objectContaining({
|
||||
document_id: 85,
|
||||
page_no: 1,
|
||||
}));
|
||||
expect(desk.definition.value?.bindings).toHaveLength(0);
|
||||
expect(desk.canvasRegions.value).toEqual(expect.arrayContaining([expect.objectContaining({
|
||||
id: 'automark:sugg-1',
|
||||
kind: 'xfa_visual',
|
||||
pageNo: 1,
|
||||
region: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
visualBindingStatus: 'suggested',
|
||||
})]));
|
||||
}, 15000);
|
||||
|
||||
it('restores only unresolved persisted automark suggestions for the annotation document', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
xfa_ocr_automark: {
|
||||
job_id: 11,
|
||||
document_id: 85,
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
render_mode: 'native_pdf',
|
||||
suggestions: [
|
||||
{
|
||||
suggestion_id: 'open-suggestion',
|
||||
field_key: 'invoiced-to-path',
|
||||
field_code: 'customer_po_no',
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 },
|
||||
match_class: 'medium',
|
||||
},
|
||||
{
|
||||
suggestion_id: 'resolved-suggestion',
|
||||
field_key: 'invoiced-to-path',
|
||||
field_code: 'customer_po_no',
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.5, y0: 0.6, x1: 0.7, y1: 0.8 },
|
||||
decision: 'rejected',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52, leaseToken: 'lease', saveState: 'saved', editorSessionId: 'sess', enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail', pageUnavailable: 'native page unavailable' },
|
||||
xfaAutoMark: { enqueueFailed: '入队失败', jobFailed: '任务失败' },
|
||||
} } } } })] },
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value) break;
|
||||
}
|
||||
|
||||
expect(desk.autoMarkSuggestions.value.map((item) => item.suggestion_id)).toEqual(['open-suggestion']);
|
||||
expect(desk.canvasRegions.value.map((item) => item.id)).toContain('automark:open-suggestion');
|
||||
expect(desk.canvasRegions.value.map((item) => item.id)).not.toContain('automark:resolved-suggestion');
|
||||
expect(desk.definition.value?.bindings).toHaveLength(0);
|
||||
}, 15000);
|
||||
});
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* 用途:验证 XFA 受控原 PDF 预览使用 PDF.js 普通页面外观渲染。
|
||||
* 依赖:Vitest、Vue Test Utils、OrderProfileDocumentCanvas。
|
||||
* 逻辑:hybrid XFA 的 getXfa() 可为空;预览必须走 page.render(),保留实际页面外观流。
|
||||
*/
|
||||
import { flushPromises, mount } from '@vue/test-utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
|
||||
|
||||
const { getDocumentMock, getPageMock, renderMock } = vi.hoisted(() => ({
|
||||
getDocumentMock: vi.fn(),
|
||||
getPageMock: vi.fn(),
|
||||
renderMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('pdfjs-dist', () => ({
|
||||
GlobalWorkerOptions: {},
|
||||
getDocument: (...args: unknown[]) => getDocumentMock(...args),
|
||||
}));
|
||||
vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '/pdf.worker.min.mjs' }));
|
||||
vi.mock('@/shared/utils/auth', () => ({ getAuthHeaders: () => ({ Authorization: 'Bearer test' }) }));
|
||||
|
||||
describe('OrderProfileDocumentCanvas PDF preview', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({} as CanvasRenderingContext2D);
|
||||
renderMock.mockReset();
|
||||
renderMock.mockReturnValue({ promise: Promise.resolve() });
|
||||
getPageMock.mockReset();
|
||||
getPageMock.mockResolvedValue({
|
||||
getViewport: vi.fn(({ scale }: { scale: number }) => ({ width: 600 * scale, height: 800 * scale })),
|
||||
render: renderMock,
|
||||
getXfa: vi.fn(async () => null),
|
||||
});
|
||||
getDocumentMock.mockReset();
|
||||
getDocumentMock.mockReturnValue({ promise: Promise.resolve({ numPages: 2, getPage: getPageMock }) });
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(new Uint8Array([37, 80, 68, 70]), { status: 200 })));
|
||||
});
|
||||
|
||||
it('renders hybrid XFA through the ordinary page appearance when getXfa is empty', async () => {
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 71,
|
||||
pdfPreview: { preview_token: 'single-use-token' },
|
||||
regions: [], pageNo: 1, pageCount: 1,
|
||||
},
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
|
||||
});
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:hybrid XFA 不依赖 getXfa/XfaLayer,使用页面外观流渲染动态可见值。
|
||||
expect(getDocumentMock).toHaveBeenCalledWith(expect.objectContaining({ data: expect.any(Uint8Array) }));
|
||||
expect(getPageMock).toHaveBeenCalledWith(1);
|
||||
expect(renderMock).toHaveBeenCalledWith(expect.objectContaining({ canvasContext: expect.anything() }));
|
||||
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
|
||||
expect(wrapper.emitted('pageCount')?.[0]).toEqual([2]);
|
||||
});
|
||||
|
||||
it('keeps XFA suggestion regions on the same scaled coordinate plane as the PDF page', async () => {
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 71,
|
||||
pdfPreview: { preview_token: 'single-use-token' },
|
||||
regions: [{
|
||||
id: 'automark:sugg-1', kind: 'xfa_visual', label: '自动标注', pageNo: 1,
|
||||
region: { x0: .5, y0: .5, x1: .75, y1: .75 },
|
||||
}],
|
||||
pageNo: 1,
|
||||
pageCount: 1,
|
||||
},
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
|
||||
});
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
|
||||
await wrapper.findAll('.zoom-control button')[1].trigger('click');
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
|
||||
// PDF.js 的 viewport 已是 125%(750px);覆盖框必须以同一宽度百分比定位,不能二次放大到 937.5px。
|
||||
expect(wrapper.find('.canvas-stage').attributes('style')).toContain('width: 750px');
|
||||
expect(wrapper.find('.region').attributes('style')).toContain('left: 50%');
|
||||
});
|
||||
});
|
||||
+89
-11
@@ -6,17 +6,38 @@
|
||||
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { PDFDocumentProxy } from 'pdfjs-dist';
|
||||
|
||||
type PdfJsModule = typeof import('pdfjs-dist');
|
||||
let pdfjsLoader: Promise<PdfJsModule> | null = null;
|
||||
|
||||
/** 动态加载 PDF.js 与 worker;坐标 PDF 与 XFA 在受控管理员画布按需共用。 */
|
||||
async function loadPdfJs(): Promise<PdfJsModule> {
|
||||
if (!pdfjsLoader) {
|
||||
pdfjsLoader = (async () => {
|
||||
const [pdfjs, workerMod] = await Promise.all([
|
||||
import('pdfjs-dist'),
|
||||
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
|
||||
]);
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
|
||||
return pdfjs;
|
||||
})();
|
||||
}
|
||||
return pdfjsLoader;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
profileId: number | null;
|
||||
grant?: OrderProfilePreviewPageGrant | null;
|
||||
mode?: 'edit' | 'readonly';
|
||||
previewPagePath?: string | null;
|
||||
/** 原 PDF 令牌;启用后用 PDF.js 页面外观流渲染,绝不生成可下载 URL。 */
|
||||
pdfPreview?: { preview_token: string } | null;
|
||||
regions: OrderProfileCanvasRegion[];
|
||||
selectedRegionId?: string | null;
|
||||
creationKind?: OrderProfileCanvasRegion['kind'] | null;
|
||||
@@ -58,6 +79,7 @@ const emit = defineEmits<{
|
||||
delete: [];
|
||||
save: [];
|
||||
page: [pageNo: number];
|
||||
pageCount: [count: number];
|
||||
acceptSuggestion: [];
|
||||
rejectSuggestion: [];
|
||||
/** 页图拉取失败(父级可标 page_unavailable)。 */
|
||||
@@ -67,6 +89,10 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const imageUrl = ref('');
|
||||
const pdfCanvas = ref<HTMLCanvasElement | null>(null);
|
||||
const pdfRendered = ref(false);
|
||||
const pdfPageSize = ref<{ width: number; height: number } | null>(null);
|
||||
let pdfDocument: PDFDocumentProxy | null = null;
|
||||
const loading = ref(false);
|
||||
/** 本组件内 fetch 失败文案;与 props.loadError 合并展示。 */
|
||||
const internalLoadError = ref<string | null>(null);
|
||||
@@ -87,26 +113,62 @@ const emptyStateText = computed(() => (
|
||||
props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf')
|
||||
));
|
||||
|
||||
/**
|
||||
* 将内存中的原 PDF 按真实页面外观流绘制到 Canvas。
|
||||
* 核心逻辑:坐标 PDF 与 hybrid XFA 都用 page.render(),不生成可下载 URL。
|
||||
*/
|
||||
const renderPdfPage = async (pdf: PDFDocumentProxy) => {
|
||||
await nextTick();
|
||||
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages);
|
||||
const page = await pdf.getPage(targetPage);
|
||||
const canvas = pdfCanvas.value;
|
||||
const context = canvas?.getContext('2d');
|
||||
if (!canvas || !context) throw new Error('PDF canvas is unavailable');
|
||||
const viewport = page.getViewport({ scale: zoom.value });
|
||||
pdfPageSize.value = { width: viewport.width, height: viewport.height };
|
||||
canvas.width = Math.ceil(viewport.width);
|
||||
canvas.height = Math.ceil(viewport.height);
|
||||
await page.render({ canvas, canvasContext: context, viewport }).promise;
|
||||
pdfRendered.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。
|
||||
* 核心逻辑:失败时写入 internalLoadError 并 emit loadFailed,避免误导为「未绑定样本」。
|
||||
*/
|
||||
const loadPage = async () => {
|
||||
if (!props.profileId || !props.grant) {
|
||||
if (!props.profileId || (!props.grant && !props.pdfPreview)) {
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
imageUrl.value = '';
|
||||
pdfRendered.value = false;
|
||||
internalLoadError.value = null;
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
imageUrl.value = '';
|
||||
pdfRendered.value = false;
|
||||
internalLoadError.value = null;
|
||||
try {
|
||||
const previewPath = props.previewPagePath
|
||||
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
|
||||
if (props.pdfPreview) {
|
||||
const response = await fetch(
|
||||
`${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const pdfjs = await loadPdfJs();
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise;
|
||||
emit('pageCount', pdfDocument.numPages);
|
||||
await renderPdfPage(pdfDocument);
|
||||
return;
|
||||
}
|
||||
const grant = props.grant;
|
||||
if (!grant) throw new Error('PDF preview grant is unavailable');
|
||||
const response = await fetch(
|
||||
`${previewPath}/${props.grant.page_no}?preview_token=${encodeURIComponent(props.grant.preview_token)}`,
|
||||
`${previewPath}/${grant.page_no}?preview_token=${encodeURIComponent(grant.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
@@ -244,8 +306,14 @@ const goToPage = () => {
|
||||
if (nextPage !== props.pageNo) emit('page', nextPage);
|
||||
};
|
||||
defineExpose({ zoomIn: () => adjustZoom(.25), zoomOut: () => adjustZoom(-.25), resetZoom });
|
||||
watch(() => props.grant?.preview_token, () => { void loadPage(); }, { immediate: true });
|
||||
watch(() => props.pageNo, (value) => { pageInput.value = value; });
|
||||
watch(() => [props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
|
||||
watch(() => props.pageNo, async (value) => {
|
||||
pageInput.value = value;
|
||||
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
|
||||
});
|
||||
watch(zoom, async () => {
|
||||
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
|
||||
});
|
||||
onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(imageUrl.value); });
|
||||
</script>
|
||||
|
||||
@@ -256,7 +324,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
? t('admin.shippingOrderProfiles.workbench.readonlyCanvasAriaLabel')
|
||||
: t('admin.shippingOrderProfiles.workbench.annotationCanvasAriaLabel')"
|
||||
>
|
||||
<header v-if="imageUrl" class="canvas-toolbar">
|
||||
<header v-if="imageUrl || pdfRendered" class="canvas-toolbar">
|
||||
<div class="toolbar-actions">
|
||||
<template v-if="!readonlyMode">
|
||||
<button type="button" :disabled="undoDisabled" :title="t('admin.shippingOrderProfiles.workbench.undo')" @click="emit('undo')"><RotateCcw /></button>
|
||||
@@ -287,14 +355,14 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<button type="button" class="fit-action" @click="resetZoom">{{ t('admin.shippingOrderProfiles.workbench.fitPage') }}</button>
|
||||
</div>
|
||||
</header>
|
||||
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
|
||||
<div v-if="loading && !pdfPreview" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
|
||||
<div v-else-if="displayLoadError" class="canvas-state canvas-state--error" role="alert">
|
||||
<p>{{ displayLoadError }}</p>
|
||||
<button type="button" class="canvas-retry" @click="onRetryClick">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else-if="!imageUrl" class="canvas-state">{{ emptyStateText }}</div>
|
||||
<div v-else-if="!imageUrl && !pdfRendered && !pdfPreview" class="canvas-state">{{ emptyStateText }}</div>
|
||||
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
|
||||
<aside v-if="!readonlyMode" class="annotation-tools">
|
||||
<template v-if="xfaVisualTools">
|
||||
@@ -313,8 +381,17 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
|
||||
</aside>
|
||||
<div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind || readonlyMode }" @wheel.prevent="handleWheel">
|
||||
<div ref="canvas" class="canvas-stage" :class="{ drawing: creationKind && !readonlyMode }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
|
||||
<img :src="imageUrl" :alt="t('admin.shippingOrderProfiles.workbench.pagePreviewAlt')" draggable="false" />
|
||||
<div
|
||||
ref="canvas"
|
||||
class="canvas-stage"
|
||||
:class="{ drawing: creationKind && !readonlyMode, 'canvas-stage--xfa': Boolean(pdfPageSize) }"
|
||||
:style="pdfPageSize
|
||||
? { width: `${pdfPageSize.width}px`, minWidth: '0', '--canvas-zoom': zoom }
|
||||
: { '--canvas-zoom': zoom }"
|
||||
@pointerdown="beginCreation"
|
||||
>
|
||||
<img v-if="imageUrl" :src="imageUrl" :alt="t('admin.shippingOrderProfiles.workbench.pagePreviewAlt')" draggable="false" />
|
||||
<canvas v-else ref="pdfCanvas" class="pdf-page" aria-label="XFA PDF preview" />
|
||||
<div
|
||||
v-for="region in regions"
|
||||
:key="region.id"
|
||||
@@ -387,6 +464,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.canvas-viewport.panning:active { cursor: grabbing; }
|
||||
.canvas-stage { position: relative; margin: auto; width: calc(100% * var(--canvas-zoom)); min-width: 42rem; box-shadow: 0 16px 40px rgba(0,0,0,.35); }
|
||||
.canvas-stage img { display: block; width: 100%; user-select: none; }
|
||||
.canvas-stage canvas.pdf-page { display: block; background: white; pointer-events: none; user-select: none; }
|
||||
.canvas-stage.drawing { cursor: crosshair; }
|
||||
.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
|
||||
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 2.65rem; padding: .3rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }
|
||||
@@ -432,7 +510,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.region-exclusion .region-label, .region-exclusion .resize-handle { background: #b91c1c; }
|
||||
.region-xfa_visual { z-index: 2; border: 1.5px solid #38bdf8; background: rgb(14 165 233 / .12); }
|
||||
.region-xfa_visual .region-label, .region-xfa_visual .resize-handle { background: #0369a1; }
|
||||
.region-visual--suggested { border-color: #f59e0b; background: rgb(245 158 11 / .14); }
|
||||
.region-visual--suggested { border-style: dashed; border-color: #f59e0b; background: rgb(245 158 11 / .14); }
|
||||
.region-visual--suggested .region-label { background: #b45309; }
|
||||
.region-visual--confirmed { border-color: #22c55e; background: rgb(34 197 94 / .12); }
|
||||
.region-visual--confirmed .region-label { background: #15803d; }
|
||||
|
||||
+210
-158
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/composables/useOrderProfileXfaDesk.ts
|
||||
* 用途:XFA 混合数据源标注的数据层(definition、原生 PDF 页授权、视觉绑定、OCR automark、拆分、集合重确认)。
|
||||
* 依赖:Profile/XFA API、automark API、xfaProfileMapping.utils、vue-i18n、useMessage。
|
||||
* 用途:XFA 混合数据源标注的数据层(definition、原生 PDF 页授权、视觉绑定、统一 PDF automark、拆分、集合重确认)。
|
||||
* 依赖:Profile/XFA API、统一 PDF automark API、xfaProfileMapping.utils、vue-i18n、useMessage。
|
||||
* 逻辑:仅由 OrderProfileEditorPage 消费;不渲染独立工作台/画布;不请求 /xfa/preview;
|
||||
* datasets 覆盖为建模辅助;OCR 仅由工具栏触发;旧 worker 的 PREVIEW_UNAVAILABLE 按空建议软成功。
|
||||
*/
|
||||
@@ -12,31 +12,28 @@ import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
|
||||
import {
|
||||
acceptOrderProfileXfaOcrAutomarkSuggestion,
|
||||
authorizeOrderProfilePreviewPages,
|
||||
authorizeOrderProfilePdfPreview,
|
||||
confirmOrderProfileXfaVisualBinding,
|
||||
enqueueOrderProfileXfaOcrAutomark,
|
||||
enqueueOrderProfilePdfAutomark,
|
||||
getOrderDocumentProfileDetail,
|
||||
getOrderProfileSampleXfaCollections,
|
||||
getOrderProfileSampleXfaFieldTree,
|
||||
getOrderProfileXfaOcrAutomarkJob,
|
||||
getOrderProfilePdfAutomarkJob,
|
||||
previewOrderProfileSampleXfaSplitRules,
|
||||
listOrderProfileBoundSamples,
|
||||
rejectOrderProfileXfaOcrAutomarkSuggestion,
|
||||
rejectOrderProfileXfaVisualBinding,
|
||||
saveOrderDocumentProfileDraft,
|
||||
suggestOrderProfileXfaUnifiedMapping,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type {
|
||||
OrderProfileCanvasRegion,
|
||||
OrderProfilePreviewPageGrant,
|
||||
OrderProfileXfaPdfPreviewGrant,
|
||||
OrderXfaDatasetProfileDefinition,
|
||||
XfaCollectionCandidate,
|
||||
XfaFieldTreeNode,
|
||||
XfaSplitRuleSet,
|
||||
XfaUnifiedFieldBinding,
|
||||
XfaUnifiedMappingSuggestResponse,
|
||||
XfaValueBindingType,
|
||||
XfaVisualBindingCandidate,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { isXfaDatasetProfileDefinition } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import type { ShippingOrderFieldConfig } from '@/features/admin/types/shipping-order-schema.types';
|
||||
@@ -87,6 +84,7 @@ export interface XfaAutoMarkSuggestion {
|
||||
iou?: number | null;
|
||||
needs_review?: boolean | null;
|
||||
reason_code?: string | null;
|
||||
/** Worker 产出的页面定位;仅用于临时建议框,不属于 datasets 正式值。 */
|
||||
page_no?: number;
|
||||
normalized_bbox?: {
|
||||
x0: number;
|
||||
@@ -95,6 +93,14 @@ export interface XfaAutoMarkSuggestion {
|
||||
y1: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface PersistedXfaAutomarkResult {
|
||||
job_id?: number | string | null;
|
||||
document_id?: number | string | null;
|
||||
preview_render_checksum?: string | null;
|
||||
render_mode?: string | null;
|
||||
suggestions?: unknown;
|
||||
}
|
||||
export type XfaDeskSaveState = 'saved' | 'saving' | 'failed' | 'readonly';
|
||||
|
||||
export interface UseOrderProfileXfaDeskOptions {
|
||||
@@ -152,8 +158,8 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
const displayName = ref('');
|
||||
const profileCode = ref('');
|
||||
const schemaVersionId = ref(0);
|
||||
const pageGrant = ref<OrderProfilePreviewPageGrant | null>(null);
|
||||
const pageGrants = ref<OrderProfilePreviewPageGrant[]>([]);
|
||||
/** XFA 原 PDF 只读一次性授权;PDF.js 直接消费为内存字节。 */
|
||||
const xfaPdfGrant = ref<OrderProfileXfaPdfPreviewGrant | null>(null);
|
||||
const pageNo = ref(1);
|
||||
const pageCount = ref(1);
|
||||
/** 画布唯一模式:原生 PDF 页图(与非 XFA 同路径)。 */
|
||||
@@ -176,6 +182,60 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
const automarkJobError = ref<string | null>(null);
|
||||
let automarkPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
/**
|
||||
* 归一化 Worker/已持久化 automark 建议,确保轮询与刷新恢复投影相同的临时画框。
|
||||
* @param item - Worker Job 或 definition.xfa_ocr_automark 中的一条原始建议
|
||||
*/
|
||||
function mapAutomarkSuggestion(item: Record<string, any>): XfaAutoMarkSuggestion {
|
||||
return {
|
||||
suggestion_id: String(item.suggestion_id || ''),
|
||||
field_key: item.field_key,
|
||||
field_code: item.field_code,
|
||||
page_no: Number(item.page_no || 0) || undefined,
|
||||
normalized_bbox: item.normalized_bbox,
|
||||
suggestion_origin: item.suggestion_origin,
|
||||
confidence: item.confidence,
|
||||
status: item.status,
|
||||
match_class: item.match_class,
|
||||
summary: item.summary,
|
||||
ocr_text: item.ocr_text,
|
||||
dataset_value: item.dataset_value,
|
||||
iou: item.iou,
|
||||
needs_review: Boolean(item.needs_review || item.match_class === 'needs_review'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Profile definition 恢复当前标注样本尚未处理的 automark 建议。
|
||||
* 核心逻辑:结果必须属于当前 annotation document;含 decision 的建议已由服务端处理,
|
||||
* 禁止再次投影到画布或误导用户重复接受/驳回。
|
||||
* @param rawDefinition - Detail API 返回的原始 XFA definition
|
||||
*/
|
||||
function restorePersistedAutomarkSuggestions(
|
||||
rawDefinition: OrderXfaDatasetProfileDefinition,
|
||||
): void {
|
||||
const persisted = (rawDefinition as OrderXfaDatasetProfileDefinition & {
|
||||
xfa_ocr_automark?: PersistedXfaAutomarkResult;
|
||||
}).xfa_ocr_automark;
|
||||
automarkJobStatus.value = 'idle';
|
||||
automarkJobError.value = null;
|
||||
automarkJobId.value = null;
|
||||
autoMarkSuggestions.value = [];
|
||||
if (!persisted || Number(persisted.document_id || 0) !== annotationDocumentId.value) return;
|
||||
|
||||
const jobId = Number(persisted.job_id || 0);
|
||||
automarkJobId.value = jobId > 0 ? jobId : null;
|
||||
const checksum = String(persisted.preview_render_checksum || '').trim();
|
||||
if (checksum) syntheticPreviewChecksum.value = checksum;
|
||||
syntheticRenderMode.value = String(persisted.render_mode || 'native_pdf');
|
||||
const suggestions = Array.isArray(persisted.suggestions) ? persisted.suggestions : [];
|
||||
autoMarkSuggestions.value = suggestions
|
||||
.filter((item): item is Record<string, any> => Boolean(item && typeof item === 'object'))
|
||||
.filter((item) => !item.decision)
|
||||
.map(mapAutomarkSuggestion)
|
||||
.filter((item) => item.suggestion_id);
|
||||
}
|
||||
|
||||
/** 画布工具 kind → visual_binding.region_kind。 */
|
||||
function mapCreationKindToRegionKind(kind: OrderProfileCanvasRegion['kind'] | null): string {
|
||||
switch (kind) {
|
||||
@@ -221,7 +281,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
return { ...def, bindings };
|
||||
}
|
||||
|
||||
const pagesReady = computed(() => pageGrants.value.length > 0 && Boolean(pageGrant.value));
|
||||
const pagesReady = computed(() => Boolean(xfaPdfGrant.value));
|
||||
/** 兼容旧名:编辑画布就绪 = 原生 PDF 页授权成功。 */
|
||||
const syntheticReady = computed(() => pagesReady.value);
|
||||
/** 编辑态不再因 synthetic 失败阻断标注。 */
|
||||
@@ -238,15 +298,13 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
readonly.value
|
||||
|| pageUnavailable.value
|
||||
));
|
||||
const activePageGrant = computed(() => pageGrant.value);
|
||||
/** 复用普通 PDF 预览路径(undefined 时 canvas 使用默认 preview-pages)。 */
|
||||
const activePreviewPagePath = computed(() => undefined as string | undefined);
|
||||
const activeXfaPdfGrant = computed(() => xfaPdfGrant.value);
|
||||
/** XFA 画布只通过受控原件入口读取 PDF.js 输入。 */
|
||||
const activePreviewPagePath = computed(() => '/api/admin/shipping-notice/order-document-profiles/'
|
||||
+ `${profileId.value}/pdf-preview`);
|
||||
const creationKind = ref<OrderProfileCanvasRegion['kind'] | null>('order_field');
|
||||
const selectedBindingId = ref<string | null>(null);
|
||||
const diagnosticsOpen = ref(false);
|
||||
const suggestingBinding = ref(false);
|
||||
const pendingSuggestion = ref<XfaUnifiedMappingSuggestResponse | null>(null);
|
||||
const pendingDrawRegion = ref<OrderProfileCanvasRegion['region'] | null>(null);
|
||||
const bindingHistory = ref<XfaUnifiedFieldBinding[][]>([]);
|
||||
const bindingFuture = ref<XfaUnifiedFieldBinding[][]>([]);
|
||||
const diagnosticsPanel = ref<HTMLElement | null>(null);
|
||||
@@ -256,17 +314,13 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
let focusTrapCleanup: (() => void) | null = null;
|
||||
let dragCheckpointTaken = false;
|
||||
|
||||
const pendingCandidateCount = computed(() => (
|
||||
pendingSuggestion.value?.visual_suggestion?.candidates?.length || 0
|
||||
));
|
||||
|
||||
const flatNodes = computed(() => flattenXfaTreeNodes(tree.value));
|
||||
|
||||
/** 将 definition.bindings 投影为当前页画布区域(可选叠加 datasets 样本辅助文案)。 */
|
||||
const canvasRegions = computed((): OrderProfileCanvasRegion[] => {
|
||||
if (!definition.value?.bindings?.length) return [];
|
||||
const bindings = definition.value?.bindings || [];
|
||||
const byPath = new Map(flatNodes.value.map((item) => [item.pathId, item]));
|
||||
return definition.value.bindings
|
||||
const persisted = bindings
|
||||
.filter((item) => item.visual_binding?.page_no === pageNo.value)
|
||||
.map((item) => {
|
||||
const sample = datasetsOverlayEnabled.value
|
||||
@@ -285,6 +339,18 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
visualBindingStatus: item.visual_binding.status,
|
||||
};
|
||||
});
|
||||
const suggested = autoMarkSuggestions.value
|
||||
.filter((item) => item.page_no === pageNo.value && item.normalized_bbox)
|
||||
.map((item) => ({
|
||||
id: `automark:${item.suggestion_id}`,
|
||||
kind: 'xfa_visual' as const,
|
||||
label: item.field_code || item.field_key || item.suggestion_id,
|
||||
region: item.normalized_bbox!,
|
||||
fieldCode: item.field_code || null,
|
||||
pageNo: item.page_no!,
|
||||
visualBindingStatus: 'suggested' as const,
|
||||
}));
|
||||
return [...persisted, ...suggested];
|
||||
});
|
||||
|
||||
const selectedPathLabel = computed(() => (
|
||||
@@ -524,6 +590,18 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
authoritativePathId.value,
|
||||
));
|
||||
const blockers = computed(() => summarizeXfaMappingBlockers(coverage.value));
|
||||
/** 手工视觉框可先留在浏览器草稿,但保存前必须完成 Schema 与 datasets 正式绑定。 */
|
||||
const incompleteVisualBindingCount = computed(() => (
|
||||
(definition.value?.bindings || []).filter((binding) => {
|
||||
const fieldBound = schemaFields.value.some((field) => (
|
||||
field.enabled !== false
|
||||
&& field.field_id === binding.field_id
|
||||
&& field.field_code === binding.field_code
|
||||
&& field.scope === binding.scope
|
||||
));
|
||||
return !fieldBound || !String(binding.value_binding?.path_id || '').trim();
|
||||
}).length
|
||||
));
|
||||
const splitRuleSummary = computed(() => {
|
||||
const sets = definition.value?.split_rules || [];
|
||||
const total = sets.length;
|
||||
@@ -600,14 +678,10 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
await restoreCollectionSelection(profile.definition);
|
||||
await refreshSplitRulePreviews(profile.definition.split_rules || []);
|
||||
await loadPages();
|
||||
pageLoadError.value = null;
|
||||
// 编辑路径仅用原生 PDF 页;不自动请求 /xfa/preview,不自动跑 OCR(由工具栏触发)。
|
||||
syntheticPreviewStatus.value = 'idle';
|
||||
stopAutomarkPoll();
|
||||
automarkJobStatus.value = 'idle';
|
||||
automarkJobError.value = null;
|
||||
automarkJobId.value = null;
|
||||
autoMarkSuggestions.value = [];
|
||||
restorePersistedAutomarkSuggestions(profile.definition as OrderXfaDatasetProfileDefinition);
|
||||
} catch (error) {
|
||||
loadError.value = true;
|
||||
definition.value = null;
|
||||
@@ -649,18 +723,20 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
|
||||
/**
|
||||
* 申请受控 PDF 单页预览令牌,供画布渲染。
|
||||
* 核心逻辑:XFA 映射与原生 PDF 页授权独立;授权失败保留页级错误,
|
||||
* 让用户重试页图而非误判 datasets 解析失败。
|
||||
*/
|
||||
async function loadPages(): Promise<void> {
|
||||
if (!annotationDocumentId.value) return;
|
||||
try {
|
||||
const pages = await authorizeOrderProfilePreviewPages(profileId.value, annotationDocumentId.value);
|
||||
pageGrants.value = pages.pages || [];
|
||||
pageCount.value = pages.page_count || 1;
|
||||
pageNo.value = Math.min(Math.max(1, pageNo.value), pageCount.value);
|
||||
pageGrant.value = pageGrants.value.find((item) => item.page_no === pageNo.value) || pageGrants.value[0] || null;
|
||||
const grant = await authorizeOrderProfilePdfPreview(profileId.value, annotationDocumentId.value);
|
||||
xfaPdfGrant.value = grant;
|
||||
pageCount.value = 1;
|
||||
pageNo.value = 1;
|
||||
pageLoadError.value = null;
|
||||
} catch {
|
||||
pageGrant.value = null;
|
||||
pageGrants.value = [];
|
||||
xfaPdfGrant.value = null;
|
||||
pageLoadError.value = t('admin.shippingOrderProfiles.xfaWorkbench.pageUnavailable');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -676,7 +752,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 入队 OCR 自动标记并轮询至终态(仅工具栏「自动标记」主动触发)。
|
||||
* 入队统一 PDF 自动标记并轮询至终态(仅工具栏「自动标记」主动触发)。
|
||||
* 核心逻辑:UI 进度由调用方 suggestionProgress 驱动;本函数不渲染专用底栏;
|
||||
* 旧 worker 的 XFA_PREVIEW_UNAVAILABLE 按空建议软成功,不弹错误码。
|
||||
* @param force 是否强制重跑
|
||||
@@ -687,15 +763,13 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
automarkJobError.value = null;
|
||||
automarkJobStatus.value = 'queued';
|
||||
try {
|
||||
const res = await enqueueOrderProfileXfaOcrAutomark(profileId.value, {
|
||||
const res = await enqueueOrderProfilePdfAutomark(profileId.value, {
|
||||
document_id: annotationDocumentId.value,
|
||||
page_no: Number(pageNo.value) || 1,
|
||||
force,
|
||||
});
|
||||
automarkJobId.value = Number(res.job_id);
|
||||
automarkJobStatus.value = String(res.status || 'queued');
|
||||
if (res.preview_render_checksum) {
|
||||
syntheticPreviewChecksum.value = String(res.preview_render_checksum);
|
||||
}
|
||||
syntheticRenderMode.value = 'native_pdf';
|
||||
|
||||
// 同步轮询至终态,供页面复用 suggestingRegions / suggestionProgress。
|
||||
@@ -723,27 +797,19 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 单次拉取 OCR Job;终态写入建议;硬失败抛错;预览不可用按空建议软成功。
|
||||
* 单次拉取统一 PDF Job;终态写入视觉绑定建议;硬失败抛错;预览不可用按空建议软成功。
|
||||
*/
|
||||
async function pollAutomarkJob(): Promise<void> {
|
||||
if (!automarkJobId.value) return;
|
||||
const res = await getOrderProfileXfaOcrAutomarkJob(profileId.value, automarkJobId.value);
|
||||
const res = await getOrderProfilePdfAutomarkJob(profileId.value, automarkJobId.value);
|
||||
automarkJobStatus.value = String(res.status || 'running');
|
||||
const suggestions = Array.isArray(res.suggestions) ? res.suggestions : [];
|
||||
autoMarkSuggestions.value = suggestions.map((item: any) => ({
|
||||
suggestion_id: String(item.suggestion_id || ''),
|
||||
field_key: item.field_key,
|
||||
field_code: item.field_code,
|
||||
suggestion_origin: item.suggestion_origin,
|
||||
confidence: item.confidence,
|
||||
status: item.status,
|
||||
match_class: item.match_class,
|
||||
summary: item.summary,
|
||||
ocr_text: item.ocr_text,
|
||||
dataset_value: item.dataset_value,
|
||||
iou: item.iou,
|
||||
needs_review: Boolean(item.needs_review || item.match_class === 'needs_review'),
|
||||
})).filter((item) => item.suggestion_id);
|
||||
const suggestions = res.kind === 'visual_binding' && Array.isArray(res.candidates)
|
||||
? res.candidates
|
||||
: [];
|
||||
autoMarkSuggestions.value = suggestions
|
||||
.filter((item): item is Record<string, any> => Boolean(item && typeof item === 'object'))
|
||||
.map(mapAutomarkSuggestion)
|
||||
.filter((item) => item.suggestion_id);
|
||||
|
||||
const status = automarkJobStatus.value;
|
||||
if (status === 'failed' || status === 'dead') {
|
||||
@@ -756,14 +822,17 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
if (isSoftEmptyAutomarkFailure(failCode, failText)) {
|
||||
return;
|
||||
}
|
||||
throw new Error(t('admin.shippingOrderProfiles.xfaAutoMark.jobFailed'));
|
||||
const errorMessage = failCode
|
||||
? t('admin.shippingOrderProfiles.xfaAutoMark.jobFailedWithCode', {
|
||||
code: failCode,
|
||||
message: failText || t('admin.shippingOrderProfiles.xfaAutoMark.jobFailed'),
|
||||
})
|
||||
: (failText || t('admin.shippingOrderProfiles.xfaAutoMark.jobFailed'));
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
if (['succeeded', 'success'].includes(status)) {
|
||||
stopAutomarkPoll();
|
||||
automarkJobStatus.value = 'idle';
|
||||
if (res.preview_render_checksum) {
|
||||
syntheticPreviewChecksum.value = String(res.preview_render_checksum);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -868,30 +937,73 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
function onCanvasPage(nextPage: number): void {
|
||||
pageNo.value = nextPage;
|
||||
pageLoadError.value = null;
|
||||
pageGrant.value = pageGrants.value.find((item) => item.page_no === nextPage) || null;
|
||||
syntheticPageGrant.value = syntheticPageGrants.value.find((item) => item.page_no === nextPage) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 画框完成后调用统一 mapping 建议 API,展示候选面板。
|
||||
* 接收统一 PDF Job 返回的视觉绑定候选并投影到共享画布状态。
|
||||
*
|
||||
* 自动标注任务由父工作台统一发起和轮询;本函数只处理 XFA 特有的
|
||||
* datasets 视觉绑定候选,不重新入队,也不决定 PDF 文档类型。
|
||||
*/
|
||||
function applyPdfAutomarkCandidates(candidates: Array<Record<string, unknown>>): void {
|
||||
autoMarkSuggestions.value = candidates
|
||||
.filter((item): item is Record<string, any> => Boolean(item && typeof item === 'object'))
|
||||
.map(mapAutomarkSuggestion)
|
||||
.filter((item) => item.suggestion_id);
|
||||
}
|
||||
|
||||
/** 将统一 Job 的原生 PDF 渲染身份写入后续视觉绑定确认上下文。 */
|
||||
function applyPdfAutomarkRenderIdentity(checksum?: string | null): void {
|
||||
if (checksum) syntheticPreviewChecksum.value = String(checksum);
|
||||
syntheticRenderMode.value = 'native_pdf';
|
||||
}
|
||||
|
||||
/** 接收 PDF.js 实际页数,避免 XFA 原件被错误固定为一页。 */
|
||||
function setRenderedPageCount(count: number): void {
|
||||
pageCount.value = Math.max(1, Math.floor(Number(count) || 1));
|
||||
pageNo.value = Math.min(pageNo.value, pageCount.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手工画框后立即创建本地视觉绑定并选中,和普通 PDF 的手工标注保持一致。
|
||||
* 核心逻辑:视觉框只作为待复核证据,正式 Schema/datasets 映射仍由右侧配置完成;
|
||||
* 不调用机器候选接口,也不产生自动标注底栏。
|
||||
* @param region 归一化相对坐标框
|
||||
*/
|
||||
async function onCanvasCreate(region: OrderProfileCanvasRegion['region']): Promise<void> {
|
||||
if (readonly.value || !annotationDocumentId.value) return;
|
||||
pendingDrawRegion.value = region;
|
||||
suggestingBinding.value = true;
|
||||
pendingSuggestion.value = null;
|
||||
try {
|
||||
pendingSuggestion.value = await suggestOrderProfileXfaUnifiedMapping(profileId.value, {
|
||||
document_id: annotationDocumentId.value,
|
||||
if (readonly.value || !definition.value) return;
|
||||
checkpointBindings();
|
||||
const bindingId = crypto.randomUUID().replace(/-/g, '').slice(0, 24);
|
||||
const sequence = (definition.value.bindings || []).length + 1;
|
||||
const nextBinding: XfaUnifiedFieldBinding = {
|
||||
binding_id: bindingId,
|
||||
// 未选择 Schema 字段前仅在浏览器草稿存在;服务端保存契约会拒绝该未完成映射。
|
||||
field_id: bindingId,
|
||||
field_code: t('admin.shippingOrderProfiles.workbench.regionLabels.order_field', { count: sequence }),
|
||||
scope: 'header',
|
||||
value_binding: {
|
||||
type: 'xfa_dataset',
|
||||
path_id: null,
|
||||
data_path: null,
|
||||
},
|
||||
visual_binding: {
|
||||
page_no: pageNo.value,
|
||||
normalized_bbox: region,
|
||||
});
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.xfaUnified.suggestFailed'));
|
||||
} finally {
|
||||
suggestingBinding.value = false;
|
||||
}
|
||||
source: 'user_drawn',
|
||||
status: 'suggested',
|
||||
region_kind: mapCreationKindToRegionKind(creationKind.value),
|
||||
},
|
||||
};
|
||||
definition.value = {
|
||||
...definition.value,
|
||||
bindings: [...(definition.value.bindings || []), nextBinding],
|
||||
};
|
||||
selectedBindingId.value = bindingId;
|
||||
selectedPathId.value = null;
|
||||
selectedPathIsLeaf.value = false;
|
||||
selectedRuleId.value = null;
|
||||
creationKind.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -899,6 +1011,16 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
* @param bindingId binding_id
|
||||
*/
|
||||
function onCanvasSelect(bindingId: string): void {
|
||||
if (bindingId.startsWith('automark:')) {
|
||||
const suggestionId = bindingId.slice('automark:'.length);
|
||||
const suggestion = autoMarkSuggestions.value.find((item) => item.suggestion_id === suggestionId);
|
||||
if (suggestion?.field_key) {
|
||||
selectedPathId.value = String(suggestion.field_key);
|
||||
selectedPathIsLeaf.value = true;
|
||||
selectedRuleId.value = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
selectedBindingId.value = bindingId;
|
||||
const binding = definition.value?.bindings?.find((item) => item.binding_id === bindingId);
|
||||
const pathId = binding?.value_binding.path_id;
|
||||
@@ -909,48 +1031,6 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将视觉候选写入本地 bindings(suggested),并关联当前选中 Schema 字段(若有)。
|
||||
* @param candidate 视觉候选
|
||||
* @param pathId 选中的 datasets path_id
|
||||
*/
|
||||
function applyVisualCandidate(candidate: XfaVisualBindingCandidate, pathId: string): void {
|
||||
if (!definition.value || !pendingDrawRegion.value) return;
|
||||
checkpointBindings();
|
||||
const field = schemaFields.value.find((item) => selectedPathId.value && item.field_id);
|
||||
const node = flatNodes.value.find((item) => item.pathId === pathId);
|
||||
const bindingId = crypto.randomUUID().replace(/-/g, '').slice(0, 24);
|
||||
const scope = node ? resolveXfaNodeScope(pathId, authoritativePathId.value, flatNodes.value) : 'header';
|
||||
const nextBinding: XfaUnifiedFieldBinding = {
|
||||
binding_id: bindingId,
|
||||
field_id: field?.field_id || bindingId,
|
||||
field_code: field?.field_code || node?.localName || pathId,
|
||||
scope: scope || 'header',
|
||||
value_binding: {
|
||||
type: 'xfa_dataset',
|
||||
path_id: pathId,
|
||||
data_path: null,
|
||||
},
|
||||
visual_binding: {
|
||||
page_no: pageNo.value,
|
||||
normalized_bbox: pendingDrawRegion.value,
|
||||
source: 'user_drawn',
|
||||
status: 'suggested',
|
||||
confidence: candidate.confidence,
|
||||
region_kind: mapCreationKindToRegionKind(creationKind.value),
|
||||
} as any,
|
||||
};
|
||||
definition.value = {
|
||||
...definition.value,
|
||||
bindings: [...(definition.value.bindings || []), nextBinding],
|
||||
};
|
||||
selectedBindingId.value = bindingId;
|
||||
selectedPathId.value = pathId;
|
||||
selectedPathIsLeaf.value = true;
|
||||
pendingSuggestion.value = null;
|
||||
pendingDrawRegion.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认视觉绑定:若本地尚未持久化该 binding,先保存草稿再调 confirm API。
|
||||
* @param bindingId 目标 binding_id
|
||||
@@ -1057,11 +1137,6 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
function dismissPendingSuggestion(): void {
|
||||
pendingSuggestion.value = null;
|
||||
pendingDrawRegion.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定选中叶子或规则结果到同作用域 Schema 字段。
|
||||
* 规则继承源节点作用域,避免 Header 源规则被错误限制为明细字段。
|
||||
@@ -1162,6 +1237,10 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
|
||||
return false;
|
||||
}
|
||||
if (incompleteVisualBindingCount.value) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.incomplete_visual_binding'));
|
||||
return false;
|
||||
}
|
||||
const pendingConfirmPaths = Object.keys(splitRuleConfirmationTokens.value);
|
||||
try {
|
||||
const payloadDefinition: OrderXfaDatasetProfileDefinition & Record<string, unknown> = {
|
||||
@@ -1344,19 +1423,12 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
return flatNodes.value.find((item) => item.pathId === pathId)?.sampleValueDisplay || '';
|
||||
});
|
||||
|
||||
const selectedReadingMode = computed(() => (
|
||||
selectedBinding.value?.value_binding?.type || 'xfa_dataset'
|
||||
) as XfaValueBindingType);
|
||||
|
||||
/** datasets 增量区:仅正式取值为 xfa_dataset 且非锚点/排除时显示。 */
|
||||
/** datasets 增量区:XFA 正式值固定来自 datasets;视觉框/OCR 只承担定位、证据和复核。 */
|
||||
const showDatasetsSection = computed(() => (
|
||||
Boolean(selectedBinding.value)
|
||||
&& !DATASETS_HIDDEN_KINDS.has(selectedRegionKind.value)
|
||||
&& selectedReadingMode.value === 'xfa_dataset'
|
||||
));
|
||||
|
||||
const readingModeWarning = computed(() => false);
|
||||
|
||||
const collectionSummaryLabel = computed(() => {
|
||||
const auth = authoritativePathId.value
|
||||
? (buildXfaPathLabel(authoritativePathId.value, flatNodes.value) || authoritativePathId.value)
|
||||
@@ -1450,21 +1522,6 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新正式取值模式;非 datasets 时右侧展示警告。
|
||||
*/
|
||||
function updateSelectedReadingMode(mode: XfaValueBindingType): void {
|
||||
if (!definition.value || !selectedBindingId.value || readonly.value) return;
|
||||
definition.value = {
|
||||
...definition.value,
|
||||
bindings: (definition.value.bindings || []).map((item) => (
|
||||
item.binding_id === selectedBindingId.value
|
||||
? { ...item, value_binding: { ...item.value_binding, type: mode } }
|
||||
: item
|
||||
)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 datasets 树选择器写入 path_id。
|
||||
*/
|
||||
@@ -1580,8 +1637,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
mirrorPathIds,
|
||||
pageNo,
|
||||
pageCount,
|
||||
pageGrant,
|
||||
pageGrants,
|
||||
xfaPdfGrant,
|
||||
pagesReady,
|
||||
previewMode,
|
||||
syntheticPreviewStatus,
|
||||
@@ -1591,7 +1647,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
pageLoadError,
|
||||
pageUnavailable,
|
||||
annotationDisabled,
|
||||
activePageGrant,
|
||||
activeXfaPdfGrant,
|
||||
activePreviewPagePath,
|
||||
datasetsOverlayEnabled,
|
||||
creationKind,
|
||||
@@ -1601,13 +1657,9 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
isFieldLikeSelection,
|
||||
showDatasetsSection,
|
||||
selectedSampleValue,
|
||||
selectedReadingMode,
|
||||
readingModeWarning,
|
||||
collectionSummaryLabel,
|
||||
canvasRegions,
|
||||
pendingCandidateCount,
|
||||
pendingSuggestion,
|
||||
suggestingBinding,
|
||||
incompleteVisualBindingCount,
|
||||
bindingHistory,
|
||||
bindingFuture,
|
||||
autoMarkSuggestions,
|
||||
@@ -1629,6 +1681,7 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
onCanvasDragEnd,
|
||||
onCanvasRegionChange,
|
||||
onCanvasPage,
|
||||
setRenderedPageCount,
|
||||
onCanvasCreate,
|
||||
onCanvasSelect,
|
||||
loadSyntheticPreview,
|
||||
@@ -1636,11 +1689,11 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
reportPageLoadError,
|
||||
clearPageLoadError,
|
||||
startAutomarkJob,
|
||||
applyPdfAutomarkCandidates,
|
||||
applyPdfAutomarkRenderIdentity,
|
||||
onAcceptAutomark,
|
||||
onAdjustAutomark,
|
||||
onRejectAutomark,
|
||||
applyVisualCandidate,
|
||||
dismissPendingSuggestion,
|
||||
confirmVisualBinding,
|
||||
rejectVisualBinding,
|
||||
onBindField,
|
||||
@@ -1661,7 +1714,6 @@ export function useOrderProfileXfaDesk(options: UseOrderProfileXfaDeskOptions) {
|
||||
confirmReconfirmCollections,
|
||||
updateSelectedLabel,
|
||||
updateSelectedSchemaField,
|
||||
updateSelectedReadingMode,
|
||||
updateSelectedDatasetsPath,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -824,6 +824,10 @@ export interface OrderProfileUsagePage {
|
||||
|
||||
/** 受控预览授权只对单页生效,令牌不得持久化或复用。 */
|
||||
export interface OrderProfilePreviewPageGrant { page_no: number; preview_token: string; }
|
||||
/** 管理员编辑画布的原 PDF 单次内存预览授权,坐标 PDF 与 XFA 共用。 */
|
||||
export interface OrderProfilePdfPreviewGrant { document_id: number; preview_token: string; expires_in_seconds: number; }
|
||||
/** @deprecated 使用 OrderProfilePdfPreviewGrant;保留给旧 XFA 调用方。 */
|
||||
export type OrderProfileXfaPdfPreviewGrant = OrderProfilePdfPreviewGrant;
|
||||
|
||||
/** XFA 合成预览身份上下文(与后端 PreviewIdentityContext 对齐)。 */
|
||||
export interface XfaSyntheticPreviewIdentity {
|
||||
|
||||
@@ -31,6 +31,8 @@ import type {
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
ShippingOrderReviewQueue,
|
||||
ShippingOrderReviewIntakeParseContext,
|
||||
OrderExtractionSubmissionRequest,
|
||||
OrderExtractionSubmissionResponse,
|
||||
ConversationProcessingProjection,
|
||||
@@ -176,6 +178,10 @@ export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
|
||||
export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
|
||||
|
||||
/** 当前任务已关联库存快照的受控下载 URL;后端会再次校验任务归属与活动 link。 */
|
||||
export const workspaceShippingInventoryFileUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-file`;
|
||||
|
||||
/** 下载一个批次或显式任务集合的当前 ready 发货 Excel ZIP。 */
|
||||
export async function downloadWorkspaceShippingExportArchive(payload: { batch_no?: string; task_nos?: string[] }) {
|
||||
const response = await fetch('/api/workspace/shipping-exports/archive', {
|
||||
@@ -218,8 +224,8 @@ export const createWorkspaceOrderExtractionSubmission = (
|
||||
|
||||
/**
|
||||
* 拉取统一 ShippingProcessingProjection(唯一进度读源;含 order_intake / order_task)。
|
||||
* 核心逻辑:内嵌 conversation_processing 可选;缺省时前端由 work_items 合成分组;
|
||||
* 旧 conversation processing GET 已移除(无历史兼容)。
|
||||
* 核心逻辑:内嵌 conversation_processing.status_groups 是新版批次列表唯一读源;
|
||||
* 仅旧服务端未返回该字段时才由 work_items 合成兼容分组;旧 GET 已移除。
|
||||
*/
|
||||
type WorkspaceShippingProcessingResponse = {
|
||||
conversation_id: string;
|
||||
@@ -426,7 +432,7 @@ export const deleteWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey:
|
||||
);
|
||||
|
||||
export const validateWorkspaceShippingOrderReviewDraft = (caseNo: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
requestJson<{ case: ShippingOrderReviewCase }>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/validate`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
@@ -943,6 +949,18 @@ export const getWorkspaceShippingOrderReviewEmailEvidencePreview = (caseNo: stri
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/email-evidence-preview/${documentId}`,
|
||||
);
|
||||
|
||||
/** 获取当前 Case 所属附件与同 Intake 邮件正文;仅在接收解析工作面打开时调用。 */
|
||||
export const getWorkspaceShippingOrderReviewIntakeParseContext = (caseNo: string) =>
|
||||
requestJson<ShippingOrderReviewIntakeParseContext>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/intake-parse-context`,
|
||||
);
|
||||
|
||||
/** 获取当前 Run 所属会话的有效订单队列。 */
|
||||
export const getWorkspaceShippingOrderReviewQueue = (runNo: string) =>
|
||||
requestJson<ShippingOrderReviewQueue>(
|
||||
`/api/workspace/shipping-notice/order-review-queue/${encodeURIComponent(runNo)}`,
|
||||
);
|
||||
|
||||
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string, uploadBatchId?: string | null) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
|
||||
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user