feat(shipping-notice): 收敛复核阶段同源投影与 OT 后履约推进

统一 Case/Progress 阶段 label_key、修复 Job 成功未推进 OT 的可重试失败投影与写路径,并落地 OT 后行级匹配/波次履约与版面诊断开关。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-07 13:11:14 +08:00
1 parent 74270adc22
commit fd6a23f870
100 files changed
+12138 -1017

No files matched your search

+4
View File
@@ -112,6 +112,10 @@ SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# 字段对齐确认(生产建议 true;测试可设 false)
+4
View File
@@ -101,6 +101,10 @@ SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
+9
View File
@@ -148,8 +148,17 @@ FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
# 货代客户自动确认默认关闭;仅 approved + auto_match_allowed 强规则唯一命中时可开启。
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=true
# OT 后行级自动履约(默认关):关闭时只上线匹配事实契约/明细库存列;禁止自动决定与 wave。
SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false
# 发货通知专用 Worker 进程数;版面解析为长任务,默认并发处理同批两份文档。
SHIPPING_NOTICE_WORKER_CONCURRENCY=2
# Layout Job 内整页 OCR 结果复用(PR-1);共享默认关,dev/test 环境文件覆盖为 true,prod 保持 false 灰度。
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
# PDFium 字符预读复用与按需补图(PR-2);共享默认关,dev/test 开启,prod 灰度。
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
# 表格裁剪 OCR(PR-3);共享默认关;裁剪边距默认 3%。
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
# 通用 Job 回收阈值须高于版面 Worker 360 秒上限,避免并发 Worker 误回收正常长任务。
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS=420
# 资格达标后 waiting_to_start 且无 STP 入队记录的超时(秒);超时投影 manual_fallback。
+5
View File
@@ -120,6 +120,10 @@ SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# 字段对齐确认(生产建议 true;测试可设 false)
@@ -141,6 +145,7 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
+74 -5
View File
@@ -1921,11 +1921,16 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
)
def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
"""
为选中完整明细行创建履约波次 Task。
为选中完整明细行创建履约波次。
Body: line_keys[], expected_draft_version, idempotency_key, reason?
与确认建单同样在同事务入队自动推进。
已有正式 OT 时走 create_post_ot_fulfillment_wave + schedule_post_ot_wave_progress;
禁止调用 schedule_auto_progress_after_review_confirm。
无正式 OT 时保留历史 create_fulfillment_wave(BE-8 兼容分支,仅建单前兜底;
响应标记 legacy_pre_ot_wave=true,后续版本可收敛删除)。
"""
import logging
user = _require_user()
data = request.get_json(silent=True) or {}
from app.services.shipping_notice.order_review_confirmation_service import (
@@ -1933,17 +1938,69 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
resolve_confirm_outcome,
schedule_auto_progress_after_review_confirm,
)
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
create_fulfillment_wave,
)
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
create_post_ot_fulfillment_wave,
)
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
formal = resolve_formal_ot(case) if case is not None else {'has_formal_ot': False}
line_keys = list(data.get('line_keys') or [])
idem = data.get('idempotency_key') or request.headers.get('Idempotency-Key')
reason = str(data.get('reason') or '').strip() or None
if formal.get('has_formal_ot'):
result = create_post_ot_fulfillment_wave(
case_no=str(case_no),
line_keys=line_keys,
decision_source='user',
actor_user_id=int(user.id),
reason=reason,
idempotency_key=idem,
)
from app.services.shipping_notice.post_ot_wave_progress_service import (
schedule_post_ot_wave_progress,
)
progress = schedule_post_ot_wave_progress(
task_no=str(result.get('task_no') or ''),
wave_no=result.get('wave_no'),
line_keys=list(result.get('accepted_line_keys') or line_keys),
review_case_id=int(result.get('review_case_id') or (case.id if case is not None else 0) or 0) or None,
idempotency_row_id=result.get('idempotency_row_id'),
request_idempotency_key=str(result.get('idempotency_key') or idem or '') or None,
created_by_id=int(user.id),
commit=False,
)
db.session.commit()
result = dict(result)
result['confirm_ok'] = True
result['confirm_outcome'] = 'post_ot_wave_progress_scheduled' if (
progress or {}
).get('auto_progress_started') else 'post_ot_wave_progress_not_scheduled'
result['wave_progress'] = progress
result['auto_progress'] = progress
result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started'))
result['post_ot_wave'] = True
result['legacy_pre_ot_wave'] = False
return _ok(result)
# [STEP] BE-8:无正式 OT 的历史 wave→confirm 路径;仅兼容,不作为 OT 后主路径。
logging.getLogger(__name__).warning(
'shipping_review_fulfillment_wave_legacy_pre_ot case_no=%s line_count=%s',
case_no,
len(line_keys),
)
result = create_fulfillment_wave(
user_id=user.id,
case_no=case_no,
line_keys=list(data.get('line_keys') or []),
line_keys=line_keys,
expected_draft_version=data.get('expected_draft_version'),
idempotency_key=data.get('idempotency_key') or request.headers.get('Idempotency-Key'),
reason=str(data.get('reason') or '').strip() or None,
idempotency_key=idem,
reason=reason,
)
progress = schedule_auto_progress_after_review_confirm(
task_no=result.get('task_no'),
@@ -1959,6 +2016,8 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
result['confirm_outcome'] = resolve_confirm_outcome(progress)
result['auto_progress'] = progress
result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started'))
result['post_ot_wave'] = False
result['legacy_pre_ot_wave'] = True
return _ok(result)
@@ -2119,6 +2178,16 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
created_by_id=int(user.id),
commit=False,
)
# [STEP] BE-4:正式 OT 创建后补触发自动履约(flag 关时 enqueue 内部 no-op)
if result.get('task_no') and not result.get('idempotent_replay'):
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
enqueue_post_ot_auto_fulfill_job,
)
enqueue_post_ot_auto_fulfill_job(
task_no=str(result.get('task_no')),
trigger='ot_created',
commit=False,
)
db.session.commit()
# [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。
progress = finalize_sync_auto_progress_after_commit(progress)
+21 -1
View File
@@ -3,7 +3,8 @@ backend/app/core/config/settings.py
用途:Flask Config 类与环境文件加载(dev/test/prod)。
依赖:dotenv、app.path_utils。
逻辑:create_app 通过 config[config_name] 加载;旧路径 app.config 为兼容 shim。
逻辑:create_app 通过 config[config_name] 加载;含发货通知开关
(如 SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED);旧路径 app.config 为兼容 shim。
"""
import os
import warnings
@@ -230,6 +231,10 @@ class Config:
)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
# OT 后行级自动履约总闸:关闭时仍投影 match_result/库存列,但禁止自动写决定与批量 wave。
SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED = (
os.getenv('SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED', 'false').lower() == 'true'
)
# 订单解析主链开关:通用确定性解析 / 分路径自动冻结 / 模板自动采用 / LLM 辅助复核 / 全局紧急停止。
# 主链不依赖 Dify;LLM 仅用于复核建议且默认关闭自动路径。
SHIPPING_NOTICE_GENERIC_EXTRACTION_ENABLED = (
@@ -589,6 +594,21 @@ class Config:
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS', '360')
)
# PR-1:同 Job 内整页 OCR 结果复用;生产默认关,dev/test 由环境文件开启。
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED = os.getenv(
'SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED', 'false'
).lower() == 'true'
# PR-2:复用 MinerU 前 PDFium 字符预读,仅按需补齐页面渲染图。
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED = os.getenv(
'SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED', 'false'
).lower() == 'true'
# PR-3:表格 cell 候选使用裁剪 OCR;订单级 page_glyphs 仍整页 OCR。
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED = os.getenv(
'SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED', 'false'
).lower() == 'true'
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO = float(
os.getenv('SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO', '0.03')
)
# XFA 字段拆分规则资源上限(阶段 1:matcher 引擎与 RE2 安全执行)
XFA_SPLIT_MAX_RULES_PER_SET = int(os.getenv('XFA_SPLIT_MAX_RULES_PER_SET', '32'))
XFA_SPLIT_MAX_RULE_SETS = int(os.getenv('XFA_SPLIT_MAX_RULE_SETS', '64'))
+2
View File
@@ -16,6 +16,8 @@ from app.jobs.handlers import ( # noqa: F401
shipping_order_extraction,
shipping_process_gate,
shipping_stp_auto_create,
shipping_line_auto_fulfill,
shipping_post_ot_wave_progress,
shipping_xfa_ocr_automark,
wecom_directory_sync,
)
@@ -2,9 +2,11 @@
backend/app/jobs/handlers/shipping_document_layout.py
用途:独立执行单份 ShippingOrderDocument 的 MinerU 布局解析任务。
依赖:Layout lifecycle/runtime、FileAsset、通用 Job queue、audit_service、workflow_ledger(尽力引用)。
依赖:Layout lifecycle/runtime、layout_diagnostics、FileAsset、通用 Job queue、audit_service、
workflow_ledger(尽力引用)。
逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本;
起止与异常轻量写统一审计(若能定位 WorkflowItem 则带软引用)。
起止与异常轻量写统一审计(若能定位 WorkflowItem 则带软引用);
PR-0 将脱敏 timings/counts 写入 Job result 与 worker 日志,不进 layout snapshot。
"""
from __future__ import annotations
@@ -18,6 +20,12 @@ from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import FileAsset, Job, ShippingDocumentLayoutVersion
from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.document_layout.layout_diagnostics import (
empty_layout_counts,
empty_layout_timings,
freeze_layout_diagnostics,
ocr_engine_is_warm,
)
from app.services.shipping_notice.document_layout.lifecycle import (
claim_layout_version,
complete_layout_version,
@@ -139,11 +147,14 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
total_started = perf_counter()
asset_started = perf_counter()
content = read_asset_bytes(asset)
timings = {
'queue_wait_ms': max(round((job.started_at - job.created_at).total_seconds() * 1000), 0)
if job.started_at and job.created_at else 0,
'asset_read_ms': round((perf_counter() - asset_started) * 1000),
}
# [STEP 1] 初始化全量诊断键;ocr_engine_warm 在任何 OCR 之前读取进程状态。
timings = empty_layout_timings()
counts = empty_layout_counts()
counts['ocr_engine_warm'] = ocr_engine_is_warm()
timings['queue_wait_ms'] = max(
round((job.started_at - job.created_at).total_seconds() * 1000), 0,
) if job.started_at and job.created_at else 0
timings['asset_read_ms'] = round((perf_counter() - asset_started) * 1000)
from app.services.shipping_notice.document_layout.xfa_analysis import (
analyze_xfa_pdf,
persist_xfa_structure_analysis,
@@ -169,6 +180,11 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
and xfa_outcome.packet_result.document_kind not in {'plain_pdf', 'acroform'}
):
snapshot = dict(xfa_outcome.snapshot)
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
try:
counts['page_count'] = int(capability.get('page_count') or 0)
except (TypeError, ValueError):
counts['page_count'] = 0
persist_xfa_structure_analysis(
document_id=int(document.id),
layout_version_id=int(version.id),
@@ -212,6 +228,7 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
document_id=document.id,
content_hash=document.content_hash,
timings=timings,
counts=counts,
)
timings['snapshot_build_ms'] = round((perf_counter() - total_started) * 1000)
if snapshot is None:
@@ -230,11 +247,14 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
version=version,
metadata={'status': str(snapshot.get('status') or 'failed')},
)
timings['total_handler_ms'] = round((perf_counter() - total_started) * 1000)
frozen_timings, frozen_counts = freeze_layout_diagnostics(timings, counts)
finish_job(
job.id, result={
'status': final_status,
'provider_status': str(snapshot.get('status') or 'failed'),
'timings': {key: int(value) for key, value in timings.items()},
'timings': frozen_timings,
'counts': frozen_counts,
},
message=(
'文档版面解析完成' if final_status in {'ready', 'needs_review'}
@@ -244,11 +264,13 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout
resume_runs_waiting_for_layout(document_id=int(document.id))
timings['total_handler_ms'] = round((perf_counter() - total_started) * 1000)
else:
timings['total_handler_ms'] = round((perf_counter() - total_started) * 1000)
if ctx.logger is not None:
frozen_timings, frozen_counts = freeze_layout_diagnostics(timings, counts)
ctx.logger.info(
'shipping_document_layout_timing job_id=%s version_id=%s document_id=%s timings=%s',
job.id, version.id, document.id, timings,
'shipping_document_layout_timing job_id=%s version_id=%s document_id=%s timings=%s counts=%s',
job.id, version.id, document.id, frozen_timings, frozen_counts,
)
except Exception as exc:
db.session.rollback()
@@ -0,0 +1,80 @@
"""
backend/app/jobs/handlers/shipping_line_auto_fulfill.py
用途:消费 OT 后行级自动履约协调 Job。
依赖:JobContext、line_auto_fulfill_coordinator、query_service.get_task_by_ref。
逻辑:shipping worker 领取;flag 关闭或无 eligible 时 finish 为 skipped;失败可重试。
"""
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
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
coordinate_post_ot_auto_fulfill,
)
from app.services.shipping_notice.query_service import get_task_by_ref
@register_handler(JobType.SHIPPING_LINE_AUTO_FULFILL)
def handle_shipping_line_auto_fulfill(ctx: JobContext, payload: dict) -> None:
"""
执行 OT 后行级自动履约协调。
Args:
ctx: Worker 上下文。
payload: 须含 job_id;业务字段以 Job.payload_json 为准(task_no/trigger)。
"""
_ = 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_line_auto_fulfill_job_id')
job_id = int(job.id)
owned_attempt = int(job.attempts or 0)
frozen = dict(job.payload_json or {})
task_no = str(frozen.get('task_no') or '').strip()
trigger = str(frozen.get('trigger') or 'inventory_ready').strip()
task = get_task_by_ref(task_no) if task_no else None
if task is None:
fail_job(
job_id,
error='task_not_found',
result={'status': 'failed', 'error_code': 'SHIPPING.TASK_NOT_FOUND'},
retryable=False,
owned_attempt=owned_attempt,
)
return
try:
result = coordinate_post_ot_auto_fulfill(task=task, trigger=trigger)
db.session.commit()
if result.get('status') == 'failed':
fail_job(
job_id,
error=str(result.get('error') or 'auto_fulfill_failed'),
result=result,
retryable=True,
owned_attempt=owned_attempt,
)
return
finish_job(
job_id,
result=result,
message=str(result.get('status') or 'ok'),
owned_attempt=owned_attempt,
)
except Exception as exc: # noqa: BLE001
db.session.rollback()
fail_job(
job_id,
error=str(exc)[:500],
result={'status': 'failed'},
retryable=True,
owned_attempt=owned_attempt,
)
raise
@@ -0,0 +1,121 @@
"""
backend/app/jobs/handlers/shipping_post_ot_wave_progress.py
用途:消费 post-OT wave 专用 Excel/RPA 推进 Job。
依赖:JobContext、post_ot_wave_progress_service、fulfillment_workflow.generate_excel。
逻辑:按 task_no+wave_no 推进;失败只标记 progress_failed,不回滚已提交 wave。
"""
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
from app.services.shipping_notice.post_ot_wave_progress_service import (
mark_post_ot_wave_progress_result,
)
from app.services.shipping_notice.query_service import get_task_by_ref
@register_handler(JobType.SHIPPING_POST_OT_WAVE_PROGRESS)
def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> None:
"""
执行本 wave 的 Excel 生成推进(RPA 链路由 generate_excel 后续状态机承接)。
Args:
ctx: Worker 上下文。
payload: 须含 job_id;业务字段以 Job.payload_json 为准。
"""
_ = 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_post_ot_wave_progress_job_id')
job_id = int(job.id)
owned_attempt = int(job.attempts or 0)
frozen = dict(job.payload_json or {})
task_no = str(frozen.get('task_no') or '').strip()
wave_no = frozen.get('wave_no')
idem_row_id = frozen.get('idempotency_row_id')
progress_key = frozen.get('progress_idempotency_key')
task = get_task_by_ref(task_no) if task_no else None
if task is None:
mark_post_ot_wave_progress_result(
idempotency_row_id=idem_row_id,
progress_idempotency_key=progress_key,
ok=False,
error='task_not_found',
)
db.session.commit()
fail_job(
job_id,
error='task_not_found',
result={'status': 'failed', 'wave_no': wave_no},
retryable=False,
owned_attempt=owned_attempt,
)
return
try:
from app.services.shipping_notice.fulfillment_workflow import generate_excel
# [STEP] 为本 OT 生成/刷新发货 Excel;wave_no 写入上下文供审计与后续过滤。
gen = generate_excel({
'task_id': task.task_no,
'wave_no': wave_no,
'line_keys': list(frozen.get('line_keys') or []),
'post_ot_wave': True,
})
status = str((gen or {}).get('status') or '').strip().lower()
if status in {'failed', 'error'}:
err = str((gen or {}).get('message') or (gen or {}).get('error') or 'excel_failed')
mark_post_ot_wave_progress_result(
idempotency_row_id=idem_row_id,
progress_idempotency_key=progress_key,
ok=False,
error=err,
)
db.session.commit()
fail_job(
job_id,
error=err[:500],
result={'status': 'failed', 'wave_no': wave_no, 'generate_excel': gen},
retryable=True,
owned_attempt=owned_attempt,
)
return
mark_post_ot_wave_progress_result(
idempotency_row_id=idem_row_id,
progress_idempotency_key=progress_key,
ok=True,
)
db.session.commit()
finish_job(
job_id,
result={'status': 'ok', 'wave_no': wave_no, 'generate_excel': gen},
message='post_ot_wave_progress_ok',
owned_attempt=owned_attempt,
)
except Exception as exc: # noqa: BLE001
db.session.rollback()
# [STEP] 下游失败:重新打开会话标记 progress_failed,wave 业务事实保留。
mark_post_ot_wave_progress_result(
idempotency_row_id=idem_row_id,
progress_idempotency_key=progress_key,
ok=False,
error=str(exc)[:1000],
)
db.session.commit()
fail_job(
job_id,
error=str(exc)[:500],
result={'status': 'failed', 'wave_no': wave_no},
retryable=True,
owned_attempt=owned_attempt,
)
raise
@@ -10,37 +10,65 @@ backend/app/jobs/handlers/shipping_stp_auto_create.py
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
from app.services.shipping_notice.order_stp_auto_create_service import (
execute_stp_auto_create_job,
)
@register_handler(JobType.SHIPPING_STP_AUTO_CREATE)
def handle_shipping_stp_auto_create(ctx: JobContext) -> None:
def handle_shipping_stp_auto_create(ctx: JobContext, payload: dict) -> None:
"""
执行 STP 自动建单 Job。
核心逻辑:委托 execute_stp_auto_create_job;成功 finish,业务拒绝/异常 fail。
核心逻辑:按 Worker 传入的 job_id 读取冻结 payload 与执行代次;委托
execute_stp_auto_create_job;成功 finish,业务拒绝/异常按当前代次 fail。
Args:
ctx: Worker 上下文;当前执行体不依赖请求上下文。
payload: Worker 载荷,必须含 job_id;业务字段以 Job.payload_json 为准。
Returns:
None。
"""
payload = ctx.payload if isinstance(ctx.payload, dict) else {}
_ = 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_stp_auto_create_job_id')
job_id = int(job.id)
owned_attempt = int(job.attempts or 0)
frozen = dict(job.payload_json or {})
frozen.setdefault('job_id', job_id)
try:
result = execute_stp_auto_create_job(payload=payload, job_id=int(ctx.job_id))
result = execute_stp_auto_create_job(payload=frozen, job_id=job_id)
if result.get('ok'):
finish_job(int(ctx.job_id), message=str(result.get('message') or 'STP 自动建单完成'))
finish_job(
job_id,
result=result,
message=str(result.get('message') or 'STP 自动建单完成'),
owned_attempt=owned_attempt,
)
return
fail_job(
int(ctx.job_id),
error_code=str(result.get('error_code') or 'STP_AUTO_CREATE_FAILED'),
message=str(result.get('message') or 'STP 自动建单失败'),
job_id,
error=str(result.get('message') or result.get('error_code') or 'STP 自动建单失败'),
result=result,
retryable=True,
owned_attempt=owned_attempt,
)
except Exception as exc: # noqa: BLE001
fail_job(
int(ctx.job_id),
error_code='STP_AUTO_CREATE_EXCEPTION',
message=str(exc)[:500],
job_id,
error=str(exc)[:500],
result={'status': 'failed', 'error_code': 'SHIPPING.STP_AUTO_CREATE_FAILED'},
retryable=True,
owned_attempt=owned_attempt,
)
raise
+6 -1
View File
@@ -24,6 +24,10 @@ class JobType(StrEnum):
SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark'
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
SHIPPING_STP_AUTO_CREATE = 'shipping_stp_auto_create'
# OT 后行级自动履约协调(flag 关闭时不入队)
SHIPPING_LINE_AUTO_FULFILL = 'shipping_line_auto_fulfill'
# post-OT wave 专用 Excel/RPA 推进(禁止复用 confirm 后整单推进)
SHIPPING_POST_OT_WAVE_PROGRESS = 'shipping_post_ot_wave_progress'
SCHEDULE_RUN = 'schedule_run'
FILE_CHECK_RUN = 'file_check_run'
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
@@ -60,7 +64,8 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'shipping': frozenset({
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
'shipping_document_layout', 'shipping_process_gate', 'shipping_xfa_ocr_automark',
'shipping_stp_auto_create',
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
'shipping_post_ot_wave_progress',
}),
}
+4
View File
@@ -81,6 +81,8 @@ from app.models.shipping_order_review import (
)
from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion
from app.models.shipping_order_extraction_run import (
ShippingOrderExtractionDiagnosticAudit,
@@ -220,6 +222,8 @@ __all__ = [
'ShippingOrderReviewConfirmedRevision',
'ShippingOrderReviewLineDecision',
'ShippingOrderReviewWaveLine',
'ShippingOrderReviewWaveIdempotency',
'ShippingNoticeLineInventoryMatch',
'ShippingOrderReviewSuggestion',
'ShippingOrderProcessingRun',
'ShippingOrderProcessingRunIntake',
@@ -0,0 +1,112 @@
"""
models/shipping_notice_line_inventory_match.py
用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。
依赖:shipping_notices、shipping_inventory_files、shipping_order_review_cases(可选关联)。
逻辑:由 inventory_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingNoticeLineInventoryMatch(Base):
"""一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。"""
__tablename__ = 'shipping_notice_line_inventory_matches'
__table_args__ = (
UniqueConstraint(
'task_id',
'line_key',
'inventory_snapshot_id',
name='uq_shipping_notice_line_inv_match_task_line_snap',
),
# 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。
Index(
'uq_shipping_notice_line_inv_match_current',
'task_id',
'line_key',
unique=True,
postgresql_where=text('is_current IS TRUE'),
),
Index('ix_shipping_notice_line_inv_match_task', 'task_id'),
Index('ix_shipping_notice_line_inv_match_case', 'review_case_id'),
Index('ix_shipping_notice_line_inv_match_snapshot', 'inventory_snapshot_id'),
CheckConstraint(
"match_result IN ("
"'matched', 'not_found', 'result_missing', 'preparing', "
"'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable'"
")",
name='ck_shipping_notice_line_inv_match_result',
),
CheckConstraint(
"inventory_status IN ("
"'ready', 'preparing', 'mapping_failed', 'source_conflict', "
"'unavailable', 'invalid_key'"
")",
name='ck_shipping_notice_line_inv_match_status',
),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
nullable=False,
)
review_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='SET NULL'),
nullable=True,
)
line_key: Mapped[str] = mapped_column(String(64), nullable=False)
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'),
nullable=True,
)
match_result: Mapped[str] = mapped_column(String(32), nullable=False)
inventory_status: Mapped[str] = mapped_column(String(32), nullable=False)
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true')
matched_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# BE-7:自动履约失败独立存储(非 decision_code 枚举)
auto_fulfill_failed: Mapped[bool] = mapped_column(
Boolean, nullable=False, default=False, server_default='false',
)
auto_fulfill_error_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
auto_fulfill_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
auto_fulfill_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False,
)
@@ -1,10 +1,11 @@
"""
models/shipping_order_review_line_decision.py
用途:建单前复核 Case 的行级履约决定(版本化、可追溯)。
用途:复核 Case 的行级履约决定(版本化、可追溯);含 OT 后系统/人工来源。
依赖:ShippingOrderReviewCase、ShippingNotice、users。
逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, line_key, version) 唯一;
活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联。
活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联;
decision_source 区分 system/user(历史可空)。
"""
from __future__ import annotations
@@ -43,6 +44,10 @@ class ShippingOrderReviewLineDecision(Base):
")",
name='ck_shipping_review_line_decisions_status',
),
CheckConstraint(
"decision_source IS NULL OR decision_source IN ('system', 'user', 'unknown')",
name='ck_shipping_review_line_decisions_source',
),
CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'),
Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'line_key'),
Index('ix_shipping_review_line_decisions_case_active', 'review_case_id', 'is_active'),
@@ -67,6 +72,8 @@ class ShippingOrderReviewLineDecision(Base):
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# system=自动履约;user=人工异常/显式履约;unknown=历史无法判定。
decision_source: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
actor_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,67 @@
"""
models/shipping_order_review_wave_idempotency.py
用途:post-OT 履约 wave 请求幂等表(idempotency_key → wave 身份),无 wave 主表时提供强约束。
依赖:shipping_order_review_cases、shipping_notices。
逻辑:create_post_ot_fulfillment_wave 写入/回放;同 key 参数不一致 → 409;
progress_* 记录本 wave Excel/RPA 推进状态(失败不回滚已提交 wave)。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class ShippingOrderReviewWaveIdempotency(Base):
"""一次 post-OT wave 创建请求的幂等记录。"""
__tablename__ = 'shipping_order_review_wave_idempotency'
__table_args__ = (
UniqueConstraint(
'idempotency_key',
name='uq_shipping_review_wave_idempotency_key',
),
Index('ix_shipping_review_wave_idempotency_case', 'review_case_id'),
Index('ix_shipping_review_wave_idempotency_task', 'task_id'),
Index('ix_shipping_review_wave_idempotency_wave', 'review_case_id', 'wave_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
idempotency_key: Mapped[str] = mapped_column(String(191), nullable=False)
review_case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
)
task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'),
nullable=False,
)
task_no: Mapped[str] = mapped_column(String(64), nullable=False)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
decision_source: Mapped[str] = mapped_column(String(16), nullable=False)
# 稳定排序后的 line_key JSON 数组字符串指纹(冲突比对)。
line_keys_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
line_keys_hash: Mapped[str] = mapped_column(String(64), nullable=False)
# 行集合共享快照 ID;多快照时为空,靠 fingerprint 比对。
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
inventory_snapshot_fingerprint: Mapped[str] = mapped_column(String(256), nullable=False, default='')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='succeeded')
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 本 wave 下游推进(Excel/RPA);失败不回滚 wave 创建事实。
progress_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending')
progress_job_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
progress_error: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
progress_idempotency_key: Mapped[Optional[str]] = mapped_column(String(191), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False,
)
@@ -134,6 +134,9 @@ def _register_builtin_platform_jobs() -> None:
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
run_shipping_post_ot_auto_fulfill_compensation_schedule,
)
register_platform_job(PlatformJobDefinition(
key="shipping-order-extraction-progress-cleanup",
@@ -144,6 +147,19 @@ def _register_builtin_platform_jobs() -> None:
params_schema=({"key": "limit", "type": "number", "label": "单批上限", "required": False, "default": 1000},),
defaults={"limit": 1000},
))
register_platform_job(PlatformJobDefinition(
key="shipping-post-ot-auto-fulfill-compensation",
label="OT 后行级自动履约补偿",
handler=run_shipping_post_ot_auto_fulfill_compensation_schedule,
description=(
"每 15 分钟扫描正式 OT 上尚未入波次且匹配 ready 的行,"
"复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。"
"SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false 时空跑。"
),
category="shipping",
params_schema=({"key": "limit", "type": "number", "label": "单批 Case 上限", "required": False, "default": 50},),
defaults={"limit": 50},
))
register_platform_job(PlatformJobDefinition(
key="shipping-audit-retention",
label="货代审计到期清理与哈希校验",
@@ -0,0 +1,138 @@
"""
services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py
用途:OT 后行级自动履约补偿轮询(每 15 分钟)——补齐 matching/ot_created 事件丢失。
依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_line_keys。
逻辑:platform_api_path=shipping-post-ot-auto-fulfill-compensation;flag 关闭时 no-op;
仅扫描有正式 OT 且存在 eligible 行的 Case,复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask, ShippingOrderReviewCase
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
coordinate_post_ot_auto_fulfill,
enqueue_post_ot_auto_fulfill_job,
)
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
list_eligible_post_ot_line_keys,
)
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def run_post_ot_auto_fulfill_compensation(*, limit: int = 50) -> dict[str, Any]:
"""
扫描可补偿的正式 OT Case 并入队/协调自动履约。
Args:
limit: 单批最多处理的 Case 数。
Returns:
scanned / enqueued / coordinated / skipped / details。
"""
if not line_auto_fulfill_enabled():
return {
'scanned': 0,
'enqueued': 0,
'coordinated': 0,
'skipped': 0,
'reason': 'line_auto_fulfill_disabled',
'details': [],
}
safe_limit = min(200, max(1, int(limit or 50)))
cases = (
ShippingOrderReviewCase.query
.filter(ShippingOrderReviewCase.confirmed_task_id.isnot(None))
.order_by(ShippingOrderReviewCase.id.desc())
.limit(safe_limit * 3)
.all()
)
scanned = 0
enqueued = 0
coordinated = 0
skipped = 0
details: list[dict[str, Any]] = []
for case in cases:
if scanned >= safe_limit:
break
scanned += 1
eligible = list_eligible_post_ot_line_keys(case)
if not eligible:
skipped += 1
continue
task_no = str(getattr(case, 'confirmed_task_no', None) or '').strip()
if not task_no and case.confirmed_task_id is not None:
from app import db
from app.models import ShippingNotice
task = db.session.get(ShippingNotice, int(case.confirmed_task_id))
task_no = str(getattr(task, 'task_no', '') or '').strip() if task else ''
if not task_no:
skipped += 1
details.append({'case_no': case.case_no, 'status': 'skipped', 'reason': 'missing_task_no'})
continue
job_id = enqueue_post_ot_auto_fulfill_job(
task_no=task_no,
trigger='compensation',
commit=True,
)
if job_id is not None:
enqueued += 1
details.append({
'case_no': case.case_no,
'task_no': task_no,
'status': 'enqueued',
'job_id': int(job_id),
'eligible_count': len(eligible),
})
continue
# 入队失败时同步协调一次(仍受幂等键保护)
result = coordinate_post_ot_auto_fulfill(case=case, trigger='compensation')
coordinated += 1
details.append({
'case_no': case.case_no,
'task_no': task_no,
'status': str(result.get('status') or 'coordinated'),
'eligible_count': len(eligible),
})
return {
'scanned': scanned,
'enqueued': enqueued,
'coordinated': coordinated,
'skipped': skipped,
'details': details[:50],
}
def run_shipping_post_ot_auto_fulfill_compensation_schedule(
task: ScheduleTask,
run: ScheduleRun,
) -> ScheduleExecuteResult:
"""
平台排程入口:每 15 分钟补偿扫描。
Returns:
ScheduleExecuteResult 七元组。
"""
_ = run
params = getattr(task, 'job_params', None) or {}
result = run_post_ot_auto_fulfill_compensation(limit=int(params.get('limit') or 50))
enqueued = int(result.get('enqueued') or 0)
coordinated = int(result.get('coordinated') or 0)
skipped = int(result.get('skipped') or 0)
scanned = int(result.get('scanned') or 0)
success = enqueued + coordinated
details = list(result.get('details') or [])
warnings: list[str] = []
if result.get('reason') == 'line_auto_fulfill_disabled':
warnings.append('line_auto_fulfill_disabled')
return success, 0, skipped, scanned, details, warnings, []
@@ -53,6 +53,7 @@ from app.services.shipping_notice.document_layout.text_cell_alignment import (
)
from app.services.shipping_notice.document_layout.native_pdf import (
NativePdfPage,
attach_native_pdf_page_images,
build_native_pdf_layout_candidate,
build_native_pdf_text_table_fallbacks,
extract_native_pdf_pages,
@@ -64,6 +65,8 @@ from app.services.shipping_notice.document_layout.ocr_pdf import (
OcrTableEvidence,
build_ocr_table_evidence,
extract_ocr_lines,
extract_table_crop_ocr_lines,
get_page_ocr_lines,
page_bbox_to_normalized,
)
from app.services.shipping_notice.document_layout.schema_mapping import (
@@ -98,6 +101,7 @@ __all__ = [
'NativePdfPage',
'build_native_pdf_layout_candidate',
'build_native_pdf_text_table_fallbacks',
'attach_native_pdf_page_images',
'extract_native_pdf_pages',
'build_html_layout_candidate',
'OcrCellEvidence',
@@ -105,6 +109,8 @@ __all__ = [
'OcrTableEvidence',
'build_ocr_table_evidence',
'extract_ocr_lines',
'extract_table_crop_ocr_lines',
'get_page_ocr_lines',
'page_bbox_to_normalized',
'layout_table_to_grid',
'map_layout_document_to_schema',
@@ -0,0 +1,295 @@
"""
backend/app/services/shipping_notice/document_layout/layout_diagnostics.py
用途:Layout Job 脱敏阶段计时与计数契约(PR-0~PR-3);仅写入 Job result / worker 日志。
依赖:time.perf_counter;可选读取 ocr_pdf._ocr_engine 的 lru_cache 状态。
逻辑:由 shipping_document_layout handler 初始化;runtime / native_pdf / ocr_pdf / opencv_table 累加;
PR-1 持有页面 OCR 缓存;PR-2 持有 OpenCV geometry 缓存;PR-3 持有表格裁剪 OCR 缓存;
均不进 snapshot、不跨 Job;禁止把 timings/counts 写入 layout snapshot。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from time import perf_counter
from typing import Any
LAYOUT_DIAGNOSTIC_TIMING_KEYS: tuple[str, ...] = (
'queue_wait_ms',
'asset_read_ms',
'xfa_analysis_ms',
'mineru_wait_ms',
'mineru_result_parse_ms',
'native_pdf_extract_ms',
'native_layout_build_ms',
'native_text_alignment_ms',
'opencv_geometry_ms',
'opencv_validation_ms',
'ocr_engine_init_ms',
'ocr_inference_ms',
'layout_assembly_ms',
'layout_serialize_ms',
'coordinate_evidence_ms',
'snapshot_build_ms',
'total_handler_ms',
)
LAYOUT_DIAGNOSTIC_COUNT_KEYS: tuple[str, ...] = (
'page_count',
'mineru_table_count',
'resolved_table_count',
'partial_alignment_table_count',
'opencv_attempt_count',
'opencv_geometry_cache_hit',
'opencv_geometry_cache_miss',
'ocr_attempt_count',
'ocr_call_count',
'ocr_page_count',
'ocr_table_count',
'ocr_page_cache_hit',
'ocr_page_cache_miss',
'ocr_crop_count',
'pdfium_page_image_attach_count',
'native_token_count',
'layout_cell_count',
'ocr_engine_warm',
)
# 页面 OCR 缓存失败哨兵:与空行列表区分,表示引擎不可用。
OCR_PAGE_CACHE_UNAVAILABLE = object()
OCR_TABLE_CROP_CACHE_UNAVAILABLE = object()
def empty_layout_timings() -> dict[str, int]:
"""
构造 PR-0 全量 timing 键,未执行阶段统一为 0。
Returns:
可就地累加的 timing 字典。
"""
return {key: 0 for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS}
def empty_layout_counts() -> dict[str, Any]:
"""
构造 PR-0 全量 count 键;数值计数为 0,`ocr_engine_warm` 默认为 False。
Returns:
可就地累加的 counts 字典。
"""
counts: dict[str, Any] = {
key: 0 for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS if key != 'ocr_engine_warm'
}
counts['ocr_engine_warm'] = False
return counts
def ensure_layout_timings(timings: dict[str, Any] | None) -> dict[str, Any]:
"""
补齐缺失 timing 键为 0,不删除调用方已写入的额外键(如 native_table_detect_ms)。
Args:
timings: 既有 timing 字典;None 时返回新建空字典。
Returns:
保证含全部 PR-0 timing 键的字典。
"""
target = timings if timings is not None else {}
for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS:
if key not in target:
target[key] = 0
return target
def ensure_layout_counts(counts: dict[str, Any] | None) -> dict[str, Any]:
"""
补齐缺失 count 键;`ocr_engine_warm` 缺失时为 False。
Args:
counts: 既有 counts 字典;None 时返回新建空字典。
Returns:
保证含全部 PR-0 count 键的字典。
"""
target = counts if counts is not None else {}
for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS:
if key not in target:
target[key] = False if key == 'ocr_engine_warm' else 0
return target
def ocr_engine_is_warm() -> bool:
"""
判断当前 Worker 进程是否已持有 RapidOCR 引擎实例。
核心逻辑:读取 `_ocr_engine` 的 lru_cache;无真实 cache_info(测试 mock)时视为未 warm,
避免把 mock 调用计入初始化。
Returns:
True 表示进程内已有引擎;False 表示尚未初始化或无法判定。
"""
try:
from app.services.shipping_notice.document_layout.ocr_pdf import _ocr_engine
cache_info = getattr(_ocr_engine, 'cache_info', None)
if not callable(cache_info):
return False
currsize = getattr(cache_info(), 'currsize', None)
return isinstance(currsize, int) and currsize > 0
except Exception:
return False
def freeze_layout_diagnostics(
timings: dict[str, Any] | None,
counts: dict[str, Any] | None,
) -> tuple[dict[str, int], dict[str, Any]]:
"""
在 finish_job 前规范化 result 载荷:timing 全为 int,counts 数值为 int,warm 为 bool。
Args:
timings/counts: Job 内累加后的诊断字典。
Returns:
(timings, counts) 可直接写入 Job result 的副本。
"""
raw_timings = ensure_layout_timings(dict(timings or {}))
raw_counts = ensure_layout_counts(dict(counts or {}))
frozen_timings = {key: int(raw_timings.get(key) or 0) for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS}
# 保留已有额外 timing(如 native_table_detect_ms),但不强制进契约列表。
for key, value in raw_timings.items():
if key not in frozen_timings:
try:
frozen_timings[key] = int(value or 0)
except (TypeError, ValueError):
continue
frozen_counts: dict[str, Any] = {}
for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS:
if key == 'ocr_engine_warm':
frozen_counts[key] = bool(raw_counts.get(key))
else:
frozen_counts[key] = int(raw_counts.get(key) or 0)
return frozen_timings, frozen_counts
@dataclass
class LayoutJobDiagnostics:
"""
单次 Layout Job 内存诊断上下文;生命周期仅限当前 Job。
Attributes:
timings: 阶段耗时(毫秒),允许嵌套墙钟,不可简单求和。
counts: 计数与 ocr_engine_warm 标志。
ocr_pages: 已执行 RapidOCR 的去重页号,用于 ocr_page_count。
ocr_page_cache: PR-1 整页 OCR 结果;键为 (page_no, image_width, image_height)。
ocr_table_crop_cache: PR-3 表格裁剪 OCR 结果;键含页号、圆整 bbox 与图尺寸。
opencv_geometry_cache: PR-2 同表同图 geometry 结果缓存。
"""
timings: dict[str, Any] = field(default_factory=empty_layout_timings)
counts: dict[str, Any] = field(default_factory=empty_layout_counts)
ocr_pages: set[int] = field(default_factory=set)
ocr_page_cache: dict[tuple[int, int, int], Any] = field(default_factory=dict)
ocr_table_crop_cache: dict[tuple[Any, ...], Any] = field(default_factory=dict)
opencv_geometry_cache: dict[tuple[Any, ...], Any] = field(default_factory=dict)
def __post_init__(self) -> None:
"""确保 timings/counts 含全量契约键。"""
ensure_layout_timings(self.timings)
ensure_layout_counts(self.counts)
@staticmethod
def page_ocr_cache_key(page_no: int, image: Any) -> tuple[int, int, int]:
"""
构造 Job 内页面 OCR 缓存键。
Args:
page_no: PDF 页号。
image: 渲染页图;用像素宽高区分不同 render_scale。
Returns:
(page_no, image_width, image_height)。
"""
height, width = image.shape[:2]
return (int(page_no), int(width), int(height))
def add_ms(self, key: str, started: float) -> None:
"""
将 started 至今的墙钟毫秒累加到指定 timing 键。
Args:
key: LAYOUT_DIAGNOSTIC_TIMING_KEYS 中的键或额外诊断键。
started: perf_counter() 起点。
"""
elapsed = round((perf_counter() - started) * 1000)
self.timings[key] = int(self.timings.get(key) or 0) + max(elapsed, 0)
def set_ms(self, key: str, started: float) -> None:
"""
用 started 至今的墙钟毫秒覆盖写入(用于包围计时,如 native_layout_build_ms)。
Args:
key: timing 键。
started: perf_counter() 起点。
"""
self.timings[key] = max(round((perf_counter() - started) * 1000), 0)
def incr(self, key: str, amount: int = 1) -> None:
"""
累加数值型 count。
Args:
key: count 键(不得用于 ocr_engine_warm)。
amount: 增量,默认 1。
"""
if key == 'ocr_engine_warm':
return
self.counts[key] = int(self.counts.get(key) or 0) + int(amount)
def record_ocr_call(self, *, page_no: int | None = None) -> None:
"""
记录一次实际 RapidOCR 推理,并按页去重更新 ocr_page_count。
Args:
page_no: 页面号;缺失时只增加 ocr_call_count。
"""
self.incr('ocr_call_count')
if page_no is None:
return
page = int(page_no)
if page in self.ocr_pages:
return
self.ocr_pages.add(page)
self.counts['ocr_page_count'] = len(self.ocr_pages)
def record_layout_document_stats(self, layout: Any) -> None:
"""
从最终 LayoutDocument 回填 resolved/partial/token/cell 计数。
Args:
layout: contracts.LayoutDocument 或兼容对象。
"""
pages = list(getattr(layout, 'pages', None) or [])
if not self.counts.get('page_count'):
self.counts['page_count'] = len(pages)
resolved = 0
native_tokens = 0
cells = 0
for page in pages:
for table in list(getattr(page, 'tables', None) or []):
table_cells = [
cell
for row in list(getattr(table, 'rows', None) or [])
for cell in list(getattr(row, 'cells', None) or [])
]
if table_cells:
resolved += 1
cells += len(table_cells)
for token in list(getattr(page, 'tokens', None) or []):
if str(getattr(token, 'source', '') or '') == 'native_text':
native_tokens += 1
# partial_alignment 由 native_pdf 在方法 issue 处累加;此处只回填终态统计。
self.counts['resolved_table_count'] = resolved
self.counts['native_token_count'] = native_tokens
self.counts['layout_cell_count'] = cells
@@ -2,15 +2,18 @@
backend/app/services/shipping_notice/document_layout/native_pdf.py
用途:用项目既有 PDFium 提取原生 PDF 字符坐标、页面渲染,并组装保守的 layout.v1 表格候选。
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐和布局契约。
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐、布局契约、layout_diagnostics。
逻辑:MinerU 提供整表与 HTML;PDFium 提供独立字符/图像证据;阶段 1 优先唯一 glyph
对齐写入真实 cell bbox/token;部分唯一匹配可落盘;整体 layout 仍可 needs_review。
PR-0 可选累加 Job 级脱敏计时/计数,不改变候选算法。
PR-2:`attach_native_pdf_page_images` 在复用开关开启时仅补齐缺图页,禁止二次字符枚举。
"""
from __future__ import annotations
from dataclasses import dataclass
from html import escape
from time import perf_counter
from typing import Any
import numpy as np
@@ -31,9 +34,10 @@ from app.services.shipping_notice.document_layout.contracts import (
stable_layout_id,
)
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
from app.services.shipping_notice.document_layout.layout_diagnostics import LayoutJobDiagnostics
from app.services.shipping_notice.document_layout.mineru import MinerUParseCandidate
from app.services.shipping_notice.document_layout.opencv_table import (
reconstruct_opencv_table_geometry,
cached_reconstruct_opencv_table_geometry,
validate_opencv_cell_text,
)
from app.services.shipping_notice.document_layout.ocr_pdf import build_ocr_table_evidence
@@ -142,6 +146,72 @@ def extract_native_pdf_pages(
return pages
def layout_native_page_reuse_enabled() -> bool:
"""
读取 PR-2 PDFium 页面字符复用 / 按需补图开关。
Returns:
True 时复用前置轻量预读字符并仅补齐页面图,避免二次枚举字符层。
"""
try:
from flask import current_app, has_app_context
if not has_app_context():
return False
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED', False))
except Exception:
return False
def attach_native_pdf_page_images(
content: bytes,
pages: list[NativePdfPage],
*,
render_scale: float = 2.0,
) -> list[NativePdfPage]:
"""
在已有字符页列表上按需补齐渲染图,不重复枚举 PDF 字符层。
核心逻辑:仅打开 PDFium 渲染缺图页面;已有 image 的页原样保留;Job 结束后由调用方释放。
Args:
content: 原始 PDF 字节。
pages: 前置 `render_images=False` 提取的页面。
render_scale: 渲染倍率,须与增强链一致。
Returns:
与输入同序的页面列表;缺图页替换为带 image 的新 NativePdfPage。
Raises:
ValueError: 内容为空、倍率非法或页号越界。
"""
if not content or render_scale <= 0:
raise ValueError('native PDF content and positive render scale are required')
if not pages:
return []
if all(page.image is not None for page in pages):
return list(pages)
pdf = pdfium.PdfDocument(content)
attached: list[NativePdfPage] = []
for page in pages:
if page.image is not None:
attached.append(page)
continue
index = int(page.page_no) - 1
if index < 0 or index >= len(pdf):
raise ValueError('native PDF page_no is out of range for image attach')
image = np.asarray(pdf[index].render(scale=render_scale).to_numpy()).copy()
attached.append(NativePdfPage(
page_no=page.page_no,
width=page.width,
height=page.height,
rotation=page.rotation,
characters=page.characters,
image=image,
))
return attached
def build_native_pdf_text_table_fallbacks(
content: bytes,
*,
@@ -326,6 +396,7 @@ def build_native_pdf_layout_candidate(
content: bytes,
mineru: MinerUParseCandidate,
native_pages: list[NativePdfPage] | None = None,
diagnostics: LayoutJobDiagnostics | None = None,
) -> LayoutDocument:
"""
组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。
@@ -336,10 +407,16 @@ def build_native_pdf_layout_candidate(
content: 原始 PDF 字节。
mineru: 同一文件的 MinerU pipeline 候选。
native_pages: 可复用的 PDFium 页面;未传入时由本函数提取。
diagnostics: 可选 Job 级诊断上下文;None 时不做计时/计数。
Returns:
通过完整布局契约校验的候选;没有可证 cell 时保留空表和 blocking issue。
"""
resolved_pages = native_pages if native_pages is not None else extract_native_pdf_pages(content)
if diagnostics is not None:
diagnostics.counts['page_count'] = len(resolved_pages)
diagnostics.counts['mineru_table_count'] = sum(
len(page.tables) for page in mineru.pages
)
mineru_pages = {item.page_no: item for item in mineru.pages}
issues: list[LayoutIssue] = [LayoutIssue(
code='document_cell_truth_deferred', severity='blocking',
@@ -353,7 +430,10 @@ def build_native_pdf_layout_candidate(
try:
grid = parse_html_grid(table_candidate.html, table_id=table_candidate.candidate_id)
cells, method_issues = _candidate_cells(
native=native, grid=grid, table_bbox=table_candidate.bbox,
native=native,
grid=grid,
table_bbox=table_candidate.bbox,
diagnostics=diagnostics,
)
except Exception:
issues.append(LayoutIssue(
@@ -361,6 +441,8 @@ def build_native_pdf_layout_candidate(
table_id=table_candidate.candidate_id,
))
continue
if diagnostics is not None and 'native_pdf_cells_from_partial_unique_text' in method_issues:
diagnostics.incr('partial_alignment_table_count')
for code in method_issues:
issues.append(LayoutIssue(
code=code, severity='blocking', page_no=native.page_no,
@@ -369,6 +451,7 @@ def build_native_pdf_layout_candidate(
if not cells:
continue
try:
assembly_started = perf_counter()
layout_table = _layout_table(
native=native,
grid=grid,
@@ -378,6 +461,8 @@ def build_native_pdf_layout_candidate(
cells=cells,
page_tokens=page_tokens,
)
if diagnostics is not None:
diagnostics.add_ms('layout_assembly_ms', assembly_started)
except Exception:
issues.append(LayoutIssue(
code='native_pdf_layout_table_invalid', severity='blocking',
@@ -389,15 +474,19 @@ def build_native_pdf_layout_candidate(
issues.append(LayoutIssue(
code='native_pdf_table_cells_unresolved', severity='blocking', page_no=native.page_no,
))
assembly_started = perf_counter()
pages.append(LayoutPage(
page_no=native.page_no, width=native.width, height=native.height,
rotation=native.rotation,
tokens=[page_tokens[token_id] for token_id in sorted(page_tokens)],
tables=tables,
))
if diagnostics is not None:
diagnostics.add_ms('layout_assembly_ms', assembly_started)
if not any(page.tables for page in pages):
issues.append(LayoutIssue(code='native_pdf_no_resolved_tables', severity='blocking'))
return LayoutDocument(
assembly_started = perf_counter()
layout = LayoutDocument(
document_id=document_id,
content_hash=content_hash,
parser=LayoutParserInfo(
@@ -407,6 +496,10 @@ def build_native_pdf_layout_candidate(
pages=pages,
quality=LayoutQuality(status='needs_review', confidence=0, issues=issues),
)
if diagnostics is not None:
diagnostics.add_ms('layout_assembly_ms', assembly_started)
diagnostics.record_layout_document_stats(layout)
return layout
def _cells_from_text_alignment(
@@ -430,17 +523,29 @@ def _cells_from_text_alignment(
def _candidate_cells(
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox,
*,
native: NativePdfPage,
grid: HtmlGrid,
table_bbox: LayoutBBox,
diagnostics: LayoutJobDiagnostics | None = None,
) -> tuple[dict[str, dict[str, Any]], list[str]]:
"""
优先唯一文本对齐;完整失败时有框表才走 OpenCV;快速路径允许部分唯一匹配落盘。
核心逻辑:禁止在多候选重复文本上猜第 N 个;OpenCV 全表失败时回退已对齐的部分 native cell。
PR-0:在既有分支累加 alignment/OpenCV/OCR 诊断,不改变返回的 cells 与 issues。
Args:
native/grid/table_bbox: 既有表格候选输入。
diagnostics: 可选 Job 级诊断上下文。
"""
alignment_started = perf_counter()
alignment = align_html_cells_from_positioned_text(
grid, characters=native.characters, table_bbox=table_bbox,
page_width=native.width, page_height=native.height,
)
if diagnostics is not None:
diagnostics.add_ms('native_text_alignment_ms', alignment_started)
text_cells = _cells_from_text_alignment(native=native, alignment=alignment)
if alignment.complete and text_cells:
return text_cells, ['native_pdf_cells_from_unique_text_candidate']
@@ -451,20 +556,30 @@ def _candidate_cells(
list(alignment.issues) + ['native_pdf_cells_from_partial_unique_text'],
))
return {}, sorted(set(alignment.issues + ['native_pdf_render_deferred']))
geometry = reconstruct_opencv_table_geometry(
geometry_started = perf_counter()
geometry = cached_reconstruct_opencv_table_geometry(
native.image, page_width=native.width, page_height=native.height,
table_bbox=table_bbox, grid=grid,
diagnostics=diagnostics, page_no=native.page_no,
)
if diagnostics is not None:
diagnostics.add_ms('opencv_geometry_ms', geometry_started)
diagnostics.incr('opencv_attempt_count')
validation_started = perf_counter()
validation = validate_opencv_cell_text(
geometry, grid=grid,
bounded_text_reader=lambda bbox: _text_within(native.characters, bbox),
minimum_match_rate=1.0,
required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()},
)
if diagnostics is not None:
diagnostics.add_ms('opencv_validation_ms', validation_started)
if not validation.accepted:
ocr = build_ocr_table_evidence(
image=native.image, page_width=native.width, page_height=native.height,
table_bbox=table_bbox, grid=grid,
diagnostics=diagnostics,
page_no=native.page_no,
)
if not ocr.ready:
if text_cells:
@@ -2,22 +2,29 @@
backend/app/services/shipping_notice/document_layout/ocr_pdf.py
用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选(阶段 2)。
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约;高亮质量对齐 field_highlight_contract。
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约、layout_diagnostics、Flask 配置;高亮质量对齐 field_highlight_contract。
逻辑:OCR 只提供独立文本坐标与 candidate 级高亮;必须与多参数有框网格及全部非空 cell
文本一致才输出;OCR 结果不得自动升为 verified。
文本一致才输出;OCR 结果不得自动升为 verified。PR-0 可选写入 Job 级脱敏计时/计数;
PR-1 经 get_page_ocr_lines 在同 Job 内复用整页 OCR(含失败结果);
PR-3 表格 cell 路径可裁剪 OCR(安全边距),订单级 page_glyphs 仍走整页。
"""
from __future__ import annotations
from functools import lru_cache
from time import perf_counter
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.contracts import LayoutBBox, normalize_layout_text
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
from app.services.shipping_notice.document_layout.layout_diagnostics import (
OCR_PAGE_CACHE_UNAVAILABLE,
LayoutJobDiagnostics,
)
from app.services.shipping_notice.document_layout.opencv_table import (
reconstruct_opencv_table_geometry,
cached_reconstruct_opencv_table_geometry,
validate_opencv_cell_text,
)
@@ -76,17 +83,33 @@ def _ocr_engine() -> Any:
def extract_ocr_lines(
image: Any, *, page_width: float, page_height: float, minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
image: Any,
*,
page_width: float,
page_height: float,
minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
diagnostics: LayoutJobDiagnostics | None = None,
page_no: int | None = None,
image_origin_x: float = 0.0,
image_origin_y: float = 0.0,
full_image_width: int | None = None,
full_image_height: int | None = None,
) -> list[OcrLine]:
"""
将 RapidOCR 图像像素多边形映射为 PDF 页面坐标。
核心逻辑:像素坐标 → 页面坐标(按渲染宽高比例);低置信度行丢弃;保留 polygon 供审计。
PR-0:可选拆分引擎初始化与推理墙钟,不改变行过滤与坐标映射结果。
PR-3:裁剪 OCR 时通过 origin + full_image_* 把 crop 像素加回整页再映射。
Args:
image: PDFium 渲染的页面 ndarray。
image: PDFium 渲染的页面或表格裁剪 ndarray。
page_width/page_height: PDF 页面单位尺寸。
minimum_confidence: OCR 行最低可信度;低于阈值完全丢弃。
diagnostics: 可选 Job 级诊断上下文;None 时不做计时/计数。
page_no: 可选页号,用于 ocr_page_count 去重。
image_origin_x/image_origin_y: 裁剪图在整页渲染图中的像素原点。
full_image_width/full_image_height: 整页渲染尺寸;裁剪路径必填。
Returns:
保持 OCR 返回顺序的文本行坐标。
@@ -96,7 +119,30 @@ def extract_ocr_lines(
height, width = image.shape[:2]
if width <= 0 or height <= 0 or page_width <= 0 or page_height <= 0:
raise ValueError('OCR page dimensions must be positive')
result, _elapsed = _ocr_engine()(image)
ref_width = int(full_image_width) if full_image_width is not None else int(width)
ref_height = int(full_image_height) if full_image_height is not None else int(height)
if ref_width <= 0 or ref_height <= 0:
raise ValueError('OCR full image dimensions must be positive')
# [STEP 1] 拆分引擎获取与推理,避免把模型加载混进 ocr_inference_ms。
cache_info = getattr(_ocr_engine, 'cache_info', None)
warm_before = False
has_real_cache = False
if callable(cache_info):
try:
currsize = getattr(cache_info(), 'currsize', None)
has_real_cache = isinstance(currsize, int)
warm_before = has_real_cache and currsize > 0
except Exception:
has_real_cache = False
init_started = perf_counter()
engine = _ocr_engine()
if diagnostics is not None and has_real_cache and not warm_before:
diagnostics.add_ms('ocr_engine_init_ms', init_started)
infer_started = perf_counter()
result, _elapsed = engine(image)
if diagnostics is not None:
diagnostics.add_ms('ocr_inference_ms', infer_started)
diagnostics.record_ocr_call(page_no=page_no)
lines: list[OcrLine] = []
for index, item in enumerate(result or []):
if len(item) < 3:
@@ -110,14 +156,14 @@ def extract_ocr_lines(
continue
try:
points = [[float(point[0]), float(point[1])] for point in polygon]
xs = [point[0] for point in points]
ys = [point[1] for point in points]
# 像素 → 页面坐标;不做额外平移猜测
xs = [point[0] + float(image_origin_x) for point in points]
ys = [point[1] + float(image_origin_y) for point in points]
# 像素 → 页面坐标;裁剪路径使用整页尺寸做比例换算
bbox = LayoutBBox(
x0=min(xs) * page_width / width,
y0=min(ys) * page_height / height,
x1=max(xs) * page_width / width,
y1=max(ys) * page_height / height,
x0=min(xs) * page_width / ref_width,
y0=min(ys) * page_height / ref_height,
x1=max(xs) * page_width / ref_width,
y1=max(ys) * page_height / ref_height,
)
if bbox.x1 > page_width or bbox.y1 > page_height:
continue
@@ -126,15 +172,223 @@ def extract_ocr_lines(
bbox=bbox,
confidence=confidence,
line_id=f'ocr-line-{index}',
polygon=points,
image_width=int(width),
image_height=int(height),
polygon=[[x, y] for x, y in zip(xs, ys)],
image_width=ref_width,
image_height=ref_height,
))
except (TypeError, ValueError, IndexError):
continue
return lines
def layout_ocr_page_cache_enabled() -> bool:
"""
读取 PR-1 页面 OCR 缓存开关。
核心逻辑:优先 Flask config;无应用上下文时默认关闭,避免测试/脚本意外复用。
Returns:
True 表示同 Job 内复用整页 OcrLine 结果。
"""
try:
from flask import current_app, has_app_context
if not has_app_context():
return False
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED', False))
except Exception:
return False
def layout_ocr_crop_enabled() -> bool:
"""
读取 PR-3 表格裁剪 OCR 开关。
Returns:
True 时表格 cell 候选优先裁剪识别;订单级 page_glyphs 仍用整页 OCR。
"""
try:
from flask import current_app, has_app_context
if not has_app_context():
return False
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED', False))
except Exception:
return False
def _ocr_crop_margin_ratio() -> float:
"""读取表格裁剪安全边距比例,默认 3%,夹在 [0.02, 0.05]。"""
default = 0.03
try:
from flask import current_app, has_app_context
if not has_app_context():
return default
raw = float(current_app.config.get('SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO', default))
except Exception:
return default
return min(max(raw, 0.02), 0.05)
def _expanded_table_bbox(
table_bbox: LayoutBBox, *, page_width: float, page_height: float, margin_ratio: float,
) -> LayoutBBox:
"""按页面尺寸扩展表格 bbox 安全边距,并裁剪到页面范围。"""
pad_x = page_width * margin_ratio
pad_y = page_height * margin_ratio
return LayoutBBox(
x0=max(0.0, float(table_bbox.x0) - pad_x),
y0=max(0.0, float(table_bbox.y0) - pad_y),
x1=min(page_width, float(table_bbox.x1) + pad_x),
y1=min(page_height, float(table_bbox.y1) + pad_y),
)
def extract_table_crop_ocr_lines(
image: Any,
*,
page_width: float,
page_height: float,
table_bbox: LayoutBBox,
minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
diagnostics: LayoutJobDiagnostics | None = None,
page_no: int | None = None,
use_cache: bool | None = None,
) -> list[OcrLine]:
"""
对表格区域(含安全边距)裁剪后 OCR,坐标映射回整页页面单位。
核心逻辑:仅服务表格 cell 候选;失败结果按表 bbox 缓存。订单级字段仍应走整页 OCR。
Args:
image: 整页渲染图。
page_width/page_height/table_bbox: 页面与表格坐标。
diagnostics/page_no/use_cache: 诊断与缓存控制。
Returns:
映射回整页的 OcrLine 列表。
"""
from app.services.shipping_notice.document_layout.layout_diagnostics import (
OCR_TABLE_CROP_CACHE_UNAVAILABLE,
)
cache_on = layout_ocr_crop_enabled() if use_cache is None else bool(use_cache)
margin = _ocr_crop_margin_ratio()
expanded = _expanded_table_bbox(
table_bbox, page_width=page_width, page_height=page_height, margin_ratio=margin,
)
full_height, full_width = image.shape[:2]
x0 = max(0, int(expanded.x0 * full_width / page_width))
y0 = max(0, int(expanded.y0 * full_height / page_height))
x1 = min(full_width, max(x0 + 1, int(expanded.x1 * full_width / page_width + 0.999)))
y1 = min(full_height, max(y0 + 1, int(expanded.y1 * full_height / page_height + 0.999)))
cache_key = None
if cache_on and diagnostics is not None and page_no is not None:
cache_key = (
int(page_no), round(expanded.x0, 2), round(expanded.y0, 2),
round(expanded.x1, 2), round(expanded.y1, 2), int(full_width), int(full_height),
)
if cache_key in diagnostics.ocr_table_crop_cache:
diagnostics.incr('ocr_page_cache_hit')
cached = diagnostics.ocr_table_crop_cache[cache_key]
if cached is OCR_TABLE_CROP_CACHE_UNAVAILABLE:
raise RuntimeError('ocr_engine_unavailable')
return list(cached)
diagnostics.incr('ocr_page_cache_miss')
crop = image[y0:y1, x0:x1]
if crop.size == 0:
raise ValueError('OCR table crop is empty')
if diagnostics is not None:
diagnostics.incr('ocr_crop_count')
try:
lines = extract_ocr_lines(
crop,
page_width=page_width,
page_height=page_height,
minimum_confidence=minimum_confidence,
diagnostics=diagnostics,
page_no=page_no,
image_origin_x=float(x0),
image_origin_y=float(y0),
full_image_width=int(full_width),
full_image_height=int(full_height),
)
except Exception:
if cache_key is not None and diagnostics is not None:
diagnostics.ocr_table_crop_cache[cache_key] = OCR_TABLE_CROP_CACHE_UNAVAILABLE
raise
if cache_key is not None and diagnostics is not None:
diagnostics.ocr_table_crop_cache[cache_key] = list(lines)
return lines
def get_page_ocr_lines(
image: Any,
*,
page_width: float,
page_height: float,
minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
diagnostics: LayoutJobDiagnostics | None = None,
page_no: int | None = None,
use_cache: bool | None = None,
) -> list[OcrLine]:
"""
获取整页 OCR 行;PR-1 可在同 Job 内按页缓存(含失败结果)。
核心逻辑:缓存键为 (page_no, image_width, image_height);命中则不再调用 RapidOCR;
引擎不可用缓存为哨兵并再次抛出受控异常,供调用方映射 ocr_engine_unavailable。
Args:
image/page_width/page_height/minimum_confidence: 同 extract_ocr_lines。
diagnostics: Job 诊断上下文;提供时才可写入/读取页面缓存。
page_no: 页号;缺失时不做页面缓存(仍可直接推理)。
use_cache: 显式覆盖开关;None 时读取配置。
Returns:
OCR 行列表(可能为空)。
Raises:
Exception: 与 extract_ocr_lines 相同;缓存命中 unavailable 时抛 RuntimeError。
"""
cache_on = layout_ocr_page_cache_enabled() if use_cache is None else bool(use_cache)
cache_key = None
if (
cache_on
and diagnostics is not None
and page_no is not None
and image is not None
):
cache_key = LayoutJobDiagnostics.page_ocr_cache_key(int(page_no), image)
if cache_key in diagnostics.ocr_page_cache:
diagnostics.incr('ocr_page_cache_hit')
cached = diagnostics.ocr_page_cache[cache_key]
if cached is OCR_PAGE_CACHE_UNAVAILABLE:
raise RuntimeError('ocr_engine_unavailable')
return list(cached)
if cache_key is not None and diagnostics is not None:
diagnostics.incr('ocr_page_cache_miss')
try:
lines = extract_ocr_lines(
image,
page_width=page_width,
page_height=page_height,
minimum_confidence=minimum_confidence,
diagnostics=diagnostics,
page_no=page_no,
)
except Exception:
if cache_key is not None and diagnostics is not None:
diagnostics.ocr_page_cache[cache_key] = OCR_PAGE_CACHE_UNAVAILABLE
raise
if cache_key is not None and diagnostics is not None:
# 失败空结果也缓存,避免同页多表重复打引擎。
diagnostics.ocr_page_cache[cache_key] = list(lines)
return lines
def page_bbox_to_normalized(bbox: LayoutBBox, *, page_width: float, page_height: float) -> LayoutBBox:
"""
将页面坐标转为 0..1 归一化 bbox,供 PDF.js viewport 绘制。
@@ -163,17 +417,54 @@ def page_bbox_to_normalized(bbox: LayoutBBox, *, page_width: float, page_height:
def build_ocr_table_evidence(
*, image: Any, page_width: float, page_height: float,
table_bbox: LayoutBBox, grid: HtmlGrid,
*,
image: Any,
page_width: float,
page_height: float,
table_bbox: LayoutBBox,
grid: HtmlGrid,
diagnostics: LayoutJobDiagnostics | None = None,
page_no: int | None = None,
ocr_lines: list[OcrLine] | None = None,
) -> OcrTableEvidence:
"""
对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。
核心逻辑:通过后 cell.status 固定为 candidate;置信度不足/多候选/文本不一致不准入。
PR-0:进入本函数即计 ocr_attempt/ocr_table;OpenCV 子耗时累加到 diagnostics。
PR-1:ocr_lines 已提供时不再推理;否则经 get_page_ocr_lines 走页面缓存。
PR-3:开启裁剪 OCR 且未预传 ocr_lines 时,对表格区域裁剪识别(订单级仍用整页)。
Args:
image/page_width/page_height/table_bbox/grid: 既有扫描表门禁输入。
diagnostics: 可选 Job 级诊断上下文。
page_no: 可选页号,传给页面 OCR 缓存与去重计数。
ocr_lines: 可选预计算整页 OCR 行;提供时跳过推理。
"""
if diagnostics is not None:
diagnostics.incr('ocr_attempt_count')
diagnostics.incr('ocr_table_count')
try:
height, width = image.shape[:2]
lines = extract_ocr_lines(image, page_width=page_width, page_height=page_height)
if ocr_lines is not None:
lines = list(ocr_lines)
elif layout_ocr_crop_enabled():
lines = extract_table_crop_ocr_lines(
image,
page_width=page_width,
page_height=page_height,
table_bbox=table_bbox,
diagnostics=diagnostics,
page_no=page_no,
)
else:
lines = get_page_ocr_lines(
image,
page_width=page_width,
page_height=page_height,
diagnostics=diagnostics,
page_no=page_no,
)
except Exception:
return OcrTableEvidence(ready=False, issues=['ocr_engine_unavailable'])
if not lines:
@@ -183,16 +474,24 @@ def build_ocr_table_evidence(
image_width=int(width) if width else None,
image_height=int(height) if height else None,
)
geometry = reconstruct_opencv_table_geometry(
geometry_started = perf_counter()
geometry = cached_reconstruct_opencv_table_geometry(
image, page_width=page_width, page_height=page_height,
table_bbox=table_bbox, grid=grid,
diagnostics=diagnostics, page_no=page_no,
)
if diagnostics is not None:
diagnostics.add_ms('opencv_geometry_ms', geometry_started)
diagnostics.incr('opencv_attempt_count')
validation_started = perf_counter()
validation = validate_opencv_cell_text(
geometry, grid=grid,
bounded_text_reader=lambda bbox: _text_within(lines, bbox),
minimum_match_rate=1,
required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()},
)
if diagnostics is not None:
diagnostics.add_ms('opencv_validation_ms', validation_started)
if not validation.accepted:
return OcrTableEvidence(
ready=False,
@@ -2,9 +2,11 @@
backend/app/services/shipping_notice/document_layout/opencv_table.py
用途:在 MinerU 整表区域内用 OpenCV 恢复严格有框表网格,生成待评测的 HTML cell 几何候选。
依赖:opencv-python-headless、numpy、document_layout.html_table/contracts。
依赖:opencv-python-headless、numpy、document_layout.html_table/contracts、layout_diagnostics。
逻辑:多组形态学参数独立检测 cell 轮廓;仅当至少两组结果与 HTML 网格完全一致且边界
共识稳定时输出 ready;还必须经独立 PDF 文本验收,不得仅凭几何轮廓接受 cell(阶段 3)。
PR-2:`cached_reconstruct_opencv_table_geometry` 在同 Job 内按页/表/网格签名缓存
(含失败),不减少多配置共识组数、不改变门禁。
"""
from __future__ import annotations
@@ -115,6 +117,13 @@ def reconstruct_opencv_table_geometry(
"""
if cv2 is None:
return _not_ready(grid, 'opencv_unavailable')
# 快速退出:无效网格/空图/非法 bbox,避免无意义的多配置扫描。
if grid.row_count <= 0 or grid.column_count <= 0:
return _not_ready(grid, 'opencv_table_grid_not_detected')
if float(table_bbox.x1) <= float(table_bbox.x0) or float(table_bbox.y1) <= float(table_bbox.y0):
return _not_ready(grid, 'opencv_table_crop_invalid')
if page_image is None or getattr(page_image, 'size', 0) <= 0:
return _not_ready(grid, 'opencv_unavailable')
if min_consensus < 2 or len(configs) < min_consensus:
raise ValueError('OpenCV grid reconstruction requires at least two configurations')
image = _grayscale_page(page_image)
@@ -164,6 +173,64 @@ def reconstruct_opencv_table_geometry(
)
def cached_reconstruct_opencv_table_geometry(
page_image: np.ndarray,
*,
page_width: float,
page_height: float,
table_bbox: LayoutBBox,
grid: HtmlGrid,
diagnostics: Any | None = None,
page_no: int | None = None,
configs: tuple[OpenCVGridConfig, ...] = DEFAULT_GRID_CONFIGS,
min_consensus: int = 2,
boundary_tolerance_pixels: int = 8,
) -> OpenCVTableGeometryResult:
"""
同 Job 内复用相同 page/table/grid 的 OpenCV geometry 结果(含失败)。
核心逻辑:缓存键含页号、圆整 bbox、行列数与 rowspan/colspan 签名;不改变多配置共识门禁。
Args:
同 reconstruct_opencv_table_geometry,另加 diagnostics/page_no。
Returns:
OpenCVTableGeometryResult;命中缓存时直接返回同一对象。
"""
if diagnostics is None:
return reconstruct_opencv_table_geometry(
page_image, page_width=page_width, page_height=page_height,
table_bbox=table_bbox, grid=grid, configs=configs,
min_consensus=min_consensus,
boundary_tolerance_pixels=boundary_tolerance_pixels,
)
height, width = page_image.shape[:2]
span_sig = tuple(
(int(cell.row_index), int(cell.column_index), int(cell.row_span), int(cell.column_span))
for cell in grid.cells
)
cache_key = (
int(page_no or 0),
round(float(table_bbox.x0), 2), round(float(table_bbox.y0), 2),
round(float(table_bbox.x1), 2), round(float(table_bbox.y1), 2),
int(grid.row_count), int(grid.column_count), span_sig,
int(width), int(height), int(min_consensus), int(boundary_tolerance_pixels),
)
cached = diagnostics.opencv_geometry_cache.get(cache_key)
if cached is not None:
diagnostics.incr('opencv_geometry_cache_hit')
return cached
diagnostics.incr('opencv_geometry_cache_miss')
result = reconstruct_opencv_table_geometry(
page_image, page_width=page_width, page_height=page_height,
table_bbox=table_bbox, grid=grid, configs=configs,
min_consensus=min_consensus,
boundary_tolerance_pixels=boundary_tolerance_pixels,
)
diagnostics.opencv_geometry_cache[cache_key] = result
return result
def validate_opencv_cell_text(
geometry: OpenCVTableGeometryResult,
*,
@@ -2,9 +2,10 @@
backend/app/services/shipping_notice/document_layout/runtime.py
用途:在独立布局 Job 中调用 MinerU,并生成可持久化的紧凑文本、表格及原生 PDF 候选快照。
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf。
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf、layout_diagnostics。
逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;阶段 1 在
layout_candidate 写入真实 cell bbox 后回填 capability.cell_bbox_count,禁止长期假报 0。
PR-0 将细分 timings/counts 写入传入诊断字典,永不进入持久化快照。
"""
from __future__ import annotations
@@ -17,6 +18,11 @@ from typing import Any
from flask import current_app
from app.core.errors import AppError
from app.services.shipping_notice.document_layout.layout_diagnostics import (
LayoutJobDiagnostics,
ensure_layout_counts,
ensure_layout_timings,
)
from app.services.shipping_notice.document_layout.mineru import (
MINERU_SUPPORTED_EXTENSIONS,
MinerUClient,
@@ -97,6 +103,7 @@ def build_mineru_table_snapshot(
document_id: int | None = None,
content_hash: str | None = None,
timings: dict[str, int] | None = None,
counts: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
"""
为一个受支持附件生成紧凑 MinerU 文本与表格快照。
@@ -109,9 +116,11 @@ def build_mineru_table_snapshot(
content: 原始文件字节;不写数据库和日志。
document_id/content_hash: PDF 的版本化 Document 身份;两者齐全时生成 layout.v1 候选。
timings: 可选运维耗时字典;只写阶段毫秒数,不进入持久化快照。
counts: 可选运维计数字典;与 timings 平级写入 Job result,不进入快照。
Returns:
关闭/不支持时返回 None;成功或 Provider 降级均返回受控的版本化状态对象。
"""
diagnostics = _diagnostics_from_maps(timings=timings, counts=counts)
extension = Path(str(filename or '')).suffix.lower()
if not mineru_layout_capture_enabled(filename) or not content:
return None
@@ -123,6 +132,7 @@ def build_mineru_table_snapshot(
timings=timings,
)
if xfa_snapshot is not None:
_record_xfa_page_count(xfa_snapshot, diagnostics=diagnostics)
return xfa_snapshot
native_pages: list[Any] | None = None
if extension == '.pdf' and document_id and content_hash:
@@ -131,7 +141,10 @@ def build_mineru_table_snapshot(
native_started = perf_counter()
native_pages = extract_native_pdf_pages(content, render_images=False)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('native_pdf_extract_ms', native_started)
diagnostics.counts['page_count'] = len(native_pages)
elif timings is not None:
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
except Exception:
native_pages = None
@@ -139,7 +152,7 @@ def build_mineru_table_snapshot(
if not base_url:
fallback = _native_pdf_fallback_snapshot(
content=content, document_id=document_id, content_hash=content_hash,
native_pages=native_pages, timings=timings,
native_pages=native_pages, timings=timings, diagnostics=diagnostics,
provider_issue='mineru_base_url_missing',
)
if fallback is not None:
@@ -175,7 +188,7 @@ def build_mineru_table_snapshot(
except AppError as exc:
fallback = _native_pdf_fallback_snapshot(
content=content, document_id=document_id, content_hash=content_hash,
native_pages=native_pages, timings=timings,
native_pages=native_pages, timings=timings, diagnostics=diagnostics,
provider_issue=str(exc.code),
)
if fallback is not None:
@@ -191,7 +204,7 @@ def build_mineru_table_snapshot(
except (TypeError, ValueError):
fallback = _native_pdf_fallback_snapshot(
content=content, document_id=document_id, content_hash=content_hash,
native_pages=native_pages, timings=timings,
native_pages=native_pages, timings=timings, diagnostics=diagnostics,
provider_issue='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
)
if fallback is not None:
@@ -268,16 +281,34 @@ def build_mineru_table_snapshot(
if extension == '.pdf' and document_id and content_hash:
try:
from app.services.shipping_notice.document_layout.native_pdf import (
attach_native_pdf_page_images,
build_native_pdf_layout_candidate,
build_native_pdf_text_table_fallbacks,
extract_native_pdf_pages,
layout_native_page_reuse_enabled,
)
# MinerU 成功后进入坐标增强链;此时按需补齐页面图,供严格 OpenCV/OCR 门禁使用。
# 前置轻量预读只缓存字符,不得因为已有无图页面而跳过必要的增强证据。
# PR-2:开启复用时保留前置字符预读,仅渲染缺图页,禁止二次字符枚举。
native_started = perf_counter()
native_pages = extract_native_pdf_pages(content)
if timings is not None:
reuse = layout_native_page_reuse_enabled() and native_pages is not None
if reuse:
attached = 0
before = list(native_pages)
native_pages = attach_native_pdf_page_images(content, before)
attached = sum(
1 for old, new in zip(before, native_pages)
if old.image is None and new.image is not None
)
if diagnostics is not None:
diagnostics.incr('pdfium_page_image_attach_count', attached)
else:
native_pages = extract_native_pdf_pages(content)
if diagnostics is not None:
# 第二次提取/补图覆盖前置轻量预读耗时(既有语义:增强链提取为准)。
diagnostics.set_ms('native_pdf_extract_ms', native_started)
diagnostics.counts['page_count'] = len(native_pages)
elif timings is not None:
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
layout_source_candidate = candidate
@@ -308,23 +339,33 @@ def build_mineru_table_snapshot(
'native_pdf_text_table_fallback_used',
})
if diagnostics is not None:
diagnostics.counts['mineru_table_count'] = len(tables)
layout_started = perf_counter()
layout = build_native_pdf_layout_candidate(
document_id=int(document_id), content_hash=str(content_hash),
content=content, mineru=layout_source_candidate, native_pages=native_pages,
diagnostics=diagnostics,
)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('native_layout_build_ms', layout_started)
elif timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
serialize_started = perf_counter()
snapshot['layout_candidate'] = layout.model_dump(mode='json')
if diagnostics is not None:
diagnostics.set_ms('layout_serialize_ms', serialize_started)
snapshot['capability'] = _capability_with_layout_cells(
snapshot.get('capability'), layout_payload=snapshot['layout_candidate'],
)
# 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。
evidence_started = perf_counter()
snapshot['coordinate_evidence'] = _table_coordinate_evidence(
pages=native_pages, tables=tables,
pages=native_pages, tables=tables, diagnostics=diagnostics,
)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('coordinate_evidence_ms', evidence_started)
elif timings is not None:
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
except Exception:
snapshot['issues'] = sorted(set(
@@ -337,10 +378,67 @@ def build_mineru_table_snapshot(
return snapshot
def _diagnostics_from_maps(
*,
timings: dict[str, Any] | None,
counts: dict[str, Any] | None,
) -> LayoutJobDiagnostics | None:
"""
将 handler 传入的 timings/counts 字典包装为共享诊断上下文。
核心逻辑:任一侧非 None 即启用诊断,并保证契约键齐全;两边引用同一字典以便就地累加。
Args:
timings/counts: Job handler 持有的可变字典。
Returns:
LayoutJobDiagnostics;两者皆缺失时返回 None。
"""
if timings is None and counts is None:
return None
ensured_timings = ensure_layout_timings(timings if timings is not None else {})
ensured_counts = ensure_layout_counts(counts if counts is not None else {})
if timings is not None and timings is not ensured_timings:
timings.update(ensured_timings)
if counts is not None and counts is not ensured_counts:
counts.update(ensured_counts)
return LayoutJobDiagnostics(
timings=timings if timings is not None else ensured_timings,
counts=counts if counts is not None else ensured_counts,
)
def _record_xfa_page_count(
snapshot: dict[str, Any],
*,
diagnostics: LayoutJobDiagnostics | None,
) -> None:
"""
XFA 早退路径仅回填可安全取得的 page_count,不引入 OCR/OpenCV 逻辑。
Args:
snapshot: XFA layout 快照。
diagnostics: 可选诊断上下文。
"""
if diagnostics is None:
return
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
page_count = capability.get('page_count')
if page_count is None:
pages = snapshot.get('pages')
if isinstance(pages, list):
page_count = len(pages)
try:
diagnostics.counts['page_count'] = int(page_count or 0)
except (TypeError, ValueError):
diagnostics.counts['page_count'] = 0
def _native_pdf_fallback_snapshot(
*, content: bytes, document_id: int | None, content_hash: str | None,
native_pages: list[Any] | None, timings: dict[str, int] | None,
provider_issue: str,
diagnostics: LayoutJobDiagnostics | None = None,
) -> dict[str, Any] | None:
"""
在 MinerU 不可用时,用严格原生文字表格证据生成降级布局快照。
@@ -355,6 +453,7 @@ def _native_pdf_fallback_snapshot(
native_pages: MinerU 调用前已轻量预读的 PDFium 页面;缺失时禁止降级。
timings: 可选运维阶段耗时,不进入快照。
provider_issue: 触发降级的 MinerU 稳定问题码。
diagnostics: 可选 Job 级诊断上下文。
Returns:
证据充分时返回带 Provider 失败原因的 ready 降级快照;否则返回 None。
@@ -369,7 +468,11 @@ def _native_pdf_fallback_snapshot(
fallback_started = perf_counter()
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('native_table_detect_ms', fallback_started)
diagnostics.counts['page_count'] = len(native_pages)
diagnostics.counts['mineru_table_count'] = len(tables)
elif timings is not None:
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
if not tables:
return None
@@ -382,10 +485,16 @@ def _native_pdf_fallback_snapshot(
layout = build_native_pdf_layout_candidate(
document_id=int(document_id), content_hash=str(content_hash),
content=content, mineru=candidate, native_pages=native_pages,
diagnostics=diagnostics,
)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('native_layout_build_ms', layout_started)
elif timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
serialize_started = perf_counter()
layout_payload_preview = layout.model_dump(mode='json')
if diagnostics is not None:
diagnostics.set_ms('layout_serialize_ms', serialize_started)
capability = _capability_with_layout_cells(
candidate.capability.model_dump(mode='json'),
layout_payload=layout_payload_preview,
@@ -395,8 +504,11 @@ def _native_pdf_fallback_snapshot(
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
evidence = _table_coordinate_evidence(
pages=native_pages, tables=tables, include_page_glyphs=False,
diagnostics=diagnostics,
)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('coordinate_evidence_ms', evidence_started)
elif timings is not None:
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
@@ -454,7 +566,11 @@ def _native_pdf_candidate_from_tables(
def _table_coordinate_evidence(
*, pages: list[Any], tables: list[dict[str, Any]], include_page_glyphs: bool = True,
*,
pages: list[Any],
tables: list[dict[str, Any]],
include_page_glyphs: bool = True,
diagnostics: LayoutJobDiagnostics | None = None,
) -> dict[str, Any]:
"""
从已提取页面保存表内及整页字符证据,避免同一 PDF 重复解析和渲染。
@@ -463,6 +579,7 @@ def _table_coordinate_evidence(
pages: 本轮已提取的 NativePdfPage 列表。
tables: MinerU 或原生文字回退生成的表格摘要。
include_page_glyphs: 是否保留表格外整页字符证据;fallback 只保留表内证据。
diagnostics: 可选 Job 级诊断;页级 OCR 计入 ocr_*(嵌套于 coordinate_evidence_ms)。
Returns:
供明细重建与订单字段重放的坐标证据。
"""
@@ -498,9 +615,16 @@ def _table_coordinate_evidence(
# Only scanned pages without a usable native text layer trigger OCR. OCR failure
# intentionally leaves this page without order-field evidence rather than guessing.
try:
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
from app.services.shipping_notice.document_layout.ocr_pdf import get_page_ocr_lines
ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
# PR-1:与 layout 构建共享同一页面 OCR 缓存,禁止同页整页重复推理。
ocr_lines = get_page_ocr_lines(
page.image,
page_width=page.width,
page_height=page.height,
diagnostics=diagnostics,
page_no=int(page_no),
)
ocr_glyphs = _ocr_page_characters(ocr_lines)
except Exception:
ocr_glyphs = []
@@ -865,6 +865,13 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
order_line['__required_qty'] = purpose_line.get('quantity')
order_line['__display_part_number'] = purpose_line.get('part_number')
order_line['__display_reservation_id'] = purpose_line.get('reservation_id')
# BE-6:单位为可选匹配键;优先行字典 uom/unit。
order_line['__display_uom'] = (
purpose_line.get('uom')
or purpose_line.get('unit')
or order_line.get('uom')
or order_line.get('unit')
)
total_notice_lines = len(order_field_lines)
_sync_workflow_stage(
task,
@@ -927,6 +934,17 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
'__required_qty': purpose_line.get('quantity'),
'__display_part_number': purpose_line.get('part_number'),
'__display_reservation_id': purpose_line.get('reservation_id'),
'__display_uom': (
purpose_line.get('uom')
or purpose_line.get('unit')
or (order_field_lines[index] if index < len(order_field_lines) else {}).get('__display_uom')
or (order_field_lines[index] if index < len(order_field_lines) else {}).get('uom')
),
'uom': (
purpose_line.get('uom')
or purpose_line.get('unit')
or (order_field_lines[index] if index < len(order_field_lines) else {}).get('__display_uom')
),
'line_key': (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key'),
})
match_payload = match_order_lines_across_candidates(
@@ -935,6 +953,18 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
header_reservation_id=header_reservation,
)
apply_line_inventory_resolutions(task, match_payload)
# [STEP] Slice 1:持久化 OT 行匹配事实(ready+not_found=0;缺键→invalid_key)
from app.services.shipping_notice.line_inventory_match_persistence import (
persist_line_inventory_match_facts,
)
persist_line_inventory_match_facts(
task=task,
match_payload=match_payload,
inventory_snapshot_id=(
int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None
),
matching_rule_version='stp_line_v2',
)
match_status = str(match_payload.get('match_status') or 'unfulfillable')
line_results = list(match_payload.get('line_results') or [])
from app.services.shipping_notice.reservation_service import record_inventory_verification
@@ -973,6 +1003,15 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
actor_id=actor_id,
source='workspace_api' if actor_id else 'system',
)
# [STEP] Slice 3:匹配 ready 后入队自动履约协调(flag 关则 no-op)
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
enqueue_post_ot_auto_fulfill_job,
)
enqueue_post_ot_auto_fulfill_job(
task_no=str(task.task_no),
trigger='inventory_ready',
commit=False,
)
db.session.commit()
match_result = tool_response(
status="ok",
@@ -989,6 +1028,15 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
actor_id=actor_id,
source='workspace_api' if actor_id else 'system',
)
# 部分短缺时仍可能有 eligible 行;协调器按事实筛选。
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
enqueue_post_ot_auto_fulfill_job,
)
enqueue_post_ot_auto_fulfill_job(
task_no=str(task.task_no),
trigger='inventory_ready',
commit=False,
)
db.session.commit()
return tool_response(
status="needs_human",
@@ -0,0 +1,212 @@
"""
services/shipping_notice/line_auto_fulfill_coordinator.py
用途:OT 后行级自动履约幂等协调器——统一 matching ready / OT 回调 / 补偿入口。
依赖:line_auto_fulfill_enabled、post_ot_fulfillment_wave_service、post_ot_wave_progress_service、
ShippingNoticeLineInventoryMatch / LineDecision snapshot。
逻辑:flag 关闭时 skipped;开启时整波创建+专用推进;失败整波回滚后独立写 auto_fulfill_failed 列;
不创建 wait_inventory 半成品决定;trigger=ot_created|compensation 由确认/STP/补偿排程接线。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import (
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision,
)
from app.services.shipping_notice.line_inventory_match_persistence import resolve_review_case_for_task
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
create_post_ot_fulfillment_wave,
list_eligible_post_ot_line_keys,
)
from app.services.shipping_notice.post_ot_wave_progress_service import schedule_post_ot_wave_progress
def _mark_auto_fulfill_failed(
case: ShippingOrderReviewCase,
*,
line_keys: list[str],
error_code: str,
message: str,
) -> None:
"""
独立事务内写入失败事实:匹配事实表列优先;活动决定仅补 snapshot,不新建 wait_inventory。
核心逻辑:写 ShippingNoticeLineInventoryMatch.auto_fulfill_failed* 列;可选同步 snapshot。
"""
now = datetime.utcnow()
formal_task_id = getattr(case, 'confirmed_task_id', None)
for key in line_keys:
key_s = str(key)
if formal_task_id is not None:
fact = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(formal_task_id), line_key=key_s, is_current=True)
.first()
)
if fact is not None:
fact.auto_fulfill_failed = True
fact.auto_fulfill_error_code = str(error_code)[:128]
fact.auto_fulfill_error_message = str(message)[:1000]
fact.auto_fulfill_failed_at = now
detail = dict(fact.detail_json or {})
detail['auto_fulfill_failed'] = True
detail['auto_fulfill_error_code'] = str(error_code)[:128]
detail['auto_fulfill_error_message'] = str(message)[:1000]
detail['auto_fulfill_failed_at'] = now.isoformat() + 'Z'
fact.detail_json = detail
fact.updated_at = now
row = (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), line_key=key_s, is_active=True)
.first()
)
if row is None:
continue
payload = dict(row.snapshot_json or {})
payload['auto_fulfill_failed'] = True
payload['auto_fulfill_error_code'] = str(error_code)[:128]
payload['auto_fulfill_error_message'] = str(message)[:1000]
payload['auto_fulfill_failed_at'] = now.isoformat() + 'Z'
row.snapshot_json = payload
row.updated_at = now
def coordinate_post_ot_auto_fulfill(
*,
task: ShippingNotice | None = None,
case: ShippingOrderReviewCase | None = None,
trigger: str = 'inventory_ready',
) -> dict[str, Any]:
"""
幂等协调:收集 eligible 行并批量创建 post-OT wave,再调度本 wave 推进。
Args:
task: 正式 OT;与 case 至少提供一个。
case: 复核 Case。
trigger: inventory_ready | ot_created | compensation。
Returns:
status / accepted / skipped / reason。
"""
case_no_hint = None
if case is None and task is not None:
case = resolve_review_case_for_task(task)
if case is not None:
case_no_hint = str(case.case_no)
if case is None:
return {'status': 'skipped', 'reason': 'review_case_not_found', 'trigger': trigger}
if not line_auto_fulfill_enabled():
return {
'status': 'skipped',
'reason': 'line_auto_fulfill_disabled',
'trigger': trigger,
'case_no': case.case_no,
}
eligible = list_eligible_post_ot_line_keys(case)
if not eligible:
return {
'status': 'idle',
'reason': 'no_eligible_lines',
'trigger': trigger,
'case_no': case.case_no,
'accepted_line_keys': [],
}
idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}'
try:
# [STEP 1] 整波创建(失败则整波回滚)
result = create_post_ot_fulfillment_wave(
case_no=str(case.case_no),
line_keys=eligible,
decision_source='system',
actor_user_id=None,
reason=f'auto_fulfill:{trigger}',
idempotency_key=idem_key,
)
# [STEP 2] 仅调度本 wave 推进(禁止 confirm 专用推进)
progress = schedule_post_ot_wave_progress(
task_no=str(result.get('task_no') or ''),
wave_no=result.get('wave_no'),
line_keys=list(result.get('accepted_line_keys') or eligible),
review_case_id=int(result.get('review_case_id') or case.id),
idempotency_row_id=result.get('idempotency_row_id'),
request_idempotency_key=str(result.get('idempotency_key') or idem_key),
commit=False,
)
db.session.flush()
return {
'status': 'ok',
'trigger': trigger,
'case_no': case.case_no,
'wave_progress': progress,
**{k: result.get(k) for k in (
'task_no', 'wave_no', 'accepted_line_keys', 'skipped_line_keys',
'idempotency_row_id', 'idempotent_replay',
)},
}
except Exception as exc: # noqa: BLE001
# [STEP 3] 整波回滚,再独立写失败事实
db.session.rollback()
refreshed = (
ShippingOrderReviewCase.query
.filter_by(case_no=str(case_no_hint or ''))
.first()
)
if refreshed is not None:
_mark_auto_fulfill_failed(
refreshed,
line_keys=eligible,
error_code=getattr(exc, 'code', None) or 'SHIPPING.AUTO_FULFILL_FAILED',
message=str(exc)[:1000],
)
db.session.flush()
return {
'status': 'failed',
'trigger': trigger,
'case_no': case_no_hint,
'error': str(exc)[:500],
'eligible_line_keys': eligible,
}
def enqueue_post_ot_auto_fulfill_job(
*,
task_no: str,
trigger: str = 'inventory_ready',
commit: bool = False,
) -> int | None:
"""
入队自动履约协调 Job;flag 关闭时不入队。
Returns:
job_id 或 None。
"""
if not line_auto_fulfill_enabled():
return None
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
normalized = str(task_no or '').strip().upper()
if not normalized:
return None
return enqueue(
JobType.SHIPPING_LINE_AUTO_FULFILL,
{'task_no': normalized, 'trigger': str(trigger or 'inventory_ready')},
domain=SHIPPING_NOTICE_JOB_DOMAIN,
business_ref=normalized,
message='OT 后行级自动履约协调',
max_attempts=3,
commit=commit,
)
@@ -0,0 +1,258 @@
"""
services/shipping_notice/line_inventory_match_persistence.py
用途:inventory_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
逻辑:由 fulfillment_workflow.match_inventory 调用;按 draft line_key(行序)落库;
新快照新增行并切换 is_current;不覆盖历史快照事实。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import (
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingOrderReviewCase,
)
def _draft_line_keys_by_index(case: ShippingOrderReviewCase | None) -> dict[int, str]:
"""Case 草稿行序 → line_key。"""
if case is None or case.current_draft is None:
return {}
out: dict[int, str] = {}
for idx, line in enumerate(list(case.current_draft.lines_json or [])):
if not isinstance(line, dict):
continue
key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}'
out[idx] = key
return out
def resolve_review_case_for_task(task: ShippingNotice) -> ShippingOrderReviewCase | None:
"""
反查确认到该 OT 的 Review Case。
Args:
task: 正式 ShippingNotice。
Returns:
Case 或 None。
"""
return (
ShippingOrderReviewCase.query
.filter_by(confirmed_task_id=int(task.id))
.order_by(ShippingOrderReviewCase.id.desc())
.first()
)
def map_disposition_to_match_codes(
*,
disposition: str,
part_number: Any,
reservation_id: Any,
) -> tuple[str, str]:
"""
将 STP disposition 映射为 match_result + inventory_status。
核心逻辑:缺料号/预约单 → invalid_key;multi_file_conflict → source_conflict;
not_found(键完整)→ ready+not_found;ok/shortage → ready+matched。
"""
disp = str(disposition or '').strip()
part = str(part_number or '').strip()
res = str(reservation_id or '').strip()
if disp == 'multi_file_conflict':
return 'source_conflict', 'source_conflict'
if not part or not res:
return 'invalid_key', 'invalid_key'
if disp == 'not_found':
return 'not_found', 'ready'
if disp in {'ok', 'shortage'}:
return 'matched', 'ready'
return 'result_missing', 'unavailable'
def persist_line_inventory_match_facts(
*,
task: ShippingNotice,
match_payload: dict[str, Any],
inventory_snapshot_id: int | None = None,
matching_rule_version: str | None = 'stp_line_v2',
) -> list[ShippingNoticeLineInventoryMatch]:
"""
将 match_order_lines_across_candidates 结果持久化为当前事实。
核心逻辑:按 line_index 解析 draft line_key;同快照幂等更新;否则新增并切换 is_current;
无 inventory_snapshot_id 时禁止写入 ready/not_found;单位写入事实列。
"""
case = resolve_review_case_for_task(task)
keys_by_index = _draft_line_keys_by_index(case)
snap_id = inventory_snapshot_id
if snap_id is None and getattr(task, 'inventory_snapshot_id', None) is not None:
snap_id = int(task.inventory_snapshot_id)
line_results = [
item for item in list(match_payload.get('line_results') or []) if isinstance(item, dict)
]
resolutions = [
item for item in list(match_payload.get('resolutions') or []) if isinstance(item, dict)
]
res_by_index = {
int(item.get('line_index')): item
for item in resolutions
if item.get('line_index') is not None
}
written: list[ShippingNoticeLineInventoryMatch] = []
now = datetime.utcnow()
for result in line_results:
try:
index = int(result.get('line_index'))
except (TypeError, ValueError):
continue
res = res_by_index.get(index) or {}
line_key = str(
res.get('line_key')
or keys_by_index.get(index)
or f'line-{index + 1}'
).strip()
if not line_key:
continue
match_result, inventory_status = map_disposition_to_match_codes(
disposition=str(result.get('disposition') or res.get('disposition') or ''),
part_number=result.get('part_number') or res.get('part_number'),
reservation_id=result.get('reservation_id') or res.get('effective_reservation_id'),
)
required = result.get('required_qty')
available = result.get('available_qty')
shortage = result.get('shortage_qty')
# [STEP] BE-5:无库存快照时禁止 ready/not_found(不得规范为 0)
if snap_id is None and (
inventory_status == 'ready'
or match_result in {'matched', 'not_found'}
):
match_result, inventory_status = 'result_missing', 'unavailable'
available = None
shortage = None
# [STEP] ready+not_found:强制 available=0(与投影契约一致)
if match_result == 'not_found' and inventory_status == 'ready':
available = 0
if required is not None:
shortage = required
unit_raw = (
result.get('unit')
or result.get('uom')
or res.get('unit')
or res.get('uom')
)
unit_value = str(unit_raw or '').strip()[:32] or None
# [STEP] 同 OT+行+快照:更新;否则新建并撤销旧 current
existing = None
if snap_id is not None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(
task_id=int(task.id),
line_key=line_key,
inventory_snapshot_id=int(snap_id),
)
.first()
)
if existing is None and snap_id is None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id.is_(None))
.first()
)
if existing is None:
(
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
row = ShippingNoticeLineInventoryMatch(
task_id=int(task.id),
review_case_id=int(case.id) if case is not None else None,
line_key=line_key,
line_index=index,
inventory_snapshot_id=int(snap_id) if snap_id is not None else None,
match_result=match_result,
inventory_status=inventory_status,
required_qty=str(required) if required is not None else None,
available_qty=str(available) if available is not None else None,
shortage_qty=str(shortage) if shortage is not None else None,
reservation_id=str(result.get('reservation_id') or '')[:128] or None,
part_number=str(result.get('part_number') or '')[:128] or None,
unit=unit_value,
matching_rule_version=str(matching_rule_version or '')[:64] or None,
inventory_source_code=(
str(result.get('resolved_inventory_source_code') or '')[:64] or None
),
is_current=True,
matched_at=now,
detail_json={
'disposition': result.get('disposition'),
'line_status': result.get('line_status'),
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': result.get('inventory_file_no'),
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
},
created_at=now,
updated_at=now,
)
db.session.add(row)
written.append(row)
else:
existing.match_result = match_result
existing.inventory_status = inventory_status
existing.required_qty = str(required) if required is not None else None
existing.available_qty = str(available) if available is not None else None
existing.shortage_qty = str(shortage) if shortage is not None else None
existing.reservation_id = str(result.get('reservation_id') or '')[:128] or None
existing.part_number = str(result.get('part_number') or '')[:128] or None
existing.unit = unit_value
existing.matching_rule_version = str(matching_rule_version or '')[:64] or None
existing.inventory_source_code = (
str(result.get('resolved_inventory_source_code') or '')[:64] or None
)
existing.is_current = True
existing.matched_at = now
existing.updated_at = now
existing.detail_json = {
'disposition': result.get('disposition'),
'line_status': result.get('line_status'),
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': result.get('inventory_file_no'),
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
}
# 确保同 task+line 仅本条 current
(
ShippingNoticeLineInventoryMatch.query
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.line_key == line_key,
ShippingNoticeLineInventoryMatch.id != int(existing.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
written.append(existing)
db.session.flush()
return written
@@ -0,0 +1,562 @@
"""
services/shipping_notice/line_inventory_match_projection.py
用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。
依赖:ShippingNoticeLineInventoryMatch、Config 自动履约开关。
逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用;
ready+not_found→available=0;result_missing 不得转 0;
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮)。
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
from app.models import ShippingNoticeLineInventoryMatch
MATCH_NOT_FOUND = 'not_found'
MATCH_MATCHED = 'matched'
MATCH_RESULT_MISSING = 'result_missing'
MATCH_PREPARING = 'preparing'
MATCH_SOURCE_CONFLICT = 'source_conflict'
MATCH_INVALID_KEY = 'invalid_key'
MATCH_MAPPING_FAILED = 'mapping_failed'
MATCH_UNAVAILABLE = 'unavailable'
STATUS_READY = 'ready'
STATUS_PREPARING = 'preparing'
STATUS_MAPPING_FAILED = 'mapping_failed'
STATUS_SOURCE_CONFLICT = 'source_conflict'
STATUS_UNAVAILABLE = 'unavailable'
STATUS_INVALID_KEY = 'invalid_key'
ACTION_RETRY_PREPARATION = 'retry_inventory_preparation'
ACTION_RETRY_MATCHING = 'retry_inventory_matching'
ACTION_CLOSE = 'close_unfulfillable'
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail'
SOURCE_STATUS_RESOLVED = 'resolved'
SOURCE_STATUS_RESOLVING = 'resolving'
SOURCE_STATUS_UNRECOGNIZED = 'unrecognized'
SOURCE_STATUS_CONFLICT = 'conflict'
SOURCE_STATUS_UNAVAILABLE = 'unavailable'
def line_auto_fulfill_enabled() -> bool:
"""读取行级自动履约总闸;默认关闭。"""
try:
from flask import current_app
return bool(current_app.config.get('SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED', False))
except Exception:
from app.core.config.settings import Config
return bool(getattr(Config, 'SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED', False))
def _parse_qty(value: Any) -> Decimal | None:
"""解析数量;空/非法返回 None。"""
text = str(value if value is not None else '').strip()
if not text:
return None
try:
return Decimal(text)
except (InvalidOperation, ValueError):
return None
def normalize_match_quantities(
*,
match_result: str | None,
inventory_status: str | None,
required_qty: Any,
available_qty: Any,
) -> dict[str, Any]:
"""
按冻结语义规范 available/shortage。
核心逻辑:仅 ready+not_found 将 available 规范为 0;result_missing 保持 null 且不标短缺。
"""
req = _parse_qty(required_qty)
status = str(inventory_status or '').strip() or None
result = str(match_result or '').strip() or None
if status != STATUS_READY:
return {
'available_qty': None,
'shortage_qty': None,
'is_shortage': False,
'display_available': 'pending',
}
if result == MATCH_NOT_FOUND:
return {
'available_qty': '0',
'shortage_qty': str(req) if req is not None else None,
'is_shortage': req is not None and req > 0,
'display_available': 'number',
}
if result in {
MATCH_RESULT_MISSING,
MATCH_PREPARING,
MATCH_SOURCE_CONFLICT,
MATCH_INVALID_KEY,
MATCH_MAPPING_FAILED,
MATCH_UNAVAILABLE,
None,
'',
}:
return {
'available_qty': None,
'shortage_qty': None,
'is_shortage': False,
'display_available': 'pending',
}
avail = _parse_qty(available_qty)
if avail is None:
return {
'available_qty': None,
'shortage_qty': None,
'is_shortage': False,
'display_available': 'pending',
}
shortage = None
is_shortage = False
if req is not None:
diff = req - avail
if diff > 0:
shortage = str(diff)
is_shortage = True
else:
shortage = '0'
return {
'available_qty': str(avail),
'shortage_qty': shortage,
'is_shortage': is_shortage,
'display_available': 'number',
}
def project_inventory_source(
*,
inventory_status: str | None,
match_result: str | None,
source_code: str | None,
source_labels: dict[str, str] | None = None,
) -> dict[str, Any]:
"""
投影只读库存源对象;前端不得自行推断。
Returns:
code / label / status / source。
"""
code = str(source_code or '').strip() or None
labels = source_labels or {}
label = str(labels.get(code) or '').strip() if code else ''
status = str(inventory_status or '').strip()
result = str(match_result or '').strip()
if status == STATUS_SOURCE_CONFLICT or result == MATCH_SOURCE_CONFLICT:
source_status = SOURCE_STATUS_CONFLICT
elif status == STATUS_INVALID_KEY or result == MATCH_INVALID_KEY:
source_status = SOURCE_STATUS_UNRECOGNIZED
elif status == STATUS_UNAVAILABLE or result == MATCH_UNAVAILABLE:
source_status = SOURCE_STATUS_UNAVAILABLE
elif status == STATUS_PREPARING or result == MATCH_PREPARING or not code:
source_status = SOURCE_STATUS_RESOLVING if not code else (
SOURCE_STATUS_RESOLVED if code else SOURCE_STATUS_RESOLVING
)
if not code and status in {STATUS_PREPARING, ''} and result in {MATCH_PREPARING, ''}:
source_status = SOURCE_STATUS_RESOLVING
elif not code:
source_status = SOURCE_STATUS_UNRECOGNIZED
else:
source_status = SOURCE_STATUS_RESOLVED if code else SOURCE_STATUS_UNRECOGNIZED
if code and source_status == SOURCE_STATUS_RESOLVING and status == STATUS_READY:
source_status = SOURCE_STATUS_RESOLVED
return {
'code': code,
'label': label or None,
'status': source_status,
'source': 'inventory_source_clue',
}
def project_user_line_status(
*,
inventory_status: str | None,
match_result: str | None,
is_shortage: bool,
stored_line_status: str | None,
decision_source: str | None = None,
auto_fulfill_failed: bool = False,
inventory_rpa_running: bool = False,
file_expired: bool = False,
) -> str:
"""
将存储态 + 库存事实投影为用户态状态码(文案由前端 i18n 映射)。
Returns:
acquiring_inventory / inventory_file_missing / inventory_file_expired /
inventory_match_failed / inventory_source_unrecognized / source_conflict /
shortage / inventory_matched / auto_fulfilling / wave_created / fulfilled /
closed / auto_fulfill_failed 等。
"""
if auto_fulfill_failed:
return 'auto_fulfill_failed'
stored = str(stored_line_status or '').strip()
if stored in {'closed_unfulfillable'}:
return 'closed'
if stored in {'fulfilled'}:
return 'fulfilled'
if stored in {'task_created'}:
return 'wave_created'
if stored in {'ready_to_fulfill'} and decision_source == 'system':
return 'auto_fulfilling'
status = str(inventory_status or '').strip()
result = str(match_result or '').strip()
# [STEP] RPA 运行中才标「获取库存中」;否则 preparing 按文件未准备(可重试)。
if inventory_rpa_running:
return 'acquiring_inventory'
if file_expired:
return 'inventory_file_expired'
if status == STATUS_SOURCE_CONFLICT or result == MATCH_SOURCE_CONFLICT:
return 'source_conflict'
if status == STATUS_INVALID_KEY or result == MATCH_INVALID_KEY:
return 'inventory_source_unrecognized'
if status == STATUS_MAPPING_FAILED or result == MATCH_MAPPING_FAILED:
return 'inventory_match_failed'
if status in {STATUS_UNAVAILABLE, STATUS_PREPARING} or result in {
MATCH_UNAVAILABLE, MATCH_RESULT_MISSING, MATCH_PREPARING,
}:
return 'inventory_file_missing'
if is_shortage or result == MATCH_NOT_FOUND:
return 'shortage'
if status == STATUS_READY and result == MATCH_MATCHED:
return 'inventory_matched'
if stored in {'ready_to_fulfill'}:
return 'auto_fulfilling' if decision_source == 'system' else 'inventory_matched'
if stored in {'waiting_inventory'}:
return 'shortage'
return stored or 'acquiring_inventory'
def resolve_inventory_allowed_actions(
*,
has_formal_ot: bool,
inventory_status: str | None,
match_result: str | None,
is_shortage: bool,
stored_line_status: str | None,
user_line_status: str | None,
inventory_rpa_running: bool = False,
has_usable_snapshot: bool = False,
) -> list[str]:
"""
仅下发库存获取/匹配动作;禁止 wait/change_source/view_inventory。
矩阵:RPA 运行中→空;成功/终态→空;文件问题→preparation;
文件有效匹配失败→preparation+matching;短缺→preparation。
"""
stored = str(stored_line_status or '').strip()
user_status = str(user_line_status or '').strip()
if not has_formal_ot:
return []
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
'wave_created', 'fulfilled', 'closed',
}:
return []
if inventory_rpa_running or user_status == 'acquiring_inventory':
return []
status = str(inventory_status or '').strip()
result = str(match_result or '').strip()
if user_status == 'inventory_matched' and not is_shortage:
return []
if status == STATUS_READY and result == MATCH_MATCHED and not is_shortage:
return []
if is_shortage or result == MATCH_NOT_FOUND or user_status == 'shortage':
return [ACTION_RETRY_PREPARATION]
if (
status == STATUS_MAPPING_FAILED
or result == MATCH_MAPPING_FAILED
or user_status == 'inventory_match_failed'
):
actions = [ACTION_RETRY_PREPARATION]
if has_usable_snapshot:
actions.append(ACTION_RETRY_MATCHING)
return actions
if user_status in {
'inventory_file_missing',
'inventory_file_expired',
'inventory_source_unrecognized',
} or status in {STATUS_UNAVAILABLE, STATUS_PREPARING, STATUS_INVALID_KEY} or result in {
MATCH_UNAVAILABLE,
MATCH_PREPARING,
MATCH_RESULT_MISSING,
MATCH_INVALID_KEY,
}:
return [ACTION_RETRY_PREPARATION]
if status == STATUS_SOURCE_CONFLICT or result == MATCH_SOURCE_CONFLICT:
# 客户指定源冲突:只展示状态,不开放换源;可重试获取以刷新。
return [ACTION_RETRY_PREPARATION]
if user_status == 'auto_fulfill_failed':
return [ACTION_RETRY_PREPARATION, ACTION_RETRY_MATCHING]
return []
def resolve_line_allowed_actions(
*,
has_formal_ot: bool,
stored_line_status: str | None,
user_line_status: str | None,
) -> list[str]:
"""
行生命周期动作;本轮仅 close_unfulfillable(已完成/已关闭不展示)。
"""
if not has_formal_ot:
return []
stored = str(stored_line_status or '').strip()
user_status = str(user_line_status or '').strip()
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
'wave_created', 'fulfilled', 'closed',
}:
if user_status in {'wave_created', 'fulfilled'}:
return [ACTION_VIEW_FULFILLMENT] if user_status != 'closed' else []
return []
return [ACTION_CLOSE]
def resolve_allowed_actions(
*,
has_formal_ot: bool,
inventory_status: str | None,
match_result: str | None,
is_shortage: bool,
stored_line_status: str | None,
user_line_status: str | None,
can_manual_fulfill: bool,
inventory_rpa_running: bool = False,
has_usable_snapshot: bool = False,
) -> list[str]:
"""
兼容旧单一 allowed_actions:合并 inventory + line 域(测试/旧调用方)。
新前端应读 inventory_allowed_actions / line_allowed_actions。
"""
inv = resolve_inventory_allowed_actions(
has_formal_ot=has_formal_ot,
inventory_status=inventory_status,
match_result=match_result,
is_shortage=is_shortage,
stored_line_status=stored_line_status,
user_line_status=user_line_status,
inventory_rpa_running=inventory_rpa_running,
has_usable_snapshot=has_usable_snapshot,
)
line = resolve_line_allowed_actions(
has_formal_ot=has_formal_ot,
stored_line_status=stored_line_status,
user_line_status=user_line_status,
)
# can_manual_fulfill 保留参数兼容,本轮不开放 fulfill 按钮。
_ = can_manual_fulfill
return [*inv, *line]
def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str, Any]]:
"""加载 OT 当前行匹配事实,键为 line_key。"""
if task_id is None:
return {}
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.all()
)
out: dict[str, dict[str, Any]] = {}
for row in rows:
key = str(row.line_key or '').strip()
if not key:
continue
out[key] = serialize_match_fact(row)
return out
def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]:
"""将 ORM 行序列化为投影输入。"""
return {
'id': int(row.id),
'task_id': int(row.task_id),
'review_case_id': int(row.review_case_id) if row.review_case_id is not None else None,
'line_key': str(row.line_key),
'line_index': row.line_index,
'inventory_snapshot_id': (
int(row.inventory_snapshot_id) if row.inventory_snapshot_id is not None else None
),
'match_result': str(row.match_result or ''),
'inventory_status': str(row.inventory_status or ''),
'required_qty': row.required_qty,
'available_qty': row.available_qty,
'shortage_qty': row.shortage_qty,
'reservation_id': row.reservation_id,
'part_number': row.part_number,
'unit': row.unit,
'matching_rule_version': row.matching_rule_version,
'inventory_source_code': row.inventory_source_code,
'matched_at': row.matched_at.isoformat() if row.matched_at else None,
'is_current': bool(row.is_current),
'detail_json': dict(row.detail_json or {}),
'auto_fulfill_failed': bool(getattr(row, 'auto_fulfill_failed', False)),
'auto_fulfill_error_code': getattr(row, 'auto_fulfill_error_code', None),
'auto_fulfill_error_message': getattr(row, 'auto_fulfill_error_message', None),
'auto_fulfill_failed_at': (
row.auto_fulfill_failed_at.isoformat()
if getattr(row, 'auto_fulfill_failed_at', None)
else None
),
}
def project_line_inventory_view(
*,
has_formal_ot: bool,
fact: dict[str, Any] | None,
required_qty: Any,
stored_line_status: str | None,
decision_source: str | None,
can_fulfill_complete_line: bool,
auto_fulfill_failed: bool = False,
auto_fulfill_error_message: str | None = None,
inventory_rpa_running: bool = False,
source_labels: dict[str, str] | None = None,
) -> dict[str, Any]:
"""
单行库存+履约用户投影。
Returns:
inventory_* / inventory_source / inventory_allowed_actions /
line_allowed_actions / user_line_status 等。
"""
if not has_formal_ot:
user_status = project_user_line_status(
inventory_status=None,
match_result=None,
is_shortage=False,
stored_line_status=stored_line_status,
decision_source=decision_source,
auto_fulfill_failed=False,
)
return {
'inventory_status': None,
'match_result': None,
'available_qty': None,
'shortage_qty': None,
'is_shortage': False,
'display_available': 'pending',
'inventory_snapshot_id': None,
'inventory_checked_at': None,
'inventory_source': {
'code': None,
'label': None,
'status': SOURCE_STATUS_RESOLVING,
'source': 'inventory_source_clue',
},
'user_line_status': user_status,
'decision_source': decision_source,
'inventory_allowed_actions': [],
'line_allowed_actions': [],
'allowed_actions': [],
'auto_fulfill_error_message': None,
}
if not isinstance(fact, dict):
fact = {
'match_result': MATCH_PREPARING,
'inventory_status': STATUS_PREPARING,
'available_qty': None,
'inventory_snapshot_id': None,
'matched_at': None,
'inventory_source_code': None,
'detail_json': {},
}
match_result = str(fact.get('match_result') or MATCH_RESULT_MISSING)
inventory_status = str(fact.get('inventory_status') or STATUS_PREPARING)
detail = dict(fact.get('detail_json') or {}) if isinstance(fact.get('detail_json'), dict) else {}
file_expired = bool(detail.get('file_expired') or detail.get('snapshot_expired'))
has_usable_snapshot = fact.get('inventory_snapshot_id') is not None and not file_expired
qty = normalize_match_quantities(
match_result=match_result,
inventory_status=inventory_status,
required_qty=required_qty if required_qty is not None else fact.get('required_qty'),
available_qty=fact.get('available_qty'),
)
user_status = project_user_line_status(
inventory_status=inventory_status,
match_result=match_result,
is_shortage=bool(qty['is_shortage']),
stored_line_status=stored_line_status,
decision_source=decision_source,
auto_fulfill_failed=bool(auto_fulfill_failed),
inventory_rpa_running=bool(inventory_rpa_running),
file_expired=file_expired,
)
can_manual = bool(can_fulfill_complete_line) and inventory_status == STATUS_READY and not qty['is_shortage']
inv_actions = resolve_inventory_allowed_actions(
has_formal_ot=True,
inventory_status=inventory_status,
match_result=match_result,
is_shortage=bool(qty['is_shortage']),
stored_line_status=stored_line_status,
user_line_status=user_status,
inventory_rpa_running=bool(inventory_rpa_running),
has_usable_snapshot=has_usable_snapshot,
)
line_actions = resolve_line_allowed_actions(
has_formal_ot=True,
stored_line_status=stored_line_status,
user_line_status=user_status,
)
source = project_inventory_source(
inventory_status=inventory_status,
match_result=match_result,
source_code=fact.get('inventory_source_code'),
source_labels=source_labels,
)
return {
'inventory_status': inventory_status,
'match_result': match_result,
'available_qty': qty['available_qty'],
'shortage_qty': qty['shortage_qty'],
'is_shortage': bool(qty['is_shortage']),
'display_available': qty['display_available'],
'inventory_snapshot_id': fact.get('inventory_snapshot_id'),
'inventory_checked_at': fact.get('matched_at'),
'inventory_source_code': fact.get('inventory_source_code'),
'inventory_source': source,
'matching_rule_version': fact.get('matching_rule_version'),
'user_line_status': user_status,
'decision_source': decision_source,
'inventory_allowed_actions': inv_actions,
'line_allowed_actions': line_actions,
'allowed_actions': [*inv_actions, *line_actions],
'auto_fulfill_error_message': (
str(auto_fulfill_error_message)[:1000] if auto_fulfill_error_message else None
),
'_can_manual_fulfill': can_manual,
}
@@ -1529,7 +1529,9 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
"""
判断确认建单后的任务是否仍需自动推进。
核心逻辑:仍为 created 且已挂正式 Extraction,视为尚未被 auto_progress 消费的悬挂态。
核心逻辑:已挂正式 Extraction,且仍停在确认后早期态(created / parsed)。
确认路径会先 CONFIRM_PARSE→parsed,故不得仅认 created,否则永远不会入队。
重复调度依赖 enqueue 幂等(同 business_ref 有效 Job 不重复入队)。
Args:
task: 发货任务;None 视为不需要。
@@ -1539,10 +1541,11 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
"""
if task is None:
return False
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
if process_status != 'created':
if not getattr(task, 'current_order_extraction_id', None):
return False
return bool(getattr(task, 'current_order_extraction_id', None))
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
# created:尚未 CONFIRM_PARSE;parsed:刚确认仍待库存推进。
return process_status in {'', 'created', 'parsed'}
def resolve_confirm_outcome(progress: dict[str, Any] | None) -> str:
@@ -1,13 +1,14 @@
"""
services/shipping_notice/order_review_fulfillment_decision_service.py
用途:建单前行级履约决定(等待补货 / 完整行先行 / 关闭 / 重开)与履约波次创建。
用途:行级履约决定(等待补货 / 完整行先行 / 关闭 / 重开)与履约波次投影。
依赖:ShippingOrderReviewLineDecision、order_review_confirmation_service、
order_review_draft_service.validate_draft、fulfillment_audit、
order_review_draft_service、order_review_workbench_projection、
line_inventory_match_projection(OT 行匹配事实)、fulfillment_audit、
order_review_resume_service。
逻辑:禁止拆分数量;活动决定版本化;波次 Task 仅含选中完整行;
fulfill / 建波次均 fail-closed 校验最新库存与 Reservation;
task_created/fulfilled 不可 reopen;仅 closed_unfulfillable 可由管理员重开。
逻辑:禁止拆分数量;活动决定版本化;投影叠加 inventory_status/match_result/allowed_actions;
订单级聚合计数供侧栏主卡;旧 create_fulfillment_wave 仍走 confirm(BE-8 兼容);
OT 后自动 wave 另服务;履约「料号」= Schema part_number(内部料号),禁止 reservation 回填。
"""
from __future__ import annotations
@@ -97,18 +98,61 @@ def _parse_qty(value: Any) -> Decimal | None:
def _line_reservation_id(draft_line: dict[str, Any], proj: dict[str, Any]) -> str | None:
"""解析行有效 Reservation。"""
"""解析行有效 Reservation(履约表权威字段 reservation_id)。"""
value = str(
draft_line.get('reservation_id')
or proj.get('reservation_id')
or proj.get('effective_reservation_id')
or ''
).strip()
return value or None
def _line_part_number(
draft_line: dict[str, Any],
proj: dict[str, Any],
*,
schema_fields: dict[str, dict[str, Any]] | None = None,
) -> str | None:
"""
解析标准料号(内部料号 / field_code=part_number);禁止用 reservation_id 回填。
核心逻辑:委托 extract_line_part_number,并传入冻结 Schema 以解析 values[field_id]。
"""
from app.services.shipping_notice.order_review_workbench_projection import (
extract_line_part_number,
sanitize_part_number_vs_reservation,
)
part = extract_line_part_number(draft_line, proj, schema_fields=schema_fields)
reservation = _line_reservation_id(draft_line, proj)
return sanitize_part_number_vs_reservation(
part_number=part,
reservation_id=reservation,
)
def _line_required_qty(
draft_line: dict[str, Any],
proj: dict[str, Any],
*,
schema_fields: dict[str, dict[str, Any]] | None = None,
) -> Any:
"""
解析需求数量(field_code=qty/quantity),与订单明细同源。
"""
from app.services.shipping_notice.order_review_workbench_projection import (
extract_line_required_qty,
)
return extract_line_required_qty(draft_line, proj, schema_fields=schema_fields)
def _assess_line_fulfill_complete(
draft_line: dict[str, Any],
proj: dict[str, Any],
*,
schema_fields: dict[str, dict[str, Any]] | None = None,
) -> tuple[bool, str | None, Decimal | None, Decimal | None]:
"""
判断完整明细行是否可先行履约(fail-closed)。
@@ -116,7 +160,7 @@ def _assess_line_fulfill_complete(
Returns:
(can_fulfill, block_code, required_qty, available_qty)
"""
req = _parse_qty(draft_line.get('qty') or draft_line.get('quantity') or proj.get('required_qty'))
req = _parse_qty(_line_required_qty(draft_line, proj, schema_fields=schema_fields))
avail = _parse_qty(proj.get('available_qty'))
if req is None:
return False, 'SHIPPING.REVIEW_LINE_QTY_REQUIRED', None, avail
@@ -137,6 +181,7 @@ def _assert_line_can_fulfill_complete(
line_key: str,
draft_line: dict[str, Any],
proj: dict[str, Any],
schema_fields: dict[str, dict[str, Any]] | None = None,
) -> tuple[Decimal, Decimal]:
"""
强制完整行可履约;否则抛业务错误。
@@ -144,7 +189,11 @@ def _assert_line_can_fulfill_complete(
Returns:
(required_qty, available_qty)
"""
ok, code, req, avail = _assess_line_fulfill_complete(draft_line, proj)
ok, code, req, avail = _assess_line_fulfill_complete(
draft_line,
proj,
schema_fields=schema_fields,
)
if not ok or req is None or avail is None:
raise ConflictError(
'Line cannot fulfill complete quantity with current inventory',
@@ -218,6 +267,7 @@ def _serialize_decision(row: ShippingOrderReviewLineDecision) -> dict[str, Any]:
'line_index': row.line_index,
'decision_version': int(row.decision_version),
'decision_code': row.decision_code,
'decision_source': getattr(row, 'decision_source', None),
'line_status': row.line_status,
'is_active': bool(row.is_active),
'reason': row.reason,
@@ -231,18 +281,123 @@ def _serialize_decision(row: ShippingOrderReviewLineDecision) -> dict[str, Any]:
}
def project_review_case_line_decisions(case: ShippingOrderReviewCase) -> dict[str, Any]:
def _normalize_schema_fields_map(
schema_fields: dict[str, dict[str, Any]] | list[dict[str, Any]] | None,
) -> dict[str, dict[str, Any]]:
"""
将 list/dict 形态的 Schema 字段统一为 field_id → 定义。
Args:
schema_fields: serialize_review_case 的 fields 列表,或 draft_service 字典。
Returns:
field_id → 字段定义;非法输入返回空 dict。
"""
if isinstance(schema_fields, dict):
return {
str(field_id): dict(field)
for field_id, field in schema_fields.items()
if field_id and isinstance(field, dict)
}
if isinstance(schema_fields, list):
out: dict[str, dict[str, Any]] = {}
for raw in schema_fields:
if not isinstance(raw, dict):
continue
field_id = str(raw.get('field_id') or '').strip()
if field_id:
out[field_id] = dict(raw)
return out
return {}
def _aggregate_line_fulfillment_counts(lines_out: list[dict[str, Any]]) -> dict[str, int]:
"""
按用户态汇总订单级履约计数(侧栏聚合卡)。
核心逻辑:系统进度与人工待办分列;短缺与失败不得被「处理中」吞掉。
Args:
lines_out: project_review_case_line_decisions 已投影的行列表。
Returns:
auto_progress_count / manual_pending_count / system_failed_count /
inventory_pending_count。
"""
auto_progress_count = 0
manual_pending_count = 0
system_failed_count = 0
inventory_pending_count = 0
for item in lines_out:
user_status = str(item.get('user_line_status') or '').strip()
if user_status == 'auto_fulfill_failed':
system_failed_count += 1
elif user_status in {'auto_fulfilling', 'wave_created'}:
auto_progress_count += 1
elif user_status in {'inventory_pending', 'source_conflict', 'invalid'}:
inventory_pending_count += 1
elif user_status in {'shortage', 'pending_decision'} or item.get('is_shortage'):
manual_pending_count += 1
elif user_status == 'ready_to_fulfill' and item.get('line_status') not in _TERMINAL_ACTIVE:
# flag 关时仍可能有可履约但未入波次的行,计入人工待办以便侧栏提示。
manual_pending_count += 1
return {
'auto_progress_count': auto_progress_count,
'manual_pending_count': manual_pending_count,
'system_failed_count': system_failed_count,
'inventory_pending_count': inventory_pending_count,
}
def project_review_case_line_decisions(
case: ShippingOrderReviewCase,
*,
schema_fields: dict[str, dict[str, Any]] | list[dict[str, Any]] | None = None,
inventory_rpa_running: bool = False,
source_labels: dict[str, str] | None = None,
) -> dict[str, Any]:
"""
投影 Case 行级履约决定与库存缺口摘要。
核心逻辑:料号/数量按冻结 Schema field_code 从草稿 values 解析;
OT 后叠加行库存匹配事实投影;分域下发 inventory/line_allowed_actions;
ready+not_found 才规范 available=0,禁止把结果缺失当零库存。
Args:
case: 复核 Case。
schema_fields: 可选;优先使用 serialize_review_case 已解析的字段列表。
inventory_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。
source_labels: code→显示名映射。
Returns:
lines / open_count / ready_count / has_open_lines。
lines(含 inventory_source / 分域 actions)与聚合计数。
"""
from app.services.shipping_notice.line_inventory_match_projection import (
line_auto_fulfill_enabled,
load_current_match_facts_by_task,
project_line_inventory_view,
)
from app.services.shipping_notice.order_review_workbench_projection import (
resolve_formal_ot,
schema_fields_from_case,
)
draft_lines = _draft_line_map(case)
projections = _line_projection_map(case)
schema_fields = _normalize_schema_fields_map(schema_fields) or schema_fields_from_case(case)
formal_ot = resolve_formal_ot(case)
has_formal_ot = bool(formal_ot.get('has_formal_ot'))
match_facts = load_current_match_facts_by_task(formal_ot.get('task_id'))
labels = dict(source_labels or {})
if not labels:
draft = getattr(case, 'current_draft', None)
raw_labels = (
(getattr(draft, 'validation_result_json', None) or {}).get('inventory_source_labels')
if draft is not None
else None
)
if isinstance(raw_labels, dict):
labels = {str(k): str(v) for k, v in raw_labels.items() if k}
active_rows = (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), is_active=True)
@@ -255,10 +410,18 @@ def project_review_case_line_decisions(case: ShippingOrderReviewCase) -> dict[st
for key, draft_line in draft_lines.items():
proj = projections.get(key) or {}
decision = by_key.get(key)
can_fulfill, _block, rq, aq = _assess_line_fulfill_complete(draft_line, proj)
required = str(rq) if rq is not None else (
str(draft_line.get('qty') or draft_line.get('quantity') or '').strip() or None
can_fulfill, _block, rq, aq = _assess_line_fulfill_complete(
draft_line,
proj,
schema_fields=schema_fields,
)
required = str(rq) if rq is not None else (
str(
_line_required_qty(draft_line, proj, schema_fields=schema_fields) or ''
).strip()
or None
)
# 兼容旧 path:无 OT 事实时仍可读 line_projections;有事实后以事实为准。
available = str(aq) if aq is not None else (
str(proj.get('available_qty') or '').strip() or None
)
@@ -270,16 +433,67 @@ def project_review_case_line_decisions(case: ShippingOrderReviewCase) -> dict[st
status = decision.line_status if decision is not None else (
'ready_to_fulfill' if can_fulfill else 'pending_decision'
)
decision_source = (
getattr(decision, 'decision_source', None) if decision is not None else None
)
decision_snap = dict(decision.snapshot_json or {}) if decision is not None else {}
fact = match_facts.get(key)
fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {}
auto_failed = bool(
decision_snap.get('auto_fulfill_failed')
or (fact or {}).get('auto_fulfill_failed')
or fact_detail.get('auto_fulfill_failed')
)
auto_err = (
decision_snap.get('auto_fulfill_error_message')
or (fact or {}).get('auto_fulfill_error_message')
or fact_detail.get('auto_fulfill_error_message')
)
inv_view = project_line_inventory_view(
has_formal_ot=has_formal_ot,
fact=fact,
required_qty=required,
stored_line_status=status,
decision_source=decision_source,
can_fulfill_complete_line=can_fulfill,
auto_fulfill_failed=auto_failed,
auto_fulfill_error_message=auto_err,
inventory_rpa_running=bool(inventory_rpa_running),
source_labels=labels,
)
# [STEP] OT 后数量以匹配事实投影覆盖(含 not_found→0 / result_missing→null)
if has_formal_ot:
available = inv_view.get('available_qty')
shortage = inv_view.get('shortage_qty')
lines_out.append({
'line_key': key,
'line_index': draft_line.get('_line_index'),
'reservation_id': _line_reservation_id(draft_line, proj),
'part_number': str(draft_line.get('part_number') or '').strip() or None,
'part_number': _line_part_number(
draft_line,
proj,
schema_fields=schema_fields,
),
'required_qty': required,
'available_qty': available,
'shortage_qty': shortage,
'can_fulfill_complete_line': can_fulfill,
'line_status': status,
'user_line_status': inv_view.get('user_line_status'),
'inventory_status': inv_view.get('inventory_status'),
'match_result': inv_view.get('match_result'),
'is_shortage': bool(inv_view.get('is_shortage')),
'display_available': inv_view.get('display_available'),
'inventory_snapshot_id': inv_view.get('inventory_snapshot_id'),
'inventory_checked_at': inv_view.get('inventory_checked_at'),
'inventory_source_code': inv_view.get('inventory_source_code'),
'inventory_source': inv_view.get('inventory_source'),
'decision_source': inv_view.get('decision_source'),
'inventory_allowed_actions': list(inv_view.get('inventory_allowed_actions') or []),
'line_allowed_actions': list(inv_view.get('line_allowed_actions') or []),
'allowed_actions': list(inv_view.get('allowed_actions') or []),
'auto_fulfill_error_message': inv_view.get('auto_fulfill_error_message'),
'auto_fulfill_failed': bool(auto_failed),
'decision': _serialize_decision(decision) if decision is not None else None,
'block_reason': proj.get('block_reason'),
})
@@ -296,12 +510,76 @@ def project_review_case_line_decisions(case: ShippingOrderReviewCase) -> dict[st
and item.get('line_status') not in _TERMINAL_ACTIVE
)
]
aggregates = _aggregate_line_fulfillment_counts(lines_out)
return {
'lines': lines_out,
'open_count': len(open_lines),
'ready_count': len(ready),
'has_open_lines': bool(open_lines),
'has_shortage': any(item.get('shortage_qty') for item in lines_out),
'has_shortage': any(
item.get('is_shortage') or item.get('shortage_qty') for item in lines_out
),
**aggregates,
'line_auto_fulfill_enabled': bool(line_auto_fulfill_enabled()),
'has_line_inventory_projection': bool(has_formal_ot and lines_out),
}
def build_inventory_issue_fallback(
*,
has_formal_ot: bool,
line_fulfillment: dict[str, Any] | None,
process_gate: dict[str, Any] | None,
automation: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""
Case 级库存兜底:仅无有效行投影且库存系统失败时返回。
核心逻辑:有行投影→None;系统等待/RPA 运行中→None;失败时最多下发
retry_inventory_preparation。
Returns:
fallback 字典或 None。
"""
if not has_formal_ot:
return None
lf = line_fulfillment if isinstance(line_fulfillment, dict) else {}
lines = list(lf.get('lines') or [])
if lines:
# 存在有效行投影:库存动作只在行上,不展示 Case 卡。
return None
auto = automation if isinstance(automation, dict) else {}
auto_status = str(auto.get('status') or '').strip().lower()
if auto_status in {'processing', 'queued', 'automating', 'waiting', 'waiting_to_start'}:
return None
gate = process_gate if isinstance(process_gate, dict) else {}
if gate.get('technical_auto_only') and auto_status not in {'failed', 'error'}:
return None
reason = str(
(gate.get('current_blocking_gate') or {}).get('blocking_reason_code')
or gate.get('blocking_reason_code')
or ''
).strip()
failed_reasons = {
'inventory_file_missing',
'inventory_source_unavailable',
'inventory_preparation_failed',
'inventory_rpa_timeout',
'inventory_rpa_export_failed',
'inventory_file_empty',
}
if auto_status not in {'failed', 'error'} and reason not in failed_reasons:
return None
kind = reason if reason in failed_reasons else 'inventory_file_missing'
return {
'kind': kind,
'reason_label_key': kind,
'affected_line_count': 0,
'file_count': 0,
'allowed_actions': ['retry_inventory_preparation'],
}
@@ -391,13 +669,19 @@ def decide_review_line_fulfillment(
draft_line = lines[key]
projections = _line_projection_map(case)
proj = projections.get(key) or {}
req_qty = _parse_qty(draft_line.get('qty') or draft_line.get('quantity'))
from app.services.shipping_notice.order_review_workbench_projection import (
schema_fields_from_case,
)
schema_fields = schema_fields_from_case(case)
req_qty = _parse_qty(_line_required_qty(draft_line, proj, schema_fields=schema_fields))
avail_qty = _parse_qty(proj.get('available_qty'))
if code == DECISION_FULFILL:
req_qty, avail_qty = _assert_line_can_fulfill_complete(
line_key=key,
draft_line=draft_line,
proj=proj,
schema_fields=schema_fields,
)
# [STEP 1] 停用旧活动决定
@@ -412,6 +696,7 @@ def decide_review_line_fulfillment(
line_index=draft_line.get('_line_index'),
decision_version=_next_version(case, key),
decision_code=code,
decision_source='user',
line_status=status,
is_active=True,
reason=str(reason or '').strip()[:2000] or None,
@@ -420,10 +705,15 @@ def decide_review_line_fulfillment(
str(proj.get('available_qty') or '').strip() or None
),
reservation_id=_line_reservation_id(draft_line, proj),
part_number=str(draft_line.get('part_number') or '').strip() or None,
part_number=_line_part_number(
draft_line,
proj,
schema_fields=schema_fields,
),
actor_user_id=int(user_id),
snapshot_json={
'decision_code': code,
'decision_source': 'user',
'required_qty': str(req_qty) if req_qty is not None else None,
'available_qty': str(avail_qty) if avail_qty is not None else None,
'line_key': key,
@@ -531,8 +821,13 @@ def create_fulfillment_wave(
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
from app.services.shipping_notice.order_review_workbench_projection import (
schema_fields_from_case,
)
draft_lines = _draft_line_map(case)
projections = _line_projection_map(case)
schema_fields = schema_fields_from_case(case)
for key in keys:
if key not in draft_lines:
raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
@@ -553,6 +848,7 @@ def create_fulfillment_wave(
line_key=key,
draft_line=draft_lines[key],
proj=projections.get(key) or {},
schema_fields=schema_fields,
)
# 禁止拆分:决定中的 required_qty 必须等于草稿整行数量
if decision.required_qty and _parse_qty(decision.required_qty) != req:
@@ -9,16 +9,23 @@ backend/app/services/shipping_notice/order_review_projection.py
order_review_duplicate_service.project_review_case_duplicate、
order_review_profile_match_service.project_review_case_profile_match、
order_review_reservation_service.project_review_case_reservation、
order_review_fulfillment_decision_service.project_review_case_line_decisions、
order_review_fulfillment_decision_service.project_review_case_line_decisions /
build_inventory_issue_fallback、
order_review_workbench_projection(正式 OT / completed_checks / field_completeness)、
order_task_service.resolve_order_task_for_candidate、
schema_edit_policy.list_editable_formal_field_ids、
workflow_ledger_service.find_item_by_current_case、ShippingNotice(确认后推进态)。
逻辑:只返回工作台展示所需的字段定义、机器/人工草稿值、问题、建单资格与行级库存候选;
固定投影 customer_resolution / field_conflicts / duplicate / profile_match /
reservation / line_fulfillment / automation;
profile_match 按 is_admin 裁剪(普通用户仅 admin_only 占位);
automation 区分 waiting_to_start / queued / running / manual_fallback,禁止资格冒充正在推进;
管理员另附 technical_progress(如 document_materialization pending);
field_completeness / completed_checks / current_stage / reservation /
line_fulfillment(分域 inventory/line_allowed_actions)/ inventory_issue_fallback /
automation;
profile_match:普通用户四态裁剪,管理员保留完整审计;
automation 区分 pre_ot_stp / post_ot_progress 与 owner_type,禁止资格冒充正在推进;
正式 OT automation/needs_retry 同源绑定 shipping_notice_run Job;
current_stage 与 Progress 共用 project_stage_for_task;
正式 OT 后 process_gate 清除建单前阻断;管理员另附 technical_progress;
task_missing 时 available_actions=view/contact_admin 且 recovery_available=false;
Case 级暴露 candidate_id / order_task_no(Candidate 一对一 OT,禁止前端回退 Run 根号);
为每行/表头投影 field_meta(value_source / locked / override_reason);
已确认 Case 附带 confirmed_task_no 与 post_confirm_auto_progress,供刷新后恢复「已建单待推进」;
@@ -48,44 +55,70 @@ def _safe_filename(value: Any) -> str | None:
def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[str, Any] | None:
"""
投影已确认 Case 的任务号与「是否仍需自动推进」态,供前端刷新后恢复重试入口。
投影已绑定正式 OT 的任务号与自动推进态(与 automation 同源 Job 判定)。
核心逻辑:与 schedule_auto_progress_after_review_confirm 同一判定
(process_status=created 且已挂 Extraction);未确认则不投影。
核心逻辑:委托 project_post_ot_automation_from_job(shipping_notice_run);
needs_retry 与 automation.status=failed 必须同源;无 confirmed_task_id 则不投影。
Args:
case: 复核 Case。
Returns:
含 task_no / needs_retry / status / message 的摘要;未确认时为 None。
含 task_no / needs_retry / status / job_id / message 的摘要;无正式 OT 绑定时为 None。
"""
if str(case.status or '') != 'confirmed' or not case.confirmed_task_id:
if not case.confirmed_task_id:
return None
from app.models import ShippingNotice
from app.services.shipping_notice.order_review_confirmation_service import (
_task_needs_post_confirm_auto_progress,
from app.services.shipping_notice.order_review_workbench_projection import (
project_post_ot_automation_from_job,
resolve_formal_ot,
)
task = db.session.get(ShippingNotice, int(case.confirmed_task_id))
if task is None:
formal_ot = resolve_formal_ot(case)
if formal_ot.get('task_missing'):
return {
'task_no': None,
'needs_retry': False,
'status': 'task_missing',
'message': '已确认但关联任务不可用',
'message': '正式任务关联异常,请联系管理员',
'task_process_status': None,
'job_id': None,
'error_code': 'task_missing',
'recovery_available': False,
}
needs_retry = bool(_task_needs_post_confirm_auto_progress(task))
if not formal_ot.get('has_formal_ot'):
return None
auto = project_post_ot_automation_from_job(formal_ot.get('task'))
needs_retry = bool(auto.get('needs_retry'))
status = str(auto.get('status') or '')
# needs_retry 时保留 manual_fallback;其余可重试统一 needs_retry 供旧消费方。
if needs_retry and status == 'manual_fallback':
mapped_status = 'manual_fallback'
elif needs_retry:
mapped_status = 'needs_retry'
else:
mapped_status = status
return {
'task_no': str(task.task_no or ''),
'task_no': auto.get('task_no') or formal_ot.get('task_no'),
'needs_retry': needs_retry,
'status': 'needs_retry' if needs_retry else 'advanced_or_idle',
'status': mapped_status,
'message': (
'已建单但任务仍停在待推进,可重试自动推进'
'自动推进失败,可重试'
if needs_retry
else '任务已离开待推进态或不需推进'
else (
'已建单,等待系统启动自动推进'
if status == 'waiting_to_start'
else '任务自动推进进行中或已完成'
)
),
'task_process_status': str(getattr(task, 'process_status', None) or ''),
'task_process_status': auto.get('task_process_status'),
'job_id': auto.get('job_id'),
'error_code': auto.get('error_code'),
'reason_code': auto.get('reason_code'),
'attempts': auto.get('attempts'),
'max_attempts': auto.get('max_attempts'),
'completed_at': auto.get('completed_at'),
'recovery_available': False if formal_ot.get('task_missing') else None,
}
@@ -124,18 +157,18 @@ def _project_case_automation_status(
投影用户可见的自动建单/推进状态;资格达标不等于正在推进。
核心逻辑:
- confirmed + needs_retry → failed(可重试)
- confirmed + 已有 Task 且非 retry → queued/running/completed
- 存在 STP Job queued/running → 对应状态
- STP Job failed → failed(可重试)
- can_auto_create 且未入队 → waiting_to_start;超时无 Job → manual_fallback
- 其余 → idle
- 已有正式 OT:只消费 post_confirm / OT process_status(禁止再读 STP 主态)
- post_confirm needs_retry → failed(可重试)
- 正式 OT + process_status created/空 → waiting_to_start(无 Job)或 queued
- 无正式 OT:查 STP Job queued/running/failed;can_auto_create 未入队 → waiting_to_start
- phase / owner_type 由 enrich_automation_status 在 serialize 时补齐
Returns:
status / retryable / task_no / can_auto_create / job_id。
"""
from datetime import datetime, timezone
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
from app.services.shipping_notice.order_stp_auto_create_service import (
build_stp_idempotency_key,
find_active_stp_job,
@@ -144,37 +177,90 @@ def _project_case_automation_status(
can_auto = bool((validation or {}).get('can_auto_create'))
can_build = bool((validation or {}).get('can_build'))
task_no = None
if isinstance(post_confirm, dict):
task_no = str(post_confirm.get('task_no') or '').strip() or None
if post_confirm.get('needs_retry'):
formal_ot = resolve_formal_ot(case)
# [STEP 1] 正式 OT:与 post_confirm 共用 project_post_ot_automation_from_job,禁止只读 process_status。
if formal_ot.get('has_formal_ot') or formal_ot.get('task_missing') or (
isinstance(post_confirm, dict) and (
post_confirm.get('task_no') or str(post_confirm.get('status') or '') == 'task_missing'
)
):
from app.services.shipping_notice.order_review_workbench_projection import (
project_post_ot_automation_from_job,
)
# 优先复用 post_confirm:needs_retry 可操作态优先于 task_missing 诊断。
if isinstance(post_confirm, dict) and post_confirm.get('needs_retry'):
raw_status = str(post_confirm.get('status') or '').strip().lower()
out_status = 'manual_fallback' if raw_status == 'manual_fallback' else 'failed'
return {
'status': 'failed',
'status': out_status,
'retryable': True,
'task_no': task_no,
'task_no': post_confirm.get('task_no') or formal_ot.get('task_no'),
'can_auto_create': can_auto,
'can_build': can_build,
'job_id': None,
'reason_code': 'post_confirm_auto_progress_failed',
}
if task_no:
process_status = str(post_confirm.get('task_process_status') or '').strip().lower()
if process_status in {'created', ''}:
status = 'queued'
elif process_status in {'completed', 'closed', 'done'}:
status = 'completed'
else:
status = 'running'
return {
'status': status,
'retryable': False,
'task_no': task_no,
'can_auto_create': can_auto,
'can_build': can_build,
'job_id': None,
'job_id': post_confirm.get('job_id'),
'error_code': post_confirm.get('error_code'),
'reason_code': (
post_confirm.get('reason_code')
or post_confirm.get('error_code')
or 'post_confirm_auto_progress_failed'
),
'attempts': post_confirm.get('attempts'),
'max_attempts': post_confirm.get('max_attempts'),
'completed_at': post_confirm.get('completed_at'),
}
# [STEP] 查当前有效 STP Job;无有效 Job 时再看最新历史(failed → 可重试)。
if formal_ot.get('task_missing') or (
isinstance(post_confirm, dict)
and str(post_confirm.get('status') or '') == 'task_missing'
):
return {
'status': 'failed',
'retryable': False,
'task_no': None,
'can_auto_create': can_auto,
'can_build': can_build,
'job_id': None,
'reason_code': 'task_missing',
'error_code': 'task_missing',
}
# 复用已算好的 post_confirm(同源);缺省时再查 Job。
if isinstance(post_confirm, dict) and post_confirm.get('status') not in (None, ''):
status = str(post_confirm.get('status') or '').strip().lower()
if status == 'needs_retry':
status = 'failed'
return {
'status': status,
'retryable': bool(post_confirm.get('needs_retry') or status in {'failed', 'manual_fallback'}),
'task_no': post_confirm.get('task_no') or formal_ot.get('task_no'),
'can_auto_create': can_auto,
'can_build': can_build,
'job_id': post_confirm.get('job_id'),
'error_code': post_confirm.get('error_code'),
'reason_code': post_confirm.get('reason_code') or post_confirm.get('error_code'),
'attempts': post_confirm.get('attempts'),
'max_attempts': post_confirm.get('max_attempts'),
'completed_at': post_confirm.get('completed_at'),
}
auto = project_post_ot_automation_from_job(formal_ot.get('task'))
return {
'status': auto.get('status') or 'waiting_to_start',
'retryable': bool(auto.get('retryable')),
'task_no': auto.get('task_no') or formal_ot.get('task_no'),
'can_auto_create': can_auto,
'can_build': can_build,
'job_id': auto.get('job_id'),
'error_code': auto.get('error_code'),
'reason_code': auto.get('reason_code') or auto.get('error_code'),
'attempts': auto.get('attempts'),
'max_attempts': auto.get('max_attempts'),
'completed_at': auto.get('completed_at'),
}
# [STEP 2] 建单前:查当前有效 STP Job;无有效 Job 时再看最新历史(failed → 可重试)。
job = None
latest = None
draft = getattr(case, 'current_draft', None)
@@ -466,13 +552,22 @@ def serialize_review_case(
Args:
case: 复核 Case。
is_admin: 为 True 时返回完整 profile_match 审计;普通用户仅返回
``{available: false, visibility: admin_only}``,禁止下发模板 ID/分数/内部原因码。
is_admin: 为 True 时返回完整 profile_match 审计;普通用户仅四态裁剪,
禁止下发模板 ID/分数/内部原因码。
"""
from app.services.shipping_notice.schema_edit_policy import (
is_excel_ready_for_task,
list_editable_formal_field_ids,
)
from app.services.shipping_notice.order_review_workbench_projection import (
apply_post_ot_gate_rules,
enrich_automation_status,
project_completed_checks,
project_field_completeness,
project_stage_for_task,
project_user_profile_match,
resolve_formal_ot,
)
run = case.run
draft = case.current_draft
@@ -533,6 +628,8 @@ def serialize_review_case(
.all()
)
llm_suggestions = [serialize_suggestion(row) for row in rows]
formal_ot = resolve_formal_ot(case)
process_gate = None
technical_progress = None
from app.models import ShippingProcessExecution
@@ -548,7 +645,10 @@ def serialize_review_case(
.first()
)
if execution is not None:
process_gate = project_user_gate_summary(execution)
process_gate = apply_post_ot_gate_rules(
project_user_gate_summary(execution),
has_formal_ot=bool(formal_ot.get('has_formal_ot')),
)
# [STEP] 管理员 technical_progress:如实投影当前技术 Gate(含 pending),不经用户态过滤。
if is_admin:
full_exec = serialize_process_execution(execution, include_diagnostics=False)
@@ -559,15 +659,33 @@ def serialize_review_case(
'status': str(current.get('status') or ''),
'blocking_reason_code': current.get('blocking_reason_code'),
}
elif formal_ot.get('has_formal_ot') or formal_ot.get('task_missing'):
# 无 Execution 时仍给出 OT 后系统自动态,避免前端回退到人工待办。
process_gate = {
'execution_no': None,
'status': 'running' if formal_ot.get('has_formal_ot') else 'failed',
'current_blocking_gate': None,
'technical_auto_only': True,
'owner_type': 'system' if formal_ot.get('has_formal_ot') else 'unknown',
'available_actions': [],
'gates_track': [],
}
post_confirm = _project_post_confirm_auto_progress(case)
confirmed_task_no = None
if isinstance(post_confirm, dict) and post_confirm.get('task_no'):
if formal_ot.get('has_formal_ot'):
confirmed_task_no = formal_ot.get('task_no')
elif isinstance(post_confirm, dict) and post_confirm.get('task_no'):
confirmed_task_no = str(post_confirm.get('task_no') or '')
validation_snapshot = dict(draft.validation_result_json or {}) if draft is not None else None
automation = _project_case_automation_status(
case,
validation=validation_snapshot,
post_confirm=post_confirm if isinstance(post_confirm, dict) else None,
automation = enrich_automation_status(
_project_case_automation_status(
case,
validation=validation_snapshot,
post_confirm=post_confirm if isinstance(post_confirm, dict) else None,
),
formal_ot=formal_ot,
is_admin=is_admin,
)
from app.services.shipping_notice.order_review_customer_service import (
project_review_case_customer_resolution,
@@ -585,25 +703,53 @@ def serialize_review_case(
project_review_case_reservation,
)
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
build_inventory_issue_fallback,
project_review_case_line_decisions,
)
from app.services.shipping_notice.order_task_service import resolve_order_task_for_candidate
# [STEP] 模板匹配属审计信息:普通用户不得收到模板 ID / 候选分 / 内部原因码。
# [STEP] 模板匹配:管理员完整审计;普通用户仅四态。
admin_profile_match = project_review_case_profile_match(case)
if is_admin:
profile_match = project_review_case_profile_match(case)
profile_match = dict(admin_profile_match)
profile_match['visibility'] = 'admin'
profile_match['raw_status'] = profile_match.get('status')
profile_match['status'] = project_user_profile_match(admin_profile_match)['status']
else:
profile_match = {
'available': False,
'visibility': 'admin_only',
'status': 'hidden',
'candidates': [],
'fallback_reason_codes': [],
'needs_review': False,
'selected_profile': None,
'execution_mode': None,
'route_type': None,
profile_match = project_user_profile_match(admin_profile_match)
customer_resolution = project_review_case_customer_resolution(case)
field_conflicts = project_review_case_field_conflicts(case)
duplicate = project_review_case_duplicate(case)
field_completeness = project_field_completeness(
validation=validation_snapshot,
has_formal_ot=bool(formal_ot.get('has_formal_ot')),
)
completed_checks = project_completed_checks(
case=case,
process_gate=process_gate,
customer_resolution=customer_resolution,
duplicate=duplicate,
field_conflicts=field_conflicts if isinstance(field_conflicts, list) else [],
field_completeness=field_completeness,
profile_match=profile_match,
formal_ot=formal_ot,
)
if formal_ot.get('task_missing'):
current_stage = {
'code': 'task_missing',
'label_key': 'task_missing',
'source': 'formal_ot',
'inconsistent': True,
'process_status': None,
'current_step': None,
'stage_node': None,
}
elif formal_ot.get('has_formal_ot'):
current_stage = project_stage_for_task(formal_ot.get('task'))
else:
# 建单前:固定 order_review;STP 入队态只走 automation,不冒充库存阶段。
current_stage = project_stage_for_task(None, default_code='order_review')
# [UI-03] Case 级暴露 Candidate 绑定的 OT,禁止前端回退 Run 根号。
linked_order_task = resolve_order_task_for_candidate(
@@ -614,13 +760,52 @@ def serialize_review_case(
)
order_data_version = None
confirmed_notice = None
if str(case.status or '') == 'confirmed' and case.confirmed_task_id:
from app.models import ShippingNotice
confirmed_notice = formal_ot.get('task') if formal_ot.get('has_formal_ot') else None
if confirmed_notice is not None:
order_data_version = int(confirmed_notice.order_data_version or 1)
confirmed_notice = db.session.get(ShippingNotice, int(case.confirmed_task_id))
if confirmed_notice is not None:
order_data_version = int(confirmed_notice.order_data_version or 1)
if is_admin and formal_ot.get('task_missing'):
technical_progress = {
'gate_code': (technical_progress or {}).get('gate_code'),
'status': 'task_missing',
'blocking_reason_code': 'task_missing',
'enqueue_status': 'task_missing',
'confirmed_task_id': formal_ot.get('task_id') or (
int(case.confirmed_task_id) if case.confirmed_task_id else None
),
'recovery_available': False,
}
# task_missing:禁止 confirm;无恢复 API 时明确 view + contact_admin。
available_actions = _allowed_actions(case)
if formal_ot.get('task_missing') or formal_ot.get('has_formal_ot'):
available_actions = [a for a in available_actions if a != 'confirm']
if formal_ot.get('task_missing'):
available_actions = ['view', 'contact_admin']
# [STEP] 行履约投影依赖 automation / labels;Case 兜底仅无行投影且系统失败。
# waiting_to_start / waiting = 尚未真正跑库存 RPA,禁止当成 running 清空行动作。
auto_status = str((automation or {}).get('status') or '').strip().lower()
inventory_rpa_running = auto_status in {
'processing', 'queued', 'automating', 'running',
}
source_labels: dict[str, str] = {}
if isinstance(validation_snapshot, dict):
raw_labels = validation_snapshot.get('inventory_source_labels') or {}
if isinstance(raw_labels, dict):
source_labels = {str(k): str(v) for k, v in raw_labels.items() if k}
line_fulfillment = project_review_case_line_decisions(
case,
schema_fields=schema_fields,
inventory_rpa_running=inventory_rpa_running,
source_labels=source_labels,
)
inventory_issue_fallback = build_inventory_issue_fallback(
has_formal_ot=bool(formal_ot.get('has_formal_ot')),
line_fulfillment=line_fulfillment,
process_gate=process_gate if isinstance(process_gate, dict) else None,
automation=automation if isinstance(automation, dict) else None,
)
return {
'case_no': case.case_no,
@@ -632,8 +817,14 @@ def serialize_review_case(
'disposition': case.disposition,
'confirmed_task_id': int(case.confirmed_task_id) if case.confirmed_task_id else None,
'confirmed_task_no': confirmed_task_no,
'has_formal_ot': bool(formal_ot.get('has_formal_ot')),
'task_missing': bool(formal_ot.get('task_missing')),
'recovery_available': False if formal_ot.get('task_missing') else None,
'post_confirm_auto_progress': post_confirm,
'automation': automation,
'current_stage': current_stage,
'completed_checks': completed_checks,
'field_completeness': field_completeness,
'technical_progress': technical_progress,
'candidate': {
'id': int(candidate.id),
@@ -641,17 +832,16 @@ def serialize_review_case(
'validation_status': candidate.validation_status,
'po_number': candidate.po_number,
} if candidate is not None else None,
'customer_resolution': project_review_case_customer_resolution(case),
'field_conflicts': project_review_case_field_conflicts(case),
'duplicate': project_review_case_duplicate(case),
'customer_resolution': customer_resolution,
'field_conflicts': field_conflicts,
'duplicate': duplicate,
'profile_match': profile_match,
'reservation': project_review_case_reservation(case),
'line_fulfillment': project_review_case_line_decisions(case),
'line_fulfillment': line_fulfillment,
'schema': {'schema_version_id': int(run.schema_version_id), 'fields': schema_fields},
'draft': projected_draft,
'llm_suggestions': llm_suggestions,
'available_actions': _allowed_actions(case),
# 正式任务可编辑字段(默认空;仅 Schema task_edit_policy 放行;Excel ready 后全空)。
'available_actions': available_actions,
'formal_editable_field_ids': (
list_editable_formal_field_ids(
schema_fields,
@@ -662,6 +852,7 @@ def serialize_review_case(
),
'order_data_version': order_data_version,
'process_gate': process_gate,
'inventory_issue_fallback': inventory_issue_fallback,
}
@@ -683,7 +874,6 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
})
return {
'run_no': run.run_no,
# 已被新版识别替代的 Run 不可继续编辑,前端据此跳转而非渲染空白旧 Case。
'superseded_by_run_no': run.superseding_run.run_no if run.superseding_run is not None else None,
'summary': counts,
'items': items,
File diff suppressed because it is too large. Load diff
@@ -56,17 +56,17 @@ def compute_effective_reservation_id(
def default_derivation_rules() -> list[dict[str, Any]]:
"""
返回新草稿默认派生规则(关闭状态)。
返回新草稿默认派生规则(启用状态)。
核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=False,
避免未评审规则自动改写内部项次。
核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=True,
内部项次为空时自动从客户 PO 行号派生;人工已锁定或目标有值时不覆盖。
Returns:
可写入 definition_json.derivation_rules 的规则列表。
"""
return [{
'rule_id': DEFAULT_DERIVATION_RULE_ID,
'enabled': False,
'enabled': True,
'source_field_code': 'customer_po_line_no',
'target_field_code': 'line_no',
'strategy': 'copy_if_empty',
@@ -841,6 +841,16 @@ def execute_stp_auto_create_job(*, payload: dict[str, Any], job_id: int) -> dict
created_by_id=int(owner_id),
commit=False,
)
# [STEP] BE-4:STP 建 OT 成功后补触发自动履约协调(flag 关时 no-op)
if created.get('task_no') and not created.get('idempotent_replay'):
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
enqueue_post_ot_auto_fulfill_job,
)
enqueue_post_ot_auto_fulfill_job(
task_no=str(created.get('task_no')),
trigger='ot_created',
commit=False,
)
db.session.commit()
progress = finalize_sync_auto_progress_after_commit(progress)
return {
@@ -0,0 +1,429 @@
"""
services/shipping_notice/post_ot_fulfillment_wave_service.py
用途:正式 OT 已存在后的行级履约波次(create_post_ot_fulfillment_wave);禁止再走 confirm_review_case。
依赖:ShippingOrderReviewWaveLine、ShippingOrderReviewWaveIdempotency、LineDecision、
line_inventory_match 事实、fulfillment_audit、post_ot_wave_progress_service。
逻辑:服务端按匹配事实重校验;独立幂等表强约束;同 key 参数冲突 409;
成功后由调用方 schedule_post_ot_wave_progress(本模块不调用 confirm 推进)。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from decimal import Decimal, InvalidOperation
from typing import Any
from sqlalchemy import func
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingNotice,
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision,
ShippingOrderReviewWaveIdempotency,
ShippingOrderReviewWaveLine,
)
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
DECISION_FULFILL,
_STATUS_BY_DECISION,
_active_decision,
_draft_line_map,
_next_version,
project_review_case_line_decisions,
)
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
def _parse_qty(value: Any) -> Decimal | None:
"""解析数量。"""
text = str(value if value is not None else '').strip()
if not text:
return None
try:
return Decimal(text)
except (InvalidOperation, ValueError):
return None
def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]:
"""
按匹配事实 fail-closed 校验可完整履约。
Raises:
ConflictError: 事实未 ready、短缺、或数量无效。
"""
if str(line.get('inventory_status') or '') != 'ready':
raise ConflictError(
'Inventory not ready for post-OT wave',
code='SHIPPING.REVIEW_LINE_INVENTORY_NOT_READY',
details={'line_key': line.get('line_key'), 'inventory_status': line.get('inventory_status')},
)
if str(line.get('match_result') or '') != 'matched':
raise ConflictError(
'Line match result does not allow fulfill',
code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE',
details={'line_key': line.get('line_key'), 'match_result': line.get('match_result')},
)
if line.get('is_shortage'):
raise ConflictError(
'Line has inventory shortage',
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
details={'line_key': line.get('line_key')},
)
req = _parse_qty(line.get('required_qty'))
avail = _parse_qty(line.get('available_qty'))
if req is None or avail is None or avail < req:
raise ConflictError(
'Line cannot fulfill complete quantity with current inventory facts',
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
details={'line_key': line.get('line_key')},
)
return req, avail
def _stable_line_keys(keys: list[str]) -> list[str]:
"""稳定排序行键。"""
return sorted({str(k).strip() for k in keys if str(k).strip()})
def _line_keys_hash(keys: list[str]) -> str:
"""行集合指纹。"""
payload = json.dumps(_stable_line_keys(keys), ensure_ascii=False, separators=(',', ':'))
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
def _snapshot_fingerprint(lines: list[dict[str, Any]], keys: list[str]) -> tuple[int | None, str]:
"""
从行投影提取库存快照指纹。
Returns:
(单一 snapshot_id 或 None, fingerprint 字符串)。
"""
ids: list[int] = []
by_key = {str(item.get('line_key') or ''): item for item in lines}
for key in keys:
item = by_key.get(key) or {}
raw = item.get('inventory_snapshot_id')
if raw is None or raw == '':
continue
try:
ids.append(int(raw))
except (TypeError, ValueError):
continue
unique = sorted(set(ids))
fingerprint = ','.join(str(i) for i in unique) if unique else 'none'
single = unique[0] if len(unique) == 1 else None
return single, fingerprint
def _params_conflict(
row: ShippingOrderReviewWaveIdempotency,
*,
line_keys: list[str],
fingerprint: str,
decision_source: str,
) -> bool:
"""同 key 参数是否与已存记录冲突。"""
if str(row.decision_source or '') != str(decision_source):
return True
if str(row.line_keys_hash or '') != _line_keys_hash(line_keys):
return True
if str(row.inventory_snapshot_fingerprint or '') != str(fingerprint):
return True
return False
def create_post_ot_fulfillment_wave(
*,
case_no: str,
line_keys: list[str],
decision_source: str = 'system',
actor_user_id: int | None = None,
reason: str | None = None,
idempotency_key: str | None = None,
) -> dict[str, Any]:
"""
在已有正式 OT 上为选中行创建履约波次(不调用 confirm_review_case)。
核心逻辑:要求 has_formal_ot;按 line_fulfillment 事实重校验;独立幂等表回放/409;
新行写入 wave_lines 并更新决定为 task_created。
Args:
case_no: Case 编号。
line_keys: 本波次行键。
decision_source: system | user。
actor_user_id: 人工操作人;系统可为 None。
reason: 备注。
idempotency_key: 可选幂等键(独立表强约束)。
Returns:
wave_no / task_no / accepted_line_keys / skipped_line_keys / line_fulfillment /
idempotency_row_id / idempotent_replay。
"""
keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()]
if not keys:
raise ValidationError('line_keys required', code='SHIPPING.REVIEW_LINE_WAVE_EMPTY')
if len(keys) != len(set(keys)):
raise ValidationError('Duplicate line_keys', code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE')
source = str(decision_source or 'system').strip()
if source not in {'system', 'user'}:
raise ValidationError('Invalid decision_source', code='SHIPPING.REVIEW_DECISION_SOURCE_INVALID')
idem_key = str(idempotency_key or '').strip()[:191] or None
# [STEP 1] 加载 Case 与正式 OT
case = (
ShippingOrderReviewCase.query
.filter_by(case_no=str(case_no or '').strip())
.first()
)
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
assert_case_is_current_workflow_version(case=case)
formal = resolve_formal_ot(case)
if not formal.get('has_formal_ot') or formal.get('task') is None:
raise ConflictError(
'Formal OT required for post-OT fulfillment wave',
code='SHIPPING.REVIEW_POST_OT_WAVE_REQUIRES_OT',
)
task: ShippingNotice = formal['task']
projected = project_review_case_line_decisions(case)
projected_lines = [item for item in list(projected.get('lines') or []) if isinstance(item, dict)]
by_key = {
str(item.get('line_key') or ''): item
for item in projected_lines
}
snap_id, snap_fp = _snapshot_fingerprint(projected_lines, keys)
# [STEP 1b] 幂等回放 / 参数冲突 409
if idem_key:
existing = (
ShippingOrderReviewWaveIdempotency.query
.filter_by(idempotency_key=idem_key)
.first()
)
if existing is not None:
if _params_conflict(
existing,
line_keys=keys,
fingerprint=snap_fp,
decision_source=source,
):
raise ConflictError(
'Idempotency key reuse with conflicting wave parameters',
code='SHIPPING.REVIEW_POST_OT_WAVE_IDEMPOTENCY_CONFLICT',
details={
'idempotency_key': idem_key,
'existing_line_keys_hash': existing.line_keys_hash,
'existing_snapshot_fingerprint': existing.inventory_snapshot_fingerprint,
'existing_decision_source': existing.decision_source,
},
)
replay = dict(existing.result_json or {})
replay['idempotent_replay'] = True
replay['idempotency_row_id'] = int(existing.id)
replay['line_fulfillment'] = project_review_case_line_decisions(case)
return replay
assigned = {
str(row.line_key)
for row in ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(case.id)).all()
}
accepted: list[str] = []
skipped: list[str] = []
for key in keys:
if key in assigned:
skipped.append(key)
continue
line = by_key.get(key)
if line is None:
raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
if str(line.get('line_status') or '') == 'closed_unfulfillable':
raise ConflictError(
'Closed line cannot enter wave',
code='SHIPPING.REVIEW_LINE_CLOSED',
details={'line_key': key},
)
_assert_fact_allows_fulfill(line)
accepted.append(key)
wave_no = None
if accepted:
max_wave = (
db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no))
.filter(ShippingOrderReviewWaveLine.review_case_id == int(case.id))
.scalar()
)
wave_no = int(max_wave or 0) + 1
from app.services.shipping_notice.order_review_confirmation_service import (
_persist_wave_lines_for_task,
)
_persist_wave_lines_for_task(
case=case,
task=task,
line_keys=accepted,
wave_no=wave_no,
revision_id=None,
)
# [STEP 2] 写入/推进履约决定(含已在 wave 的幂等行)
draft_lines = _draft_line_map(case)
now = datetime.utcnow()
for key in keys:
line = by_key.get(key) or {}
current = _active_decision(case, key)
if current is not None and current.line_status in {'task_created', 'fulfilled'}:
continue
if current is not None:
current.is_active = False
current.updated_at = now
req = str(line.get('required_qty') or '') or None
avail = str(line.get('available_qty') or '') or None
row = ShippingOrderReviewLineDecision(
review_case_id=int(case.id),
line_key=key,
line_index=(draft_lines.get(key) or {}).get('_line_index'),
decision_version=_next_version(case, key),
decision_code=DECISION_FULFILL,
decision_source=source,
line_status='task_created' if key in assigned or key in accepted else _STATUS_BY_DECISION[DECISION_FULFILL],
is_active=True,
reason=str(reason or '').strip()[:2000] or None,
required_qty=req,
available_qty=avail,
reservation_id=line.get('reservation_id'),
part_number=line.get('part_number'),
task_id=int(task.id),
wave_no=wave_no if key in accepted else (
int(current.wave_no) if current is not None and current.wave_no is not None else None
),
actor_user_id=int(actor_user_id) if actor_user_id is not None else None,
snapshot_json={
'decision_code': DECISION_FULFILL,
'decision_source': source,
'idempotency_key': idem_key,
'inventory_snapshot_id': line.get('inventory_snapshot_id'),
'match_result': line.get('match_result'),
},
created_at=now,
updated_at=now,
)
if key in accepted:
row.line_status = 'task_created'
row.wave_no = wave_no
elif key in assigned:
row.line_status = 'task_created'
existing_wave = (
ShippingOrderReviewWaveLine.query
.filter_by(review_case_id=int(case.id), line_key=key)
.first()
)
if existing_wave is not None:
row.wave_no = int(existing_wave.wave_no)
db.session.add(row)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='review_post_ot_fulfillment_wave',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action='create_post_ot_fulfillment_wave',
actor_type='system' if source == 'system' else 'user',
actor_id=int(actor_user_id) if actor_user_id is not None else None,
review_case_no=str(case.case_no),
run_no=str(case.run.run_no) if case.run is not None else None,
task_no=str(task.task_no),
before_json={'line_keys': keys},
after_json={
'wave_no': wave_no,
'accepted_line_keys': accepted,
'skipped_line_keys': skipped,
'decision_source': source,
'idempotency_key': idem_key,
},
)
result = {
'case_no': case.case_no,
'task_no': task.task_no,
'task_id': int(task.id),
'review_case_id': int(case.id),
'wave_no': wave_no,
'accepted_line_keys': accepted,
'skipped_line_keys': skipped,
'decision_source': source,
'idempotent_replay': False,
'line_fulfillment': project_review_case_line_decisions(case),
}
# [STEP 3] 持久化幂等记录(无显式 key 时用 UUID,避免误撞自然键)
import uuid
persist_key = idem_key or f'post-ot-wave:{uuid.uuid4().hex}'[:191]
idem_row = ShippingOrderReviewWaveIdempotency(
idempotency_key=persist_key,
review_case_id=int(case.id),
task_id=int(task.id),
task_no=str(task.task_no),
wave_no=wave_no,
decision_source=source,
line_keys_json=_stable_line_keys(keys),
line_keys_hash=_line_keys_hash(keys),
inventory_snapshot_id=snap_id,
inventory_snapshot_fingerprint=snap_fp,
status='succeeded',
result_json={k: v for k, v in result.items() if k != 'line_fulfillment'},
progress_status='pending',
created_at=now,
updated_at=now,
)
db.session.add(idem_row)
db.session.flush()
result['idempotency_row_id'] = int(idem_row.id)
result['idempotency_key'] = persist_key
idem_row.result_json = {k: v for k, v in result.items() if k != 'line_fulfillment'}
db.session.flush()
return result
def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
"""
列出可自动/人工完整履约的行(ready+matched+非短缺+未关闭+未终态)。
Args:
case: 复核 Case。
Returns:
line_key 列表。
"""
projected = project_review_case_line_decisions(case)
out: list[str] = []
for item in list(projected.get('lines') or []):
if not isinstance(item, dict):
continue
if str(item.get('line_status') or '') in {'closed_unfulfillable', 'fulfilled', 'task_created'}:
continue
if str(item.get('inventory_status') or '') != 'ready':
continue
if str(item.get('match_result') or '') != 'matched':
continue
if item.get('is_shortage'):
continue
if item.get('user_line_status') == 'auto_fulfill_failed':
continue
if item.get('auto_fulfill_failed'):
continue
req = _parse_qty(item.get('required_qty'))
avail = _parse_qty(item.get('available_qty'))
if req is None or avail is None or avail < req:
continue
out.append(str(item.get('line_key') or ''))
return [k for k in out if k]
@@ -0,0 +1,179 @@
"""
services/shipping_notice/post_ot_wave_progress_service.py
用途:正式 OT 后履约 wave 的专用推进调度(Excel/RPA),禁止复用 confirm 后整单推进。
依赖:Job 队列、ShippingOrderReviewWaveIdempotency、fulfillment_workflow.generate_excel。
逻辑:create_post_ot_fulfillment_wave 成功后调用;幂等键含 wave_no;下游失败只标 progress_failed,不回滚 wave。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import ShippingOrderReviewWaveIdempotency
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
def _progress_idempotency_key(
*,
task_no: str,
wave_no: int | None,
request_key: str | None,
) -> str:
"""构造 wave 推进幂等键(含 wave_no)。"""
wave_token = f'w{int(wave_no)}' if wave_no is not None else 'w0'
base = str(request_key or '').strip() or 'anon'
return f'post-ot-wave-progress:{str(task_no).strip().upper()}:{wave_token}:{base}'[:191]
def schedule_post_ot_wave_progress(
*,
task_no: str,
wave_no: int | None,
line_keys: list[str],
review_case_id: int | None = None,
idempotency_row_id: int | None = None,
request_idempotency_key: str | None = None,
created_by_id: int | None = None,
commit: bool = False,
) -> dict[str, Any]:
"""
为本 wave 入队 Excel/RPA 推进 Job;不得调用 schedule_auto_progress_after_review_confirm。
核心逻辑:幂等键含 task_no+wave_no;同进度键已有 Job 则复用;仅推进本 wave 上下文。
Args:
task_no: 正式 OT 编号。
wave_no: 本波次号;可为 None(仅跳过行时)。
line_keys: 本波行键。
review_case_id: 复核 Case id。
idempotency_row_id: wave 幂等行 id(用于回写 progress_*)。
request_idempotency_key: 原始 wave 请求幂等键。
created_by_id: 操作人(审计)。
commit: 是否自行提交入队。
Returns:
调度摘要(progress_status / job_id / progress_idempotency_key)。
"""
_ = created_by_id
normalized = str(task_no or '').strip().upper()
keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()]
if not normalized:
return {
'auto_progress_started': False,
'status': 'not_scheduled',
'reason': 'missing_task_no',
'wave_no': wave_no,
}
if wave_no is None and not keys:
return {
'auto_progress_started': False,
'status': 'skipped',
'reason': 'no_new_wave_lines',
'wave_no': None,
}
progress_key = _progress_idempotency_key(
task_no=normalized,
wave_no=wave_no,
request_key=request_idempotency_key,
)
# [STEP 1] 同进度键已调度则幂等返回
existing = (
ShippingOrderReviewWaveIdempotency.query
.filter_by(progress_idempotency_key=progress_key)
.first()
)
if existing is not None and existing.progress_job_id is not None:
return {
'auto_progress_started': True,
'status': 'idempotent_replay',
'wave_no': existing.wave_no,
'progress_status': existing.progress_status,
'progress_job_id': int(existing.progress_job_id),
'progress_idempotency_key': progress_key,
}
# [STEP 2] 入队本 wave 推进 Job
job_id = enqueue(
JobType.SHIPPING_POST_OT_WAVE_PROGRESS,
{
'task_no': normalized,
'wave_no': int(wave_no) if wave_no is not None else None,
'line_keys': keys,
'review_case_id': int(review_case_id) if review_case_id is not None else None,
'idempotency_row_id': int(idempotency_row_id) if idempotency_row_id is not None else None,
'progress_idempotency_key': progress_key,
},
domain=SHIPPING_NOTICE_JOB_DOMAIN,
business_ref=normalized,
message=f'post-OT wave={wave_no} Excel/RPA 推进',
max_attempts=3,
commit=commit,
)
row = None
if idempotency_row_id is not None:
row = db.session.get(ShippingOrderReviewWaveIdempotency, int(idempotency_row_id))
if row is None and review_case_id is not None and wave_no is not None:
row = (
ShippingOrderReviewWaveIdempotency.query
.filter_by(review_case_id=int(review_case_id), wave_no=int(wave_no))
.order_by(ShippingOrderReviewWaveIdempotency.id.desc())
.first()
)
now = datetime.utcnow()
if row is not None:
row.progress_status = 'scheduled'
row.progress_job_id = int(job_id) if job_id is not None else None
row.progress_idempotency_key = progress_key
row.progress_error = None
row.updated_at = now
db.session.flush()
return {
'auto_progress_started': job_id is not None,
'status': 'queued' if job_id is not None else 'enqueue_failed',
'wave_no': wave_no,
'progress_status': 'scheduled' if job_id is not None else 'failed',
'progress_job_id': int(job_id) if job_id is not None else None,
'progress_idempotency_key': progress_key,
'line_keys': keys,
}
def mark_post_ot_wave_progress_result(
*,
idempotency_row_id: int | None,
progress_idempotency_key: str | None,
ok: bool,
error: str | None = None,
) -> None:
"""
回写本 wave 推进结果;失败只更新 progress_*,不删除 wave_lines。
Args:
idempotency_row_id: 幂等行主键。
progress_idempotency_key: 推进幂等键。
ok: 是否成功。
error: 失败原因。
"""
row = None
if idempotency_row_id is not None:
row = db.session.get(ShippingOrderReviewWaveIdempotency, int(idempotency_row_id))
if row is None and progress_idempotency_key:
row = (
ShippingOrderReviewWaveIdempotency.query
.filter_by(progress_idempotency_key=str(progress_idempotency_key))
.first()
)
if row is None:
return
row.progress_status = 'succeeded' if ok else 'failed'
row.progress_error = (str(error)[:2000] if error and not ok else None)
row.updated_at = datetime.utcnow()
@@ -6,6 +6,7 @@ services/shipping_notice/process_gate_projection.py
error_explainability_contract(统一 explainability / request_id)。
逻辑:Chat、复核台与任务中心读取用户安全投影;管理员诊断中心读取完整投影;
用户端同一时间最多一个阻断 + 一个主要恢复动作;诊断 Finding 不进入用户阻断;
pending/queued/running 不冒充人工待办,但保留 execution_status 供观测;
explainability.details 仅白名单业务事实;request_id 仅真实 HTTP 请求号,
execution_no 写入 details;blocking_message 为中文兜底,前端优先 i18n。
"""
@@ -270,9 +271,11 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
核心逻辑:技术 Gate(system/worker)的 POST 重试动作不对业务用户投影;
仅保留导航至复核工作台的业务动作。业务用户看到「系统自动处理中」只读态。
正式 OT 创建后的建单前 Gate 清除、owner_type 分层由
order_review_workbench_projection.apply_post_ot_gate_rules 在 Case 序列化时叠加。
Returns:
current_blocking_gate、reason、next_action、diagnostic_hint(可选非阻断提示)。
current_blocking_gate、reason、next_action、diagnostic_hint、technical_auto_only。
"""
full = serialize_process_execution(execution, include_diagnostics=False)
current = full.get('current_gate')
@@ -281,14 +284,23 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated',
}:
blocking = current
# [STEP] 已通过的客户确认不得再成为用户当前阻断;pending/queued 技术 Gate 也不冒充人工优先处理。
# [STEP] 已通过的客户确认不得再成为用户当前阻断;pending/queued/running 不冒充人工待办,
# 但保留 execution_status 供 OT 后观测(系统等待 ≠ 无 Gate)。
execution_status = None
if blocking:
gate_code = str(blocking.get('gate_code') or '').strip().lower()
gate_status = str(blocking.get('status') or '').strip().lower()
if gate_code in {'customer_resolution', 'customer_confirmed'} and gate_status == 'passed':
blocking = None
elif gate_status in {'pending', 'queued', 'running', 'passed', 'skipped'}:
elif gate_status in {'pending', 'queued', 'running'}:
execution_status = gate_status
blocking = None
elif gate_status in {'passed', 'skipped'}:
blocking = None
if execution_status is None:
full_status = str(full.get('status') or '').strip().lower()
if full_status in {'pending', 'queued', 'running'}:
execution_status = full_status
diagnostic_hint = None
for gate in full.get('gates') or []:
for finding in gate.get('findings') or []:
@@ -337,12 +349,17 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
return {
'execution_no': full.get('execution_no'),
'status': full.get('status'),
'execution_status': execution_status,
'current_blocking_gate': blocking,
'blocking_reason_code': reason_code,
'blocking_message': _user_facing_blocking_message(reason_code),
'explainability': explainability,
'next_action_code': next_action,
'technical_auto_only': technical_auto_only,
'owner_type': (
'system' if technical_auto_only or execution_status
else ('human' if blocking and next_action else ('unknown' if blocking else 'system'))
),
'responsible_party': (
(explainability or {}).get('responsible_party')
or full.get('responsible_party')
@@ -165,7 +165,8 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
【触发时机】写状态机回写 OT、投影组装 order_task 工作项。
核心逻辑:上传完成 → completed;上传中/待上传 → freight_uploading;
导出/Excel → excel_generating;匹配 → inventory_matching;建单/拉库存细分。
导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching;
matching/inventory_ready/matched → inventory_matching;建单中 → order_creating。
领域映射唯一来源,禁止写状态机反向依赖投影私有函数。
Args:
@@ -191,15 +192,19 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
if ps == 'matched' and export_path:
return ('automating', 'excel_generating')
if ps in {'matching', 'inventory_ready', 'waiting_inventory', 'matched', 'parsed'} or 'match' in step:
if ps in {'matching', 'inventory_ready', 'matched'} or 'match' in step:
return ('automating', 'inventory_matching')
# 正式建单后的库存获取:waiting_inventory / parsed → 获取库存(禁止仍映射到 matching)。
if ps in {'waiting_inventory', 'parsed'} or 'fetch' in step or step.startswith('step4'):
return ('automating', 'inventory_fetching')
if ps == 'pending_review':
return ('waiting_review', 'waiting_review')
if ps in {'creating', 'order_creating', 'confirming'} or 'create' in step or step.startswith('step3'):
return ('automating', 'order_creating')
if ps in {'fetching_inventory', 'inventory_fetching'} or 'fetch' in step or step.startswith('step4'):
if ps in {'fetching_inventory', 'inventory_fetching'}:
return ('automating', 'inventory_fetching')
if ps in {'parsing', 'parsed_pending'}:
return ('automating', 'order_creating')
@@ -231,12 +231,20 @@ def claim_next_shipping_notice_job() -> Job | None:
JobType.SHIPPING_PROCESS_GATE,
JobType.SHIPPING_XFA_OCR_AUTOMARK,
JobType.SHIPPING_STP_AUTO_CREATE,
JobType.SHIPPING_LINE_AUTO_FULFILL,
JobType.SHIPPING_POST_OT_WAVE_PROGRESS,
],
)
def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | None = None) -> tuple[bool, str]:
"""执行单票发货任务;既可被通用 Job handler 调用,也可被 sync enqueue 直调。"""
"""
执行单票发货任务;既可被通用 Job handler 调用,也可被 sync enqueue 直调。
核心逻辑:委托 batch_orchestrator._run_single_task;若 Job 软成功但
OT 仍停在 created(已挂 Extraction),则 fail_job 并带
auto_progress_job_succeeded_but_task_not_advanced,供幂等重试直至 max_attempts。
"""
from app.services.shipping_notice.batch_orchestrator import _run_single_task
raw_job_id = payload.get('job_id')
@@ -265,6 +273,26 @@ def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | No
status = str(result.get('status') or '').strip().lower()
success = status in {'ok', 'running', 'needs_human', 'skipped'}
# [STEP] 正式 OT 已挂 Extraction 却仍停在 created:软成功不得 finish Job,须 fail/重试。
# 根因:orchestrator 对 created+extraction 调 auto_progress 后若未推进,旧逻辑仍会 finish_job。
refreshed = get_task_by_ref(task_no)
hang_created = bool(
refreshed is not None
and getattr(refreshed, 'current_order_extraction_id', None)
and str(getattr(refreshed, 'process_status', None) or '').strip().lower() in {'', 'created'}
and status in {'ok', 'needs_human', 'skipped'}
)
if hang_created:
success = False
status = 'failed'
result = {
**dict(result or {}),
'status': 'failed',
'error_code': 'auto_progress_job_succeeded_but_task_not_advanced',
'message': str(result.get('message') or '')
or '自动推进 Job 结束但正式 OT 仍停在 created,将按幂等重试',
}
if job_id is not None:
job = db.session.get(Job, job_id)
if job is not None:
@@ -12,6 +12,7 @@ services/shipping_notice/shipping_processing_projection.py
Intake/OT 均填充 current_gate(优先真实 ProcessExecution)与 source_summary;
输出前 reconcile status/stage/gate/action,并结合 Notice 失效起点 / Excel Artifact
写入 stage_nodes 与 available_actions;stage/status 以 OT 已写入值为准(BE-07,禁止 Notice 覆盖);
已挂正式 Notice 时 stage/stage_label_key 与 Case.current_stage 同源(project_stage_for_task);
**只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert);已建 Notice 时填 shipping_notice_no;
work_items 构建后由 _conversation_processing_from_work_items 重建兼容 conversation_processing。
"""
@@ -967,6 +968,22 @@ def _project_order_task_work_item(
)
if stage not in SHIPPING_PROCESSING_STAGES:
stage = map_run_to_processing_stage(run, source_type=source_type)
# [BE-02] 已挂正式 Notice 时与 Case.current_stage 同源(project_stage_for_task)。
stage_label_key = None
if order_task.shipping_notice_id:
notice_for_stage = db.session.get(ShippingNotice, int(order_task.shipping_notice_id))
if notice_for_stage is not None:
from app.services.shipping_notice.order_review_workbench_projection import (
project_stage_for_task,
)
shared = project_stage_for_task(notice_for_stage)
shared_code = str(shared.get('code') or '').strip().lower()
if shared_code in SHIPPING_PROCESSING_STAGES:
stage = shared_code
stage_label_key = str(shared.get('label_key') or '').strip() or None
# order_creating 无共享投影时仍统一用户文案键。
if not stage_label_key and stage == 'order_creating':
stage_label_key = 'waiting_system_start'
raw_status = str(getattr(order_task, 'status', None) or '').strip().lower()
if raw_status in SHIPPING_PROCESSING_STATUSES:
status = raw_status
@@ -1047,6 +1064,10 @@ def _project_order_task_work_item(
'intake_no': _first_intake_no_for_run(run),
'status': status,
'stage': stage,
# 与 Case.current_stage.label_key 同源;前端禁止用 stage 码直接当用户文案。
'stage_label_key': stage_label_key or (
'waiting_system_start' if stage == 'order_creating' else stage
),
'progress_version': int(
getattr(order_task, 'progress_version', None)
or getattr(run, 'progress_version', None)
@@ -649,6 +649,7 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N
将命名状态迁移写入 ShippingNotice 的 process_status / review_status / pending_human_reason。
核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。
库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → inventory_fetching 等)。
Args:
task: 待更新的 ShippingNotice 实例(尚未 commit)。
@@ -663,3 +664,12 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N
task.pending_human_reason = spec.pending_human_reason
if spec.clear_error_message:
task.error_message = None
# [STEP] 履约态变更后回写 OT stage,避免进度条卡在 order_creating。
try:
from app.services.shipping_notice.order_task_stage_machine import (
sync_order_task_stage_for_notice,
)
sync_order_task_stage_for_notice(task)
except Exception: # noqa: BLE001 — 无 OT / 无 Flask 上下文时跳过,不阻断主迁移
pass
@@ -33,6 +33,11 @@ def _norm_part(value: Any) -> str:
return str(value or '').strip().upper()
def _norm_unit(value: Any) -> str:
"""单位匹配键:去空白并大写;空串表示未配置单位。"""
return str(value or '').strip().upper()
def _qty(value: Any) -> Decimal:
"""解析数量;非法视为 0。"""
try:
@@ -41,19 +46,20 @@ def _qty(value: Any) -> Decimal:
return Decimal('0')
def _inventory_row_key(row: dict[str, Any]) -> tuple[str, str] | None:
def _inventory_row_key(row: dict[str, Any]) -> tuple[str, str, str] | None:
"""
从库存行提取 Reservation + Part Number 键。
从库存行提取 Reservation + Part Number + Unit 键。
核心逻辑:优先标准键名,兼容常见别名;不做数值归一化 Reservation。
核心逻辑:优先标准键名,兼容常见别名;单位缺省为空串(与订单侧对齐后参与匹配)。
"""
reservation = validated_reservation_id(
row.get('reservation_id') or row.get('Reservation ID') or row.get('reservation')
)
part = _norm_part(row.get('part_number') or row.get('Part Number') or row.get('mpn') or row.get('sku'))
unit = _norm_unit(row.get('uom') or row.get('unit') or row.get('UOM') or row.get('Unit'))
if not reservation or not part:
return None
return reservation, part
return reservation, part, unit
def _inventory_row_qty(row: dict[str, Any]) -> Decimal:
@@ -205,18 +211,18 @@ def match_order_lines_across_candidates(
header_reservation_id: Any = None,
) -> dict[str, Any]:
"""
跨候选库存行按有效 Reservation + Part Number 匹配。
跨候选库存行按有效 Reservation + Part Number + Unit 匹配。
Args:
order_lines: 含 part_number / reservation_id / quantity(或 qty)的订单行。
order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。
inventory_lines: 已打 ``__source_code`` 的库存行。
header_reservation_id: 头级 Reservation,用于行级回退。
Returns:
match_status、line_results、shortage_json、resolutions。
"""
# [STEP 1] 按 (reservation, part, source) 聚合可用量与样例行。
buckets: dict[tuple[str, str, str], dict[str, Any]] = {}
# [STEP 1] 按 (reservation, part, unit, source) 聚合可用量与样例行。
buckets: dict[tuple[str, str, str, str], dict[str, Any]] = {}
for row in inventory_lines:
key = _inventory_row_key(row)
if key is None:
@@ -224,7 +230,7 @@ def match_order_lines_across_candidates(
source = str(row.get('__source_code') or '').strip().upper()
if not source:
continue
bucket_key = (key[0], key[1], source)
bucket_key = (key[0], key[1], key[2], source)
bucket = buckets.get(bucket_key)
if bucket is None:
bucket = {'available_qty': Decimal('0'), 'sample_row': row, 'source_code': source}
@@ -239,15 +245,23 @@ def match_order_lines_across_candidates(
for index, line in enumerate(order_lines):
part = _norm_part(line.get('part_number') or line.get('__display_part_number'))
unit = _norm_unit(
line.get('uom')
or line.get('unit')
or line.get('__display_uom')
)
effective = compute_effective_reservation_id(
line_reservation_id=line.get('reservation_id') or line.get('__display_reservation_id'),
header_reservation_id=header_reservation_id,
)
required = _qty(line.get('quantity') if line.get('quantity') is not None else line.get('__required_qty', line.get('qty')))
# [STEP] 订单带单位时只命中同单位库存;双方皆空则退化为料号+预约单。
source_hits = [
buckets[key]
for key in buckets
if key[0] == (effective or '') and key[1] == part
if key[0] == (effective or '')
and key[1] == part
and key[2] == unit
] if effective and part else []
if not effective or not part:
@@ -256,6 +270,7 @@ def match_order_lines_across_candidates(
'line_index': index,
'part_number': part or None,
'reservation_id': effective,
'unit': unit or None,
'required_qty': float(required),
'available_qty': 0.0,
'shortage_qty': float(required),
@@ -270,6 +285,7 @@ def match_order_lines_across_candidates(
'line_index': index,
'part_number': part,
'reservation_id': effective,
'unit': unit or None,
'required_qty': float(required),
'available_qty': float(sum(item['available_qty'] for item in source_hits)),
'shortage_qty': 0.0,
@@ -285,6 +301,7 @@ def match_order_lines_across_candidates(
'line_index': index,
'part_number': part,
'reservation_id': effective,
'unit': unit or None,
'required_qty': float(required),
'available_qty': 0.0,
'shortage_qty': float(required),
@@ -303,6 +320,7 @@ def match_order_lines_across_candidates(
'line_index': index,
'part_number': part,
'reservation_id': effective,
'unit': unit or None,
'required_qty': float(required),
'available_qty': float(available),
'shortage_qty': 0.0,
@@ -313,6 +331,7 @@ def match_order_lines_across_candidates(
'inventory_row_ref': {
'reservation_id': effective,
'part_number': part,
'unit': unit or None,
'source_code': hit['source_code'],
},
}
@@ -323,6 +342,7 @@ def match_order_lines_across_candidates(
'line_index': index,
'part_number': part,
'reservation_id': effective,
'unit': unit or None,
'required_qty': float(required),
'available_qty': float(available),
'shortage_qty': float(max(required - available, Decimal('0'))),
@@ -339,6 +359,7 @@ def match_order_lines_across_candidates(
'disposition': result['disposition'],
'effective_reservation_id': effective,
'part_number': part or None,
'unit': unit or None,
'resolved_inventory_source_code': result.get('resolved_inventory_source_code'),
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': result.get('inventory_file_no'),
@@ -3,12 +3,14 @@ services/shipping_notice/ui_state.py
用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、
process_gate_projection(统一 Gate 用户摘要)。
process_gate_projection(统一 Gate 用户摘要)、
order_review_workbench_projection.apply_post_ot_gate_rules。
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
stp_facts、progress_nodes);
若存在 ProcessExecution:阻断时清空 action_buttons;非阻断时仅保留
download_excel / mark_manual_uploaded / refresh(恢复动作仅由 process_gate 驱动);
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办);
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
"""
@@ -615,10 +617,16 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
"""
按 Task 查找活动 Execution 的用户 Gate 摘要。
核心逻辑:Task 本身即正式 OT,套用 apply_post_ot_gate_rules,
使 inventory_preparation 等系统等待不进入 current_blocking_gate。
Returns:
project_user_gate_summary;无 Execution 时 None。
用户态 Gate 摘要;无 Execution 时 None。
"""
from app.models import ShippingProcessExecution
from app.services.shipping_notice.order_review_workbench_projection import (
apply_post_ot_gate_rules,
)
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
task_id = getattr(task, 'id', None)
@@ -636,7 +644,10 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
)
if execution is None:
return None
return project_user_gate_summary(execution)
return apply_post_ot_gate_rules(
project_user_gate_summary(execution),
has_formal_ot=True,
)
def build_batch_ui_state(batch: Any) -> dict[str, Any]:
@@ -0,0 +1,146 @@
"""
migrations/versions/cr2b3c4d5e6f_add_shipping_notice_line_inventory_matches.py
用途:正式 OT 行级库存匹配事实表 + 行履约决定 decision_source 列(Slice 0)。
依赖:alembic.op、shipping_notices、shipping_inventory_files、shipping_order_review_cases、
shipping_order_review_line_decisions。
逻辑:Revises cq1a2b3c4d5e;新建 shipping_notice_line_inventory_matches;
为 line_decisions 增加可空 decision_source;自动履约 flag 默认关闭不依赖本表写入。
Revision ID: cr2b3c4d5e6f
Revises: cq1a2b3c4d5e
Create Date: 2026-08-07 08:50:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'cr2b3c4d5e6f'
down_revision = 'cq1a2b3c4d5e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""创建 OT 行库存匹配事实表,并扩展行决定来源字段。"""
# [STEP 1] OT 行级匹配事实(历史快照不可覆盖)
op.create_table(
'shipping_notice_line_inventory_matches',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column(
'task_id',
sa.Integer(),
sa.ForeignKey('shipping_notices.id', ondelete='CASCADE'),
nullable=False,
),
sa.Column(
'review_case_id',
sa.Integer(),
sa.ForeignKey('shipping_order_review_cases.id', ondelete='SET NULL'),
nullable=True,
),
sa.Column('line_key', sa.String(length=64), nullable=False),
sa.Column('line_index', sa.Integer(), nullable=True),
sa.Column(
'inventory_snapshot_id',
sa.Integer(),
sa.ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'),
nullable=True,
),
sa.Column('match_result', sa.String(length=32), nullable=False),
sa.Column('inventory_status', sa.String(length=32), nullable=False),
sa.Column('required_qty', sa.String(length=32), nullable=True),
sa.Column('available_qty', sa.String(length=32), nullable=True),
sa.Column('shortage_qty', sa.String(length=32), nullable=True),
sa.Column('reservation_id', sa.String(length=128), nullable=True),
sa.Column('part_number', sa.String(length=128), nullable=True),
sa.Column('unit', sa.String(length=32), nullable=True),
sa.Column('matching_rule_version', sa.String(length=64), nullable=True),
sa.Column('inventory_source_code', sa.String(length=64), nullable=True),
sa.Column('is_current', sa.Boolean(), nullable=False, server_default=sa.text('true')),
sa.Column('matched_at', sa.DateTime(), nullable=False),
sa.Column('detail_json', sa.JSON(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint(
'task_id',
'line_key',
'inventory_snapshot_id',
name='uq_shipping_notice_line_inv_match_task_line_snap',
),
sa.CheckConstraint(
"match_result IN ("
"'matched', 'not_found', 'result_missing', 'preparing', "
"'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable'"
")",
name='ck_shipping_notice_line_inv_match_result',
),
sa.CheckConstraint(
"inventory_status IN ("
"'ready', 'preparing', 'mapping_failed', 'source_conflict', "
"'unavailable', 'invalid_key'"
")",
name='ck_shipping_notice_line_inv_match_status',
),
)
op.create_index(
'ix_shipping_notice_line_inv_match_task',
'shipping_notice_line_inventory_matches',
['task_id'],
)
op.create_index(
'ix_shipping_notice_line_inv_match_case',
'shipping_notice_line_inventory_matches',
['review_case_id'],
)
op.create_index(
'ix_shipping_notice_line_inv_match_snapshot',
'shipping_notice_line_inventory_matches',
['inventory_snapshot_id'],
)
# [STEP 2] PostgreSQL:当前事实唯一;其他方言由应用层保证 is_current
bind = op.get_bind()
if bind.dialect.name == 'postgresql':
op.execute(
sa.text(
'CREATE UNIQUE INDEX uq_shipping_notice_line_inv_match_current '
'ON shipping_notice_line_inventory_matches (task_id, line_key) '
'WHERE is_current IS TRUE'
)
)
# [STEP 3] 行决定来源:system | user(历史可空)
with op.batch_alter_table('shipping_order_review_line_decisions', schema=None) as batch_op:
batch_op.add_column(sa.Column('decision_source', sa.String(length=16), nullable=True))
batch_op.create_check_constraint(
'ck_shipping_review_line_decisions_source',
"decision_source IS NULL OR decision_source IN ('system', 'user', 'unknown')",
)
def downgrade() -> None:
"""回滚事实表与 decision_source。"""
with op.batch_alter_table('shipping_order_review_line_decisions', schema=None) as batch_op:
batch_op.drop_constraint('ck_shipping_review_line_decisions_source', type_='check')
batch_op.drop_column('decision_source')
bind = op.get_bind()
if bind.dialect.name == 'postgresql':
op.execute(sa.text('DROP INDEX IF EXISTS uq_shipping_notice_line_inv_match_current'))
op.drop_index(
'ix_shipping_notice_line_inv_match_snapshot',
table_name='shipping_notice_line_inventory_matches',
)
op.drop_index(
'ix_shipping_notice_line_inv_match_case',
table_name='shipping_notice_line_inventory_matches',
)
op.drop_index(
'ix_shipping_notice_line_inv_match_task',
table_name='shipping_notice_line_inventory_matches',
)
op.drop_table('shipping_notice_line_inventory_matches')
@@ -0,0 +1,96 @@
"""
migrations/versions/cs3c4d5e6f7a_add_shipping_review_wave_idempotency.py
用途:post-OT wave 独立幂等表(BE-3)。
依赖:alembic.op、shipping_order_review_cases、shipping_notices。
逻辑:Revises cr2b3c4d5e6f;idempotency_key 唯一;同 key 参数冲突由服务层 409。
Revision ID: cs3c4d5e6f7a
Revises: cr2b3c4d5e6f
Create Date: 2026-08-07 09:40:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'cs3c4d5e6f7a'
down_revision = 'cr2b3c4d5e6f'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""创建 shipping_order_review_wave_idempotency。"""
op.create_table(
'shipping_order_review_wave_idempotency',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('idempotency_key', sa.String(length=191), nullable=False),
sa.Column(
'review_case_id',
sa.Integer(),
sa.ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False,
),
sa.Column(
'task_id',
sa.Integer(),
sa.ForeignKey('shipping_notices.id', ondelete='CASCADE'),
nullable=False,
),
sa.Column('task_no', sa.String(length=64), nullable=False),
sa.Column('wave_no', sa.Integer(), nullable=True),
sa.Column('decision_source', sa.String(length=16), nullable=False),
sa.Column('line_keys_json', sa.JSON(), nullable=False),
sa.Column('line_keys_hash', sa.String(length=64), nullable=False),
sa.Column('inventory_snapshot_id', sa.Integer(), nullable=True),
sa.Column(
'inventory_snapshot_fingerprint',
sa.String(length=256),
nullable=False,
server_default='',
),
sa.Column('status', sa.String(length=32), nullable=False, server_default='succeeded'),
sa.Column('result_json', sa.JSON(), nullable=False),
sa.Column('progress_status', sa.String(length=32), nullable=False, server_default='pending'),
sa.Column('progress_job_id', sa.Integer(), nullable=True),
sa.Column('progress_error', sa.Text(), nullable=True),
sa.Column('progress_idempotency_key', sa.String(length=191), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('idempotency_key', name='uq_shipping_review_wave_idempotency_key'),
)
op.create_index(
'ix_shipping_review_wave_idempotency_case',
'shipping_order_review_wave_idempotency',
['review_case_id'],
)
op.create_index(
'ix_shipping_review_wave_idempotency_task',
'shipping_order_review_wave_idempotency',
['task_id'],
)
op.create_index(
'ix_shipping_review_wave_idempotency_wave',
'shipping_order_review_wave_idempotency',
['review_case_id', 'wave_no'],
)
def downgrade() -> None:
"""删除幂等表。"""
op.drop_index(
'ix_shipping_review_wave_idempotency_wave',
table_name='shipping_order_review_wave_idempotency',
)
op.drop_index(
'ix_shipping_review_wave_idempotency_task',
table_name='shipping_order_review_wave_idempotency',
)
op.drop_index(
'ix_shipping_review_wave_idempotency_case',
table_name='shipping_order_review_wave_idempotency',
)
op.drop_table('shipping_order_review_wave_idempotency')
@@ -0,0 +1,152 @@
"""
migrations/versions/ct4d5e6f7a8b_post_ot_auto_fulfill_p1.py
用途:BE-7 匹配事实失败列 + BE-4 补偿排程种子。
依赖:alembic.op、shipping_notice_line_inventory_matches、schedule_tasks。
逻辑:Revises cs3c4d5e6f7a;为匹配事实增加 auto_fulfill_failed 列;
种子 SCH-POST-OT-AUTO-FULFILL-COMP 每 15 分钟。
Revision ID: ct4d5e6f7a8b
Revises: cs3c4d5e6f7a
Create Date: 2026-08-07 10:20:00.000000
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import sqlalchemy as sa
from alembic import op
revision = 'ct4d5e6f7a8b'
down_revision = 'cs3c4d5e6f7a'
branch_labels = None
depends_on = None
_SCHEDULE_NO = 'SCH-POST-OT-AUTO-FULFILL-COMP'
_CRON_EXPR = '*/15 * * * *'
_TZ_NAME = 'Asia/Shanghai'
def _compute_next_run_at_utc_naive() -> datetime:
"""按 */15 与 Asia/Shanghai 计算下次执行(UTC naive)。"""
try:
from croniter import croniter
from zoneinfo import ZoneInfo
tz = ZoneInfo(_TZ_NAME)
base = datetime.now(tz)
next_local = croniter(_CRON_EXPR, base).get_next(datetime)
if next_local.tzinfo is None:
next_local = next_local.replace(tzinfo=tz)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
except Exception:
tz = timezone(timedelta(hours=8))
now_local = datetime.now(tz)
minute = (now_local.minute // 15 + 1) * 15
if minute >= 60:
next_local = now_local.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
else:
next_local = now_local.replace(minute=minute, second=0, microsecond=0)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
def upgrade() -> None:
"""增加失败列并种子补偿排程。"""
op.add_column(
'shipping_notice_line_inventory_matches',
sa.Column(
'auto_fulfill_failed',
sa.Boolean(),
nullable=False,
server_default=sa.text('false'),
),
)
op.add_column(
'shipping_notice_line_inventory_matches',
sa.Column('auto_fulfill_error_code', sa.String(length=128), nullable=True),
)
op.add_column(
'shipping_notice_line_inventory_matches',
sa.Column('auto_fulfill_error_message', sa.Text(), nullable=True),
)
op.add_column(
'shipping_notice_line_inventory_matches',
sa.Column('auto_fulfill_failed_at', sa.DateTime(), nullable=True),
)
op.create_index(
'ix_shipping_notice_line_inv_match_auto_fail',
'shipping_notice_line_inventory_matches',
['auto_fulfill_failed'],
)
conn = op.get_bind()
exists = conn.execute(
sa.text(
"SELECT 1 FROM schedule_tasks "
"WHERE schedule_no = :sno OR platform_api_path = 'shipping-post-ot-auto-fulfill-compensation' "
"LIMIT 1"
),
{'sno': _SCHEDULE_NO},
).first()
if exists:
return
owner = conn.execute(
sa.text("SELECT id FROM users WHERE role = 'admin' ORDER BY id ASC LIMIT 1")
).first()
if owner is None:
owner = conn.execute(sa.text('SELECT id FROM users ORDER BY id ASC LIMIT 1')).first()
if owner is None:
return
now = datetime.utcnow()
next_run = _compute_next_run_at_utc_naive()
conn.execute(
sa.text(
"""
INSERT INTO schedule_tasks (
schedule_no, name, schedule_type, owner_user_id,
cron_expr, schedule_timezone, wait_seconds,
platform_api_path, job_params,
kb_sync_enabled, notify_enabled,
enabled, next_run_at, last_run_at,
created_by, updated_by, created_at, updated_at
) VALUES (
:schedule_no, :name, 'platform_job', :owner_user_id,
:cron_expr, 'Asia/Shanghai', 0,
'shipping-post-ot-auto-fulfill-compensation', :job_params,
false, false,
true, :next_run_at, NULL,
:owner_user_id, :owner_user_id, :now, :now
)
"""
),
{
'schedule_no': _SCHEDULE_NO,
'name': 'OT 后行级自动履约补偿',
'owner_user_id': int(owner[0]),
'cron_expr': _CRON_EXPR,
'job_params': '{"limit": 50}',
'next_run_at': next_run,
'now': now,
},
)
def downgrade() -> None:
"""删除补偿排程与失败列。"""
conn = op.get_bind()
conn.execute(
sa.text('DELETE FROM schedule_tasks WHERE schedule_no = :sno'),
{'sno': _SCHEDULE_NO},
)
op.drop_index(
'ix_shipping_notice_line_inv_match_auto_fail',
table_name='shipping_notice_line_inventory_matches',
)
op.drop_column('shipping_notice_line_inventory_matches', 'auto_fulfill_failed_at')
op.drop_column('shipping_notice_line_inventory_matches', 'auto_fulfill_error_message')
op.drop_column('shipping_notice_line_inventory_matches', 'auto_fulfill_error_code')
op.drop_column('shipping_notice_line_inventory_matches', 'auto_fulfill_failed')
@@ -0,0 +1,158 @@
"""
tests/test_line_inventory_allowed_actions.py
用途:锁定 inventory/line 动作分域矩阵(无 wait/换源;RPA 运行中无 preparation)。
"""
from __future__ import annotations
def test_shortage_allows_retry_preparation_not_wait():
from app.services.shipping_notice.line_inventory_match_projection import (
resolve_inventory_allowed_actions,
resolve_line_allowed_actions,
)
inv = resolve_inventory_allowed_actions(
has_formal_ot=True,
inventory_status='ready',
match_result='not_found',
is_shortage=True,
stored_line_status='pending_decision',
user_line_status='shortage',
)
line = resolve_line_allowed_actions(
has_formal_ot=True,
stored_line_status='pending_decision',
user_line_status='shortage',
)
assert inv == ['retry_inventory_preparation']
assert 'wait_inventory' not in inv
assert 'change_inventory_source' not in inv
assert line == ['close_unfulfillable']
def test_rpa_running_hides_inventory_actions():
from app.services.shipping_notice.line_inventory_match_projection import (
resolve_inventory_allowed_actions,
)
inv = resolve_inventory_allowed_actions(
has_formal_ot=True,
inventory_status='preparing',
match_result='preparing',
is_shortage=False,
stored_line_status='pending_decision',
user_line_status='acquiring_inventory',
inventory_rpa_running=True,
)
assert inv == []
def test_match_failed_with_snapshot_allows_matching():
from app.services.shipping_notice.line_inventory_match_projection import (
resolve_inventory_allowed_actions,
)
inv = resolve_inventory_allowed_actions(
has_formal_ot=True,
inventory_status='mapping_failed',
match_result='mapping_failed',
is_shortage=False,
stored_line_status='pending_decision',
user_line_status='inventory_match_failed',
has_usable_snapshot=True,
)
assert inv == ['retry_inventory_preparation', 'retry_inventory_matching']
def test_matched_hides_inventory_icon_actions():
from app.services.shipping_notice.line_inventory_match_projection import (
resolve_inventory_allowed_actions,
)
inv = resolve_inventory_allowed_actions(
has_formal_ot=True,
inventory_status='ready',
match_result='matched',
is_shortage=False,
stored_line_status='ready_to_fulfill',
user_line_status='inventory_matched',
)
assert inv == []
def test_fallback_only_without_lines():
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
build_inventory_issue_fallback,
)
assert build_inventory_issue_fallback(
has_formal_ot=True,
line_fulfillment={'lines': [{'line_key': 'L1'}]},
process_gate={'blocking_reason_code': 'inventory_file_missing'},
automation={'status': 'failed'},
) is None
fb = build_inventory_issue_fallback(
has_formal_ot=True,
line_fulfillment={'lines': []},
process_gate={'blocking_reason_code': 'inventory_file_missing'},
automation={'status': 'failed'},
)
assert fb is not None
assert fb['allowed_actions'] == ['retry_inventory_preparation']
def test_waiting_to_start_allows_retry_preparation():
"""automation waiting_to_start 不得清空库存重试动作(非真正 RPA 运行中)。"""
from app.services.shipping_notice.line_inventory_match_projection import (
resolve_inventory_allowed_actions,
project_user_line_status,
)
user_status = project_user_line_status(
inventory_status='preparing',
match_result='preparing',
is_shortage=False,
stored_line_status='pending_decision',
inventory_rpa_running=False,
)
assert user_status == 'inventory_file_missing'
inv = resolve_inventory_allowed_actions(
has_formal_ot=True,
inventory_status='preparing',
match_result='preparing',
is_shortage=False,
stored_line_status='pending_decision',
user_line_status=user_status,
inventory_rpa_running=False,
)
assert inv == ['retry_inventory_preparation']
def test_fallback_hidden_while_waiting():
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
build_inventory_issue_fallback,
)
assert build_inventory_issue_fallback(
has_formal_ot=True,
line_fulfillment={'lines': []},
process_gate={},
automation={'status': 'waiting_to_start'},
) is None
def test_waiting_inventory_maps_to_inventory_fetching_stage():
"""waiting_inventory 必须映射到获取库存阶,禁止再落到 matching。"""
from types import SimpleNamespace
from app.services.shipping_notice.processing_projection_invariants import (
map_notice_to_processing_status_stage,
)
status, stage = map_notice_to_processing_status_stage(
SimpleNamespace(process_status='waiting_inventory', current_step=None, export_file_path=None),
)
assert status == 'automating'
assert stage == 'inventory_fetching'
@@ -0,0 +1,56 @@
"""
tests/test_line_inventory_match_persistence.py
用途:锁定 disposition → match_result 映射与 not_found/invalid_key 语义。
依赖:pytest、line_inventory_match_persistence。
逻辑:纯单元;不写库。
"""
from __future__ import annotations
from app.services.shipping_notice.line_inventory_match_persistence import (
map_disposition_to_match_codes,
)
def test_complete_key_not_found_is_ready_not_found():
"""键完整且 not_found → ready + not_found。"""
match_result, status = map_disposition_to_match_codes(
disposition='not_found',
part_number='PN-1',
reservation_id='RSV-1',
)
assert match_result == 'not_found'
assert status == 'ready'
def test_missing_key_is_invalid_not_zero_stock():
"""缺料号/预约单 → invalid_key,不得当零库存。"""
match_result, status = map_disposition_to_match_codes(
disposition='not_found',
part_number='',
reservation_id='RSV-1',
)
assert match_result == 'invalid_key'
assert status == 'invalid_key'
def test_multi_file_conflict_maps_to_source_conflict():
"""多源冲突 → source_conflict。"""
match_result, status = map_disposition_to_match_codes(
disposition='multi_file_conflict',
part_number='PN-1',
reservation_id='RSV-1',
)
assert match_result == 'source_conflict'
assert status == 'source_conflict'
def test_ok_and_shortage_are_matched_ready():
"""ok/shortage 均为 ready+matched(数量差由投影比较)。"""
assert map_disposition_to_match_codes(
disposition='ok', part_number='A', reservation_id='B',
) == ('matched', 'ready')
assert map_disposition_to_match_codes(
disposition='shortage', part_number='A', reservation_id='B',
) == ('matched', 'ready')
@@ -0,0 +1,179 @@
"""
tests/test_line_inventory_match_projection.py
用途:锁定库存匹配投影契约——not_found→0、result_missing 不得转 0、动作分域。
依赖:pytest、line_inventory_match_projection。
逻辑:纯单元测试,不启 Flask 全应用。
"""
from __future__ import annotations
from app.services.shipping_notice.line_inventory_match_projection import (
ACTION_CLOSE,
ACTION_RETRY_MATCHING,
ACTION_RETRY_PREPARATION,
ACTION_VIEW_FULFILLMENT,
normalize_match_quantities,
project_line_inventory_view,
project_user_line_status,
resolve_inventory_allowed_actions,
resolve_line_allowed_actions,
)
def test_ready_not_found_normalizes_to_zero_shortage():
"""ready + not_found 必须规范为 available=0 并标短缺。"""
qty = normalize_match_quantities(
match_result='not_found',
inventory_status='ready',
required_qty='30',
available_qty=None,
)
assert qty['available_qty'] == '0'
assert qty['shortage_qty'] == '30'
assert qty['is_shortage'] is True
def test_ready_result_missing_must_not_become_zero():
"""ready + result_missing 不得转 0,也不能标短缺。"""
qty = normalize_match_quantities(
match_result='result_missing',
inventory_status='ready',
required_qty='30',
available_qty=None,
)
assert qty['available_qty'] is None
assert qty['shortage_qty'] is None
assert qty['is_shortage'] is False
assert qty['display_available'] == 'pending'
def test_preparing_keeps_null_quantities():
"""库存处理中:可用数量保持未知。"""
qty = normalize_match_quantities(
match_result='preparing',
inventory_status='preparing',
required_qty='30',
available_qty=None,
)
assert qty['available_qty'] is None
assert qty['is_shortage'] is False
def test_matched_compares_quantities():
"""matched 按实际数量比较短缺。"""
ok = normalize_match_quantities(
match_result='matched',
inventory_status='ready',
required_qty='30',
available_qty='50',
)
assert ok['is_shortage'] is False
assert ok['available_qty'] == '50'
short = normalize_match_quantities(
match_result='matched',
inventory_status='ready',
required_qty='30',
available_qty='10',
)
assert short['is_shortage'] is True
assert short['shortage_qty'] == '20'
def test_preparing_without_rpa_allows_retry_preparation():
"""文件未准备(非 RPA 运行中)可重试获取;关闭在 line 域。"""
inv = resolve_inventory_allowed_actions(
has_formal_ot=True,
inventory_status='preparing',
match_result='preparing',
is_shortage=False,
stored_line_status='pending_decision',
user_line_status='inventory_file_missing',
inventory_rpa_running=False,
)
line = resolve_line_allowed_actions(
has_formal_ot=True,
stored_line_status='pending_decision',
user_line_status='inventory_file_missing',
)
assert inv == [ACTION_RETRY_PREPARATION]
assert ACTION_CLOSE in line
assert ACTION_RETRY_MATCHING not in inv
def test_shortage_actions_preparation_and_close_only():
"""短缺:库存域仅 preparation;行域可关闭;禁止 wait/换源。"""
inv = resolve_inventory_allowed_actions(
has_formal_ot=True,
inventory_status='ready',
match_result='not_found',
is_shortage=True,
stored_line_status='pending_decision',
user_line_status='shortage',
)
line = resolve_line_allowed_actions(
has_formal_ot=True,
stored_line_status='pending_decision',
user_line_status='shortage',
)
assert inv == [ACTION_RETRY_PREPARATION]
assert line == [ACTION_CLOSE]
def test_wave_created_only_view_detail():
"""已入波次仅查看履约详情。"""
line = resolve_line_allowed_actions(
has_formal_ot=True,
stored_line_status='task_created',
user_line_status='wave_created',
)
inv = resolve_inventory_allowed_actions(
has_formal_ot=True,
inventory_status='ready',
match_result='matched',
is_shortage=False,
stored_line_status='task_created',
user_line_status='wave_created',
)
assert inv == []
assert line == [ACTION_VIEW_FULFILLMENT]
def test_result_missing_projects_file_missing_and_retry_prep():
"""结果缺失投影为文件未准备,开放重试获取,不当短缺。"""
view = project_line_inventory_view(
has_formal_ot=True,
fact={
'match_result': 'result_missing',
'inventory_status': 'ready',
'available_qty': None,
'inventory_snapshot_id': 9,
'matched_at': '2026-08-07T00:00:00',
},
required_qty='30',
stored_line_status='pending_decision',
decision_source=None,
can_fulfill_complete_line=False,
)
assert view['available_qty'] is None
assert view['is_shortage'] is False
assert view['user_line_status'] == 'inventory_file_missing'
assert ACTION_RETRY_PREPARATION in view['inventory_allowed_actions']
assert ACTION_CLOSE in view['line_allowed_actions']
def test_user_status_maps_closed_and_system_ready():
"""存储态关闭与系统 ready 投影为用户态。"""
assert project_user_line_status(
inventory_status='ready',
match_result='matched',
is_shortage=False,
stored_line_status='closed_unfulfillable',
) == 'closed'
assert project_user_line_status(
inventory_status='ready',
match_result='matched',
is_shortage=False,
stored_line_status='ready_to_fulfill',
decision_source='system',
) == 'auto_fulfilling'
@@ -0,0 +1,163 @@
"""
tests/test_post_ot_auto_fulfill_p1.py
用途:锁定 BE-4/5/6/7——ot_created 接线、补偿入口、无快照 fail-closed、单位匹配键、失败列。
依赖:pytest、unittest.mock。
逻辑:定向单测,不依赖真实排程 runner。
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
def test_persist_without_snapshot_forbids_ready_not_found(app):
"""BE-5:无 snapshot 时不得写入 ready/not_found。"""
from app.services.shipping_notice import line_inventory_match_persistence as svc
task = SimpleNamespace(id=1, inventory_snapshot_id=None)
added = []
with app.app_context():
with (
patch.object(svc, 'resolve_review_case_for_task', return_value=None),
patch.object(svc, '_draft_line_keys_by_index', return_value={0: 'L1'}),
patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q,
patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)),
patch.object(svc.db.session, 'flush'),
):
match_q.filter_by.return_value.filter.return_value.first.return_value = None
match_q.filter_by.return_value.update.return_value = None
match_q.filter_by.return_value.first.return_value = None
svc.persist_line_inventory_match_facts(
task=task,
inventory_snapshot_id=None,
match_payload={
'line_results': [{
'line_index': 0,
'disposition': 'not_found',
'part_number': 'PN1',
'reservation_id': 'R1',
'required_qty': 10,
'available_qty': 0,
'shortage_qty': 10,
}],
'resolutions': [],
},
)
assert len(added) == 1
assert added[0].match_result == 'result_missing'
assert added[0].inventory_status == 'unavailable'
assert added[0].available_qty is None
def test_unit_participates_in_match_key():
"""BE-6:同料号预约单但单位不同不得命中。"""
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
out = match_order_lines_across_candidates(
order_lines=[{
'part_number': 'PN-1',
'reservation_id': '12345',
'quantity': 2,
'uom': 'PCS',
}],
inventory_lines=[{
'reservation_id': '12345',
'part_number': 'PN-1',
'uom': 'BOX',
'qty': 100,
'__source_code': 'SRC1',
}],
header_reservation_id=None,
)
assert out['line_results'][0]['disposition'] == 'not_found'
out_ok = match_order_lines_across_candidates(
order_lines=[{
'part_number': 'PN-1',
'reservation_id': '12345',
'quantity': 2,
'uom': 'PCS',
}],
inventory_lines=[{
'reservation_id': '12345',
'part_number': 'PN-1',
'uom': 'PCS',
'qty': 100,
'__source_code': 'SRC1',
}],
header_reservation_id=None,
)
assert out_ok['line_results'][0]['disposition'] == 'ok'
assert out_ok['line_results'][0].get('unit') == 'PCS'
def test_compensation_runner_noops_when_flag_disabled(app, monkeypatch):
"""BE-4:flag 关闭时补偿扫描空跑。"""
from app.services.schedule import shipping_post_ot_auto_fulfill_compensation_job as job
monkeypatch.setattr(job, 'line_auto_fulfill_enabled', lambda: False)
with app.app_context():
result = job.run_post_ot_auto_fulfill_compensation(limit=10)
assert result['reason'] == 'line_auto_fulfill_disabled'
assert result['scanned'] == 0
def test_mark_auto_fulfill_failed_sets_fact_columns(app):
"""BE-7:失败写入匹配事实独立列,不新建 wait_inventory。"""
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
case = SimpleNamespace(id=1, case_no='RC-1', confirmed_task_id=9)
fact = SimpleNamespace(
detail_json={},
auto_fulfill_failed=False,
auto_fulfill_error_code=None,
auto_fulfill_error_message=None,
auto_fulfill_failed_at=None,
updated_at=None,
)
added = []
with app.app_context():
with (
patch.object(coord.ShippingNoticeLineInventoryMatch, 'query') as match_q,
patch.object(coord.ShippingOrderReviewLineDecision, 'query') as dec_q,
patch.object(coord.db.session, 'add', side_effect=lambda row: added.append(row)),
):
match_q.filter_by.return_value.first.return_value = fact
dec_q.filter_by.return_value.first.return_value = None
coord._mark_auto_fulfill_failed(
case,
line_keys=['L1'],
error_code='SHIPPING.AUTO_FULFILL_FAILED',
message='boom',
)
assert fact.auto_fulfill_failed is True
assert fact.auto_fulfill_error_code == 'SHIPPING.AUTO_FULFILL_FAILED'
assert added == []
def test_aggregate_line_fulfillment_counts_keeps_shortage_visible():
"""UI-3/BE:系统进度与短缺分列,失败单独计数。"""
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
_aggregate_line_fulfillment_counts,
)
counts = _aggregate_line_fulfillment_counts([
{'user_line_status': 'auto_fulfilling'},
{'user_line_status': 'wave_created'},
{'user_line_status': 'shortage', 'is_shortage': True},
{'user_line_status': 'inventory_pending'},
{'user_line_status': 'auto_fulfill_failed'},
])
assert counts['auto_progress_count'] == 2
assert counts['manual_pending_count'] == 1
assert counts['inventory_pending_count'] == 1
assert counts['system_failed_count'] == 1
@@ -0,0 +1,252 @@
"""
tests/test_post_ot_fulfillment_wave_p0.py
用途:锁定本轮 P0——整波失败回滚、幂等回放、参数冲突 409、post-OT 不调用 confirm 推进。
依赖:pytest、unittest.mock、ConflictError、post_ot / coordinator / progress 服务。
逻辑:以 mock 隔离 DB 与队列;断言事务边界与调度边界。
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from app.core.errors import ConflictError
def test_create_post_ot_wave_idempotent_replay_returns_original(app):
"""同 key 且参数一致必须返回原 wave,不二次建波。"""
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
existing = SimpleNamespace(
id=11,
decision_source='system',
line_keys_hash=svc._line_keys_hash(['L1']),
inventory_snapshot_fingerprint='9',
result_json={
'case_no': 'RC-1',
'task_no': 'SN-1',
'wave_no': 2,
'accepted_line_keys': ['L1'],
'skipped_line_keys': [],
},
)
case = SimpleNamespace(id=1, case_no='RC-1', run=None)
task = SimpleNamespace(id=7, task_no='SN-1')
with app.app_context():
with (
patch.object(svc.ShippingOrderReviewCase, 'query') as case_q,
patch.object(svc, 'assert_case_is_current_workflow_version'),
patch.object(svc, 'resolve_formal_ot', return_value={'has_formal_ot': True, 'task': task}),
patch.object(
svc,
'project_review_case_line_decisions',
return_value={
'lines': [{
'line_key': 'L1',
'inventory_status': 'ready',
'match_result': 'matched',
'is_shortage': False,
'required_qty': '10',
'available_qty': '10',
'inventory_snapshot_id': 9,
}],
},
),
patch.object(svc.ShippingOrderReviewWaveIdempotency, 'query') as idem_q,
):
case_q.filter_by.return_value.first.return_value = case
idem_q.filter_by.return_value.first.return_value = existing
out = svc.create_post_ot_fulfillment_wave(
case_no='RC-1',
line_keys=['L1'],
decision_source='system',
idempotency_key='k-replay',
)
assert out['idempotent_replay'] is True
assert out['wave_no'] == 2
assert out['idempotency_row_id'] == 11
def test_create_post_ot_wave_param_conflict_raises_409(app):
"""同 key 但 line_set/snapshot/source 不一致 → ConflictError(409)。"""
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
existing = SimpleNamespace(
id=11,
decision_source='system',
line_keys_hash=svc._line_keys_hash(['L1']),
inventory_snapshot_fingerprint='9',
result_json={},
)
case = SimpleNamespace(id=1, case_no='RC-1', run=None)
task = SimpleNamespace(id=7, task_no='SN-1')
with app.app_context():
with (
patch.object(svc.ShippingOrderReviewCase, 'query') as case_q,
patch.object(svc, 'assert_case_is_current_workflow_version'),
patch.object(svc, 'resolve_formal_ot', return_value={'has_formal_ot': True, 'task': task}),
patch.object(
svc,
'project_review_case_line_decisions',
return_value={
'lines': [{
'line_key': 'L1',
'inventory_status': 'ready',
'match_result': 'matched',
'is_shortage': False,
'required_qty': '10',
'available_qty': '10',
'inventory_snapshot_id': 99, # 与已存 fingerprint=9 冲突
}],
},
),
patch.object(svc.ShippingOrderReviewWaveIdempotency, 'query') as idem_q,
):
case_q.filter_by.return_value.first.return_value = case
idem_q.filter_by.return_value.first.return_value = existing
with pytest.raises(ConflictError) as ei:
svc.create_post_ot_fulfillment_wave(
case_no='RC-1',
line_keys=['L1'],
decision_source='system',
idempotency_key='k-conflict',
)
assert ei.value.http_status == 409
assert ei.value.code == 'SHIPPING.REVIEW_POST_OT_WAVE_IDEMPOTENCY_CONFLICT'
def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app):
"""整波失败必须 rollback,且失败标记不得创建 wait_inventory 半成品。"""
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
case = SimpleNamespace(id=3, case_no='RC-FAIL', confirmed_task_id=8)
calls: list[str] = []
def _boom(**_kwargs):
calls.append('create')
raise RuntimeError('wave_explode')
def _mark(case_obj, **kwargs):
calls.append('mark')
assert kwargs['line_keys'] == ['L1']
assert case_obj.case_no == 'RC-FAIL'
with app.app_context():
with (
patch.object(coord, 'line_auto_fulfill_enabled', return_value=True),
patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']),
patch.object(coord, 'create_post_ot_fulfillment_wave', side_effect=_boom),
patch.object(coord.db.session, 'rollback', side_effect=lambda: calls.append('rollback')),
patch.object(coord.db.session, 'flush', side_effect=lambda: calls.append('flush')),
patch.object(coord.ShippingOrderReviewCase, 'query') as case_q,
patch.object(coord, '_mark_auto_fulfill_failed', side_effect=_mark),
patch.object(coord, 'schedule_post_ot_wave_progress') as schedule_mock,
):
case_q.filter_by.return_value.first.return_value = case
out = coord.coordinate_post_ot_auto_fulfill(case=case, trigger='inventory_ready')
assert out['status'] == 'failed'
assert calls == ['create', 'rollback', 'mark', 'flush']
schedule_mock.assert_not_called()
def test_mark_auto_fulfill_failed_does_not_create_wait_inventory(app):
"""无活动决定时只写匹配事实 detail,不新建 wait_inventory 决定。"""
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
case = SimpleNamespace(id=4, case_no='RC-2', confirmed_task_id=12)
fact = SimpleNamespace(detail_json={}, updated_at=None)
added: list = []
with app.app_context():
with (
patch.object(coord.ShippingNoticeLineInventoryMatch, 'query') as match_q,
patch.object(coord.ShippingOrderReviewLineDecision, 'query') as dec_q,
patch.object(coord.db.session, 'add', side_effect=lambda row: added.append(row)),
):
match_q.filter_by.return_value.first.return_value = fact
dec_q.filter_by.return_value.first.return_value = None
coord._mark_auto_fulfill_failed(
case,
line_keys=['L9'],
error_code='SHIPPING.AUTO_FULFILL_FAILED',
message='boom',
)
assert fact.detail_json.get('auto_fulfill_failed') is True
assert added == []
def test_post_ot_api_does_not_call_confirm_auto_progress(app, monkeypatch):
"""正式 OT 的 wave API 必须走 schedule_post_ot_wave_progress,禁止 confirm 推进。"""
from app.api.workspace import shipping_notice as api
calls: dict[str, int] = {'confirm': 0, 'post': 0}
def _fake_create(**kwargs):
return {
'task_no': 'SN-9',
'wave_no': 3,
'accepted_line_keys': ['L1'],
'review_case_id': 1,
'idempotency_row_id': 5,
'idempotency_key': 'k1',
'line_fulfillment': {'lines': []},
}
def _fake_post(**kwargs):
calls['post'] += 1
return {'auto_progress_started': True, 'status': 'queued', 'wave_no': 3}
def _fake_confirm(**kwargs):
calls['confirm'] += 1
raise AssertionError('must not call schedule_auto_progress_after_review_confirm')
user = SimpleNamespace(id=1)
case = SimpleNamespace(id=1, case_no='RC-9')
with app.app_context():
with app.test_request_context(
'/api/workspace/shipping-notice/order-review-cases/RC-9/line-fulfillment/wave',
method='POST',
json={'line_keys': ['L1'], 'idempotency_key': 'k1'},
):
monkeypatch.setattr(api, '_require_user', lambda: user)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_draft_service.soft_load_review_case_for_audit',
lambda **_k: case,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
lambda _c: {'has_formal_ot': True, 'task': SimpleNamespace(task_no='SN-9')},
)
monkeypatch.setattr(
'app.services.shipping_notice.post_ot_fulfillment_wave_service.create_post_ot_fulfillment_wave',
_fake_create,
)
monkeypatch.setattr(
'app.services.shipping_notice.post_ot_wave_progress_service.schedule_post_ot_wave_progress',
_fake_post,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_confirmation_service.schedule_auto_progress_after_review_confirm',
_fake_confirm,
)
monkeypatch.setattr(api.db.session, 'commit', lambda: None)
monkeypatch.setattr(api, '_ok', lambda data: data)
out = api.workspace_create_shipping_order_review_fulfillment_wave('RC-9')
assert calls['post'] == 1
assert calls['confirm'] == 0
assert out['post_ot_wave'] is True
assert out['wave_progress']['wave_no'] == 3
@@ -0,0 +1,87 @@
"""
backend/tests/test_shipping_document_layout_diagnostics.py
用途:验证 Layout Job PR-0 脱敏 timings/counts 契约与 OCR 计时拆分。
依赖:layout_diagnostics、ocr_pdf、unittest.mock。
逻辑:覆盖全键初始化、freeze 规范化、extract_ocr_lines 推理计数,以及诊断字段不进入快照的断言辅助。
"""
from __future__ import annotations
from unittest.mock import patch
import numpy as np
from app.services.shipping_notice.document_layout.layout_diagnostics import (
LAYOUT_DIAGNOSTIC_COUNT_KEYS,
LAYOUT_DIAGNOSTIC_TIMING_KEYS,
LayoutJobDiagnostics,
empty_layout_counts,
empty_layout_timings,
freeze_layout_diagnostics,
)
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
def test_empty_diagnostics_contain_full_contract_keys():
"""PR-0 初始化必须保证全部 timing/count 键存在,未执行阶段为 0。"""
timings = empty_layout_timings()
counts = empty_layout_counts()
assert set(timings) >= set(LAYOUT_DIAGNOSTIC_TIMING_KEYS)
assert set(counts) >= set(LAYOUT_DIAGNOSTIC_COUNT_KEYS)
assert all(timings[key] == 0 for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS)
assert counts['ocr_engine_warm'] is False
assert all(counts[key] == 0 for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS if key != 'ocr_engine_warm')
def test_freeze_layout_diagnostics_normalizes_types_and_keeps_extra_timing():
"""freeze 输出 int/bool,并保留额外 timing 键供降级路径兼容。"""
timings = empty_layout_timings()
counts = empty_layout_counts()
timings['native_layout_build_ms'] = 12.7
timings['native_table_detect_ms'] = 3
counts['ocr_call_count'] = 2
counts['ocr_engine_warm'] = 1
frozen_timings, frozen_counts = freeze_layout_diagnostics(timings, counts)
assert frozen_timings['native_layout_build_ms'] == 12
assert frozen_timings['native_table_detect_ms'] == 3
assert frozen_counts['ocr_call_count'] == 2
assert frozen_counts['ocr_engine_warm'] is True
def test_extract_ocr_lines_records_inference_without_changing_lines():
"""传入 diagnostics 时必须增加 ocr_call_count,且行坐标结果与无诊断调用一致。"""
image = np.zeros((200, 400, 3), dtype=np.uint8)
response = [
[[[40, 20], [120, 20], [120, 60], [40, 60]], 'Part', 0.95],
]
diagnostics = LayoutJobDiagnostics()
with patch('app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine') as engine:
engine.return_value.return_value = (response, 0.1)
# mock 无 cache_info 时不得把调用计为 engine init
lines_with = extract_ocr_lines(
image, page_width=200, page_height=100,
diagnostics=diagnostics, page_no=1,
)
lines_without = extract_ocr_lines(image, page_width=200, page_height=100)
assert lines_with[0].text == lines_without[0].text
assert lines_with[0].bbox.model_dump() == lines_without[0].bbox.model_dump()
assert diagnostics.counts['ocr_call_count'] == 1
assert diagnostics.counts['ocr_page_count'] == 1
assert diagnostics.timings['ocr_engine_init_ms'] == 0
assert diagnostics.timings['ocr_inference_ms'] >= 0
def test_snapshot_must_not_embed_diagnostics_keys():
"""回归辅助:正式 snapshot 不得出现 timings/counts 诊断字段。"""
snapshot = {
'status': 'ready',
'tables': [],
'layout_candidate': {'pages': []},
'coordinate_evidence': {'tables': {}, 'pages': {}},
}
assert 'timings' not in snapshot
assert 'counts' not in snapshot
assert 'timings' not in snapshot['layout_candidate']
assert 'counts' not in snapshot['coordinate_evidence']
@@ -2,8 +2,9 @@
backend/tests/test_shipping_document_layout_job.py
用途:验证独立布局 Job 从对象存储读取附件、按 lease 收口并在失败时同步版本状态。
依赖:shipping_document_layout handler、lifecycle、通用 Job queue。
逻辑:构造 queued 版本后模拟 Worker claim;成功更新 current,失败重排不得留下 running lease。
依赖:shipping_document_layout handler、lifecycle、layout_diagnostics、通用 Job queue。
逻辑:构造 queued 版本后模拟 Worker claim;成功更新 current,失败重排不得留下 running lease;
PR-0 断言 Job result 含全量 timings/counts,且诊断字段不进入 layout snapshot。
"""
from __future__ import annotations
@@ -16,10 +17,37 @@ from app import db
from app.jobs.context import JobContext
from app.jobs.handlers.shipping_document_layout import LAYOUT_JOB_ERROR, run_shipping_document_layout
from app.models import Job
from app.services.shipping_notice.document_layout.layout_diagnostics import (
LAYOUT_DIAGNOSTIC_COUNT_KEYS,
LAYOUT_DIAGNOSTIC_TIMING_KEYS,
)
from app.services.shipping_notice.document_layout.lifecycle import schedule_layout_version
from tests.test_shipping_document_layout_lifecycle import _document, _snapshot
def _assert_layout_job_diagnostics_contract(result: dict) -> None:
"""
断言 Job result 含 PR-0 全量 timings/counts,且诊断字段不进 snapshot。
核心断言:契约键齐全;未执行阶段为 0;ocr_engine_warm 为 bool。
"""
timings = result.get('timings')
counts = result.get('counts')
assert isinstance(timings, dict)
assert isinstance(counts, dict)
for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS:
assert key in timings
assert isinstance(timings[key], int)
assert timings[key] >= 0
for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS:
assert key in counts
if key == 'ocr_engine_warm':
assert isinstance(counts[key], bool)
else:
assert isinstance(counts[key], int)
assert counts[key] >= 0
def _running_layout_job(app):
"""创建布局版本并模拟通用队列已领取该 Job。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
@@ -59,6 +87,9 @@ def test_layout_job_completes_version_and_updates_document_current(app):
assert job.result_json['status'] == 'ready'
assert job.result_json['provider_status'] == 'ready'
assert job.message == '文档版面解析完成'
_assert_layout_job_diagnostics_contract(job.result_json)
assert 'timings' not in version.payload_json
assert 'counts' not in version.payload_json
def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
@@ -182,6 +213,12 @@ def test_layout_job_xfa_hybrid_skips_mineru_path(app):
assert version.payload_json['xfa_capability']['structure_analysis_ready'] is True
assert document.current_layout_version_id == version.id
assert job.status == 'success'
_assert_layout_job_diagnostics_contract(job.result_json)
# XFA 早退未走 OCR/OpenCV;细分字段仍存在且为 0。
assert job.result_json['counts']['ocr_call_count'] == 0
assert job.result_json['timings']['ocr_inference_ms'] == 0
assert 'timings' not in version.payload_json
assert 'counts' not in version.payload_json
def test_runtime_xfa_probe_skips_mineru_for_hybrid(app):
@@ -23,6 +23,7 @@ from app.services.shipping_notice.document_layout.mineru import (
)
from app.services.shipping_notice.document_layout.native_pdf import (
NativePdfPage,
attach_native_pdf_page_images,
build_native_pdf_layout_candidate,
build_native_pdf_text_table_fallbacks,
extract_native_pdf_pages,
@@ -76,6 +77,44 @@ def _page(text: str) -> NativePdfPage:
)
def test_attach_native_pdf_page_images_renders_only_missing_pages():
"""PR-2:已有 image 的页不得重渲染;缺图页补齐后字符层保持原引用。"""
writer = PdfWriter()
writer.add_blank_page(width=200, height=100)
writer.add_blank_page(width=200, height=100)
buffer = BytesIO()
writer.write(buffer)
content = buffer.getvalue()
chars_a = [
PositionedCharacter(
text='A', source_index=0, bbox=LayoutBBox(x0=1, y0=1, x1=2, y1=2),
),
]
chars_b = [
PositionedCharacter(
text='B', source_index=0, bbox=LayoutBBox(x0=1, y0=1, x1=2, y1=2),
),
]
existing = np.full((20, 40), 7, dtype=np.uint8)
pages = [
NativePdfPage(
page_no=1, width=200, height=100, rotation=0,
characters=chars_a, image=existing,
),
NativePdfPage(
page_no=2, width=200, height=100, rotation=0,
characters=chars_b, image=None,
),
]
attached = attach_native_pdf_page_images(content, pages, render_scale=1.0)
assert attached[0].image is existing
assert attached[0].characters is chars_a
assert attached[1].image is not None
assert attached[1].image.shape[0] > 0
assert attached[1].characters is chars_b
def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
"""PDFium 空格即使没有 bbox,也必须成为下一可见字符的可靠边界并保留原始序号。"""
class FakeTextPage:
@@ -232,7 +271,7 @@ def test_native_pdf_repeated_text_does_not_create_cells():
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
return_value=[_page('QtyQty')],
), patch(
'app.services.shipping_notice.document_layout.native_pdf.reconstruct_opencv_table_geometry',
'app.services.shipping_notice.document_layout.native_pdf.cached_reconstruct_opencv_table_geometry',
) as opencv:
opencv.return_value.ready = False
opencv.return_value.issues = ['opencv_table_grid_not_detected']
@@ -351,8 +390,14 @@ def test_scanned_pdf_uses_ocr_tokens_only_after_grid_evidence():
evidence = OcrTableEvidence(
ready=True,
lines=[
OcrLine(text='Part', bbox=LayoutBBox(x0=10, y0=10, x1=60, y1=30), confidence=.99),
OcrLine(text='Qty', bbox=LayoutBBox(x0=110, y0=10, x1=150, y1=30), confidence=.98),
OcrLine(
text='Part', bbox=LayoutBBox(x0=10, y0=10, x1=60, y1=30), confidence=.99,
line_id='ocr-line-0', image_width=400, image_height=200,
),
OcrLine(
text='Qty', bbox=LayoutBBox(x0=110, y0=10, x1=150, y1=30), confidence=.98,
line_id='ocr-line-1', image_width=400, image_height=200,
),
],
cells=[
OcrCellEvidence(
@@ -369,7 +414,7 @@ def test_scanned_pdf_uses_ocr_tokens_only_after_grid_evidence():
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
return_value=[page],
), patch(
'app.services.shipping_notice.document_layout.native_pdf.reconstruct_opencv_table_geometry',
'app.services.shipping_notice.document_layout.native_pdf.cached_reconstruct_opencv_table_geometry',
) as geometry, patch(
'app.services.shipping_notice.document_layout.native_pdf.validate_opencv_cell_text',
) as validation, patch(
@@ -14,10 +14,13 @@ import numpy as np
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.layout_diagnostics import LayoutJobDiagnostics
from app.services.shipping_notice.document_layout.ocr_pdf import (
OcrLine,
build_ocr_table_evidence,
extract_ocr_lines,
extract_table_crop_ocr_lines,
get_page_ocr_lines,
page_bbox_to_normalized,
)
from app.services.shipping_notice.document_layout.opencv_table import (
@@ -91,9 +94,12 @@ def test_ocr_table_requires_geometry_and_all_cell_text():
_ocr_line('Qty', LayoutBBox(x0=120, y0=10, x1=150, y1=30), .98, index=1),
]
with patch(
'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines', return_value=lines,
'app.services.shipping_notice.document_layout.ocr_pdf.get_page_ocr_lines', return_value=lines,
), patch(
'app.services.shipping_notice.document_layout.ocr_pdf.reconstruct_opencv_table_geometry',
'app.services.shipping_notice.document_layout.ocr_pdf.layout_ocr_crop_enabled',
return_value=False,
), patch(
'app.services.shipping_notice.document_layout.ocr_pdf.cached_reconstruct_opencv_table_geometry',
return_value=geometry,
):
result = build_ocr_table_evidence(
@@ -107,11 +113,12 @@ def test_ocr_table_requires_geometry_and_all_cell_text():
assert all(item.normalized_bbox is not None for item in result.cells)
def test_ocr_engine_failure_is_safe_unsupported_candidate():
def test_ocr_engine_failure_is_safe_unsupported_candidate(app):
"""OCR 引擎缺失或异常必须返回机器问题码,不得抛出或生成 cell。"""
app.config['SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED'] = False
grid = parse_html_grid('<table><tr><td>A</td></tr></table>', table_id='fail')
with patch(
'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines',
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.ocr_pdf.get_page_ocr_lines',
side_effect=RuntimeError('model missing'),
):
result = build_ocr_table_evidence(
@@ -122,3 +129,75 @@ def test_ocr_engine_failure_is_safe_unsupported_candidate():
assert result.ready is False
assert result.cells == []
assert result.issues == ['ocr_engine_unavailable']
def test_page_ocr_cache_reuses_lines_within_same_job(app):
"""同一 Job 同页二次 OCR 必须命中缓存,只推理一次。"""
app.config['SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED'] = True
image = np.zeros((200, 400, 3), dtype=np.uint8)
response = [[[[40, 20], [120, 20], [120, 60], [40, 60]], 'Part', 0.95]]
diagnostics = LayoutJobDiagnostics()
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine',
) as engine:
engine.return_value.return_value = (response, 0.1)
first = get_page_ocr_lines(
image, page_width=200, page_height=100, diagnostics=diagnostics, page_no=1,
)
second = get_page_ocr_lines(
image, page_width=200, page_height=100, diagnostics=diagnostics, page_no=1,
)
assert first[0].text == second[0].text == 'Part'
assert diagnostics.counts['ocr_call_count'] == 1
assert diagnostics.counts['ocr_page_cache_miss'] == 1
assert diagnostics.counts['ocr_page_cache_hit'] == 1
assert engine.return_value.call_count == 1
def test_page_ocr_cache_disabled_always_infers(app):
"""关闭页面缓存时,同页多次调用必须重复推理。"""
app.config['SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED'] = False
image = np.zeros((200, 400, 3), dtype=np.uint8)
response = [[[[40, 20], [120, 20], [120, 60], [40, 60]], 'Part', 0.95]]
diagnostics = LayoutJobDiagnostics()
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine',
) as engine:
engine.return_value.return_value = (response, 0.1)
get_page_ocr_lines(
image, page_width=200, page_height=100, diagnostics=diagnostics, page_no=1,
)
get_page_ocr_lines(
image, page_width=200, page_height=100, diagnostics=diagnostics, page_no=1,
)
assert diagnostics.counts['ocr_call_count'] == 2
assert diagnostics.counts['ocr_page_cache_hit'] == 0
assert engine.return_value.call_count == 2
def test_table_crop_ocr_maps_coordinates_back_to_page(app, monkeypatch):
"""裁剪 OCR 必须把 crop 像素原点加回整页后再换算页面坐标。"""
app.config['SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED'] = True
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.ocr_pdf._ocr_crop_margin_ratio',
lambda: 0.0,
)
image = np.zeros((100, 200, 3), dtype=np.uint8)
# 表格区域 [100,0]-[200,50] 页面坐标 → 像素 [100,0]-[200,50]
table_bbox = LayoutBBox(x0=100, y0=0, x1=200, y1=50)
# crop 内相对多边形
response = [[[[10, 10], [40, 10], [40, 30], [10, 30]], 'SKU', 0.99]]
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine',
) as engine:
engine.return_value.return_value = (response, 0.05)
lines = extract_table_crop_ocr_lines(
image, page_width=200, page_height=100, table_bbox=table_bbox, page_no=1,
)
assert len(lines) == 1
assert lines[0].text == 'SKU'
# origin_x=100 → 页面 x = (10+100)*200/200 = 110
assert lines[0].bbox.model_dump() == {'x0': 110.0, 'y0': 10.0, 'x1': 140.0, 'y1': 30.0}
@@ -14,8 +14,10 @@ import pytest
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.layout_diagnostics import LayoutJobDiagnostics
from app.services.shipping_notice.document_layout.opencv_table import (
DEFAULT_GRID_CONFIGS,
cached_reconstruct_opencv_table_geometry,
reconstruct_opencv_table_geometry,
validate_opencv_cell_text,
)
@@ -205,6 +207,28 @@ def test_opencv_text_validation_rejects_required_cell_mismatch_even_above_rate()
assert 'opencv_table_required_cell_text_mismatch' in result.issues
def test_cached_opencv_geometry_hits_within_same_job():
"""同 Job 二次同表几何重建必须命中缓存,且 ready 结果不变。"""
grid = parse_html_grid(
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
table_id='cache',
)
image = _page_with_grid(rows=2, columns=2)
diagnostics = LayoutJobDiagnostics()
first = cached_reconstruct_opencv_table_geometry(
image, page_width=600, page_height=400, table_bbox=_bbox(), grid=grid,
diagnostics=diagnostics, page_no=1,
)
second = cached_reconstruct_opencv_table_geometry(
image, page_width=600, page_height=400, table_bbox=_bbox(), grid=grid,
diagnostics=diagnostics, page_no=1,
)
assert first.ready is True
assert second is first
assert diagnostics.counts['opencv_geometry_cache_miss'] == 1
assert diagnostics.counts['opencv_geometry_cache_hit'] == 1
def test_opencv_text_validation_rejects_low_overall_match_rate():
"""非高风险 cell 大量错位也必须因整表一致率不足而拒绝。"""
grid = parse_html_grid(
@@ -37,30 +37,59 @@ def test_resolve_confirm_outcome_distinguishes_progress_failure():
def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monkeypatch):
"""已确认且任务仍 created+Extraction 时,投影需 needs_retry 供前端刷新恢复。"""
"""Job success 但 OT 仍 created 时,投影 needs_retry 供前端刷新恢复。"""
from types import SimpleNamespace as NS
from app.services.shipping_notice import order_review_projection as projection
from app.services.shipping_notice import order_review_workbench_projection as workbench
case = MagicMock(status='confirmed', confirmed_task_id=9)
stuck = MagicMock(task_no='SN-STUCK-1', process_status='created', current_order_extraction_id=3)
finished = NS(
id=55,
status='success',
attempts=1,
max_attempts=3,
result_json={},
error_message=None,
finished_at=None,
)
with app.app_context():
monkeypatch.setattr(projection.db.session, 'get', lambda model, pk: stuck)
monkeypatch.setattr(
workbench,
'resolve_formal_ot',
lambda _case: {
'has_formal_ot': True,
'task_missing': False,
'task': stuck,
'task_no': 'SN-STUCK-1',
'task_id': 9,
},
)
monkeypatch.setattr(workbench, 'find_active_shipping_notice_run_job', lambda **_k: None)
monkeypatch.setattr(workbench, 'find_latest_shipping_notice_run_job', lambda **_k: finished)
summary = projection._project_post_confirm_auto_progress(case)
# 关键断言:刷新后可据此恢复琥珀色重试入口。
# 关键断言:刷新后可据此恢复琥珀色重试入口,且保留成功 Job 身份。
assert summary is not None
assert summary['task_no'] == 'SN-STUCK-1'
assert summary['needs_retry'] is True
assert summary['status'] == 'needs_retry'
assert summary['job_id'] == 55
assert summary['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced'
def test_task_needs_post_confirm_auto_progress_requires_created_with_extraction():
"""仅 created 且已挂 Extraction 的任务需要确认后补推。"""
def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction():
"""created/parsed 且已挂 Extraction 的任务需要确认后补推。"""
stuck = MagicMock(
process_status='created',
current_order_extraction_id=12,
)
parsed = MagicMock(
process_status='parsed',
current_order_extraction_id=12,
)
progressed = MagicMock(
process_status='waiting_upload',
current_order_extraction_id=12,
@@ -70,6 +99,7 @@ def test_task_needs_post_confirm_auto_progress_requires_created_with_extraction(
current_order_extraction_id=None,
)
assert _task_needs_post_confirm_auto_progress(stuck) is True
assert _task_needs_post_confirm_auto_progress(parsed) is True
assert _task_needs_post_confirm_auto_progress(progressed) is False
assert _task_needs_post_confirm_auto_progress(shell) is False
assert _task_needs_post_confirm_auto_progress(None) is False
@@ -113,6 +143,42 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
assert db.session.get(Job, job_id) is None
def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypatch):
"""确认后 process_status=parsed 仍须入队(CONFIRM_PARSE 后常见态)。"""
with app.app_context():
task = ShippingNotice(
task_no='SN-CONFIRM-AP-PARSED',
user_id=1,
process_status='parsed',
current_order_extraction_id=99,
)
db.session.add(task)
db.session.flush()
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker')
schedule = schedule_auto_progress_after_review_confirm(
task_no=task.task_no,
idempotent_replay=False,
created_by_id=1,
commit=False,
)
assert schedule is not None
assert schedule.get('auto_progress_started') is True
job = (
db.session.query(Job)
.filter(
Job.domain == SHIPPING_NOTICE_JOB_DOMAIN,
Job.job_type == JobType.SHIPPING_NOTICE_RUN.value,
Job.business_ref == task.task_no,
Job.status == 'queued',
)
.one()
)
assert int(job.id) > 0
db.session.rollback()
def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkeypatch):
"""幂等回放在任务仍悬挂于 created 时必须补推,不能无条件跳过。"""
with app.app_context():
@@ -221,20 +287,18 @@ def test_finalize_sync_auto_progress_swallows_execution_errors():
def test_run_single_task_auto_progresses_created_task_with_extraction(app, monkeypatch):
"""复核确认后的 created+Extraction 任务必须由编排器调用 auto_progress。"""
from app.models import ShippingBatch
from app.services.shipping_notice import batch_orchestrator
with app.app_context():
batch = ShippingBatch(batch_no='SB-CONFIRM-AP', file_count=1)
# ShippingBatch 已物理下线;仅用 ShippingNotice 表达确认建单后的悬挂态。
task = ShippingNotice(
task_no='SN-CONFIRM-AP-4',
batch=batch,
user_id=1,
source_type='review_confirmation',
process_status='created',
current_order_extraction_id=66,
)
db.session.add_all([batch, task])
db.session.add(task)
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
@@ -0,0 +1,309 @@
"""
tests/test_shipping_review_workbench_stage_layering.py
用途:锁定复核工作台正式 OT 后状态分层——Gate 清除、automation phase、
field_completeness、completed_checks、profile_match 四态、
part_number(内部料号 / Schema field_id)与 reservation 分离。
依赖:pytest、order_review_workbench_projection、types.SimpleNamespace。
逻辑:纯单元测试;断言关键契约,不启 Flask 全应用。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.order_review_workbench_projection import (
apply_post_ot_gate_rules,
assert_part_number_not_reservation,
enrich_automation_status,
extract_line_part_number,
extract_line_required_qty,
map_profile_match_user_status,
project_completed_checks,
project_field_completeness,
project_stage_for_task,
project_user_profile_match,
sanitize_part_number_vs_reservation,
)
def test_profile_match_unknown_not_collapsed_to_unmatched():
"""unknown / 无结论不得伪装成 unmatched。"""
assert map_profile_match_user_status('unknown') == 'unknown'
assert map_profile_match_user_status('needs_review', candidates=[], needs_review=True) == 'unknown'
assert map_profile_match_user_status('needs_review', candidates=[{'x': 1}], needs_review=True) == 'ambiguous'
assert map_profile_match_user_status('matched') == 'matched'
assert map_profile_match_user_status('not_matched') == 'unmatched'
def test_user_profile_match_strips_admin_fields():
"""普通用户不得看到候选分 / Profile code。"""
payload = project_user_profile_match({
'available': True,
'status': 'matched',
'needs_review': False,
'candidates': [{'profile_code': 'P1', 'score': 0.9}],
'selected_profile': {'profile_code': 'P1', 'display_name': '模板A', 'checksum': 'abc'},
'fallback_reason_codes': ['x'],
})
assert payload['status'] == 'matched'
assert payload['candidates'] == []
assert payload['fallback_reason_codes'] == []
assert payload['selected_profile'] == {'display_name': '模板A'}
def test_field_completeness_ready_after_formal_ot():
"""正式 OT 后 field_completeness 强制 ready,issues 清空。"""
blocked = project_field_completeness(
validation={
'issues': [{'code': 'required_field_missing', 'field_code': 'part_number'}],
'failed_gates': ['field_completeness'],
},
has_formal_ot=False,
)
assert blocked['status'] == 'blocked'
assert blocked['issues']
ready = project_field_completeness(
validation={
'issues': [{'code': 'required_field_missing', 'field_code': 'part_number'}],
'failed_gates': ['field_completeness'],
},
has_formal_ot=True,
)
assert ready['status'] == 'ready'
assert ready['issues'] == []
def test_completed_checks_include_formal_ot_milestone():
"""正式 OT 里程碑进入 completed_checks。"""
case = SimpleNamespace(updated_at=None)
checks = project_completed_checks(
case=case,
process_gate={
'gates_track': [
{'gate_code': 'field_completeness', 'status': 'passed'},
{'gate_code': 'customer_resolution', 'status': 'passed'},
],
},
customer_resolution={'resolved': True},
duplicate={'needs_adjudication': False},
field_conflicts=[],
field_completeness={'status': 'ready'},
profile_match={'status': 'matched'},
formal_ot={'has_formal_ot': True, 'task': SimpleNamespace(created_at=None)},
)
codes = {item['code'] for item in checks}
assert 'formal_ot_created' in codes
assert 'field_completeness' in codes
assert 'order_review_completed' in codes
def test_post_ot_clears_pre_ot_blocking_gate():
"""正式 OT 后建单前 Gate 不得成为当前阻断。"""
summary = apply_post_ot_gate_rules(
{
'current_blocking_gate': {
'gate_code': 'field_completeness',
'status': 'blocked_manual',
},
'next_action_code': 'edit_order_fields',
'technical_auto_only': False,
'blocking_reason_code': 'required_field_missing',
'blocking_message': '缺字段',
},
has_formal_ot=True,
)
assert summary['current_blocking_gate'] is None
assert summary['technical_auto_only'] is True
assert summary['owner_type'] == 'system'
def test_inventory_preparation_is_system_wait_not_human_blocker():
"""库存准备 Worker 等待不得冒充人工待办。"""
summary = apply_post_ot_gate_rules(
{
'current_blocking_gate': {
'gate_code': 'inventory_preparation',
'status': 'waiting_external',
},
'next_action_code': 'poll_inventory_preparation',
'technical_auto_only': False,
},
has_formal_ot=True,
)
assert summary['current_blocking_gate'] is None
assert summary['technical_auto_only'] is True
assert summary['owner_type'] == 'system'
def test_human_inventory_gate_kept_after_ot():
"""正式 OT 后人工库存阻断可保留。"""
summary = apply_post_ot_gate_rules(
{
'current_blocking_gate': {
'gate_code': 'inventory_sufficiency',
'status': 'blocked_manual',
},
'next_action_code': 'submit_fulfillment_decision',
'technical_auto_only': False,
},
has_formal_ot=True,
)
assert summary['current_blocking_gate']['gate_code'] == 'inventory_sufficiency'
assert summary['owner_type'] == 'human'
assert summary['technical_auto_only'] is False
def test_automation_phase_post_ot_waiting_to_start():
"""正式 OT 后无 Job → waiting_to_start + phase=post_ot_progress。"""
result = enrich_automation_status(
{'status': 'idle', 'job_id': None},
formal_ot={'has_formal_ot': True, 'task_missing': False, 'task_no': 'OT-1'},
is_admin=True,
)
assert result['phase'] == 'post_ot_progress'
assert result['status'] == 'waiting_to_start'
assert result['owner_type'] == 'system'
assert result['technical']['enqueue_status'] == 'no_job'
def test_task_missing_does_not_reopen_confirm():
"""task_missing 标记 failed,不可重试伪装建单。"""
result = enrich_automation_status(
{'status': 'idle'},
formal_ot={'has_formal_ot': False, 'task_missing': True, 'task_id': 9},
is_admin=True,
)
assert result['status'] == 'failed'
assert result['retryable'] is False
assert result['reason_code'] == 'task_missing'
def test_project_stage_for_task_created_is_order_creating():
"""正式 OT 仍为 created 时阶段统一为 order_creating,label_key=waiting_system_start。"""
task = SimpleNamespace(
id=1,
order_task_id=None,
process_status='created',
current_step=None,
stage_nodes_json=None,
step_payload_json=None,
)
stage = project_stage_for_task(task)
assert stage['code'] == 'order_creating'
assert stage['label_key'] == 'waiting_system_start'
assert stage['source'] == 'process_status'
def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch):
"""Job success + OT 仍 created → failed/retryable,保留 job_id,不得伪装 waiting。"""
from types import SimpleNamespace as NS
from app.services.shipping_notice import order_review_workbench_projection as mod
from app.services.shipping_notice.order_review_workbench_projection import (
project_post_ot_automation_from_job,
)
task = NS(
task_no='SN-HANG-1',
process_status='created',
current_order_extraction_id=9,
)
finished = NS(
id=77,
status='success',
attempts=1,
max_attempts=3,
result_json={},
error_message=None,
finished_at=None,
)
monkeypatch.setattr(mod, 'find_active_shipping_notice_run_job', lambda **_k: None)
monkeypatch.setattr(mod, 'find_latest_shipping_notice_run_job', lambda **_k: finished)
auto = project_post_ot_automation_from_job(task)
assert auto['status'] == 'failed'
assert auto['retryable'] is True
assert auto['needs_retry'] is True
assert auto['job_id'] == 77
assert auto['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced'
assert auto['attempts'] == 1
def test_project_stage_for_task_without_ot_is_order_review():
"""无正式 OT 时右侧阶段固定 order_review。"""
stage = project_stage_for_task(None, default_code='order_review')
assert stage['code'] == 'order_review'
def test_sanitize_part_number_fail_closed():
"""生产投影串位时丢弃料号。"""
assert sanitize_part_number_vs_reservation(part_number='A', reservation_id='B') == 'A'
assert sanitize_part_number_vs_reservation(part_number='SAME', reservation_id='SAME') is None
def test_part_number_never_falls_back_to_reservation():
"""料号不得回退为预约单号。"""
part = extract_line_part_number(
{'reservation_id': 'RSV-1', 'part_number': 'RSV-1'},
{'effective_reservation_id': 'RSV-1'},
)
assert part is None
part2 = extract_line_part_number(
{'reservation_id': 'RSV-1', 'part_number': '2000484577'},
{},
)
assert part2 == '2000484577'
assert_part_number_not_reservation(part_number='A', reservation_id='B')
try:
assert_part_number_not_reservation(part_number='SAME', reservation_id='SAME')
raised = False
except AssertionError:
raised = True
assert raised
def test_part_number_resolves_from_schema_field_id_values():
"""内部料号在 values[field_id] 时须解析为履约表料号,且不等于预约单号。"""
part_field_id = 'fld-part-uuid-001'
qty_field_id = 'fld-qty-uuid-002'
schema_fields = {
part_field_id: {
'field_id': part_field_id,
'field_code': 'part_number',
'scope': 'line',
'display_name': '内部料号',
},
qty_field_id: {
'field_id': qty_field_id,
'field_code': 'qty',
'scope': 'line',
'display_name': '数量',
},
}
draft_line = {
'line_key': 'L1',
'reservation_id': '2000484577',
'values': {
part_field_id: {'value': 'PN-INTERNAL-88', 'source': 'manual'},
qty_field_id: {'value': '12', 'source': 'machine'},
},
'machine_fields': [],
}
# 无 Schema 时 UUID key 无法猜出料号
assert extract_line_part_number(draft_line, {}) is None
# 有 Schema 时与订单明细内部料号一致
part = extract_line_part_number(draft_line, {}, schema_fields=schema_fields)
assert part == 'PN-INTERNAL-88'
assert part != '2000484577'
qty = extract_line_required_qty(draft_line, {}, schema_fields=schema_fields)
assert str(qty) == '12'
# 料号若误存为预约单号则丢弃
bad = {
**draft_line,
'values': {
part_field_id: {'value': '2000484577', 'source': 'manual'},
},
}
assert extract_line_part_number(bad, {}, schema_fields=schema_fields) is None
@@ -89,7 +89,7 @@ def test_automation_failed_retryable_when_post_confirm_needs_retry():
def test_serialize_review_case_hides_profile_match_for_non_admin():
"""普通用户不得收到模板 ID / 候选分;仅 admin_only 占位。"""
"""普通用户只拿四态裁剪,不得收到候选分 / Profile ID。"""
from app.services.shipping_notice.order_review_projection import serialize_review_case
case = SimpleNamespace(
@@ -128,6 +128,19 @@ def test_serialize_review_case_hides_profile_match_for_non_admin():
), patch(
'app.services.shipping_notice.order_task_service.resolve_order_task_for_candidate',
return_value=None,
), patch(
'app.services.shipping_notice.order_review_profile_match_service.project_review_case_profile_match',
return_value={
'available': True,
'status': 'matched',
'candidates': [{'profile_code': 'P1', 'score': 0.9}],
'selected_profile': {'profile_code': 'P1', 'display_name': 'T'},
'fallback_reason_codes': ['x'],
'needs_review': False,
},
), patch(
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
return_value={'has_formal_ot': False, 'task_missing': False, 'task': None, 'task_no': None, 'task_id': None},
), patch(
'app.services.shipping_notice.order_review_projection.db',
) as mock_db, patch(
@@ -137,9 +150,12 @@ def test_serialize_review_case_hides_profile_match_for_non_admin():
mock_exec.query.filter_by.return_value.order_by.return_value.first.return_value = None
payload = serialize_review_case(case, is_admin=False)
assert payload['profile_match']['available'] is False
assert payload['profile_match']['visibility'] == 'admin_only'
assert payload['profile_match']['visibility'] == 'user'
assert payload['profile_match']['status'] == 'matched'
assert payload['profile_match'].get('candidates') == []
assert payload['automation']['phase'] == 'pre_ot_stp'
assert 'field_completeness' in payload
assert 'completed_checks' in payload
assert payload['automation']['status'] in {'idle', 'waiting_to_start'}
@@ -193,6 +209,9 @@ def test_serialize_review_case_exposes_profile_match_for_admin():
), patch(
'app.services.shipping_notice.order_review_profile_match_service.project_review_case_profile_match',
return_value=admin_payload,
), patch(
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
return_value={'has_formal_ot': False, 'task_missing': False, 'task': None, 'task_no': None, 'task_id': None},
), patch(
'app.services.shipping_notice.order_review_projection.db',
) as mock_db, patch(
@@ -205,6 +224,92 @@ def test_serialize_review_case_exposes_profile_match_for_admin():
assert payload['profile_match']['available'] is True
assert payload['profile_match']['visibility'] == 'admin'
assert payload['profile_match']['candidates'][0]['profile_id'] == 9
assert payload['profile_match']['status'] == 'matched'
def test_task_missing_technical_progress_admin_only():
"""task_missing 时 technical_progress 仅管理员可见;普通用户不得拿到诊断对象。"""
from app.services.shipping_notice.order_review_projection import serialize_review_case
case = SimpleNamespace(
id=3,
case_no='SORC-TM-1',
run_id=3,
unit_id=None,
document_id=12,
candidate_id=None,
status='confirmed',
disposition=None,
confirmed_task_id=99,
current_draft=None,
run=SimpleNamespace(
run_no='RUN-TM',
schema_version_id=1,
input_snapshot_json={'schema': {'definition': {'fields': []}}, 'documents': []},
),
)
formal_ot = {
'has_formal_ot': False,
'task_missing': True,
'task': None,
'task_no': None,
'task_id': 99,
}
common_patches = [
patch(
'app.services.shipping_notice.order_review_customer_service.project_review_case_customer_resolution',
return_value={'resolved': True},
),
patch(
'app.services.shipping_notice.order_review_field_conflict_service.project_review_case_field_conflicts',
return_value=[],
),
patch(
'app.services.shipping_notice.order_review_duplicate_service.project_review_case_duplicate',
return_value={'needs_adjudication': False},
),
patch(
'app.services.shipping_notice.order_review_reservation_service.project_review_case_reservation',
return_value=None,
),
patch(
'app.services.shipping_notice.order_review_fulfillment_decision_service.project_review_case_line_decisions',
return_value=None,
),
patch(
'app.services.shipping_notice.order_task_service.resolve_order_task_for_candidate',
return_value=None,
),
patch(
'app.services.shipping_notice.order_review_profile_match_service.project_review_case_profile_match',
return_value={'available': False, 'status': 'unavailable', 'candidates': []},
),
patch(
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
return_value=formal_ot,
),
patch('app.services.shipping_notice.order_review_projection.db'),
patch('app.models.ShippingProcessExecution'),
]
with common_patches[0], common_patches[1], common_patches[2], common_patches[3], \
common_patches[4], common_patches[5], common_patches[6], common_patches[7], \
common_patches[8] as mock_db, common_patches[9] as mock_exec:
mock_db.session.get.return_value = None
mock_exec.query.filter_by.return_value.order_by.return_value.first.return_value = None
user_payload = serialize_review_case(case, is_admin=False)
admin_payload = serialize_review_case(case, is_admin=True)
assert user_payload['task_missing'] is True
assert user_payload.get('technical_progress') in (None, {})
assert not (user_payload.get('automation') or {}).get('technical')
assert admin_payload['task_missing'] is True
tech = admin_payload.get('technical_progress') or {}
assert tech.get('status') == 'task_missing'
assert tech.get('confirmed_task_id') == 99
assert (admin_payload.get('automation') or {}).get('technical', {}).get('enqueue_status') == 'task_missing'
def test_project_user_gate_summary_clears_stale_confirm_customer(monkeypatch):
@@ -170,3 +170,73 @@ def test_automation_projection_uses_active_job_over_failed_history(app):
)
assert result['status'] == 'queued'
assert result['job_id'] == 88
def test_stp_handler_accepts_worker_contract_and_finishes_owned_attempt(app):
"""Worker 按 handler(ctx, payload) 调用时,STP Handler 应消费冻结载荷并按代次成功收口。"""
from app.jobs.context import JobContext
from app.jobs.handlers import shipping_stp_auto_create as handler
job = SimpleNamespace(
id=906,
attempts=2,
payload_json={'case_no': 'SORC-STP-HANDLER', 'draft_version': 3},
)
ctx = JobContext(config={}, logger=MagicMock(), extras={})
with patch.object(handler.db.session, 'get', return_value=job), patch.object(
handler,
'execute_stp_auto_create_job',
return_value={'ok': True, 'message': 'done', 'task_no': 'SN-1'},
) as execute_mock, patch.object(handler, 'finish_job') as finish_mock, patch.object(
handler,
'fail_job',
) as fail_mock:
handler.handle_shipping_stp_auto_create(ctx, {'job_id': 906})
execute_mock.assert_called_once_with(
payload={'case_no': 'SORC-STP-HANDLER', 'draft_version': 3, 'job_id': 906},
job_id=906,
)
finish_mock.assert_called_once_with(
906,
result={'ok': True, 'message': 'done', 'task_no': 'SN-1'},
message='done',
owned_attempt=2,
)
fail_mock.assert_not_called()
def test_stp_handler_uses_fail_job_contract_for_business_failure(app):
"""业务失败必须使用 fail_job(error/result/retryable/owned_attempt),不得传旧参数名。"""
from app.jobs.context import JobContext
from app.jobs.handlers import shipping_stp_auto_create as handler
job = SimpleNamespace(
id=907,
attempts=1,
payload_json={'case_no': 'SORC-STP-HANDLER-FAIL'},
)
result = {
'ok': False,
'error_code': 'SHIPPING.STP_NOT_ELIGIBLE',
'message': 'not eligible',
}
ctx = JobContext(config={}, logger=MagicMock(), extras={})
with patch.object(handler.db.session, 'get', return_value=job), patch.object(
handler,
'execute_stp_auto_create_job',
return_value=result,
), patch.object(handler, 'finish_job') as finish_mock, patch.object(
handler,
'fail_job',
) as fail_mock:
handler.handle_shipping_stp_auto_create(ctx, {'job_id': 907})
fail_mock.assert_called_once_with(
907,
error='not eligible',
result=result,
retryable=True,
owned_attempt=1,
)
finish_mock.assert_not_called()
@@ -211,8 +211,8 @@ def test_allowed_system_facts_use_export_sequence_not_line_no():
assert 'line_no' not in ALLOWED_SYSTEM_FACTS
def test_default_derivation_rules_are_disabled_copy_if_empty():
"""新草稿预置 customer_po_line_no→line_no,默认关闭。"""
def test_default_derivation_rules_are_enabled_copy_if_empty():
"""新草稿预置 customer_po_line_no→line_no,默认启用,空项次自动从客户PO行号派生。"""
from app.services.shipping_notice.order_schema.field_rules import (
default_derivation_rules,
normalize_derivation_rules,
@@ -221,7 +221,7 @@ def test_default_derivation_rules_are_disabled_copy_if_empty():
rules = default_derivation_rules()
assert rules == [{
'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO',
'enabled': False,
'enabled': True,
'source_field_code': 'customer_po_line_no',
'target_field_code': 'line_no',
'strategy': 'copy_if_empty',
@@ -0,0 +1,236 @@
# 正式 OT 后行级自动履约 — 实施冻结
> 用途:正式 OT 后行级库存匹配事实、自动履约与订单明细操作列合并的实施冻结说明。
> 依赖:复核工作台、STP 整单建单、库存匹配/Gate、行级履约决定与 wave。
> 逻辑:建单前不因数量短缺拦截 STP;数量事实仅 OT 后匹配产生;UI 履约操作并入订单明细右侧操作列。
> 状态:**已冻结,可按切片实施**
> 默认开关:`SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false`
> 关联:`order_review_fulfillment_decision_service.py`、`stp_line_inventory_match.py`、`ShippingOrderReviewView.vue`
## 1. 核心结论
```text
行级履约决定不再作为独立页面区块;
库存满足时系统自动履约(flag 打开后);
库存不足时才让人决定;
库存未完成时既不能当作 0,也不能自动履约。
```
关键校正(对齐当前代码):
> 系统是「先建正式 OT,后做库存匹配」。建单前**不能**依据数量短缺拦截 STP。数量短缺只能在 OT 创建后的库存匹配完成后判断。
## 2. 端到端链路
```text
建单前:
现有资格检查(含库存源是否唯一)
→ confirm_review_case / STP
→ 创建正式 OT
(不判断数量短缺,不创建履约 wave)
OT 后:
inventory_preparation
→ inventory_matching
→ 写入 OT 行库存匹配事实表
匹配 ready:
├─ not_found → available=0 → shortage → 人工等待/关闭
├─ available>=required → 自动或人工进入 post-OT wave
├─ available<required → shortage → 人工处理
└─ result_missing/conflict/invalid → 库存处理中或异常恢复
post-OT wave:
同一 ShippingNotice 下多个 wave
→ Excel/RPA 按 wave 触发
→ OT 作为父级审计与查询实体
```
## 3. STP 与行级履约边界
| 路径 | 职责 |
|---|---|
| STP / `confirm_review_case` | 仅首次创建正式 OT |
| `create_post_ot_fulfillment_wave`(新增) | 仅 OT 已存在后的行级履约波次 |
| 旧 `create_fulfillment_wave` → `confirm_review_case` | 历史兼容;**禁止新增业务调用** |
建单前禁止 STP 的依据仅限现有建单资格与库存源 Gate,**不含**数量短缺。
## 4. 库存事实真相源
新增 **OT 级行库存匹配事实表**(Slice 0),不把 `validation.line_projections` 或 Job payload 当正式真相。
每条事实至少绑定:
```text
shipping_notice / OT
line_key
line_index
inventory_snapshot_id
match_result
inventory_status
required_qty
available_qty
shortage_qty
reservation_id
part_number
unit(若 Schema 配置)
matching_rule_version
matched_at
is_current
```
约束:
- 同一 OT、同一行、同一库存快照只能有一条结果;
- 新快照产生新事实,不覆盖历史;
- 当前有效结果由后端投影选择(`is_current`);
- `line_projections` 仅兼容投影/计算输入;
- Job payload 只保存执行上下文。
### 4.1 `match_result` / `inventory_status`
| match_result | inventory_status(投影) | available_qty | 可否短缺标红 | 可否自动履约 |
|---|---|---|---|---|
| `not_found` | `ready` | **规范为 0** | 是 | 否 |
| `matched`(且 qty 已写) | `ready` | 实际值 | 按比较 | qty≥需求时是 |
| `result_missing` | 异常/不可用 | **null** | 否 | 否 |
| `preparing` | `preparing` | null | 否 | 否 |
| `source_conflict` | `source_conflict` | null | 否 | 否 |
| `invalid_key` | `invalid_key` | null | 否 | 否 |
| `mapping_failed` | `mapping_failed` | null | 否 | 否 |
**硬规则:** `ready + available_qty=null` **不得**直接当 0;仅 `ready + not_found` 规范为 0。
### 4.2 匹配键
```text
Schema 配置了单位字段 → 料号 + 预约单 + 单位
否则 → 料号 + 预约单
```
单位缺失/非法/不一致且无法换算 → `invalid_key` 或 `mapping_failed`,不得当零库存。
## 5. 自动履约(flag 打开后)
- 仅正式 OT 存在后;
- 同一 Case/同一次库存状态变更中,全部 eligible 行合并 **一个** wave;
- 服务端事务内重校验;幂等键逻辑含:`OT + wave_candidate + line_set + inventory_snapshot_id`;
- `decision_source=system`;不显示「确认履约」;
- 人工关闭行永久排除;仅管理员 reopen 后重新校验;
- 失败态:`auto_fulfill_failed`(用户态投影),先重校验,不显示确认履约。
### 5.1 触发(统一幂等协调器)
1. **主**:inventory matching 完成且逐行 ready;
2. **补**:OT 创建时库存已 ready;
3. **补偿**:定时轮询(事件丢失/入队失败/Worker 重启/历史 OT)。
### 5.2 flag 关闭时
可上线:契约、投影、明细库存列、操作列、审计字段。
禁止:自动写完整行决定、自动批量 wave、自动重试。
用户仍可经明确入口走人工完整行履约:`create_post_ot_fulfillment_wave` + `decision_source=user`。
短缺人工关闭仍用 `decide_review_line_fulfillment`:`close_unfulfillable`(更多操作)。
库存获取/匹配仅走 `inventory_allowed_actions`:`retry_inventory_preparation` / `retry_inventory_matching`。
**禁止**更换库存源、等待补货按钮、切换完整库存工作台。
## 6. UI:订单明细合并 + 单一操作列
独立「行级履约决定」表格取消;明细表固定库存列。
最少必显列:内部料号、需求数量、**库存源(只读)**、可用数量、缺口、状态、操作。
`#` 与操作列 sticky;库存核心列不可默认隐藏。
### 6.1 操作列(与复制/删除共用最右侧)
履约相关图标**必须**并入现有 sticky 操作列,禁止再出现第二块履约操作区。
| 行状态 | 操作图标 |
|---|---|
| 普通可编辑(无 OT 库存态) | 复制、删除 |
| 库存不足 | 复制、删除、库存处理(重试获取)、更多操作(关闭) |
| 文件缺失/过期/RPA 失败 | 复制、删除、库存处理(重试获取) |
| 匹配失败(有快照) | 复制、删除、库存处理(重试获取 + 重新匹配) |
| RPA 执行中 / 匹配成功 | 复制、删除(成功时可查看履约详情) |
| 已入波次 / 已履约 | 复制(若仍允许)、更多操作(查看履约详情);**禁用删除** |
| 已关闭 | 无库存/关闭动作 |
- 库存满足:**不显示确认履约**;短缺是**状态**不是按钮;
- 图标必须有 `title` / `aria-label` / 悬浮提示 / 键盘可访问名称(四语言);
- 删除须确认;已入 wave/任务的行后端强制禁止删除;
- 最多 3 个图标直接展示,超过再收进 `⋮`。
### 6.2 OT 尚未 matching ready
```text
可用数量:待确认
缺口:—
状态:获取库存中 / 库存文件未准备 等(后端投影)
inventory_allowed_actions:RPA 运行中为空;否则可含 retry_inventory_preparation
line_allowed_actions:可含 close_unfulfillable(未终态)
```
### 6.3 查看入口
- 「查看履约详情」首期:行内展开摘要(wave/task、快照、校验时间、失败原因、审计入口);Drawer 第二期;
- 「库存处理」:行内轻量浮层动作,**不**进入库存工作台。
### 6.4 右侧主卡聚合(部分入波次 + 部分短缺)
不得只显示「系统处理中」而隐藏短缺入口;同时展示系统进度与人工待处理行数。
有行投影时不上 Case 级库存操作卡;仅无行投影且系统失败时用 `inventory_issue_fallback`。
## 7. 存储 vs 用户态
- DB 继续保存既有 `line_status` / `decision_code`;
- 新增可空 `decision_source`(`system` / `user`);历史可 `unknown` / `legacy_inferred`;
- 用户态投影:`auto_fulfilling` / `shortage` / `inventory_pending` / `wave_created` / `fulfilled` / `closed` / `auto_fulfill_failed` 等。
## 8. 实施切片
| Slice | 内容 | Flag | 状态 |
|---|---|---|---|
| **0** | OT 行匹配事实表;投影契约 | 关 | 已落地 |
| **1** | matching 后写事实;`ready+not_found=0`;缺键 `invalid_key` | 关 | 已落地 |
| **2** | `create_post_ot_fulfillment_wave`;wave API OT 后改走此路径 | 关 | 已落地 |
| **3** | matching ready → 入队协调 Job(flag 关 no-op) | 关 | 已落地(补偿轮询可后续加强) |
| **4** | 明细库存列 + 右侧操作图标;隐藏独立履约表 | 关 | 已落地 |
| **5** | `auto_fulfill_failed` 投影与重校验动作 | 关 | 已落地 |
| **6** | STP 保持现状 | — | 冻结确认 |
自动履约开关打开前必须完成:not_found 区分、snapshot 可追溯、post-OT wave 幂等、失败恢复、定向测试。
## 8.1 本轮 P0 门禁(2026-08-07)
已落地(flag 仍默认 `false`,全环境禁止擅自打开):
- BE-2:自动履约失败整波回滚,独立写 `auto_fulfill_failed`(不新建 `wait_inventory`)
- BE-3:独立幂等表 `shipping_order_review_wave_idempotency`;同 key 参数冲突 409
- BE-1:`schedule_post_ot_wave_progress`;post-OT API 禁止调用 `schedule_auto_progress_after_review_confirm`
- UI-1:决定菜单逐项遵守 `allowed_actions`
## 8.2 明确债务(不阻塞本轮「flag 保持关闭」验收)
| 债项 | 等级 | 说明 |
|---|---|---|
| BE-4 `ot_created` / compensation 接线 | P1 | **已落地**:确认/STP 后 `ot_created` 入队;平台 Job `shipping-post-ot-auto-fulfill-compensation` 每 15 分钟 |
| BE-5 `inventory_snapshot_id` 强制非空 | P1 | **已落地**:无快照禁止 ready/not_found,降级 `result_missing/unavailable` |
| BE-6 单位参与匹配键 | P1 | **已落地**:匹配键含 unit/uom(`stp_line_v2`);事实表写入 unit |
| BE-7 失败存储码独立化 | P1 | **已落地**:匹配事实表 `auto_fulfill_failed*` 列;仍不新建 wait_inventory |
| UI-2 行内履约详情展开 | P1 | **已落地**:展开行内摘要;不进库存模式 |
| UI-3 订单级聚合卡 | P1 | **已落地**(无进库存工作台;入口滚到明细) |
| UI-4 状态 badge | P2 | **已落地** |
| BE-8 旧 confirm wave 分支收敛 | P2 | **已收紧**:`legacy_pre_ot_wave` |
| 明细库存源 + 动作分域 | P0 | **已落地**:只读 `inventory_source`;`inventory_allowed_actions` / `line_allowed_actions`;Case `inventory_issue_fallback` 仅无行投影失败时 |
## 9. 验收要点(摘要)
- `ready+not_found` → 0 标红短缺,不自动履约;
- `result_missing` / preparing / conflict → 不标红、不当 0、不自动履约;
- flag 关:无自动决定/wave;操作列按 `inventory_allowed_actions` / `line_allowed_actions`;
- 人工关闭永不被系统静默重开;
- 页面仅一个操作列,无独立履约按钮区;
- **BE-5 / BE-6 已落地**:无快照 fail-closed;单位参与匹配键。打开自动履约开关前仍须完成定向验收与灰度。
@@ -278,7 +278,7 @@ Task 工作台 = 非主界面,仅保留备用深链
1. **主任务区唯一**:中央区域只承载「订单字段 + 订单明细」。
2. **PDF 是证据工具**:默认不占用主布局列;按需以**右下角浮动证据面板**打开;仅用户主动「固定为侧栏」才进入双栏。
3. **侧栏只展示当前阻断项**:完整检查按需展开。
3. **侧栏只展示当前阻断项**:完整检查按需展开。正式 OT 后右侧改为「当前处理主卡 → 人工阻断 → 已完成检查 → 更多状态」;建单前「订单检查」为主卡,automation 仅在更多状态摘要;系统等待不冒充人工待办。
4. **已通过数据默认收起**:异常数据优先置顶。
5. **AI 建议不常驻主区域**:字段级按需抽屉,主动触发。
6. **操作栏固定且不挤压内容区**:底部固定,主内容区独立滚动。
@@ -1,13 +1,71 @@
# 订单复核工作台状态隔离契约
> 状态:**本轮冻结实现契约(2026-08-06)**
> 范围:Case/PDF 切换隔离、Evidence focus 消费、Validation Snapshot 绑定、automation 文案、profile_match 权限裁剪
> 非范围:Gate Handler 全链补齐、正式邮件多附件第二阶段回归、统一前端 View Model 重构
> 状态:**本轮冻结实现契约(2026-08-07 收敛修订)**
> 范围:Case/PDF 切换隔离、Evidence focus 消费、Validation Snapshot 绑定、automation 文案、
> profile_match 四态裁剪、正式 OT 后阶段分层、`field_completeness` / `completed_checks` /
> `owner_type` / `automation.phase`
> 非范围:Gate Handler 全链补齐、状态模型表结构重构、新增 Gate 类型、统一前端 View Model 重构
---
## 1. 状态分层
```text
Document / PDF
↓
Review Case + Draft
↓
Validation Snapshot
↓
Build Eligibility / Process Gate / Automation
↓
Formal OT(confirmed_task_id → ShippingNotice)
↓
process_status + current_step + stage_nodes(顶部当前阶段唯一数据源)
```
| 绑定 | 范围 |
| --- | --- |
| 建单前顶部阶段 | Case 订单复核 |
| 正式 OT 后顶部阶段 | **ShippingNotice** process_status / current_step / stage_nodes |
| 字段 / 证据 / 资格 / 当前阻断 / automation | **当前 Case** |
| 正式 OT 判定 | `confirmed_task_id` 指向可读 Task(`status=confirmed` 不足够) |
### 1.1 正式 OT 创建后(硬冻结)
```text
Case 订单复核结束
→ automation.phase = post_ot_progress(主卡)
→ 订单检查进入已完成检查 / 更多状态
→ current_blocking_gate 清除建单前 Gate
→ 系统等待:technical_auto_only=true + owner_type=system,不显示人工待办
→ 禁止恢复「确认建单」
```
### 1.2 automation.phase
| phase | 含义 | waiting_to_start 文案 |
| --- | --- | --- |
| `pre_ot_stp` | 建单前 STP | 等待系统启动自动建单 |
| `post_ot_progress` | 正式 OT 自动推进 | 等待系统启动(禁止「建单」字样) |
无 Job 时用户态仍为 `waiting_to_start`;管理员 `technical.enqueue_status=no_job`。
### 1.3 profile_match / field_completeness
- 普通用户 `profile_match.status`:`matched|unmatched|ambiguous|unknown`(不得把 unknown 压成 unmatched)
- `field_completeness` 与 Process Gate `field_completeness` 同源;正式 OT 后 `status=ready`
- `required_field_missing` 只出现在字段完整性,不进模板匹配失败
### 1.4 completed_checks
后端稳定投影;前端禁止自行拼接 Gate/里程碑。至少含:
`document_available` … `formal_ot_created`(见实现模块注释)。
---
## 1(原). 状态分层(兼容)
```text
Document / PDF
↓
@@ -22,7 +80,7 @@ Unified Progress Projection(Run 级进度条)
| 绑定 | 范围 |
| --- | --- |
| 顶部 15 步进度 | **整 Run**(切换 PDF 不跳变) |
| 顶部 15 步进度 | **整 Run**(切换 PDF 不跳变;正式 OT 后当前阶段文案以 OT 为准) |
| 字段 / 证据 / 资格 / 当前阻断 / automation | **当前 Case** |
---
@@ -88,16 +146,19 @@ Unified Progress Projection(Run 级进度条)
can_auto_create=true ≠ 正在推进
```
| 后端事实 | 用户文案 |
| 事实 | 用户文案 |
| --- | --- |
| `automation.status=waiting_to_start` | 已满足自动建单条件,等待系统启动(保留人工确认兜底) |
| `queued` / Job 已入队 | 系统正在自动建单(隐藏确认) |
| `automation.status=waiting_to_start` + `phase=pre_ot_stp` | 等待系统启动自动建单 |
| `automation.status=waiting_to_start` + `phase=post_ot_progress` | 等待系统启动(禁止「建单」) |
| `queued` / Job 已入队 | 系统正在自动建单或推进(隐藏确认) |
| `running` + Task | 系统正在自动推进(隐藏确认) |
| `failed` / `manual_fallback` | 自动推进失败,可重试;未 confirmed 时可人工确认 |
| 超时无 STP 记录 | `manual_fallback`(阈值 `SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS`) |
| `task_missing` | 正式任务关联异常;禁止恢复确认建单 |
Case 投影字段:`automation: { status, retryable, task_no, can_auto_create, can_build, job_id }`;
管理员另附 `technical_progress: { gate_code, status }`。
Case 投影字段:`automation: { status, phase, owner_type, retryable, task_no, can_auto_create, can_build, job_id }`;
另附 `field_completeness`、`completed_checks`、`current_stage`、`has_formal_ot`、`task_missing`;
管理员另附 `technical_progress` / `automation.technical`(如 `enqueue_status=no_job`)。
STP 入队路径:资格达标 → `ensure_stp_auto_create_for_case` → Job `queued`(幂等键 `stp-auto:{run_no}:doc-{id}:v{ver}`)。
@@ -107,17 +168,9 @@ XFA:`can_auto_create=false` 时不得显示 automating;不放宽冻结门禁
## 5. profile_match 权限
- 判定:`user.role == 'admin'`
- 普通用户 Case API:
```json
{
"available": false,
"visibility": "admin_only"
}
```
- 管理员:完整模板审计对象
- 判定:本轮暂 `user.role == 'admin'`(权限封装,避免散落前端)
- 普通用户 Case API:四态 `matched|unmatched|ambiguous|unknown`,无候选分 / Profile ID / 原因链
- 管理员:完整模板审计对象 + 用户态 `status` 映射
- 禁止仅靠前端 `v-if` 隐藏敏感字段
---
@@ -127,6 +180,9 @@ XFA:`can_auto_create=false` 时不得显示 automating;不放宽冻结门禁
- 用户态只允许一个 `current_blocking_gate`
- 客户确认通过后不得再投影 `confirm_customer` / 「优先处理:客户已确认」
- `pending|queued|running` 技术 Gate 不冒充人工优先处理;普通用户看 `automation.status`
- 正式 OT 后:建单前 Gate 必须从 `current_blocking_gate` 清除;`inventory_preparation` Worker 等待 → `technical_auto_only=true` + `owner_type=system`
- 人工库存/履约阻断:域内 Gate + `owner_type=human` + 可执行动作
- 前端必须同时消费 `technical_auto_only` / `owner_type`,禁止仅凭 `available_actions=[]` 推断
---
+55 -109
View File
@@ -503,7 +503,10 @@ MinerU 请求并发:2
- HXOPS 提交并发固定为 2,不直接用满服务声明并发 3。
- Compose 使用独立 `hxops-shipping-worker`,由 `SHIPPING_NOTICE_WORKER_CONCURRENCY=2` 启动两个进程;同批两份版面 Job 通过 PostgreSQL `SKIP LOCKED` 并行领取,禁止让第二份等待第一份完成。
- `SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS=420` 必须高于版面 Worker 的 360 秒上限,避免另一个并发进程把正常长任务误判为失联并重复领取。
- 每个版面 Job 输出 `queue_wait_ms / asset_read_ms / mineru_wait_ms / mineru_result_parse_ms / native_pdf_extract_ms / native_layout_build_ms / coordinate_evidence_ms / snapshot_build_ms / total_handler_ms`;日志只包含 Job、版本、Document ID 和耗时,不包含文件名、正文或 Provider 原始响应。
- 每个版面 Job 的 `result` 平级输出脱敏 `timings` 与 `counts`(PR-0 诊断契约),**不得**写入 layout snapshot / `layout_candidate` / `coordinate_evidence`。保留旧 timing:`queue_wait_ms / asset_read_ms / xfa_analysis_ms / mineru_wait_ms / mineru_result_parse_ms / native_pdf_extract_ms / native_layout_build_ms / coordinate_evidence_ms / snapshot_build_ms / total_handler_ms`。新增细分 timing:`native_text_alignment_ms / opencv_geometry_ms / opencv_validation_ms / ocr_engine_init_ms / ocr_inference_ms / layout_assembly_ms / layout_serialize_ms`(仅 `layout.model_dump`)。新增 counts:`page_count / mineru_table_count / resolved_table_count / partial_alignment_table_count / opencv_attempt_count / ocr_attempt_count / ocr_call_count / ocr_page_count / ocr_table_count / ocr_page_cache_hit / ocr_page_cache_miss / native_token_count / layout_cell_count / ocr_engine_warm`(bool)。子阶段为墙钟嵌套,不可简单求和;未执行阶段统一写 `0`。worker 日志格式:`shipping_document_layout_timing job_id=... version_id=... document_id=... timings={...} counts={...}`;只含 Job、版本、Document ID 与诊断字段,不包含文件名、正文、HTML、OCR/Provider 原始响应。
- PR-1 页面 OCR 缓存:`SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED`(dev/test 默认 true,prod 默认 false,可纯环境变量回滚)。开启后,同一 Layout Job 内相同 `document` 的同一 `page_no + 渲染图尺寸` 最多整页 RapidOCR 一次;layout 表格门禁与 `_table_coordinate_evidence` 必须共享该结果;空行与 `ocr_engine_unavailable` 失败结果也缓存。缓存仅存进程内存,不进 snapshot、不跨 Job。关闭开关时行为与 PR-0 一致。
- PR-2 PDFium 页面复用:`SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED`。开启后保留 MinerU 前字符轻量预读,仅 `attach_native_pdf_page_images` 补齐缺图页,禁止二次字符枚举。同 Job 内 OpenCV geometry 按 `page_no + 圆整 bbox + 网格签名` 缓存(含失败),不减少多配置共识组数。
- PR-3 表格裁剪 OCR:`SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED` + `SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO`(默认 0.03,夹紧 2%~5%)。仅表格 cell 候选走裁剪识别;订单级 `page_glyphs` 在原生文字为空时仍整页 OCR。生产默认关,须 checksum/语义双跑通过后灰度。
- PDFium 在 MinerU 前只做轻量字符预读,不承担表格结构主裁决;其页面和字符在 MinerU 表格坐标补证、原生表格回退、layout.v1 候选和坐标证据之间复用。前置预读不渲染高分辨率页面图,只有进入 MinerU 后的 OpenCV/OCR 增强链时才按需渲染。单次阶段内禁止重复解析和渲染。
- PDFium 原始文本流中的空格可能只有零宽 bbox。原生证据保留真实 `char_index`,不为零 bbox 空格伪造可选 glyph,而是在下一有效字符记录可选 `boundary_before`。订单字段、模板受控区域和坐标表格统一采用“明确文本流边界优先、既有几何阈值兜底”;历史冻结证据缺少该字段时保持原行为。原值保留空格,模板与锚点比较仍使用既有空白折叠值,禁止通过降低全局阈值修复,以免拆分 PO、料号、金额和日期。
- MinerU 是 PDF 表格结构的首选 Provider。PDFium 预读即使能够恢复候选表,也不得跳过 MinerU;MinerU 已输出表格时必须保留 Provider 的表格结构,PDFium 只补充真实字符坐标和证据。只有 MinerU 返回 `tables=[]`、配置缺失、调用失败或响应非法时,才允许严格原生文字回退:同页必须命中多个通用明细表头语义、形成稳定列边界和数字型多列数据行;降级快照必须同时保留 MinerU 问题码与 `mineru_provider_fallback_used`,无法证明时保持原 Provider 失败,禁止猜测。
@@ -1923,7 +1926,7 @@ cd C:\HxopsRpaTest
$env:HXOPS_API_BASE = "http://测试后端地址:端口"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "请替换为测试环境SHIPPING_NOTICE_TOOL_API_KEY"
# SHIPPING_NOTICE_RPA_CREDENTIAL_KEY 由受控 Secret 工具注入当前进程;
# 手工部署请直接使用下方 set_rpa_worker_env.ps1 的安全交互输入。
# Secret 由 new_rpa_worker_secret.ps1 安全交互创建。
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
@@ -1953,46 +1956,6 @@ $env:SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20"
正式环境测试时,将 `C:\HxopsRpaTest` 改为 `C:\HxopsRpaProd`,`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` 改为 `prod`,`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` 改为 `hxops-rpa-prod-data`,并把 `HXOPS_API_BASE`、`SHIPPING_NOTICE_TOOL_API_KEY` 改为正式后端对应值。
也可使用仓库脚本一次性写入用户级永久变量(推荐):
```powershell
cd C:\HxopsRpaTest
.\scripts\rpa\set_rpa_worker_env.ps1 -Environment test -ApiBase "http://测试后端:端口" -ToolApiKey "<与后端一致的密钥>"
```
脚本会交互式安全提示输入 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`,不会把该主密钥
放进命令行历史或输出到控制台。后端侧必须通过 Jenkins/CI、Docker Secret 或系统
环境变量注入同一值;`.env.shared` 只保留空占位。
#### 1.5.5b RPA 环境变量命名迁移
新部署只允许使用统一命名空间。旧名称在当前版本仅作为 fallback,全部环境迁移完成后将删除兼容读取。
| 历史名称 | 规范名称 |
| --- | --- |
| `SHIPPING_RPA_CREDENTIAL_KEY` | `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` |
| `FREIGHT_INVENTORY_DROP_DIR` | `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR` |
| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR` |
| `FREIGHT_UPLOAD_QUEUE_DIR` | `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR` |
| `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` | `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR` |
| `FREIGHT_RPA_SHARED_SCOPE_ID` | `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` |
| `FREIGHT_RPA_<配置项>` | `SHIPPING_NOTICE_RPA_WORKER_<配置项>` |
迁移步骤:先运行新版 `set_rpa_worker_env.ps1` 写入新变量,重启 PowerShell/计划任务并完成
心跳、哨兵及真实库存导出验证;确认稳定后再清理 Windows 用户级旧变量:
```powershell
[Environment]::GetEnvironmentVariables("User").Keys |
Where-Object { $_ -like "FREIGHT_RPA_*" -or $_ -in @(
"FREIGHT_INVENTORY_DROP_DIR",
"FREIGHT_UPLOAD_QUEUE_DIR",
"SHIPPING_RPA_CREDENTIAL_KEY"
) } |
ForEach-Object { [Environment]::SetEnvironmentVariable([string]$_, $null, "User") }
```
清理前不得跳过验证;旧变量删除后需要重新打开 PowerShell,并再次确认 Worker 启动、心跳和库存导出正常。
#### 1.5.5a RPA Worker 心跳、共享 scope 与哨兵
test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是否匹配、共享目录是否有效。Windows Worker 需周期性 `POST /api/shipping-notice/rpa/heartbeat`,并在**库存 trigger 共享目录**(`SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR`,如 `...\inventory_triggers`)写入哨兵文件 `.hxops_rpa_shared_mount`(默认文件名,可由 `SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME` 覆盖)。
@@ -2226,107 +2189,90 @@ volumes:
容器内环境变量仍使用对应环境的 `/mnt/hxops-rpa-test-data/...` 或 `/mnt/hxops-rpa-prod-data/...`。
#### 1.5.10 Windows RPA 主机:永久环境变量与自启动
#### 1.5.10 Windows RPA 主机:进程级环境与自启动
手动验证通过后,可设置用户级永久环境变量:
同一 Windows 用户通过两个独立计划任务同时运行 test/prod。每个任务调用 `start_rpa_worker.ps1`,只给对应 Worker 子进程注入环境变量;Secret 使用当前用户 DPAPI 文件保存,不写入用户级或机器级环境变量。
Windows 如禁止运行 `.ps1`,仅对单次 Secret 创建使用临时 Bypass:
```powershell
[Environment]::SetEnvironmentVariable("HXOPS_API_BASE", "http://192.168.1.20:8890", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_TOOL_API_KEY", "请替换为与后端一致的ASCII密钥", "User")
# 凭据主密钥不要以内联明文命令设置;优先使用 set_rpa_worker_env.ps1 的安全交互输入。
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS", "3", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR", "C:\HxopsRpaTest\data\inventory_triggers", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR", "C:\HxopsRpaTest\data\inventory_drop", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR", "C:\HxopsRpaTest\data\upload_triggers", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR", "C:\HxopsRpaTest\data\upload_queue", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "C:\HxopsRpaTest\data\browser_profile", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", "C:\HxopsRpaTest\data\logs\worker.log", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "10485760", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "5", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "请替换为DSV账号", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "请替换为DSV密码", "User")
# 心跳与共享 scope(test 示例;正式改为 prod + hxops-rpa-prod-data + C:\HxopsRpaProd\...)
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT", "test", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data", "User")
[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20", "User")
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1" -Environment test
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1" -Environment prod
```
或使用脚本(参数按实际后端地址与密钥填写):
若文件来自网络或压缩包并被标记为阻止,先执行 `Unblock-File`。也可用 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` 仅放行当前窗口。禁止永久设置 `Unrestricted` 或修改 `LocalMachine` 策略。
Windows PowerShell 5.1 读取无 BOM UTF-8 脚本时可能出现中文变乱和“字符串缺少终止符”。`new_rpa_worker_secret.ps1` 和 `start_rpa_worker.ps1` 必须保持 UTF-8 BOM,应从仓库原样复制,不要用 ANSI 编辑器另存。
先分别创建仅包含 Tool API Key 和 Credential Key 的 Secret:
```powershell
cd C:\HxopsRpaTest
.\scripts\rpa\set_rpa_worker_env.ps1 -Environment test -ApiBase "http://192.168.1.20:8890" -ToolApiKey "<密钥>"
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod
```
脚本随后会安全提示输入与 test 后端一致的 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。
默认 Secret 路径为 `C:\HxopsRpaSecrets\test.xml` 与 `prod.xml`。文件不得进入仓库、SMB 共享、日志或其他 Windows 用户目录。
以上写法适合只常驻一个 worker。若同一台 Windows 主机要同时常驻测试与正式,建议不要依赖用户级环境变量,而是分别准备两个启动脚本或任务计划,确保每个任务内显式设置各自的目录、API Base、scope 与 Key。
DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Profile 中配置。后端将加密凭据作为 trigger 的 `credential_envelope` 发送给 Worker,Worker 只用 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 解密,不从 Windows Secret 文件重新录入。
关闭并重新打开 PowerShell 后检查:
手工启动 test:
如果 Windows PowerShell 报“在此系统上禁止运行脚本”,这是执行策略拦截 `.ps1`。使用以下命令仅对本次 Worker 进程临时放行,不修改系统或用户的永久策略:
```powershell
echo $env:HXOPS_API_BASE
echo $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR
echo $env:SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID
echo $env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
"C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" `
-Environment test `
-ApiBase "http://<test后端地址>:<端口>" `
-WorkerRoot "C:\HxopsRpaTest" `
-SecretFile "C:\HxopsRpaSecrets\test.xml"
```
确认 worker 可手动启动:
若脚本来自网络或压缩包,先确认路径并按需解除文件阻止:
```powershell
cd C:\HxopsRpaTest
python scripts\rpa\freight_rpa_worker.py
Test-Path "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
Unblock-File "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
```
启动后应看到 `[logging] tee enabled path=...`;日志会同时写入 `C:\HxopsRpaTest\data\logs\worker.log`。正式环境建议配置为 `C:\HxopsRpaProd\data\logs\worker.log`。
日志默认按大小轮转,避免单个文件长期膨胀:
```text
SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES=10485760 # 单个 worker.log 最大 10MB;设为 0 可禁用轮转
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT=5 # 最多保留 worker.log.1 到 worker.log.5
```
确认可用后再创建任务计划。先查 Python 路径:
`-ApiBase` 必须是 HXOPS 测试业务后端地址。`HXOPS_TOOLS_API_BASE`(例如 `:8890`)是 Tool API,不能填入 Worker 的 `-ApiBase`。如果使用 `http://192.168.100.192:5052`,必须先确认该地址确实是测试后端并可从 Windows Worker 访问:
```powershell
where python
Test-NetConnection 192.168.100.192 -Port 5052
Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing
```
用实际 Python 路径创建登录后自启动任务;可见浏览器模式建议优先用 `AtLogOn`:
只有连通性检查通过后才启动 Worker;失败时应核对测试服务器实际端口映射、防火墙和对外域名。不要通过修改 `Unrestricted` 或 `LocalMachine` 执行策略来绕过问题。
连通性确认后,也可以使用仓库原始命令:
```powershell
$Action = New-ScheduledTaskAction `
-Execute "C:\Users\rpa\AppData\Local\Programs\Python\Python312\python.exe" `
-Argument "C:\HxopsRpaTest\scripts\rpa\freight_rpa_worker.py" `
-WorkingDirectory "C:\HxopsRpaTest"
$Trigger = New-ScheduledTaskTrigger -AtLogOn
Register-ScheduledTask `
-TaskName "HXOPS Inventory RPA Worker TEST" `
-Action $Action `
-Trigger $Trigger `
-Description "HXOPS inventory export RPA worker TEST"
.\scripts\rpa\start_rpa_worker.ps1 `
-Environment test `
-ApiBase "http://测试后端:端口" `
-WorkerRoot "C:\HxopsRpaTest" `
-SecretFile "C:\HxopsRpaSecrets\test.xml"
```
正式环境任务计划使用 `C:\HxopsRpaProd`,任务名建议为 `HXOPS Inventory RPA Worker PROD`。
手工启动 prod:
```powershell
C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1 `
-Environment prod `
-ApiBase "http://正式后端:端口" `
-WorkerRoot "C:\HxopsRpaProd" `
-SecretFile "C:\HxopsRpaSecrets\prod.xml"
```
后台任务必须使用 `AtLogOn + Interactive`,并分别绑定 test/prod 的 WorkerRoot、ApiBase 和 SecretFile。完整任务计划命令、重启策略和日常启停见 `scripts/rpa/README.md` 的“Windows RPA 主机后台常驻与任务计划(同一用户双环境)”。
#### 1.5.11 端到端验证
1. Windows 手工打开 Edge,确认能访问 DSV/Crane。
2. Windows 执行 `python scripts\rpa\dsv_login_smoke.py`。
3. 在管理端创建一个库存 RPA trigger,确认其包含 Source、Profile 和密文凭据。
4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\inventory_triggers` 能看到。
5. Windows 启动 `python scripts\rpa\freight_rpa_worker.py`。
5. Windows 按当前方案执行 `start_rpa_worker.ps1`;不要直接运行 `freight_rpa_worker.py`。
6. 确认哨兵:`Get-Content C:\HxopsRpaTest\data\inventory_triggers\.hxops_rpa_shared_mount` 含正确 `scope_id`。
7. HXOPS 管理端或 `GET /api/admin/rpa-workers/status` 显示 Worker 在线。
8. HXOPS 页面或排程触发库存 RPA 导出。
@@ -2391,7 +2337,7 @@ $env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "uploa
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile"
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log"
python scripts\rpa\freight_rpa_worker.py
\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase "<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
```
启动成功后,控制台会输出 `[freight_rpa_worker] started`,并持续轮询 trigger。另开一个 PowerShell 可检查日志和哨兵;本地未配置 shared scope 时不要求哨兵包含 test/prod scope:
+3 -2
View File
@@ -64,7 +64,7 @@
| EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 |
| EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake 快览:只解析邮件正文、白名单 HTML 表格快照和附件目录;上传阶段不抽取附件全文、不创建附件 FileAsset/Document、不生成 Candidate、不判订单重复;解析失败、超时、取消保持幂等 |
| 上传与发送门禁状态一致性 | 已实现 | Intake 状态接口返回 `preview_status / ready_for_extraction / attachment_directory_complete` 等快览事实;聊天附件快览成功后显示“已就绪/已发现 N 个附件”并允许发送,不再因上传阶段版面任务阻塞;真正的订单识别进度在点击发送后单独展示 |
| 版面解析并发与耗时诊断 | 已实现 | 独立 `hxops-shipping-worker` 默认双进程并行领取同批版面 Job;PDFium 先轻量预读字符但不裁决表格,MinerU 始终作为 PDF 表格结构首选 Provider;仅 MinerU 空表/失败时允许严格 PDFium 回退。Job 结果保存脱敏分段耗时且不记录原文 |
| 版面解析并发与耗时诊断 | 已实现 | 独立 `hxops-shipping-worker` 默认双进程并行领取同批版面 Job;PDFium 先轻量预读字符但不裁决表格,MinerU 始终作为 PDF 表格结构首选 Provider;仅 MinerU 空表/失败时允许严格 PDFium 回退。Job `result` 平级保存脱敏 `timings`+`counts`(含 OCR/OpenCV/对齐细分与 `ocr_engine_warm`),worker 日志同步输出;诊断字段不进 layout snapshot,不记录原文/HTML/OCR 原始响应(PR-0)。PR-1:`SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED` 控制同 Job 整页 OCR 复用;PR-2:`SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED` 字符预读复用+按需补图,OpenCV geometry Job 内缓存;PR-3:`SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED` 表格裁剪 OCR(prod 默认关) |
| 对话输入框多附件统一提交 | 已实现 | 用户可分多次选择 EML/PDF;当前输入框内全部已就绪 Intake 在一次发送中冻结为同一个订单抽取 Run。`uploadBatchId` 仅用于单次上传幂等与状态关联,不再截断发送范围 |
| 无框订单明细表原生 PDF 回退 | 已实现 | 仅当 MinerU 未输出表格、PDF 原生文字坐标完整且同页命中多个通用明细表头时,从表头到合计行生成待配置候选表;正常 MinerU 表格路径不变,解析器修订 `v4` 防止复用旧零表格缓存 |
| 点击发送完整订单抽取 | 已实现(终态分阶段) | Run 冻结文档、Schema、模板 Profile、路由/评分/门禁与解析器版本;Worker 执行异型模板或通用确定性解析;完整性门禁与紧急停止控制自动冻结;Dify 仅提供复核最小证据建议且不得自动冻结;上线清单见 order-extraction-go-live-checklist.md |
@@ -86,7 +86,8 @@
| 订单模板录入 UX 重构(阶段 0-7) | 已完成 | 已完成 Draft Revision、Lease、向导、独立草稿编辑器自动保存、不可变验证运行与两步发布报告;样本上传仅负责资产保存和 PDF/EML Document 物化,版面解析作为后台预热且不阻断上传。盲测复核区分准备中、兼容性诊断和正式复核:仅 ready Layout 的真实 table_id 可确认,确认时冻结 LayoutVersion/checksum/parser 身份,执行不回读最新布局;临时 PDF 恢复仅作诊断。同模板族历史 annotation/training/新旧 blind test 文档可重新复核复用,当前版本建模样本仍严格排除。编辑器在可见状态自动续租。Dify 无需配置变更。 |
| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。字段和明细可按冻结 bbox 定位 PDF 原文(明细按 table/cell 反查),版本历史按需展开;确认后展示 `auto_progress` 真实结果/检查点并可直达任务进度工作台。单 PDF 重识别复用 WorkflowItem 真实状态展示已提交/版面解析/字段提取/草稿生成,完成后自动打开新版;“跳转当前版本”点击时强制刷新工作项,目标未就绪时明确提示。 |
| **复核工作台布局重构(阶段 0–5)** | 已实现(待真机视觉签署) | 替换旧三栏:主编辑区 + 阻断摘要侧栏;PDF **默认右下角浮动证据面板**(八向 resize、记忆尺寸位置、展开/移侧;用户主动「固定为侧栏」才双栏),不挤占订单网格;Ctrl/Cmd+滚轮与适合宽度/页面;溢出拖拽平移;双击字段定位与证据联动高亮;异常字段 Alt+[/] 导航;真正按需加载;Chat/证据/pdfjs 异步分包;AI/版本历史/完整检查按需抽屉且审计失败阻断展示;确认与自动推进态解耦并可重试;同事务入队 `shipping_notice_run`;单一主滚动 + sticky 底栏。真机三档 viewport 清单见 layout-plan §11.1。权威方案:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md)。 |
| **复核工作台状态隔离(Case/证据/资格/自动化)** | 进行中(本轮代码已落地) | Case 切换请求代次 + 瞬态清理;`focus=evidence` 首次消费;Validation Snapshot 绑定 case/draft/validation_version;普通用户 `profile_match` 后端裁剪;客户确认后不再「优先处理:客户已确认」;`can_auto_create` 仅显示「等待系统启动」。契约:[review-workbench-state-isolation-contract.md](features/shipping-notice/review-workbench-state-isolation-contract.md)。 |
| **复核工作台状态隔离(Case/证据/资格/自动化)** | 进行中(正式 OT 后分层已落地) | Case 切换请求代次 + 瞬态清理;正式 OT 后右侧主卡切自动处理、订单检查折叠、系统等待不冒充人工待办;`profile_match` 四态 + `field_completeness`;`completed_checks` 后端投影;`automation.phase` 区分建单前/后文案。契约:[review-workbench-state-isolation-contract.md](features/shipping-notice/review-workbench-state-isolation-contract.md)。 |
| **OT 后行级自动履约(明细合并 + 匹配事实)** | P0+P1+P2+布局/动作分域已落地;flag 默认关 | 明细只读库存源;库存浮层仅 preparation/matching;关闭在更多操作;Case 兜底仅无行投影失败;15 阶等宽+布局清理。flag 保持 false。冻结:[post-ot-line-auto-fulfillment-freeze.md](features/shipping-notice/post-ot-line-auto-fulfillment-freeze.md)。 |
| **双工作台架构 + Candidate Qualification(阶段 0–6)** | 阶段 0–6 达标(评审整改后) | **已完成**:双工作台边界;Candidate Qualification(追加式快照 + 审计);模板审批不再硬阻断自动建单;对话「本次处理中」轻量侧栏;复核返回对话;货代上传 RPA 可按 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 接入自动链;Process Gate 对话内恢复;审计事件字典含 chat_* / qualification / upload_rpa。权威:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md) §0。 |
| **对话侧 Task 进度与「本次处理中」** | 阶段 2–5 已实现 | 侧栏以用户可见任务(OT)分组为主路径;`ShippingConversationProcessingCard` + processing API;`WF-...` 下沉;发送走统一提交无确认框。 |
| **会话多任务聚合与统一提交(阶段 0–5)** | 整改中 | 契约冻结(§1.6.1);统一提交 + 独立 submission 幂等;同 PDF 指纹继承 OT(跨 Schema);投影按「当前有效最新 Run」;未查看 completed 仍可见;任务级取消/重试均走 Run API;状态四语言 + 更新时间。权威:technical.md §1.6.1。 |
@@ -0,0 +1,58 @@
<!--
features/chat/components/shipping-review/ReviewCompletedChecksPanel.vue
用途:右侧「已完成检查」折叠列表;仅消费后端 completed_checks。
依赖:vue-i18n。
逻辑:默认折叠;禁止前端自行拼接 Gate/里程碑。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
export interface CompletedCheckItem {
code: string;
status?: string;
completed_at?: string | null;
}
const props = defineProps<{
items?: CompletedCheckItem[] | null;
defaultOpen?: boolean;
}>();
const { t, te } = useI18n();
const checks = computed(() => (props.items || []).filter((item) => String(item.status || 'passed') === 'passed'));
const visible = computed(() => checks.value.length > 0);
/**
* 检查项本地化标签。
*/
function checkLabel(code: string): string {
const key = `chat.shippingOrderReview.completedChecks.codes.${code}`;
return te(key) ? t(key) : code;
}
</script>
<template>
<details
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-2 text-xs dark:border-slate-800 dark:bg-slate-900"
:open="defaultOpen"
data-testid="review-completed-checks"
>
<summary class="cursor-pointer px-1 py-1 font-medium text-muted">
{{ t('chat.shippingOrderReview.completedChecks.title', { count: checks.length }) }}
</summary>
<ul class="mt-2 space-y-1 px-1 pb-1">
<li
v-for="item in checks"
:key="item.code"
class="flex items-center gap-2 text-[11px] text-secondary"
:data-testid="`review-completed-check-${item.code}`"
>
<span class="text-emerald-600 dark:text-emerald-400" aria-hidden="true">✓</span>
<span>{{ checkLabel(item.code) }}</span>
</li>
</ul>
</details>
</template>
@@ -0,0 +1,155 @@
<!--
features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue
用途:正式 OT 创建后的右侧「当前处理状态」主卡(阶段 + 自动推进合并)。
依赖:vue-i18n、ShippingOrderReviewAutomation、resolveShippingProcessingStageLabel。
逻辑:优先消费 Progress 同源的 stageCode + stageLabelKey;Case current_stage 仅降级;
禁止把阶段码直接当用户文案;Job 明细与 task_missing 诊断仅管理员区;
由 ShippingOrderReviewView 在 has_formal_ot / task_missing 时置顶渲染。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { RefreshCw } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewAutomation } from '@/features/chat/types/shipping.api.types';
import { resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
const props = defineProps<{
stageCode?: string | null;
stageLabelKey?: string | null;
stageInconsistent?: boolean;
taskMissing?: boolean;
taskNo?: string | null;
confirmedTaskId?: number | null;
showAdminDiagnosis?: boolean;
automation?: ShippingOrderReviewAutomation | null;
showRetry?: boolean;
retrying?: boolean;
}>();
const emit = defineEmits<{
retry: [];
}>();
const { t, te } = useI18n();
/**
* 当前处理阶段展示文案:消费 label_key,禁止直接展示阶段码。
*/
const stageLabel = computed(() => {
if (props.taskMissing) {
return t('chat.shippingOrderReview.currentProcessing.taskMissing');
}
if (props.stageInconsistent) {
return t('chat.shippingOrderReview.currentProcessing.stateInconsistent');
}
return resolveShippingProcessingStageLabel(
String(props.stageCode || ''),
te,
t,
props.stageLabelKey,
);
});
/**
* 自动推进用户态文案(消费 phase,禁止前端猜建单/推进)。
*/
const statusLabel = computed(() => {
const automation = props.automation;
const status = String(automation?.status || '').trim().toLowerCase();
const phase = String(automation?.phase || '').trim();
if (props.taskMissing) {
return t('chat.shippingOrderReview.currentProcessing.statusTaskMissing');
}
if (status === 'waiting_to_start') {
return phase === 'pre_ot_stp'
? t('chat.shippingOrderReview.automation.waitingPreOt')
: t('chat.shippingOrderReview.automation.waitingPostOt');
}
if (status === 'queued' || status === 'running') {
return t('chat.shippingOrderReview.currentProcessing.statusRunning');
}
if (status === 'failed' || status === 'manual_fallback') {
return t('chat.shippingOrderReview.currentProcessing.statusFailedRetryable');
}
if (status === 'completed') {
return t('chat.shippingOrderReview.currentProcessing.statusCompleted');
}
return t('chat.shippingOrderReview.currentProcessing.statusIdle');
});
/**
* 主卡重试:仅在有 task_no 且非 task_missing 时由父组件控制 showRetry。
*/
const canShowRetry = computed(() => (
Boolean(props.showRetry)
&& !props.taskMissing
&& Boolean(String(props.taskNo || '').trim())
));
</script>
<template>
<section
class="rounded-xl border border-sky-200 bg-sky-50/80 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/30"
data-testid="review-current-processing-card"
:data-task-missing="taskMissing ? '1' : '0'"
:data-automation-status="String(automation?.status || '')"
:data-automation-phase="String(automation?.phase || '')"
>
<header class="mb-2">
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-100">
{{ t('chat.shippingOrderReview.currentProcessing.title') }}
</h2>
<p class="mt-0.5 text-xs text-sky-900/80 dark:text-sky-200/80">
{{ stageLabel }}
</p>
</header>
<dl class="space-y-1 text-xs text-sky-950 dark:text-sky-100">
<div class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentProcessing.status') }}</dt>
<dd data-testid="review-current-processing-status">{{ statusLabel }}</dd>
</div>
<div v-if="taskNo" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentProcessing.formalOt') }}</dt>
<dd class="font-mono" data-testid="review-current-processing-ot">{{ taskNo }}</dd>
</div>
</dl>
<p
v-if="taskMissing"
class="mt-2 text-[11px] text-rose-800 dark:text-rose-200"
data-testid="review-current-processing-task-missing"
>
{{ t('chat.shippingOrderReview.currentProcessing.taskMissingHint') }}
</p>
<aside
v-if="taskMissing && showAdminDiagnosis"
class="mt-2 rounded border border-rose-300 bg-rose-50/80 p-2 text-[11px] text-rose-950 dark:border-rose-800 dark:bg-rose-950/40 dark:text-rose-100"
data-testid="review-current-processing-admin-diagnosis"
>
<p class="font-medium">{{ t('chat.shippingOrderReview.currentProcessing.adminDiagnosisTitle') }}</p>
<p v-if="confirmedTaskId != null" class="mt-1 font-mono">
{{ t('chat.shippingOrderReview.currentProcessing.confirmedTaskId', { id: confirmedTaskId }) }}
</p>
<p class="mt-1">
{{ t('chat.shippingOrderReview.currentProcessing.adminDiagnosisStatus') }}
</p>
<p class="mt-1 text-muted">
{{ t('chat.shippingOrderReview.currentProcessing.adminDiagnosisHint') }}
</p>
</aside>
<button
v-if="canShowRetry"
type="button"
class="mt-3 inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-2.5 py-1.5 text-xs text-amber-950 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-current-processing-retry"
:disabled="retrying"
@click="emit('retry')"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ t('chat.shippingOrderReview.autoProgress.retryStp') }}
</button>
</section>
</template>
@@ -0,0 +1,79 @@
<!--
features/chat/components/shipping-review/ReviewFieldCompletenessPanel.vue
用途:字段完整性用户态卡片;与模板匹配分离,消费 Case.field_completeness。
依赖:vue-i18n。
逻辑:仅展示 blocked/ready 与缺失字段;required_field_missing 不进入模板匹配区。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
export interface FieldCompletenessIssue {
code?: string;
field_id?: string | null;
field_code?: string | null;
line_index?: number | null;
message?: string | null;
}
const props = defineProps<{
completeness?: {
status?: string;
issues?: FieldCompletenessIssue[];
} | null;
fieldLabels?: Record<string, string>;
}>();
const { t } = useI18n();
const status = computed(() => String(props.completeness?.status || '').trim().toLowerCase());
const blocked = computed(() => status.value === 'blocked');
const issues = computed(() => props.completeness?.issues || []);
const visible = computed(() => Boolean(status.value));
/**
* 字段展示名。
*/
function fieldLabel(issue: FieldCompletenessIssue): string {
const code = String(issue.field_code || issue.field_id || '').trim();
if (!code) return t('chat.shippingOrderReview.fieldCompleteness.unknownField');
return props.fieldLabels?.[code] || code;
}
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-field-completeness-panel"
:data-status="status"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.fieldCompleteness.title') }}</h2>
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.fieldCompleteness.subtitle') }}</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="blocked
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'"
>
{{ blocked
? t('chat.shippingOrderReview.fieldCompleteness.blocked')
: t('chat.shippingOrderReview.fieldCompleteness.ready') }}
</span>
</header>
<ul v-if="blocked && issues.length" class="mt-2 space-y-1 text-[11px] text-secondary">
<li
v-for="(issue, idx) in issues"
:key="`${issue.field_id || issue.field_code || idx}`"
class="rounded-lg border border-default bg-surface-soft px-2.5 py-1.5"
>
<span class="font-medium">{{ fieldLabel(issue) }}</span>
<span v-if="issue.code" class="ml-2 font-mono text-muted">{{ issue.code }}</span>
</li>
</ul>
</section>
</template>
@@ -2,7 +2,8 @@
features/chat/components/shipping-review/ReviewFulfillmentDecisionPanel.vue
用途:复核工作台行级履约决定(等待补货 / 完整行先行 / 关闭)。
依赖:vue-i18n、decide/wave line-fulfillment API、showReviewResumeOutcome。
逻辑:展示 qty/shortage;逐行决定;选中 fulfill 行可确认波次;关闭 emit open-close-dialog。
逻辑:分列展示料号/需求数量/可用数量/预约单号/状态;禁止 part_number 回退预约单号;
逐行决定;选中 fulfill 行可确认波次;关闭 emit open-close-dialog。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -181,8 +182,9 @@ function onCloseRemaining() {
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.waveSelect') }}</th>
<th class="px-1 py-1 font-medium">#</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.partNumber') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.qty') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.requiredQty') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.reservationId') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.status') }}</th>
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</th>
</tr>
@@ -204,14 +206,12 @@ function onCloseRemaining() {
>
</td>
<td class="px-1 py-1">{{ (line.line_index ?? 0) + 1 }}</td>
<td class="px-1 py-1 font-mono">{{ line.part_number || line.reservation_id || '—' }}</td>
<td class="px-1 py-1">
{{ line.required_qty ?? '—' }}
<span v-if="line.available_qty" class="text-muted"> / {{ line.available_qty }}</span>
</td>
<td class="px-1 py-1" :class="line.shortage_qty ? 'font-medium text-rose-700 dark:text-rose-300' : ''">
{{ line.shortage_qty || '—' }}
<td class="px-1 py-1 font-mono" data-testid="review-fulfill-part-number">
{{ line.part_number || t('chat.shippingOrderReview.fulfillmentDecision.partUnrecognized') }}
</td>
<td class="px-1 py-1">{{ line.required_qty ?? '—' }}</td>
<td class="px-1 py-1">{{ line.available_qty ?? '—' }}</td>
<td class="px-1 py-1 font-mono">{{ line.reservation_id || '—' }}</td>
<td class="px-1 py-1">{{ lineStatusLabel(line.line_status) }}</td>
<td v-if="editable && !TERMINAL_STATUSES.has(String(line.line_status || ''))" class="px-1 py-1">
<div class="flex flex-wrap gap-1">
@@ -1,65 +0,0 @@
<!--
features/chat/components/shipping-review/ReviewFulfillmentSummaryCard.vue
用途:复核侧栏紧凑展示行级履约缺口摘要,完整表格在库存模式主区处理。
依赖:vue-i18n、ShippingOrderReviewLineFulfillment。
逻辑:仅显示开放行/缺口计数与进入库存处理入口;不渲染 7 列表格。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
}>();
const emit = defineEmits<{
'enter-inventory': [];
}>();
const { t } = useI18n();
const visible = computed(() => Boolean(
props.lineFulfillment?.has_open_lines
|| props.lineFulfillment?.has_shortage
|| (props.lineFulfillment?.open_count || 0) > 0,
));
const openCount = computed(() => Number(props.lineFulfillment?.open_count || 0));
const readyCount = computed(() => Number(props.lineFulfillment?.ready_count || 0));
const shortageCount = computed(() => (
props.lineFulfillment?.lines || []
).filter((line) => Boolean(line.shortage_qty)).length);
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40"
data-testid="review-fulfillment-summary-card"
>
<header class="mb-2">
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">
{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}
</h2>
<p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">
{{ t('chat.shippingOrderReview.fulfillmentDecision.railHint') }}
</p>
</header>
<ul class="space-y-1 text-xs text-secondary">
<li>{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: openCount }) }}</li>
<li>{{ t('chat.shippingOrderReview.fulfillmentDecision.readyCount', { count: readyCount }) }}</li>
<li v-if="shortageCount">
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortageCount', { count: shortageCount }) }}
</li>
</ul>
<button
type="button"
class="mt-3 w-full rounded-xl border border-sky-300 bg-white px-3 py-1.5 text-sm text-sky-950 hover:bg-sky-100 dark:border-sky-800 dark:bg-slate-900 dark:text-sky-50 dark:hover:bg-sky-950"
data-testid="review-fulfillment-enter-inventory"
@click="emit('enter-inventory')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.enterInventory') }}
</button>
</section>
</template>
@@ -0,0 +1,76 @@
<!--
features/chat/components/shipping-review/ReviewInventoryIssueFallbackCard.vue
用途:无行投影且库存系统失败时的 Case 级兜底卡;仅重试获取库存。
依赖:vue-i18n。
逻辑:由 ShippingOrderReviewView 在 inventory_issue_fallback 或行级库存问题聚合时挂载;
禁止进库存工作台、禁止匹配/关闭/换源。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
export interface InventoryIssueFallback {
kind?: string | null;
reason_label_key?: string | null;
affected_line_count?: number | null;
file_count?: number | null;
allowed_actions?: string[] | null;
}
const props = defineProps<{
fallback: InventoryIssueFallback | null | undefined;
busy?: boolean;
}>();
const emit = defineEmits<{
'retry-preparation': [];
}>();
const { t, te } = useI18n();
const visible = computed(() => {
const actions = props.fallback?.allowed_actions || [];
return Boolean(props.fallback && actions.includes('retry_inventory_preparation'));
});
/**
* 失败原因文案。
*/
const reasonLabel = computed(() => {
const keyCode = String(props.fallback?.reason_label_key || props.fallback?.kind || '').trim();
const key = `chat.shippingOrderReview.inventoryFallback.kinds.${keyCode}`;
return te(key) ? t(key) : t('chat.shippingOrderReview.inventoryFallback.kinds.inventory_file_missing');
});
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-amber-200 bg-amber-50/70 p-3 shadow-sm dark:border-amber-900 dark:bg-amber-950/30"
data-testid="review-inventory-issue-fallback"
>
<h2 class="text-sm font-semibold text-amber-950 dark:text-amber-50">
{{ t('chat.shippingOrderReview.inventoryFallback.title') }}
</h2>
<p class="mt-1 text-xs text-amber-900 dark:text-amber-100" data-testid="review-inventory-fallback-reason">
{{ reasonLabel }}
</p>
<p
v-if="(fallback?.affected_line_count || 0) > 0"
class="mt-1 text-[11px] text-amber-800/90 dark:text-amber-200/90"
>
{{ t('chat.shippingOrderReview.inventoryFallback.affectedLines', {
count: fallback?.affected_line_count || 0,
}) }}
</p>
<button
type="button"
class="mt-3 w-full rounded-xl border border-amber-300 bg-white px-3 py-1.5 text-sm text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-800 dark:bg-slate-900 dark:text-amber-50"
data-testid="review-inventory-fallback-retry"
:disabled="busy"
@click="emit('retry-preparation')"
>
{{ t('chat.shippingOrderReview.lineOps.retryPreparation') }}
</button>
</section>
</template>
@@ -3,7 +3,7 @@
用途:标准复核侧栏中的异常库存行摘要列表(只显示需处理行)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection。
逻辑:行列表由后端 recovery/suggestion 投影提供,前端不自行发明异常规则;
点击行可定位明细或进入库存处理模式。
点击行可定位明细;正式 OT 后 showEnterAction=false,禁止切库存工作台。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
@@ -12,9 +12,11 @@ import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/featur
defineProps<{
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
/**
* 仅展示「进入库存」入口,不列出行明细(Gate/履约摘要已表达缺口时使用)。
* 仅展示摘要标题,不列出行明细(Gate/履约摘要已表达缺口时使用)。
*/
summaryOnly?: boolean;
/** 是否展示「进入库存」按钮;正式 OT 后应关闭。 */
showEnterAction?: boolean;
}>();
const emit = defineEmits<{
@@ -44,6 +46,7 @@ function blockReasonLabel(reason?: string | null): string {
<header class="mb-2 flex items-center justify-between gap-2">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workbench.inventoryIssues') }}</h2>
<button
v-if="showEnterAction"
type="button"
class="rounded border border-amber-300 px-2 py-1 text-xs text-amber-900 hover:bg-amber-50 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950/40"
data-testid="review-inventory-issues-enter"
@@ -0,0 +1,76 @@
/**
* features/chat/components/shipping-review/ReviewLineFulfillmentAggregateCard.spec.ts
* 用途:锁定 UI-3 订单级聚合卡——同时展示系统进度与人工待办,无逐行摘要。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewLineFulfillmentAggregateCard from './ReviewLineFulfillmentAggregateCard.vue';
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
lineFulfillmentAggregate: {
title: '履约进度摘要',
hint: '同时展示系统进度与人工待办',
autoProgress: '系统处理中 {count} 行',
manualPending: '待人工处理 {count} 行',
inventoryPending: '库存处理中 {count} 行',
systemFailed: '自动履约失败 {count} 行',
enterInventory: '进入库存/履约处理',
viewLines: '查看订单明细',
},
},
},
},
},
});
describe('ReviewLineFulfillmentAggregateCard', () => {
it('shows system progress and manual pending together with inventory entry', async () => {
const lineFulfillment: ShippingOrderReviewLineFulfillment = {
lines: [],
auto_progress_count: 2,
manual_pending_count: 1,
system_failed_count: 0,
inventory_pending_count: 0,
};
const wrapper = mount(ReviewLineFulfillmentAggregateCard, {
props: { lineFulfillment },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-auto-progress"]').text())
.toContain('2');
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-manual-pending"]').text())
.toContain('1');
// 断言:不得只有系统进度而无短缺入口
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-enter-inventory"]').exists())
.toBe(true);
await wrapper.get('[data-testid="review-line-fulfillment-aggregate-enter-inventory"]').trigger('click');
expect(wrapper.emitted('enter-inventory')).toBeTruthy();
});
it('hides when all aggregate counts are zero', () => {
const wrapper = mount(ReviewLineFulfillmentAggregateCard, {
props: {
lineFulfillment: {
lines: [],
auto_progress_count: 0,
manual_pending_count: 0,
system_failed_count: 0,
inventory_pending_count: 0,
},
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-line-fulfillment-aggregate-card"]').exists()).toBe(false);
});
});
@@ -0,0 +1,114 @@
<!--
features/chat/components/shipping-review/ReviewLineFulfillmentAggregateCard.vue
用途:正式 OT 后右侧订单级履约聚合卡(系统进度 / 人工待办 / 失败),无逐行摘要。
依赖:vue-i18n、ShippingOrderReviewLineFulfillment。
逻辑:由 ShippingOrderReviewView 在 hasFormalOt 时挂载于侧栏主卡区;
同时展示系统进度与短缺入口,禁止只显示「系统处理中」。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
}>();
const emit = defineEmits<{
'enter-inventory': [];
}>();
const { t } = useI18n();
/**
* 聚合计数(后端投影;缺省按 0)。
*/
const autoProgressCount = computed(() => Number(props.lineFulfillment?.auto_progress_count || 0));
const manualPendingCount = computed(() => Number(props.lineFulfillment?.manual_pending_count || 0));
const systemFailedCount = computed(() => Number(props.lineFulfillment?.system_failed_count || 0));
const inventoryPendingCount = computed(() => Number(
props.lineFulfillment?.inventory_pending_count || 0,
));
/**
* 有任一非零计数才展示;避免空卡占位。
*/
const visible = computed(() => (
autoProgressCount.value > 0
|| manualPendingCount.value > 0
|| systemFailedCount.value > 0
|| inventoryPendingCount.value > 0
));
/**
* 人工/库存/失败需进入明细处理;纯系统进度可不强调入口。
* 本轮禁止切换库存工作台,入口改为由父级滚到明细。
*/
const showEnterInventory = computed(() => (
manualPendingCount.value > 0
|| systemFailedCount.value > 0
|| inventoryPendingCount.value > 0
));
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-line-fulfillment-aggregate-card"
>
<header class="mb-2">
<h2 class="text-sm font-semibold text-slate-900 dark:text-slate-50">
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.title') }}
</h2>
<p class="mt-0.5 text-xs text-muted">
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.hint') }}
</p>
</header>
<ul class="space-y-1 text-xs text-secondary">
<li
v-if="autoProgressCount > 0"
data-testid="review-line-fulfillment-aggregate-auto-progress"
>
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.autoProgress', {
count: autoProgressCount,
}) }}
</li>
<li
v-if="manualPendingCount > 0"
class="font-medium text-amber-800 dark:text-amber-200"
data-testid="review-line-fulfillment-aggregate-manual-pending"
>
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.manualPending', {
count: manualPendingCount,
}) }}
</li>
<li
v-if="inventoryPendingCount > 0"
data-testid="review-line-fulfillment-aggregate-inventory-pending"
>
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.inventoryPending', {
count: inventoryPendingCount,
}) }}
</li>
<li
v-if="systemFailedCount > 0"
class="font-medium text-rose-700 dark:text-rose-300"
data-testid="review-line-fulfillment-aggregate-system-failed"
>
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.systemFailed', {
count: systemFailedCount,
}) }}
</li>
</ul>
<button
v-if="showEnterInventory"
type="button"
class="mt-3 w-full rounded-xl border border-slate-300 bg-slate-50 px-3 py-1.5 text-sm text-slate-900 hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-50 dark:hover:bg-slate-800"
data-testid="review-line-fulfillment-aggregate-enter-inventory"
@click="emit('enter-inventory')"
>
{{ t('chat.shippingOrderReview.lineFulfillmentAggregate.viewLines') }}
</button>
</section>
</template>
@@ -0,0 +1,73 @@
/**
* features/chat/components/shipping-review/ReviewLineFulfillmentDetail.spec.ts
* 用途:锁定 UI-2 行内履约摘要字段与审计入口。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewLineFulfillmentDetail from './ReviewLineFulfillmentDetail.vue';
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
lineFulfillmentDetail: {
title: '行履约摘要',
wave: '履约波次',
task: '正式任务',
snapshotId: '库存快照 ID',
matchedAt: '匹配校验时间',
decisionSource: '决定来源',
decisionSourceValue: {
system: '系统自动',
user: '人工',
unknown: '未知',
},
failureReason: '自动履约失败原因',
noFailure: '无',
openAudit: '打开审计',
close: '收起',
},
},
},
},
},
});
describe('ReviewLineFulfillmentDetail', () => {
it('renders wave/task/snapshot/source/failure and emits audit', async () => {
const line: ShippingOrderReviewLineFulfillmentLine = {
line_key: 'L1',
inventory_snapshot_id: 42,
inventory_checked_at: '2026-08-07T01:00:00Z',
decision_source: 'system',
auto_fulfill_error_message: 'wave_explode',
decision: {
wave_no: 3,
task_id: 9,
decision_source: 'system',
},
};
const wrapper = mount(ReviewLineFulfillmentDetail, {
props: { line, taskNo: 'SN-100' },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-line-fulfillment-summary"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-line-fulfillment-field-wave"]').text()).toContain('3');
expect(wrapper.find('[data-testid="review-line-fulfillment-field-task"]').text()).toContain('SN-100');
expect(wrapper.find('[data-testid="review-line-fulfillment-field-snapshot"]').text()).toContain('42');
expect(wrapper.find('[data-testid="review-line-fulfillment-field-decisionSource"]').text()).toContain('系统自动');
expect(wrapper.find('[data-testid="review-line-fulfillment-field-failure"]').text()).toContain('wave_explode');
await wrapper.get('[data-testid="review-line-fulfillment-open-audit"]').trigger('click');
expect(wrapper.emitted('open-audit')).toBeTruthy();
await wrapper.get('[data-testid="review-line-fulfillment-summary-close"]').trigger('click');
expect(wrapper.emitted('close')).toBeTruthy();
});
});
@@ -0,0 +1,133 @@
<!--
features/chat/components/shipping-review/ReviewLineFulfillmentDetail.vue
用途:订单明细行内履约摘要(查看履约详情);不进入库存工作台。
依赖:vue-i18n、ShippingOrderReviewLineFulfillmentLine。
逻辑:由 ShippingOrderReviewView 在展开行下方挂载;展示 wave/task/快照/匹配时间/
决定来源/失败原因,并提供审计入口。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
line: ShippingOrderReviewLineFulfillmentLine | null | undefined;
taskNo?: string | null;
}>();
const emit = defineEmits<{
'open-audit': [];
close: [];
}>();
const { t, te } = useI18n();
/**
* 展示用字段行。
*/
const rows = computed(() => {
const line = props.line;
const decision = line?.decision;
const waveNo = decision?.wave_no ?? null;
const taskNo = String(props.taskNo || '').trim()
|| (decision?.task_id != null ? String(decision.task_id) : '');
const source = String(line?.decision_source || decision?.decision_source || '').trim();
const sourceKey = `chat.shippingOrderReview.lineFulfillmentDetail.decisionSourceValue.${source}`;
const sourceLabel = source
? (te(sourceKey) ? t(sourceKey) : source)
: '—';
const failure = String(line?.auto_fulfill_error_message || '').trim();
return [
{
key: 'wave',
label: t('chat.shippingOrderReview.lineFulfillmentDetail.wave'),
value: waveNo != null ? String(waveNo) : '—',
},
{
key: 'task',
label: t('chat.shippingOrderReview.lineFulfillmentDetail.task'),
value: taskNo || '—',
},
{
key: 'snapshot',
label: t('chat.shippingOrderReview.lineFulfillmentDetail.snapshotId'),
value: line?.inventory_snapshot_id != null ? String(line.inventory_snapshot_id) : '—',
},
{
key: 'matchedAt',
label: t('chat.shippingOrderReview.lineFulfillmentDetail.matchedAt'),
value: formatTime(line?.inventory_checked_at),
},
{
key: 'decisionSource',
label: t('chat.shippingOrderReview.lineFulfillmentDetail.decisionSource'),
value: sourceLabel,
},
{
key: 'failure',
label: t('chat.shippingOrderReview.lineFulfillmentDetail.failureReason'),
value: failure || t('chat.shippingOrderReview.lineFulfillmentDetail.noFailure'),
emphasize: Boolean(failure),
},
];
});
/**
* 格式化匹配/校验时间。
*/
function formatTime(value: string | null | undefined): string {
if (!value) return '—';
const date = new Date(value);
return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString();
}
</script>
<template>
<div
class="rounded-md border border-slate-200 bg-slate-50/80 px-3 py-2 text-xs dark:border-slate-700 dark:bg-slate-950/50"
data-testid="review-line-fulfillment-summary"
role="region"
:aria-label="t('chat.shippingOrderReview.lineFulfillmentDetail.title')"
>
<div class="mb-2 flex items-center justify-between gap-2">
<p class="font-medium text-slate-700 dark:text-slate-200">
{{ t('chat.shippingOrderReview.lineFulfillmentDetail.title') }}
</p>
<div class="flex items-center gap-2">
<button
type="button"
class="rounded border border-slate-300 px-2 py-0.5 text-[11px] text-sky-700 hover:bg-white dark:border-slate-600 dark:text-sky-300 dark:hover:bg-slate-900"
data-testid="review-line-fulfillment-open-audit"
@click="emit('open-audit')"
>
{{ t('chat.shippingOrderReview.lineFulfillmentDetail.openAudit') }}
</button>
<button
type="button"
class="rounded px-2 py-0.5 text-[11px] text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-800"
data-testid="review-line-fulfillment-summary-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.lineFulfillmentDetail.close') }}
</button>
</div>
</div>
<dl class="grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3">
<div
v-for="row in rows"
:key="row.key"
class="min-w-0 rounded bg-white/70 px-2 py-1.5 dark:bg-slate-900/60"
:data-testid="`review-line-fulfillment-field-${row.key}`"
>
<dt class="text-[10px] font-medium text-slate-500 dark:text-slate-400">{{ row.label }}</dt>
<dd
class="mt-0.5 break-words text-[11px] text-slate-800 dark:text-slate-100"
:class="row.emphasize ? 'font-medium text-rose-700 dark:text-rose-300' : ''"
>
{{ row.value }}
</dd>
</div>
</dl>
</div>
</template>
@@ -0,0 +1,115 @@
/**
* features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts
* 用途:锁定库存浮层仅渲染 inventory_allowed_actions;关闭在更多操作;Teleport 菜单可见。
*/
import { afterEach, describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewLineInventoryOps from './ReviewLineInventoryOps.vue';
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
lineOps: {
inventoryProcessing: '库存处理',
retryPreparation: '重试获取库存',
retryMatching: '重新匹配库存',
moreActions: '更多操作',
viewFulfillment: '查看履约详情',
},
fulfillmentDecision: {
closeLine: '关闭该明细',
},
},
},
},
},
});
function mountOps(line: Partial<ShippingOrderReviewLineFulfillmentLine>) {
return mount(ReviewLineInventoryOps, {
props: {
line: line as ShippingOrderReviewLineFulfillmentLine,
editable: true,
},
attachTo: document.body,
global: { plugins: [i18n] },
});
}
afterEach(() => {
document.body.innerHTML = '';
});
describe('ReviewLineInventoryOps', () => {
it('shows only preparation when matching not allowed', async () => {
const wrapper = mountOps({
inventory_allowed_actions: ['retry_inventory_preparation'],
line_allowed_actions: [],
});
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-retry-preparation"]')).toBeTruthy();
expect(document.querySelector('[data-testid="review-line-retry-matching"]')).toBeFalsy();
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeFalsy();
wrapper.unmount();
});
it('puts close under more actions, not inventory panel', async () => {
const wrapper = mountOps({
inventory_allowed_actions: ['retry_inventory_preparation'],
line_allowed_actions: ['close_unfulfillable'],
});
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeFalsy();
await wrapper.get('[data-testid="review-line-more-actions"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-decide-close"]')).toBeTruthy();
wrapper.unmount();
});
it('hides inventory icon when no inventory actions and no problem status', () => {
const wrapper = mountOps({
inventory_allowed_actions: [],
line_allowed_actions: ['close_unfulfillable'],
user_line_status: 'inventory_matched',
inventory_status: 'ready',
display_available: '50',
});
expect(wrapper.find('[data-testid="review-line-view-inventory"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-line-more-actions"]').exists()).toBe(true);
wrapper.unmount();
});
it('shows inventory icon from problem status even when backend actions empty', async () => {
const wrapper = mountOps({
inventory_allowed_actions: [],
line_allowed_actions: [],
user_line_status: 'inventory_pending',
inventory_status: 'preparing',
display_available: 'pending',
});
expect(wrapper.find('[data-testid="review-line-view-inventory"]').exists()).toBe(true);
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-retry-preparation"]')).toBeTruthy();
wrapper.unmount();
});
it('emits retry-inventory for both floating actions', async () => {
const wrapper = mountOps({
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
line_allowed_actions: [],
});
await wrapper.get('[data-testid="review-line-view-inventory"]').trigger('click');
expect(document.querySelector('[data-testid="review-line-retry-preparation"]')).toBeTruthy();
expect(document.querySelector('[data-testid="review-line-retry-matching"]')).toBeTruthy();
(document.querySelector('[data-testid="review-line-retry-matching"]') as HTMLButtonElement).click();
await wrapper.vm.$nextTick();
expect(wrapper.emitted('retry-inventory')?.[0]).toEqual(['retry_inventory_matching']);
wrapper.unmount();
});
});
@@ -0,0 +1,297 @@
<!--
features/chat/components/shipping-review/ReviewLineInventoryOps.vue
用途:明细行库存处理浮层 + 行级更多操作(关闭);不进库存工作台、不在右侧挂动作。
依赖:vue-i18n、lucide、line.inventory_allowed_actions / line_allowed_actions。
逻辑:优先后端动作;库存问题态后端漏下发时前端兜底 preparation(+匹配失败时 matching);
菜单 Teleport 到 body,避免表格 overflow 裁切。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { MoreHorizontal, Warehouse } from 'lucide-vue-next';
import type { ShippingOrderReviewLineFulfillmentLine } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
line: ShippingOrderReviewLineFulfillmentLine | null | undefined;
editable: boolean;
busy?: boolean;
}>();
const emit = defineEmits<{
'retry-inventory': [actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching'];
'close-line': [];
'view-fulfillment': [];
}>();
const { t } = useI18n();
const inventoryMenuOpen = ref(false);
const moreMenuOpen = ref(false);
const inventoryBtnRef = ref<HTMLElement | null>(null);
const moreBtnRef = ref<HTMLElement | null>(null);
const inventoryMenuStyle = ref<Record<string, string>>({});
const moreMenuStyle = ref<Record<string, string>>({});
const PROBLEM_USER_STATUSES = new Set([
'inventory_file_missing',
'inventory_file_expired',
'inventory_match_failed',
'inventory_source_unrecognized',
'source_conflict',
'shortage',
'inventory_pending',
'acquiring_inventory',
'auto_fulfill_failed',
]);
const PROBLEM_INVENTORY_STATUSES = new Set([
'preparing',
'unavailable',
'mapping_failed',
'source_conflict',
'invalid_key',
]);
/**
* 库存动作集合:后端优先;问题态漏下发时兜底 preparation / matching。
*/
const inventoryActions = computed(() => {
const fromBe = [...(props.line?.inventory_allowed_actions || [])].filter(Boolean);
if (fromBe.length) return new Set(fromBe);
if (!props.line) return new Set<string>();
const userStatus = String(props.line.user_line_status || '').trim();
const invStatus = String(props.line.inventory_status || '').trim();
const matchResult = String(props.line.match_result || '').trim();
const isProblem = (
PROBLEM_USER_STATUSES.has(userStatus)
|| PROBLEM_INVENTORY_STATUSES.has(invStatus)
|| props.line.display_available === 'pending'
|| Boolean(props.line.is_shortage)
);
if (!isProblem) return new Set<string>();
const actions = new Set<string>(['retry_inventory_preparation']);
if (
userStatus === 'inventory_match_failed'
|| invStatus === 'mapping_failed'
|| matchResult === 'mapping_failed'
) {
actions.add('retry_inventory_matching');
}
return actions;
});
const lineActions = computed(() => {
const fromBe = [...(props.line?.line_allowed_actions || [])].filter(Boolean);
if (fromBe.length) return new Set(fromBe);
const userStatus = String(props.line?.user_line_status || '').trim();
if (!props.line) return new Set<string>();
if (['wave_created', 'fulfilled', 'closed'].includes(userStatus)) {
return userStatus === 'closed' ? new Set<string>() : new Set(['view_fulfillment_detail']);
}
if (PROBLEM_USER_STATUSES.has(userStatus) || Boolean(props.line.is_shortage)) {
return new Set(['close_unfulfillable']);
}
return new Set<string>();
});
const showInventoryOps = computed(() => (
inventoryActions.value.has('retry_inventory_preparation')
|| inventoryActions.value.has('retry_inventory_matching')
));
const canRetryPreparation = computed(() => inventoryActions.value.has('retry_inventory_preparation'));
const canRetryMatching = computed(() => inventoryActions.value.has('retry_inventory_matching'));
const canClose = computed(() => lineActions.value.has('close_unfulfillable'));
const canViewFulfillment = computed(() => lineActions.value.has('view_fulfillment_detail'));
const showMore = computed(() => canClose.value || canViewFulfillment.value);
/**
* 按触发按钮定位浮动菜单(fixed,避免被表格 overflow 裁切)。
*/
function placeMenu(anchor: HTMLElement | null, target: typeof inventoryMenuStyle) {
if (!anchor || typeof window === 'undefined') return;
const rect = anchor.getBoundingClientRect();
const width = 168;
const left = Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8));
target.value = {
position: 'fixed',
top: `${Math.round(rect.bottom + 4)}px`,
left: `${Math.round(left)}px`,
width: `${width}px`,
zIndex: '80',
};
}
/**
* 关闭所有浮层。
*/
function closeMenus() {
inventoryMenuOpen.value = false;
moreMenuOpen.value = false;
}
/**
* 文档点击/滚动时关闭浮层,避免残留遮挡。
*/
function onDocPointerDown(event: Event) {
const target = event.target as Node | null;
if (!target) return;
const el = target as HTMLElement;
if (el.closest?.('[data-testid="review-line-inventory-panel"]')) return;
if (el.closest?.('[data-testid="review-line-more-menu"]')) return;
if (el.closest?.('[data-testid="review-line-view-inventory"]')) return;
if (el.closest?.('[data-testid="review-line-more-actions"]')) return;
closeMenus();
}
function onViewportChange() {
if (inventoryMenuOpen.value) placeMenu(inventoryBtnRef.value, inventoryMenuStyle);
if (moreMenuOpen.value) placeMenu(moreBtnRef.value, moreMenuStyle);
}
/**
* 切换库存处理浮层。
*/
async function toggleInventoryMenu() {
moreMenuOpen.value = false;
inventoryMenuOpen.value = !inventoryMenuOpen.value;
if (inventoryMenuOpen.value) {
await nextTick();
placeMenu(inventoryBtnRef.value, inventoryMenuStyle);
}
}
/**
* 切换更多操作浮层。
*/
async function toggleMoreMenu() {
inventoryMenuOpen.value = false;
moreMenuOpen.value = !moreMenuOpen.value;
if (moreMenuOpen.value) {
await nextTick();
placeMenu(moreBtnRef.value, moreMenuStyle);
}
}
/**
* 触发库存动作并关闭浮层。
*/
function onRetry(actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching') {
closeMenus();
emit('retry-inventory', actionCode);
}
/**
* 关闭明细(由父级弹确认框)。
*/
function onCloseLine() {
closeMenus();
emit('close-line');
}
if (typeof document !== 'undefined') {
document.addEventListener('pointerdown', onDocPointerDown, true);
window.addEventListener('scroll', onViewportChange, true);
window.addEventListener('resize', onViewportChange);
}
onBeforeUnmount(() => {
if (typeof document === 'undefined') return;
document.removeEventListener('pointerdown', onDocPointerDown, true);
window.removeEventListener('scroll', onViewportChange, true);
window.removeEventListener('resize', onViewportChange);
});
</script>
<template>
<div class="relative inline-flex items-center gap-0.5">
<button
v-if="showInventoryOps"
ref="inventoryBtnRef"
type="button"
class="rounded p-1.5 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800"
data-testid="review-line-view-inventory"
:disabled="busy"
:aria-label="t('chat.shippingOrderReview.lineOps.inventoryProcessing')"
:title="t('chat.shippingOrderReview.lineOps.inventoryProcessing')"
:aria-expanded="inventoryMenuOpen"
@click="toggleInventoryMenu"
>
<Warehouse class="h-3.5 w-3.5" aria-hidden="true" />
</button>
<button
v-if="showMore"
ref="moreBtnRef"
type="button"
class="rounded p-1.5 hover:bg-slate-100 disabled:opacity-50 dark:hover:bg-slate-800"
data-testid="review-line-more-actions"
:disabled="!editable || busy"
:aria-label="t('chat.shippingOrderReview.lineOps.moreActions')"
:title="t('chat.shippingOrderReview.lineOps.moreActions')"
:aria-expanded="moreMenuOpen"
@click="toggleMoreMenu"
>
<MoreHorizontal class="h-3.5 w-3.5" aria-hidden="true" />
</button>
<Teleport to="body">
<div
v-if="inventoryMenuOpen && showInventoryOps"
class="rounded-md border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-900"
role="menu"
data-testid="review-line-inventory-panel"
:style="inventoryMenuStyle"
>
<button
v-if="canRetryPreparation"
type="button"
class="block w-full px-3 py-2 text-left text-xs hover:bg-slate-50 dark:hover:bg-slate-800"
role="menuitem"
data-testid="review-line-retry-preparation"
@click="onRetry('retry_inventory_preparation')"
>
{{ t('chat.shippingOrderReview.lineOps.retryPreparation') }}
</button>
<button
v-if="canRetryMatching"
type="button"
class="block w-full px-3 py-2 text-left text-xs hover:bg-slate-50 dark:hover:bg-slate-800"
role="menuitem"
data-testid="review-line-retry-matching"
@click="onRetry('retry_inventory_matching')"
>
{{ t('chat.shippingOrderReview.lineOps.retryMatching') }}
</button>
</div>
<div
v-if="moreMenuOpen && showMore"
class="rounded-md border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-900"
role="menu"
data-testid="review-line-more-menu"
:style="moreMenuStyle"
>
<button
v-if="canViewFulfillment"
type="button"
class="block w-full px-3 py-2 text-left text-xs hover:bg-slate-50 dark:hover:bg-slate-800"
role="menuitem"
data-testid="review-line-fulfillment-detail"
@click="closeMenus(); emit('view-fulfillment')"
>
{{ t('chat.shippingOrderReview.lineOps.viewFulfillment') }}
</button>
<button
v-if="canClose"
type="button"
class="block w-full px-3 py-2 text-left text-xs text-rose-700 hover:bg-rose-50 dark:text-rose-300 dark:hover:bg-rose-950/40"
role="menuitem"
data-testid="review-line-decide-close"
@click="onCloseLine"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeLine') }}
</button>
</div>
</Teleport>
</div>
</template>
@@ -1,8 +1,9 @@
<!--
features/chat/components/shipping-review/ReviewProfileMatchPanel.vue
用途:复核工作台文档模板匹配只读区(选中模板 / 候选分 / 回退原因)。
用途:复核工作台文档模板匹配只读区(用户四态;管理员详细在技术诊断)。
依赖:vue-i18n、ShippingOrderReviewProfileMatch。
逻辑:A3 只展示;换模板/重抽取仍走 Process Gate 或重新识别 PDF。
逻辑:普通用户只显示 matched/unmatched/ambiguous/unknown;
required_field_missing 不在此展示;分数/Profile ID 仅 admin visibility。
-->
<script setup lang="ts">
import { computed } from 'vue';
@@ -15,11 +16,18 @@ const props = defineProps<{
const { t, te } = useI18n();
const visible = computed(() => Boolean(props.profileMatch?.available));
const visible = computed(() => {
const match = props.profileMatch;
if (!match) return false;
if (match.visibility === 'admin_only' && match.available === false) return false;
return Boolean(match.available !== false);
});
const isAdminView = computed(() => String(props.profileMatch?.visibility || '') === 'admin');
const needsReview = computed(() => Boolean(props.profileMatch?.needs_review));
/**
* 匹配状态本地化。
* 匹配状态本地化(用户四态)。
*/
const statusLabel = computed(() => {
const status = String(props.profileMatch?.status || '').trim();
@@ -28,27 +36,19 @@ const statusLabel = computed(() => {
});
/**
* 选中模板展示名。
* 选中模板展示名(用户仅 display_name)。
*/
const selectedLabel = computed(() => {
const selected = props.profileMatch?.selected_profile;
if (!selected?.profile_code) {
if (!selected) {
return t('chat.shippingOrderReview.profileMatch.noSelected');
}
const name = String(selected.display_name || selected.profile_code).trim();
const name = String(selected.display_name || selected.profile_code || '').trim();
if (!name) return t('chat.shippingOrderReview.profileMatch.noSelected');
if (!isAdminView.value) return name;
const version = selected.version != null ? ` v${selected.version}` : '';
return `${name}${version}`;
});
/**
* 回退原因本地化列表。
*/
const fallbackLabels = computed(() =>
(props.profileMatch?.fallback_reason_codes || []).map((code) => {
const key = `chat.shippingOrderReview.profileMatch.reasons.${code}`;
return te(key) ? t(key) : code;
}),
);
</script>
<template>
@@ -56,6 +56,7 @@ const fallbackLabels = computed(() =>
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-profile-match-panel"
:data-status="String(profileMatch?.status || '')"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
@@ -78,47 +79,33 @@ const fallbackLabels = computed(() =>
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.selected') }}</dt>
<dd class="font-medium text-primary" data-testid="review-profile-match-selected">{{ selectedLabel }}</dd>
</div>
<div v-if="profileMatch?.route_type" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.routeType') }}</dt>
<dd class="font-mono">{{ profileMatch.route_type }}</dd>
</div>
<div v-if="profileMatch?.execution_mode" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt>
<dd class="font-mono">{{ profileMatch.execution_mode }}</dd>
</div>
</dl>
<ul
v-if="(profileMatch?.candidates || []).length"
class="mt-2 space-y-1.5"
data-testid="review-profile-match-candidates"
>
<li
v-for="(item, idx) in profileMatch?.candidates || []"
:key="`${item.profile_code}-${item.version}-${idx}`"
class="rounded-lg border border-default bg-surface-soft px-2.5 py-1.5 text-[11px] text-secondary"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="font-medium text-primary">
{{ item.display_name || item.profile_code }}
<span v-if="item.version != null" class="text-muted">v{{ item.version }}</span>
</span>
<span v-if="item.score != null" class="font-mono text-muted">
{{ t('chat.shippingOrderReview.profileMatch.score', { score: Number(item.score).toFixed(2) }) }}
</span>
<template v-if="isAdminView">
<dl class="mt-2 space-y-1 text-xs text-secondary">
<div v-if="profileMatch?.route_type" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.routeType') }}</dt>
<dd class="font-mono">{{ profileMatch.route_type }}</dd>
</div>
<p v-if="item.reason_codes?.length" class="mt-0.5 text-muted">
{{ item.reason_codes.join(', ') }}
</p>
</li>
</ul>
<ul v-if="fallbackLabels.length" class="mt-2 list-disc space-y-0.5 pl-4 text-[11px] text-amber-900 dark:text-amber-100">
<li v-for="label in fallbackLabels" :key="label">{{ label }}</li>
</ul>
<p class="mt-2 text-[11px] text-muted">
{{ t('chat.shippingOrderReview.profileMatch.reselectHint') }}
</p>
<div v-if="profileMatch?.execution_mode" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt>
<dd class="font-mono">{{ profileMatch.execution_mode }}</dd>
</div>
</dl>
<ul
v-if="(profileMatch?.candidates || []).length"
class="mt-2 space-y-1.5"
data-testid="review-profile-match-candidates"
>
<li
v-for="(item, idx) in profileMatch?.candidates || []"
:key="`${item.profile_code}-${item.version}-${idx}`"
class="rounded-lg border border-default bg-surface-soft px-2.5 py-1.5 text-[11px] text-secondary"
>
<span class="font-mono">{{ item.profile_code }}</span>
<span v-if="item.score != null" class="ml-2 text-muted">{{ item.score }}</span>
</li>
</ul>
</template>
</section>
</template>
@@ -3,6 +3,7 @@
用途:订单处理工作台只读进度区外壳——挂载压缩版 ReviewProgressStrip + 人工上传入口。
依赖:vue-i18n、ShippingProcessingProjection、ReviewProgressStrip、shippingProcessingFulfillment。
逻辑:标题与「当前需要」由 Strip 统一渲染;surface=review 永不渲染 review-generic-next-steps;
正式 OT 已创建时传 hasFormalOt 抑制「请确认建单」;
仅人工上传保留任务台跳转;其他 Gate 只靠 Strip + Footer;写操作不在本面板。
-->
<script setup lang="ts">
@@ -24,6 +25,8 @@ const props = defineProps<{
polling?: boolean;
/** 统一进度投影:节点与文案的权威来源。 */
processingProjection?: ShippingProcessingProjection | null;
/** 正式 OT 已创建;抑制确认建单类「当前需要」。 */
hasFormalOt?: boolean;
}>();
const emit = defineEmits<{
@@ -47,7 +50,7 @@ const showTaskWorkbenchLink = computed(() => {
<template>
<section
class="rounded-xl border border-default bg-surface-soft/60 p-3"
class="rounded-xl border border-default bg-surface-soft/60 p-2.5"
data-testid="review-workflow-progress-panel"
>
<div
@@ -62,6 +65,7 @@ const showTaskWorkbenchLink = computed(() => {
v-else-if="processingProjection"
:projection="processingProjection"
:polling="polling"
:has-formal-ot="hasFormalOt || Boolean(String(taskNo || '').trim())"
@open-process-details="emit('open-process-details')"
@refresh="emit('refresh')"
/>
@@ -357,6 +357,8 @@ export function useShippingOrderReview() {
const loadFailed = ref(false);
const saving = ref(false);
const saveFailed = ref(false);
/** 显式校验期间清空旧资格投影,避免短暂显示过期的“不可建单”。 */
const validationInProgress = ref(false);
/** ???????????????????????????? */
const draftConflict = ref<DraftVersionConflict | null>(null);
const versionsLoading = ref(false);
@@ -730,11 +732,15 @@ export function useShippingOrderReview() {
/** ?? Case ???????????validate ???? */
const buildEligibility = computed(
() => activeCase.value?.draft?.build_eligibility ?? null,
() => validationInProgress.value ? null : (activeCase.value?.draft?.build_eligibility ?? null),
);
/** ?? build_eligibility ? can_build ? false ???????? */
const canConfirmBuild = computed(() => !isBuildConfirmBlocked(buildEligibility.value));
const canConfirmBuild = computed(() => (
!validationInProgress.value
&& Boolean(buildEligibility.value)
&& !isBuildConfirmBlocked(buildEligibility.value)
));
/** ????????????????? */
const manualInventoryLines = computed(() =>
@@ -956,7 +962,14 @@ export function useShippingOrderReview() {
saveFailed.value = false;
const localVersion = version();
try {
activeCase.value = await action();
const nextCase = await action();
// [STEP] 只接受当前 Case 且不低于本地 Draft 版本的响应;旧请求不得回写新快照。
const currentCaseNo = String(activeCase.value?.case_no || '').trim();
const nextCaseNo = String(nextCase?.case_no || '').trim();
const nextVersion = Number(nextCase?.draft?.draft_version ?? 0);
if (nextCaseNo === currentCaseNo && nextVersion >= localVersion) {
activeCase.value = nextCase;
}
draftConflict.value = null;
if (reviewRun.value && activeCase.value) {
const item = reviewRun.value.items.find((row) => row.case_no === activeCase.value?.case_no);
@@ -1154,7 +1167,15 @@ export function useShippingOrderReview() {
const addLine = () => activeCase.value && save(() => addWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, version()));
const copyLine = (lineKey: string) => activeCase.value && save(() => copyWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, lineKey, version()));
const deleteLine = (lineKey: string) => activeCase.value && save(() => deleteWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, lineKey, version()));
const validate = () => activeCase.value && save(() => validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version()));
const validate = async () => {
if (!activeCase.value) return;
validationInProgress.value = true;
try {
await save(() => validateWorkspaceShippingOrderReviewDraft(activeCase.value!.case_no, version()));
} finally {
validationInProgress.value = false;
}
};
/**
* ????????????????? Case?
@@ -1533,6 +1554,7 @@ export function useShippingOrderReview() {
caseSwitchLoading,
caseSwitchFailed,
saving,
validationInProgress,
saveFailed,
versionsLoading,
load,
@@ -140,6 +140,7 @@ export function normalizeShippingProcessingProjection(
intakeNo: readString(item, 'intake_no', 'intakeNo'),
status: (readString(item, 'status', 'status') || 'processing') as ShippingProcessingStatus,
stage: (readString(item, 'stage', 'stage') || 'upload_received') as ShippingProcessingStage,
stageLabelKey: readNullableString(item, 'stage_label_key', 'stageLabelKey'),
progressVersion: Number(item.progress_version ?? item.progressVersion ?? 0) || 0,
lastActivityAt: readString(item, 'last_activity_at', 'lastActivityAt'),
stageNodes: stageNodes?.length ? stageNodes : undefined,
@@ -2,7 +2,8 @@
* features/chat/shipping/shippingProcessingLabels.ts
* 用途:将统一 ShippingProcessing 状态/阶段码映射到四语言 i18n 键。
* 依赖:vue-i18n Composer(由调用方传入 t / te)。
* 逻辑:统一读 chat.shippingProcessing.*(含原 shippingWorkflow 合并键,如 taskStatus)。
* 逻辑:统一读 chat.shippingProcessing.*;阶段展示优先消费后端 label_key
* (如 waiting_system_start),禁止把 stage code 直接当用户文案。
*/
/** 会话 processing 旧 status_label → 统一 ShippingProcessingStatus。 */
@@ -79,7 +80,7 @@ export function resolveShippingProcessingMessage(
}
/**
* 解析统一处理阶段的展示文案键。
* 解析统一处理阶段的展示文案键(技术阶段码)。
* @param stage - ShippingProcessingStage 码
* @returns i18n key
*/
@@ -90,6 +91,41 @@ export function shippingProcessingStageKey(stage: string): string {
: 'chat.shippingProcessing.stage.upload_received';
}
/**
* 解析阶段用户文案:优先后端 label_key,禁止直接展示 stage code。
* 核心逻辑:label_key → stageLabel.* / currentProcessing.stages.*;再回退 stage.*。
*
* @param stage - 技术阶段码
* @param te - i18n te
* @param t - i18n t
* @param labelKey - 后端投影 label_key(如 waiting_system_start)
* @returns 本地化文案
*/
export function resolveShippingProcessingStageLabel(
stage: string,
te: (key: string) => boolean,
t: (key: string) => string,
labelKey?: string | null,
): string {
const lk = String(labelKey || '').trim();
if (lk) {
const stageLabelKey = `chat.shippingProcessing.stageLabel.${lk}`;
if (te(stageLabelKey)) return t(stageLabelKey);
const reviewKey = `chat.shippingOrderReview.currentProcessing.stages.${lk}`;
if (te(reviewKey)) return t(reviewKey);
}
const code = String(stage || '').trim();
if (!code) return '—';
const stageKey = shippingProcessingStageKey(code);
if (te(stageKey)) return t(stageKey);
const reviewCodeKey = `chat.shippingOrderReview.currentProcessing.stages.${code}`;
if (te(reviewCodeKey)) return t(reviewCodeKey);
// 禁止把码当文案:无键时回退通用等待文案,而非裸 code。
return te('chat.shippingProcessing.stageLabel.waiting_system_start')
? t('chat.shippingProcessing.stageLabel.waiting_system_start')
: code;
}
/**
* 解析工作项类型文案键。
* @param workItemType - order_intake | order_task
@@ -159,6 +159,11 @@ export interface ShippingProcessingProjection {
intakeNo: string;
status: ShippingProcessingStatus;
stage: ShippingProcessingStage;
/**
* 后端阶段用户文案键(如 waiting_system_start);与 Case.current_stage.label_key 同源。
* 禁止前端把 stage 技术码直接当用户文案。
*/
stageLabelKey?: string | null;
progressVersion: number;
lastActivityAt: string;
/** 后端 15 阶节点态;存在时 UI 优先消费,禁止页面自行推导。 */
@@ -779,6 +784,8 @@ export interface ShippingProcessGateUserSummary {
next_action_code?: ShippingProcessGateActionCode | string | null;
/** 当前阻断仅剩技术自动恢复时为 true(业务用户无写操作) */
technical_auto_only?: boolean;
/** 当前 Gate 责任方:system | human | unknown */
owner_type?: 'system' | 'human' | 'unknown' | string | null;
responsible_party?: ShippingProcessGateResponsibleParty | string | null;
diagnostic_hint?: string | null;
case_no?: string | null;
@@ -1988,15 +1995,54 @@ export interface ShippingOrderReviewCase {
duplicate?: ShippingOrderReviewDuplicate | null;
/** 建单前文档模板匹配只读摘要 */
profile_match?: ShippingOrderReviewProfileMatch | null;
/** 字段完整性(与 Process Gate field_completeness 同源) */
field_completeness?: {
status: 'ready' | 'blocked' | string;
issues: Array<{
code?: string;
field_id?: string | null;
field_code?: string | null;
line_index?: number | null;
message?: string | null;
}>;
} | null;
/** 后端组装的已完成检查;前端禁止自行拼接 */
completed_checks?: Array<{
code: string;
status: 'passed' | string;
completed_at?: string | null;
}> | null;
/** 正式 OT 驱动的当前阶段;建单前为 order_review */
current_stage?: {
code?: string | null;
label_key?: string | null;
source?: string | null;
inconsistent?: boolean;
process_status?: string | null;
current_step?: string | null;
stage_node?: Record<string, unknown> | null;
} | null;
/** 建单前 Reservation 校验摘要 */
reservation?: ShippingOrderReviewReservation | null;
/** 行级履约决定与库存缺口摘要 */
line_fulfillment?: ShippingOrderReviewLineFulfillment | null;
/** 无行投影且库存系统失败时的 Case 级兜底;有行投影时必须为空。 */
inventory_issue_fallback?: {
kind?: string | null;
reason_label_key?: string | null;
affected_line_count?: number | null;
file_count?: number | null;
allowed_actions?: string[] | null;
} | null;
status: string;
disposition?: string | null;
confirmed_task_id?: number | null;
/** 已确认时关联的任务号;供刷新后恢复推进入口。 */
confirmed_task_no?: string | null;
/** 后端权威:confirmed_task_id 指向可读正式 OT */
has_formal_ot?: boolean;
/** confirmed_task_id 有值但 ShippingNotice 不可读 */
task_missing?: boolean;
/**
* 确认建单后的自动推进投影:needs_retry=true 时前端应展示琥珀色重试条。
* 与即时 confirm 响应的 auto_progress 字段语义对齐,供页面重载恢复。
@@ -2322,6 +2368,12 @@ export interface ShippingOrderReviewAutomation {
can_build?: boolean;
job_id?: number | null;
reason_code?: string | null;
/** pre_ot_stp = 建单前 STP;post_ot_progress = 正式 OT 自动推进 */
phase?: 'pre_ot_stp' | 'post_ot_progress' | string | null;
/** 自动执行责任方 */
owner_type?: 'system' | 'human' | 'unknown' | string | null;
/** 管理员诊断:enqueue_status 等 */
technical?: Record<string, unknown> | null;
}
/** 管理员可见的技术 Gate 进度(普通用户不下发)。 */
@@ -2367,6 +2419,7 @@ export interface ShippingOrderReviewLineFulfillmentDecision {
line_index?: number | null;
decision_version?: number;
decision_code?: string;
decision_source?: 'system' | 'user' | 'unknown' | null;
line_status?: string;
is_active?: boolean;
reason?: string | null;
@@ -2388,7 +2441,7 @@ export type ShippingOrderReviewLineFulfillmentDecisionCode =
| 'use_new_inventory_file'
| 'change_inventory_source';
/** 行级履约与库存缺口投影行。 */
/** 行级履约与库存缺口投影行(含 OT 匹配事实与 allowed_actions)。 */
export interface ShippingOrderReviewLineFulfillmentLine {
line_key: string;
line_index?: number | null;
@@ -2399,6 +2452,26 @@ export interface ShippingOrderReviewLineFulfillmentLine {
shortage_qty?: string | null;
can_fulfill_complete_line?: boolean;
line_status?: string;
user_line_status?: string | null;
inventory_status?: string | null;
match_result?: string | null;
is_shortage?: boolean;
display_available?: 'pending' | 'number' | string | null;
inventory_snapshot_id?: number | null;
inventory_checked_at?: string | null;
inventory_source_code?: string | null;
inventory_source?: {
code?: string | null;
label?: string | null;
status?: 'resolved' | 'resolving' | 'unrecognized' | 'conflict' | 'unavailable' | string | null;
source?: string | null;
} | null;
decision_source?: 'system' | 'user' | 'unknown' | null;
/** @deprecated 使用 inventory_allowed_actions + line_allowed_actions */
allowed_actions?: string[];
inventory_allowed_actions?: string[];
line_allowed_actions?: string[];
auto_fulfill_error_message?: string | null;
decision?: ShippingOrderReviewLineFulfillmentDecision | null;
block_reason?: string | null;
}
@@ -2410,6 +2483,17 @@ export interface ShippingOrderReviewLineFulfillment {
ready_count?: number;
has_open_lines?: boolean;
has_shortage?: boolean;
/** 系统自动履约中 / 已入波次行数(订单级聚合卡)。 */
auto_progress_count?: number;
/** 短缺或待人工决定行数。 */
manual_pending_count?: number;
/** 自动履约失败行数。 */
system_failed_count?: number;
/** 库存处理中 / 冲突 / 无效键行数。 */
inventory_pending_count?: number;
/** 是否已形成可消费的行级库存投影(有则不上 Case 兜底卡)。 */
has_line_inventory_projection?: boolean;
line_auto_fulfill_enabled?: boolean;
}
/** 复核 Case 业务审计时间线条目(含白名单前后快照;敏感事件脱敏)。 */
@@ -15,6 +15,7 @@ import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import {
auditWorkspaceShippingOrderReviewEligibilityDetails,
auditWorkspaceShippingOrderReviewVersionHistory,
autoProgressWorkspaceShippingTask,
retryWorkspaceShippingOrderStpAutoCreate,
} from '@/features/chat/api/shipping.api';
@@ -63,6 +64,8 @@ const reviewRun = ref({
});
const workItem = ref<Record<string, any> | null>(null);
const reviewProgressContext = ref<Record<string, any> | null>(null);
/** 与 activeCase 同源共享,供断言 Progress 优先阶段源。 */
const shippingProcessingProjection = ref<Record<string, any> | null>(null);
const activeCase = ref({
case_no: 'CASE-1',
@@ -125,9 +128,26 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
};
});
/** mock 工厂句柄:vi.mock 提升后由下方 createReviewComposableMock 赋值。 */
const reviewComposableMockApi = vi.hoisted(() => ({
create: null as null | (() => Record<string, unknown>),
}));
vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
REVIEW_BUILD_ELIGIBILITY_BLOCKED: 'SHIPPING.REVIEW_BUILD_ELIGIBILITY_BLOCKED',
useShippingOrderReview: () => ({
useShippingOrderReview: () => {
if (!reviewComposableMockApi.create) {
throw new Error('createReviewComposableMock not initialized');
}
return reviewComposableMockApi.create();
},
}));
/**
* 统一维护 useShippingOrderReview mock 契约,避免新增返回字段时漏改。
*/
function createReviewComposableMock() {
return {
reviewRun,
activeCase,
reviewProgressContext,
@@ -152,6 +172,7 @@ vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
caseSwitchFailed: ref(false),
requestedCaseNo: ref(null),
saving: ref(false),
validationInProgress: ref(false),
saveFailed: ref(false),
versionsLoading: ref(false),
evidence: ref([
@@ -204,7 +225,7 @@ vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
isWorkItemClosed: computed(() => false),
showWorkflowProgress: computed(() => false),
workflowProgressPolling: computed(() => false),
shippingProcessingProjection: ref(null),
shippingProcessingProjection,
shippingProcessingLoading: ref(false),
shippingProcessingError: ref(null),
refreshShippingProcessing: vi.fn(),
@@ -218,8 +239,10 @@ vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
reparseLastRefreshedAt: computed(() => null),
reparseStalePolls: computed(() => 0),
refreshReparseProgress: vi.fn(),
}),
}));
};
}
reviewComposableMockApi.create = createReviewComposableMock;
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => messageMocks,
@@ -299,12 +322,39 @@ vi.mock('../components/shipping-review/ReviewVersionHistoryDrawer.vue', () => ({
},
}));
vi.mock('../components/shipping-review/ReviewWorkflowProgressPanel.vue', () => ({
default: {
name: 'ReviewWorkflowProgressPanel',
template: '<div data-testid="mock-progress" />',
},
}));
vi.mock('../components/shipping-review/ReviewWorkflowProgressPanel.vue', async () => {
const { computed } = await import('vue');
const { useI18n } = await import('vue-i18n');
const { resolveShippingProcessingStageLabel } = await import(
'@/features/chat/shipping/shippingProcessingLabels'
);
return {
default: {
name: 'ReviewWorkflowProgressPanel',
props: ['processingProjection', 'hasFormalOt', 'polling'],
setup(props: { processingProjection?: Record<string, unknown> | null }) {
const { t, te } = useI18n();
const stageLabel = computed(() => {
const projection = props.processingProjection;
if (!projection) return '';
return resolveShippingProcessingStageLabel(
String(projection.stage || ''),
te,
t,
projection.stageLabelKey != null
? String(projection.stageLabelKey)
: null,
);
});
return { stageLabel };
},
template:
'<div data-testid="mock-progress">'
+ '<span data-testid="review-progress-stage-label">{{ stageLabel }}</span>'
+ '</div>',
},
};
});
/**
* 挂载复核工作台视图并注入最小 Chat 上下文。
@@ -462,12 +512,45 @@ async function mountView() {
retryStp: '重试自动推进',
retryStpSuccess: '已重新入队自动建单',
},
currentProcessing: {
title: '当前处理状态',
status: '状态',
formalOt: '正式 OT',
waitingStart: '等待系统启动',
taskMissing: '正式任务关联异常',
taskMissingHint: '正式任务关联异常,请联系管理员',
stateInconsistent: '状态同步中',
statusRunning: '系统处理中',
statusFailedRetryable: '失败可重试',
statusCompleted: '已完成',
statusIdle: '待机',
statusTaskMissing: '关联异常',
stages: {
waiting_system_start: '等待系统启动',
waiting_to_start: '等待系统启动',
order_creating: '等待系统启动',
inventory_matching: '库存匹配',
},
},
automation: {
waitingPreOt: '等待自动建单',
waitingPostOt: '等待系统启动自动推进',
},
confirmSuccess: '{taskNo}',
confirmAutoProgress: '{taskNo}',
confirmProgressFailed: '已创建任务 {taskNo},但自动推进失败,请重试推进',
jumpToCurrentVersion: '跳转',
currentVersionUnavailable: '不可用',
},
shippingProcessing: {
stage: {
order_creating: '创建正式订单',
inventory_matching: '库存匹配',
},
stageLabel: {
waiting_system_start: '等待系统启动',
},
},
},
errors: { generic: '错误' },
},
@@ -522,8 +605,18 @@ function resetActiveCaseFixture() {
...activeCase.value,
status: 'draft',
confirmed_task_no: null,
confirmed_task_id: null,
has_formal_ot: false,
task_missing: false,
recovery_available: null,
post_confirm_auto_progress: null,
current_stage: null,
technical_progress: null,
automation: { status: 'idle', can_auto_create: false, can_build: true },
available_actions: ['validate', 'confirm', 'mark_non_order', 'reparse'],
profile_match: { available: false, visibility: 'admin_only', candidates: [] },
};
shippingProcessingProjection.value = null;
}
describe('ShippingOrderReviewView layout phase 1', () => {
@@ -731,6 +824,105 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
expect(banner.text()).toContain('SN-RECOVER-1');
});
it('retries formal OT auto-progress from main card after refresh without confirmSuccess (UI-01)', async () => {
// 关键断言:刷新后无 confirmSuccess 时,主卡仍用 confirmed_task_no 调 auto-progress API。
vi.mocked(autoProgressWorkspaceShippingTask).mockClear();
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 42,
confirmed_task_no: 'SN-OT-FAIL-1',
current_stage: { code: 'order_creating', inconsistent: false },
automation: {
status: 'failed',
retryable: true,
phase: 'post_ot_progress',
can_auto_create: false,
can_build: true,
},
post_confirm_auto_progress: {
task_no: 'SN-OT-FAIL-1',
needs_retry: true,
status: 'needs_retry',
},
};
const wrapper = await mountView();
await flushPromises();
const retryBtn = wrapper.find('[data-testid="review-current-processing-retry"]');
expect(retryBtn.exists()).toBe(true);
await retryBtn.trigger('click');
await flushPromises();
expect(autoProgressWorkspaceShippingTask).toHaveBeenCalledWith('SN-OT-FAIL-1');
});
it('keeps top / wide / narrow stage labels identical via Progress projection (waiting_system_start)', async () => {
// 关键断言:Case.current_stage 故意降级为误导码;三处必须消费 Progress label_key 文案。
shippingProcessingProjection.value = {
workItemType: 'order_task',
workItemNo: 'OT-WAIT-1',
sourceType: 'eml',
rootOrderTaskNo: 'OT-WAIT-1',
shippingNoticeNo: 'SN-WAIT-1',
conversationId: 'conv-1',
submissionNo: 'SUB-1',
intakeNo: 'INT-1',
status: 'automating',
stage: 'order_creating',
stageLabelKey: 'waiting_system_start',
progressVersion: 1,
lastActivityAt: '2026-08-07T00:00:00Z',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-1',
},
childOrderTasks: [],
};
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 88,
confirmed_task_no: 'SN-WAIT-1',
// 故意与 Progress 文案分叉:若宽屏仍直读 Case code,会显示「库存匹配」。
current_stage: {
code: 'inventory_matching',
label_key: 'inventory_matching',
inconsistent: false,
},
automation: {
status: 'waiting_to_start',
retryable: false,
phase: 'post_ot_progress',
can_auto_create: false,
can_build: true,
},
};
const wrapper = await mountView();
await flushPromises();
const expected = '等待系统启动';
const top = wrapper.find('[data-testid="review-progress-stage-label"]');
const cards = wrapper.findAll('[data-testid="review-current-processing-card"]');
expect(top.exists()).toBe(true);
expect(cards.length).toBeGreaterThanOrEqual(2);
expect(top.text()).toContain(expected);
for (const card of cards) {
expect(card.text()).toContain(expected);
expect(card.text()).not.toContain('库存匹配');
expect(card.text()).not.toContain('创建正式订单');
}
});
it('shows STP retry button for failed automation and calls retry API (UI-02)', async () => {
activeCase.value = {
...activeCase.value,
File diff suppressed because it is too large. Load diff
@@ -91,6 +91,38 @@ describe('ProcessGateRecoveryCard', () => {
}
});
it('hides the card for system worker / technical_auto_only waits', () => {
const wrapper = mount(ProcessGateRecoveryCard, {
props: {
summary: baseSummary({
technical_auto_only: true,
owner_type: 'system',
responsible_party: 'worker',
next_action_code: 'retry_inventory_preparation',
}),
canHandle: false,
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="process-gate-recovery-card"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('待处理事项');
});
it('hides the card when responsible_party is worker without owner_type', () => {
const wrapper = mount(ProcessGateRecoveryCard, {
props: {
summary: baseSummary({
responsible_party: 'worker',
owner_type: undefined,
technical_auto_only: false,
}),
canHandle: false,
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="process-gate-recovery-card"]').exists()).toBe(false);
});
it('maps audit event codes to business labels and clears cache on execution change', async () => {
const wrapper = mount(ProcessGateRecoveryCard, {
props: { summary: baseSummary({ execution_no: 'EXEC-1' }), canHandle: true },
@@ -1,9 +1,10 @@
/**
* features/shipping-process-gates/components/ProcessGateRecoveryCard.vue
* 用途:任务工作台展示当前待处理环节、原因、业务事实 details、责任方、下一步说明与恢复动作。
* 用途:任务/复核工作台展示当前待处理环节、原因、业务事实 details、责任方、下一步说明与恢复动作。
* 依赖:useShippingProcessGateRecovery、processGateNavigation、process-gates.api、
* ShippingProcessGateUserSummary / ShippingExplainabilityReason。
* 逻辑:导航类动作 router.push;confirm_customer 发射 confirmCustomer 由父级开弹窗;
* 逻辑:仅 owner_type=human(且非 technical_auto_only)时渲染;系统 Worker 等待整卡隐藏;
* 导航类动作 router.push;confirm_customer 发射 confirmCustomer 由父级开弹窗;
* POST 类动作调 Workspace API;409 触发 refreshed;
* 展示 explainability.details 白名单业务事实;下一步文案独立于按钮;
* 可展开审计;canHandle=false 时不渲染恢复主按钮,提示用 Footer;
@@ -81,6 +82,23 @@ const nextActionCode = computed(() =>
);
const hasRecoveryAction = computed(() => Boolean(blockingGate.value && nextActionCode.value));
/**
* 是否对业务用户展示「待处理事项」。
* 核心逻辑:technical_auto_only / owner_type=system 时整卡不渲染;
* 兼容旧投影:无 owner_type 时 responsible_party 为 system/worker 也不展示。
*/
const showAsHumanPending = computed(() => {
if (!props.summary || !blockingGate.value) return false;
if (props.summary.technical_auto_only) return false;
const owner = String(props.summary.owner_type || '').trim().toLowerCase();
if (owner === 'system') return false;
if (!owner) {
const party = String(props.summary.responsible_party || '').trim().toLowerCase();
if (party === 'system' || party === 'worker') return false;
}
return true;
});
/** 最近 Attempt 序号(用户可见);用于展示「已尝试 N 次」,不推导百分比。 */
const latestAttemptNo = computed(() => {
const raw = (blockingGate.value as { latest_attempt?: { attempt_no?: number } } | null)
@@ -311,8 +329,9 @@ function formatAuditEventLabel(item: Record<string, unknown>): string {
<template>
<section
v-if="summary && blockingGate"
v-if="showAsHumanPending"
class="rounded-2xl border border-amber-200/80 bg-amber-50/60 px-4 py-3 dark:border-amber-900/50 dark:bg-amber-950/20"
data-testid="process-gate-recovery-card"
>
<div class="mb-2 text-xs font-semibold uppercase tracking-wide text-amber-800 dark:text-amber-200">
{{ $t('workspace.shippingNotice.processGate.title') }}
@@ -153,4 +153,29 @@ describe('ReviewProgressStrip', () => {
await wrapper.get('[data-testid="review-progress-open-details"]').trigger('click');
expect(wrapper.emitted('open-process-details')).toHaveLength(1);
});
it('places process-details CTA on the title row', () => {
const wrapper = mountStrip(buildProjection());
const titleRow = wrapper.get('[data-testid="review-progress-title"]').element.parentElement;
const details = wrapper.get('[data-testid="review-progress-open-details"]').element;
expect(titleRow?.contains(details)).toBe(true);
});
it('places current-need inside the title row text (not a separate block)', () => {
const wrapper = mountStrip(buildProjection({
status: 'waiting',
currentGate: {
gateCode: 'freight_upload',
status: 'blocked',
nextActionCode: 'retry_freight_upload_rpa',
blockingReasonCode: null,
attemptNo: 1,
},
}));
const titleEl = wrapper.get('[data-testid="review-progress-title"]');
const need = wrapper.get('[data-testid="review-progress-current-need"]');
expect(titleEl.element.contains(need.element)).toBe(true);
expect(need.text()).toContain('当前需要');
expect(need.classes()).not.toContain('sr-only');
});
});
@@ -1,10 +1,9 @@
<!--
features/shipping-progress/components/ReviewProgressStrip.vue
用途:订单处理工作台只读进度——宽屏仅 15 阶主进度;窄屏摘要版。
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、stageNodesAuthority、gateReasonLabel.resolveCurrentNeedLabel。
逻辑:由 ReviewWorkflowProgressPanel 挂载;禁止点击节点;宽屏隐藏五域与 n/15 文案;
窄屏不展示 15 阶横条;有阻断 Gate 且非自动推进时显示「当前需要」(优先级 C);
「查看流程详情/完整流程」同一 emit;写操作只在 Footer。
用途:订单处理工作台只读进度——xl 等宽 15 阶;md 横向滚动;窄屏仅 N/15。
依赖:vue-i18n、ShippingProcessingProjection、progressWindow、stageNodesAuthority、gateReasonLabel。
逻辑:由 ReviewWorkflowProgressPanel 挂载;禁止点击节点;「当前需要」并入标题行文案;
「查看流程详情」在标题行右侧;正式 OT 后抑制「请确认建单」;写操作只在 Footer。
-->
<script setup lang="ts">
import { computed, watch } from 'vue';
@@ -13,7 +12,7 @@ import type {
ShippingProcessingProjection,
ShippingProcessingStageNodeStatus,
} from '@/features/chat/types/shipping.api.types';
import { shippingProcessingStageKey } from '@/features/chat/shipping/shippingProcessingLabels';
import { shippingProcessingStageKey, resolveShippingProcessingStageLabel } from '@/features/chat/shipping/shippingProcessingLabels';
import { buildProgressRangeHint } from '../progressWindow';
import {
readAuthoritativeStageNodes,
@@ -25,6 +24,8 @@ const props = defineProps<{
projection: ShippingProcessingProjection;
/** 宿主轮询中提示(显示在标题行)。 */
polling?: boolean;
/** 正式 OT 已创建时禁止再投影「请确认建单」类当前需要。 */
hasFormalOt?: boolean;
}>();
const emit = defineEmits<{
@@ -35,23 +36,38 @@ const emit = defineEmits<{
const { t, te } = useI18n();
const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']);
const CONFIRM_BUILD_ACTION_CODES = new Set([
'confirm_create',
'confirm_build',
'open_order_review',
'confirm_order',
]);
const SYSTEM_TECH_ACTION_PREFIXES = ['retry_', 'poll_'];
/** 权威 15 阶;非法时 null(fail-closed)。 */
const stageNodes = computed(() => readAuthoritativeStageNodes(props.projection));
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
const isAutomating = computed(() => (
AUTOMATING_STATUSES.has(String(props.projection.status || '').trim().toLowerCase())
&& !props.projection.currentGate?.nextActionCode
));
const stageLabel = computed(() => {
const stage = props.projection.stage;
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : String(stage || '');
/**
* 是否处于系统自动推进(含技术重试/轮询动作,避免被 nextAction 误判为人工待办)。
*/
const isAutomating = computed(() => {
const status = String(props.projection.status || '').trim().toLowerCase();
if (!AUTOMATING_STATUSES.has(status)) return false;
const next = String(props.projection.currentGate?.nextActionCode || '').trim().toLowerCase();
if (!next) return true;
if (SYSTEM_TECH_ACTION_PREFIXES.some((prefix) => next.startsWith(prefix))) return true;
return false;
});
const stageLabel = computed(() => resolveShippingProcessingStageLabel(
props.projection.stage,
te,
t,
props.projection.stageLabelKey,
));
/**
* 单行标题:自动推进用「系统处理中 · 阶段」;否则「订单处理进度 · 阶段」。
*/
@@ -65,11 +81,18 @@ const titleLine = computed(() => {
/**
* 有阻断 Gate 且非自动推进时展示「当前需要」。
* 正式 OT 已创建后禁止再显示确认建单类文案。
*/
const showCurrentNeed = computed(() => {
if (isAutomating.value) return false;
const gate = props.projection.currentGate;
if (!gate) return false;
const next = String(gate.nextActionCode || '').trim().toLowerCase();
if (props.hasFormalOt && CONFIRM_BUILD_ACTION_CODES.has(next)) return false;
if (props.hasFormalOt) {
const reason = String(gate.blockingReasonCode || '').trim().toLowerCase();
if (reason === 'waiting_review' || reason.includes('confirm')) return false;
}
return Boolean(
String(gate.blockingReasonCode || '').trim()
|| String(gate.nextActionCode || '').trim(),
@@ -110,26 +133,32 @@ function nodeToneClass(status: ShippingProcessingStageNodeStatus, isCurrent: boo
}
/**
* 节点展示短标签。
* 节点展示短标签(允许两行,不再截断到 4 字硬砍)。
*/
function nodeShortLabel(stage: string): string {
const key = shippingProcessingStageKey(stage);
const label = te(key) ? t(key) : stage;
return String(label).slice(0, 4);
return te(key) ? t(key) : stage;
}
</script>
<template>
<div
class="space-y-2"
class="space-y-1.5"
data-testid="review-progress-strip"
>
<div class="flex items-start justify-between gap-2">
<div class="flex flex-wrap items-center justify-between gap-x-3 gap-y-1.5">
<div
class="min-w-0 text-sm font-semibold text-primary"
class="min-w-0 flex-1 text-sm font-semibold text-primary"
data-testid="review-progress-title"
>
{{ titleLine }}
<span
v-if="showCurrentNeed && currentNeed"
class="ml-2 font-semibold text-amber-800 dark:text-amber-200"
data-testid="review-progress-current-need"
>
· {{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeed }}
</span>
<span
v-if="polling"
class="ml-2 text-[11px] font-normal text-muted"
@@ -138,25 +167,37 @@ function nodeShortLabel(stage: string): string {
{{ t('chat.shippingOrderReview.workflowProgress.polling') }}
</span>
</div>
<button
v-if="isAutomating"
type="button"
class="shrink-0 rounded-lg border border-default bg-surface px-2.5 py-1 text-[11px] font-medium text-secondary hover:bg-surface-muted"
data-testid="review-progress-refresh"
@click="emit('refresh')"
>
{{ t('chat.shippingProcessing.action.refresh') }}
</button>
<div class="flex shrink-0 flex-wrap items-center gap-2">
<button
v-if="isAutomating"
type="button"
class="rounded-lg border border-default bg-surface px-2.5 py-1 text-[11px] font-medium text-secondary hover:bg-surface-muted"
data-testid="review-progress-refresh"
@click="emit('refresh')"
>
{{ t('chat.shippingProcessing.action.refresh') }}
</button>
<button
type="button"
class="rounded-lg border border-default bg-surface px-2.5 py-1 text-[11px] font-medium text-brand-700 hover:bg-surface-muted dark:text-brand-300"
data-testid="review-progress-open-details"
@click="emit('open-process-details')"
>
<span class="hidden md:inline">{{ t('chat.shippingProcessing.progress.viewProcessDetails') }}</span>
<span class="md:hidden">{{ t('chat.shippingProcessing.progress.viewFullProcess') }}</span>
</button>
</div>
</div>
<!-- 宽屏:唯一主进度 = 15 阶只读条。 -->
<!-- xl:15 阶等宽铺满 -->
<div
v-if="stageNodes"
class="hidden lg:block"
class="hidden xl:block"
data-testid="review-progress-stage-nodes"
>
<div
class="flex gap-1 overflow-x-auto pb-1"
class="grid gap-1"
style="grid-template-columns: repeat(15, minmax(0, 1fr));"
role="list"
aria-label="shipping-processing-stages"
>
@@ -164,7 +205,7 @@ function nodeShortLabel(stage: string): string {
v-for="node in stageNodes"
:key="node.stage"
role="listitem"
class="min-w-[3.25rem] shrink-0 select-none rounded-md px-1.5 py-1 text-center text-[10px] leading-tight pointer-events-none"
class="min-w-0 select-none rounded-md px-0.5 py-1 text-center text-[10px] leading-tight pointer-events-none"
:class="nodeToneClass(node.status, node.stage === projection.stage)"
:data-stage="node.stage"
:data-status="node.status"
@@ -172,22 +213,51 @@ function nodeShortLabel(stage: string): string {
:title="te(shippingProcessingStageKey(node.stage)) ? t(shippingProcessingStageKey(node.stage)) : node.stage"
>
<div class="font-semibold">{{ node.absoluteIndex + 1 }}</div>
<div class="truncate">{{ nodeShortLabel(node.stage) }}</div>
<div class="line-clamp-2 break-words">{{ nodeShortLabel(node.stage) }}</div>
</div>
</div>
</div>
<!-- md–xl:横向滚动、节点等宽 -->
<div
v-if="stageNodes"
class="hidden overflow-x-auto pb-1 md:block xl:hidden"
data-testid="review-progress-stage-nodes-scroll"
>
<div
class="flex gap-1"
role="list"
aria-label="shipping-processing-stages"
>
<div
v-for="node in stageNodes"
:key="`scroll-${node.stage}`"
role="listitem"
class="w-14 shrink-0 select-none rounded-md px-1 py-1 text-center text-[10px] leading-tight pointer-events-none"
:class="nodeToneClass(node.status, node.stage === projection.stage)"
:data-stage="node.stage"
:data-status="node.status"
:data-current="node.stage === projection.stage ? '1' : '0'"
:title="te(shippingProcessingStageKey(node.stage)) ? t(shippingProcessingStageKey(node.stage)) : node.stage"
>
<div class="font-semibold">{{ node.absoluteIndex + 1 }}</div>
<div class="line-clamp-2 break-words">{{ nodeShortLabel(node.stage) }}</div>
</div>
</div>
</div>
<p
v-else
class="hidden text-[11px] text-amber-800 lg:block dark:text-amber-200"
class="hidden text-[11px] text-amber-800 md:block dark:text-amber-200"
data-testid="review-progress-stage-nodes-unavailable"
>
{{ t('chat.shippingProcessing.progress.stageNodesUnavailable') }}
</p>
<!-- 窄屏摘要:仅已完成 n/15(宽屏由节点色表达,不重复文案)。 -->
<!-- &lt;md:仅已完成 N/15 + 标题中的当前阶段 -->
<p
v-if="rangeHint"
class="text-[11px] text-secondary lg:hidden"
class="text-[11px] text-secondary md:hidden"
data-testid="review-progress-completed-summary"
>
{{ t('chat.shippingProcessing.progress.completedOfTotal', {
@@ -196,25 +266,5 @@ function nodeShortLabel(stage: string): string {
}) }}
</p>
<p
v-if="showCurrentNeed && currentNeed"
class="text-[11px] text-amber-800 dark:text-amber-200"
data-testid="review-progress-current-need"
>
<span class="font-medium text-secondary">{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}</span>
{{ currentNeed }}
</p>
<div class="flex flex-wrap items-center gap-2">
<button
type="button"
class="rounded-lg border border-default bg-surface px-2.5 py-1 text-[11px] font-medium text-brand-700 hover:bg-surface-muted dark:text-brand-300"
data-testid="review-progress-open-details"
@click="emit('open-process-details')"
>
<span class="hidden lg:inline">{{ t('chat.shippingProcessing.progress.viewProcessDetails') }}</span>
<span class="lg:hidden">{{ t('chat.shippingProcessing.progress.viewFullProcess') }}</span>
</button>
</div>
</div>
</template>
@@ -3,7 +3,8 @@
* 用途:渲染统一 Gate 恢复卡片与 STP 履约待办说明(表单/弹窗入口)。
* 依赖:ProcessGateRecoveryCard、shipping.api、shipping-tasks.api、ManualUploadEvidenceDialog。
* 逻辑:gateCanHandle 控制 Gate 卡写按钮;actionsExecutable 控制 invokeActionByCode / 对话框写;
* hidePrimaryActions=true 时不渲染 action_buttons(订单处理工作台写入口仅 Footer)。
* hidePrimaryActions=true 时不渲染 action_buttons(订单处理工作台写入口仅 Footer);
* 系统 Worker / technical_auto_only 不计入人工阻断,避免「待处理事项」冒充系统等待。
*/
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -179,7 +180,28 @@ const allowedIds = computed(() => {
if (Array.isArray(fromSummary) && fromSummary.length) return new Set(fromSummary.map(String));
return new Set(actionButtons.value.map((item) => item.id));
});
const hasBlockingGate = computed(() => Boolean(processGateSummary.value?.current_blocking_gate));
const hasBlockingGate = computed(() => {
const gate = processGateSummary.value;
if (!gate?.current_blocking_gate) return false;
if (gate.technical_auto_only) return false;
const owner = String(gate.owner_type || '').trim().toLowerCase();
if (owner === 'system') return false;
if (!owner) {
const party = String(gate.responsible_party || '').trim().toLowerCase();
if (party === 'system' || party === 'worker') return false;
}
return true;
});
/** 系统自动等待:禁止用「待处理事项」或 STP 待办卡冒充人工动作。 */
const isSystemAutoWait = computed(() => {
const gate = processGateSummary.value;
if (!gate) return false;
if (gate.technical_auto_only) return true;
if (String(gate.owner_type || '').trim().toLowerCase() === 'system') return true;
if (!gate.current_blocking_gate) return false;
return !hasBlockingGate.value;
});
const UNIFIED_OWNED_ACTION_IDS = new Set([
'retry',
@@ -500,7 +522,7 @@ defineExpose({
@confirm-customer="() => void openCustomerDialog()"
/>
<section
v-if="!hasBlockingGate"
v-if="!hasBlockingGate && !isSystemAutoWait"
class="rounded-2xl border border-brand-200/80 bg-brand-50/40 px-4 py-3"
>
<div class="mb-1 text-xs font-semibold uppercase tracking-wide text-brand-700">
+154 -4
View File
@@ -1961,13 +1961,17 @@
"shortageCount": "Shortage lines {count}",
"waveSelect": "Wave",
"partNumber": "Part number",
"requiredQty": "Required qty",
"availableQty": "Available qty",
"reservationId": "Reservation ID",
"partUnrecognized": "Unrecognized",
"qty": "Req / avail",
"shortage": "Shortage",
"status": "Status",
"actions": "Actions",
"waitInventory": "Wait inventory",
"fulfillNow": "Fulfill line now",
"closeLine": "Close",
"closeLine": "Close line",
"confirmWave": "Confirm wave ({count} lines)",
"waving": "Creating wave…",
"waveSuccess": "Fulfillment wave created",
@@ -1983,8 +1987,81 @@
"task_created": "Task created",
"fulfilled": "Fulfilled",
"reopened": "Reopened"
},
"userLineStatus": {
"shortage": "Shortage · waiting for inventory update",
"inventory_pending": "Inventory processing",
"acquiring_inventory": "Fetching inventory",
"inventory_file_missing": "Inventory file not ready",
"inventory_file_expired": "Inventory file expired",
"inventory_match_failed": "Inventory match failed",
"inventory_source_unrecognized": "Inventory source unrecognized",
"inventory_matched": "Inventory matched",
"source_conflict": "Inventory source conflict",
"invalid": "Incomplete data",
"auto_fulfilling": "Auto-fulfilling",
"wave_created": "Added to fulfillment wave",
"fulfilled": "Completed",
"closed": "Closed",
"auto_fulfill_failed": "Auto-fulfill failed",
"pending_decision": "Pending decision",
"ready_to_fulfill": "Ready to fulfill"
}
},
"lineOps": {
"decideFulfillment": "Decide fulfillment",
"viewInventory": "View inventory processing",
"resolveSource": "Resolve inventory source",
"changeSource": "Change inventory source",
"viewFulfillment": "View fulfillment details",
"recheck": "Recheck inventory",
"availablePending": "Pending",
"inventoryProcessing": "Inventory processing",
"inventoryPending": "Inventory is being processed",
"noSourceOptions": "No inventory sources available",
"retryRpa": "Retry inventory retrieval",
"retryRpaSubmitted": "Inventory RPA retry submitted",
"retryRpaFailed": "Inventory RPA retry failed",
"retryRpaUnavailable": "Retry is unavailable for the current inventory state",
"retryPreparation": "Retry inventory fetch",
"retryMatching": "Retry inventory match",
"moreActions": "More actions",
"inventorySource": "Inventory source",
"inventorySourceStatus": {
"resolved": "Resolved",
"resolving": "Resolving",
"unrecognized": "Unrecognized",
"conflict": "Conflict",
"unavailable": "Unavailable"
}
},
"lineFulfillmentDetail": {
"title": "Line fulfillment summary",
"wave": "Fulfillment wave",
"task": "Formal task",
"snapshotId": "Inventory snapshot ID",
"matchedAt": "Match checked at",
"decisionSource": "Decision source",
"decisionSourceValue": {
"system": "System",
"user": "User",
"unknown": "Unknown"
},
"failureReason": "Auto-fulfill failure reason",
"noFailure": "None",
"openAudit": "Open audit trail",
"close": "Collapse"
},
"lineFulfillmentAggregate": {
"title": "Fulfillment progress summary",
"hint": "Shows system progress and manual backlog together; use the order-line ops column for actions.",
"autoProgress": "{count} lines in system progress",
"manualPending": "{count} lines need manual action",
"inventoryPending": "{count} lines pending inventory",
"systemFailed": "{count} lines failed auto-fulfill",
"enterInventory": "Open inventory / fulfillment",
"viewLines": "View order lines"
},
"closeFulfillment": {
"titleSelected": "Close selected lines ({count})",
"titleAll": "Close remaining open lines",
@@ -2045,6 +2122,62 @@
"skipped": "Skipped"
}
},
"automation": {
"waitingPreOt": "Waiting for the system to start auto-create",
"waitingPostOt": "Waiting for the system to start"
},
"currentProcessing": {
"title": "Current processing",
"status": "Status",
"formalOt": "Formal OT",
"waitingStart": "Waiting for system start",
"taskMissing": "Formal task link error",
"taskMissingHint": "Formal task link is broken. Please contact an administrator.",
"adminDiagnosisTitle": "Admin diagnosis",
"confirmedTaskId": "confirmed_task_id: {id}",
"adminDiagnosisStatus": "Status: task_missing",
"adminDiagnosisHint": "Use task audit / data repair. This page does not auto-recover.",
"stateInconsistent": "State syncing / inconsistent state data",
"statusRunning": "System processing",
"statusFailedRetryable": "Failed — retry available",
"statusCompleted": "Completed",
"statusIdle": "Idle",
"statusTaskMissing": "Link error",
"stages": {
"waiting_to_start": "Waiting for system start",
"waiting_system_start": "Waiting for system start",
"order_creating": "Waiting for system start",
"order_review": "Order review",
"inventory_fetching": "Fetching inventory",
"fetching_inventory": "Fetching inventory",
"inventory_matching": "Inventory matching",
"excel_generating": "Excel generation",
"task_missing": "Formal task link error",
"state_inconsistent": "Inconsistent state data"
}
},
"completedChecks": {
"title": "Completed checks ({count})",
"codes": {
"document_available": "Document available",
"pdf_layout_parsed": "PDF parsed",
"profile_routed": "Template routed",
"fields_extracted": "Fields extracted",
"field_completeness": "Required fields",
"customer_resolved": "Customer identified",
"duplicate_checked": "Duplicate checked",
"field_conflicts_resolved": "Field conflicts",
"order_review_completed": "Order review",
"formal_ot_created": "Formal OT created"
}
},
"fieldCompleteness": {
"title": "Field completeness",
"subtitle": "Checks required fields independently from template matching.",
"blocked": "Blocked",
"ready": "Ready",
"unknownField": "Unknown field"
},
"fieldConflict": {
"title": "Field conflicts to resolve ({count})",
"subtitle": "Conflicting values from multiple sources are not auto-applied. Pick one value or enter a custom value before building the order.",
@@ -2110,14 +2243,16 @@
"score": "Score {score}",
"reselectHint": "If the template is wrong or the layout drifted, use “Reparse this PDF” at the top. Gate re-route is on the recovery card below.",
"status": {
"matched": "Matched",
"unmatched": "Unmatched",
"ambiguous": "Ambiguous candidates",
"unknown": "Unknown",
"unique_match": "Unique match",
"selected_by_score": "Selected by score",
"no_special_profile_feature": "No special profile feature",
"no_match": "No match",
"ambiguous": "Ambiguous candidates",
"layout_drift": "Layout drift",
"evidence_insufficient": "Insufficient evidence",
"unknown": "Unknown"
"evidence_insufficient": "Insufficient evidence"
},
"reasons": {
"profile_ambiguous": "Multiple profile candidates with insufficient margin",
@@ -2256,6 +2391,18 @@
"missing_order_table": "Missing order table",
"other": "Other (comment required)"
}
},
"inventoryFallback": {
"title": "Inventory issue",
"affectedLines": "Impact: about {count} order lines",
"kinds": {
"inventory_file_missing": "Inventory file not ready",
"inventory_source_unavailable": "Inventory source unavailable",
"inventory_preparation_failed": "Inventory preparation failed",
"inventory_rpa_timeout": "Inventory RPA timed out",
"inventory_rpa_export_failed": "Inventory export failed",
"inventory_file_empty": "Inventory file empty"
}
}
},
"shippingOrderExtractionElapsed": "Elapsed {elapsed}",
@@ -2357,6 +2504,9 @@
"freight_uploading": "Freight upload",
"completed": "Completed"
},
"stageLabel": {
"waiting_system_start": "Waiting for system start"
},
"progress": {
"completedOfTotal": "{done} / {total} completed",
"currentStage": "Current: {stage}",
+154 -4
View File
@@ -1961,13 +1961,17 @@
"shortageCount": "บรรทัดขาด {count}",
"waveSelect": "Wave",
"partNumber": "Part number",
"requiredQty": "จำนวนที่ต้องการ",
"availableQty": "จำนวนที่ใช้ได้",
"reservationId": "รหัสการจอง",
"partUnrecognized": "ไม่ระบุ",
"qty": "ต้องการ/มี",
"shortage": "ขาด",
"status": "สถานะ",
"actions": "การดำเนินการ",
"waitInventory": "รอสต็อก",
"fulfillNow": "เติมเต็มบรรทัด",
"closeLine": "ปิด",
"closeLine": "ปิดรายการ",
"confirmWave": "ยืนยัน wave ({count} บรรทัด)",
"waving": "กำลังสร้าง wave…",
"waveSuccess": "สร้าง fulfillment wave แล้ว",
@@ -1983,8 +1987,81 @@
"task_created": "สร้าง task แล้ว",
"fulfilled": "ปฏิบัติครบแล้ว",
"reopened": "เปิดใหม่แล้ว"
},
"userLineStatus": {
"shortage": "สต็อกไม่พอ · รออัปเดตสต็อก",
"inventory_pending": "กำลังประมวลผลสต็อก",
"acquiring_inventory": "กำลังดึงสต็อก",
"inventory_file_missing": "ยังไม่มีไฟล์สต็อก",
"inventory_file_expired": "ไฟล์สต็อกหมดอายุ",
"inventory_match_failed": "จับคู่สต็อกล้มเหลว",
"inventory_source_unrecognized": "ไม่รู้จักแหล่งสต็อก",
"inventory_matched": "จับคู่สต็อกสำเร็จ",
"source_conflict": "แหล่งสต็อกขัดแย้ง",
"invalid": "ข้อมูลไม่ครบ",
"auto_fulfilling": "กำลังเติมเต็มอัตโนมัติ",
"wave_created": "เข้าร่วม wave แล้ว",
"fulfilled": "เสร็จสิ้น",
"closed": "ปิดแล้ว",
"auto_fulfill_failed": "เติมเต็มอัตโนมัติล้มเหลว",
"pending_decision": "รอการตัดสินใจ",
"ready_to_fulfill": "พร้อมเติมเต็ม"
}
},
"lineOps": {
"decideFulfillment": "ตัดสินใจการปฏิบัติตาม",
"viewInventory": "ดูการประมวลผลสต็อก",
"resolveSource": "จัดการแหล่งสต็อก",
"changeSource": "เปลี่ยนแหล่งสต็อก",
"viewFulfillment": "ดูรายละเอียดการปฏิบัติตาม",
"recheck": "ตรวจสอบสต็อกอีกครั้ง",
"availablePending": "รอยืนยัน",
"inventoryProcessing": "กำลังจัดการสต็อก",
"inventoryPending": "กำลังประมวลผลสต็อก",
"noSourceOptions": "ไม่มีแหล่งสต็อกที่ใช้ได้",
"retryRpa": "ลองดึงสต็อกใหม่",
"retryRpaSubmitted": "ส่งคำขอ RPA ดึงสต็อกใหม่แล้ว",
"retryRpaFailed": "การลอง RPA ดึงสต็อกใหม่ล้มเหลว",
"retryRpaUnavailable": "สถานะสต็อกปัจจุบันไม่รองรับการลองใหม่",
"retryPreparation": "ลองดึงสต็อกอีกครั้ง",
"retryMatching": "ลองจับคู่สต็อกอีกครั้ง",
"moreActions": "การดำเนินการเพิ่มเติม",
"inventorySource": "แหล่งสต็อก",
"inventorySourceStatus": {
"resolved": "ระบุแล้ว",
"resolving": "กำลังระบุ",
"unrecognized": "ไม่ระบุ",
"conflict": "ขัดแย้ง",
"unavailable": "แหล่งสต็อกใช้ไม่ได้"
}
},
"lineFulfillmentDetail": {
"title": "สรุปการปฏิบัติตามของบรรทัด",
"wave": "Wave การปฏิบัติตาม",
"task": "งานอย่างเป็นทางการ",
"snapshotId": "Inventory snapshot ID",
"matchedAt": "เวลาตรวจสอบการจับคู่",
"decisionSource": "แหล่งการตัดสินใจ",
"decisionSourceValue": {
"system": "ระบบอัตโนมัติ",
"user": "ผู้ใช้",
"unknown": "ไม่ทราบ"
},
"failureReason": "เหตุผลที่ auto-fulfill ล้มเหลว",
"noFailure": "ไม่มี",
"openAudit": "เปิด audit",
"close": "ย่อ"
},
"lineFulfillmentAggregate": {
"title": "สรุปความคืบหน้าการปฏิบัติตาม",
"hint": "แสดงความคืบหน้าของระบบและงานที่ต้องทำด้วยมือพร้อมกัน ใช้คอลัมน์การดำเนินการของบรรทัดคำสั่ง",
"autoProgress": "ระบบกำลังดำเนินการ {count} บรรทัด",
"manualPending": "รอการดำเนินการด้วยมือ {count} บรรทัด",
"inventoryPending": "กำลังประมวลผลสต็อก {count} บรรทัด",
"systemFailed": "auto-fulfill ล้มเหลว {count} บรรทัด",
"enterInventory": "เปิดการประมวลผลสต็อก/การปฏิบัติตาม",
"viewLines": "ดูรายการคำสั่ง"
},
"closeFulfillment": {
"titleSelected": "ปิดบรรทัดที่เลือก ({count})",
"titleAll": "ปิดบรรทัดที่เปิดที่เหลือ",
@@ -2045,6 +2122,62 @@
"skipped": "ข้าม"
}
},
"automation": {
"waitingPreOt": "รอระบบเริ่มสร้างออเดอร์อัตโนมัติ",
"waitingPostOt": "รอระบบเริ่มทำงาน"
},
"currentProcessing": {
"title": "กำลังดำเนินการ",
"status": "สถานะ",
"formalOt": "OT อย่างเป็นทางการ",
"waitingStart": "รอระบบเริ่ม",
"taskMissing": "ลิงก์งานผิดปกติ",
"taskMissingHint": "ลิงก์งานผิดปกติ โปรดติดต่อผู้ดูแล",
"adminDiagnosisTitle": "การวินิจฉัยผู้ดูแล",
"confirmedTaskId": "confirmed_task_id: {id}",
"adminDiagnosisStatus": "สถานะ: task_missing",
"adminDiagnosisHint": "ใช้การตรวจสอบงาน/ซ่อมข้อมูล ไม่กู้คืนอัตโนมัติในหน้านี้",
"stateInconsistent": "กำลังซิงก์สถานะ / ข้อมูลไม่สอดคล้อง",
"statusRunning": "ระบบกำลังประมวลผล",
"statusFailedRetryable": "ล้มเหลว — ลองใหม่ได้",
"statusCompleted": "เสร็จสิ้น",
"statusIdle": "ว่าง",
"statusTaskMissing": "ลิงก์ผิดปกติ",
"stages": {
"waiting_to_start": "รอระบบเริ่ม",
"waiting_system_start": "รอระบบเริ่ม",
"order_creating": "รอระบบเริ่ม",
"order_review": "ตรวจทานออเดอร์",
"inventory_fetching": "ดึงสต็อก",
"fetching_inventory": "ดึงสต็อก",
"inventory_matching": "จับคู่สต็อก",
"excel_generating": "สร้าง Excel",
"task_missing": "ลิงก์งานผิดปกติ",
"state_inconsistent": "ข้อมูลสถานะไม่สอดคล้อง"
}
},
"completedChecks": {
"title": "การตรวจที่เสร็จแล้ว ({count})",
"codes": {
"document_available": "เอกสารพร้อม",
"pdf_layout_parsed": "แยก PDF",
"profile_routed": "จับคู่เทมเพลต",
"fields_extracted": "ดึงฟิลด์",
"field_completeness": "ตรวจฟิลด์จำเป็น",
"customer_resolved": "ระบุลูกค้า",
"duplicate_checked": "ตรวจซ้ำ",
"field_conflicts_resolved": "แก้ความขัดแย้งฟิลด์",
"order_review_completed": "ตรวจทานออเดอร์",
"formal_ot_created": "สร้าง OT แล้ว"
}
},
"fieldCompleteness": {
"title": "ความครบถ้วนของฟิลด์",
"subtitle": "ตรวจฟิลด์จำเป็นแยกจากจับคู่เทมเพลต",
"blocked": "ไม่ผ่าน",
"ready": "ผ่าน",
"unknownField": "ฟิลด์ไม่ทราบ"
},
"fieldConflict": {
"title": "ความขัดแย้งของฟิลด์ที่ต้องตัดสิน ({count})",
"subtitle": "ค่าจากหลายแหล่งไม่ตรงกันจะไม่ถูกเขียนอัตโนมัติ เลือกค่าหนึ่งหรือกรอกค่าเองก่อนสร้างคำสั่ง",
@@ -2110,14 +2243,16 @@
"score": "คะแนน {score}",
"reselectHint": "หากเทมเพลตผิดหรือเลย์เอาต์เพี้ยน ใช้ “ระบุ PDF นี้อีกครั้ง” ด้านบน การเปลี่ยนเส้นทางเกตอยู่ในการ์ดกู้คืนด้านล่าง",
"status": {
"matched": "จับคู่แล้ว",
"unmatched": "ไม่จับคู่",
"ambiguous": "มีหลายตัวเลือก",
"unknown": "ไม่ทราบ",
"unique_match": "จับคู่ได้ตัวเดียว",
"selected_by_score": "เลือกตามคะแนน",
"no_special_profile_feature": "ไม่มีคุณลักษณะเทมเพลตเฉพาะ",
"no_match": "ไม่จับคู่ได้",
"ambiguous": "มีหลายตัวเลือก",
"layout_drift": "เลย์เอาต์เพี้ยน",
"evidence_insufficient": "หลักฐานไม่พอ",
"unknown": "ไม่ทราบ"
"evidence_insufficient": "หลักฐานไม่พอ"
},
"reasons": {
"profile_ambiguous": "มีหลายเทมเพลตและคะแนนต่างกันไม่พอ",
@@ -2256,6 +2391,18 @@
"missing_order_table": "ไม่มีตารางคำสั่งซื้อ",
"other": "อื่นๆ (ต้องระบุรายละเอียด)"
}
},
"inventoryFallback": {
"title": "ปัญหาการประมวลผลสต็อก",
"affectedLines": "ผลกระทบ: ประมาณ {count} บรรทัดคำสั่ง",
"kinds": {
"inventory_file_missing": "ยังไม่มีไฟล์สต็อก",
"inventory_source_unavailable": "แหล่งสต็อกใช้ไม่ได้",
"inventory_preparation_failed": "เตรียมสต็อกล้มเหลว",
"inventory_rpa_timeout": "RPA สต็อกหมดเวลา",
"inventory_rpa_export_failed": "ส่งออกสต็อกล้มเหลว",
"inventory_file_empty": "ไฟล์สต็อกว่าง"
}
}
},
"shippingOrderExtractionElapsed": "ใช้เวลา {elapsed}",
@@ -2357,6 +2504,9 @@
"freight_uploading": "อัปโหลดไปยังผู้ขนส่ง",
"completed": "เสร็จสิ้น"
},
"stageLabel": {
"waiting_system_start": "รอระบบเริ่ม"
},
"progress": {
"completedOfTotal": "เสร็จแล้ว {done} / {total}",
"currentStage": "ปัจจุบัน: {stage}",
+155 -5
View File
@@ -1995,13 +1995,17 @@
"shortageCount": "缺口行 {count}",
"waveSelect": "波次",
"partNumber": "料号",
"requiredQty": "需求数量",
"availableQty": "可用数量",
"reservationId": "预约单号",
"partUnrecognized": "未识别",
"qty": "需求/可用",
"shortage": "缺口",
"status": "状态",
"actions": "操作",
"waitInventory": "等待补货",
"fulfillNow": "完整行先行",
"closeLine": "关闭",
"closeLine": "关闭该明细",
"confirmWave": "确认波次({count} 行)",
"waving": "创建波次中…",
"waveSuccess": "履约波次已创建",
@@ -2017,8 +2021,93 @@
"task_created": "已建单",
"fulfilled": "已履约",
"reopened": "已重开"
},
"userLineStatus": {
"shortage": "库存不足 · 等待库存更新",
"inventory_pending": "库存处理中",
"acquiring_inventory": "获取库存中",
"inventory_file_missing": "库存文件未准备",
"inventory_file_expired": "库存文件已过期",
"inventory_match_failed": "库存匹配失败",
"inventory_source_unrecognized": "库存源未识别",
"inventory_matched": "库存匹配成功",
"source_conflict": "库存源冲突",
"invalid": "数据不完整",
"auto_fulfilling": "自动履约中",
"wave_created": "已加入履约波次",
"fulfilled": "已完成",
"closed": "已关闭",
"auto_fulfill_failed": "自动履约失败",
"pending_decision": "待决定",
"ready_to_fulfill": "可完整履约"
}
},
"lineOps": {
"decideFulfillment": "决定履约",
"viewInventory": "库存处理",
"resolveSource": "处理库存来源",
"changeSource": "更换库存源",
"viewFulfillment": "查看履约详情",
"recheck": "重新校验",
"availablePending": "待确认",
"inventoryProcessing": "库存处理",
"inventoryPending": "库存处理中",
"noSourceOptions": "暂无可用库存源",
"retryPreparation": "重试获取库存",
"retryMatching": "重新匹配库存",
"moreActions": "更多操作",
"retryRpa": "重试获取库存",
"retryRpaSubmitted": "已提交库存 RPA 重试",
"retryRpaFailed": "库存 RPA 重试失败",
"retryRpaUnavailable": "当前库存处理状态暂不支持重试",
"inventorySource": "库存源",
"inventorySourceStatus": {
"resolved": "已解析",
"resolving": "解析中",
"unrecognized": "未识别",
"conflict": "存在冲突",
"unavailable": "库存源不可用"
}
},
"inventoryFallback": {
"title": "库存处理问题",
"affectedLines": "影响范围:约 {count} 行订单明细",
"kinds": {
"inventory_file_missing": "库存文件未准备",
"inventory_source_unavailable": "库存源不可用",
"inventory_preparation_failed": "库存准备失败",
"inventory_rpa_timeout": "库存 RPA 超时",
"inventory_rpa_export_failed": "库存导出失败",
"inventory_file_empty": "库存文件为空"
}
},
"lineFulfillmentDetail": {
"title": "行履约摘要",
"wave": "履约波次",
"task": "正式任务",
"snapshotId": "库存快照 ID",
"matchedAt": "匹配校验时间",
"decisionSource": "决定来源",
"decisionSourceValue": {
"system": "系统自动",
"user": "人工",
"unknown": "未知"
},
"failureReason": "自动履约失败原因",
"noFailure": "无",
"openAudit": "打开审计",
"close": "收起"
},
"lineFulfillmentAggregate": {
"title": "履约进度摘要",
"hint": "同时展示系统进度与人工待办;明细操作请在订单表右侧列处理。",
"autoProgress": "系统处理中 {count} 行",
"manualPending": "待人工处理 {count} 行",
"inventoryPending": "库存处理中 {count} 行",
"systemFailed": "自动履约失败 {count} 行",
"enterInventory": "进入库存/履约处理",
"viewLines": "查看订单明细"
},
"closeFulfillment": {
"titleSelected": "关闭所选行({count})",
"titleAll": "关闭剩余开放行",
@@ -2079,6 +2168,62 @@
"skipped": "已跳过"
}
},
"automation": {
"waitingPreOt": "等待系统启动自动建单",
"waitingPostOt": "等待系统启动"
},
"currentProcessing": {
"title": "当前处理",
"status": "状态",
"formalOt": "正式 OT",
"waitingStart": "等待系统启动",
"taskMissing": "正式任务关联异常",
"taskMissingHint": "正式任务关联异常,请联系管理员",
"adminDiagnosisTitle": "管理员诊断",
"confirmedTaskId": "confirmed_task_id:{id}",
"adminDiagnosisStatus": "状态:task_missing",
"adminDiagnosisHint": "请通过任务审计/数据修复流程处理;本页不提供自动恢复。",
"stateInconsistent": "状态同步中 / 状态数据不一致",
"statusRunning": "系统处理中",
"statusFailedRetryable": "失败可重试",
"statusCompleted": "已完成",
"statusIdle": "待机",
"statusTaskMissing": "关联异常",
"stages": {
"waiting_to_start": "等待系统启动",
"waiting_system_start": "等待系统启动",
"order_creating": "等待系统启动",
"order_review": "订单复核",
"inventory_fetching": "获取库存",
"fetching_inventory": "获取库存",
"inventory_matching": "库存匹配",
"excel_generating": "Excel 生成",
"task_missing": "正式任务关联异常",
"state_inconsistent": "状态数据不一致"
}
},
"completedChecks": {
"title": "已完成检查({count})",
"codes": {
"document_available": "文档可用",
"pdf_layout_parsed": "PDF 解析",
"profile_routed": "模板路由",
"fields_extracted": "字段抽取",
"field_completeness": "必填字段校验",
"customer_resolved": "客户识别",
"duplicate_checked": "重复检测",
"field_conflicts_resolved": "字段冲突",
"order_review_completed": "订单复核",
"formal_ot_created": "正式 OT 创建"
}
},
"fieldCompleteness": {
"title": "字段完整性",
"subtitle": "校验建单必填字段是否齐全;与模板匹配相互独立。",
"blocked": "未通过",
"ready": "已通过",
"unknownField": "未知字段"
},
"fieldConflict": {
"title": "字段冲突待裁决({count})",
"subtitle": "多来源取值不一致时不会自动写入。请选用一方或填写手工值后再建单。",
@@ -2136,7 +2281,7 @@
},
"profileMatch": {
"title": "文档模板匹配",
"subtitle": "展示本 PDF 命中的文档模板与候选分;换模板需重新识别。",
"subtitle": "展示本 PDF 是否命中文档模板;字段缺失见「字段完整性」。",
"selected": "命中模板",
"noSelected": "未选定模板",
"routeType": "路由类型",
@@ -2144,14 +2289,16 @@
"score": "得分 {score}",
"reselectHint": "若模板不对或版面漂移,请使用顶部「重新识别此 PDF」;门禁重路由见下方恢复卡片。",
"status": {
"matched": "已匹配",
"unmatched": "未匹配",
"ambiguous": "多个候选",
"unknown": "未知",
"unique_match": "唯一命中",
"selected_by_score": "按得分选定",
"no_special_profile_feature": "无专用模板特征",
"no_match": "未命中",
"ambiguous": "多个候选",
"layout_drift": "版面漂移",
"evidence_insufficient": "证据不足",
"unknown": "未知"
"evidence_insufficient": "证据不足"
},
"reasons": {
"profile_ambiguous": "多个模板候选分差不足",
@@ -2358,6 +2505,9 @@
"freight_uploading": "上传货代",
"completed": "已完成"
},
"stageLabel": {
"waiting_system_start": "等待系统启动"
},
"progress": {
"completedOfTotal": "已完成 {done} / {total}",
"currentStage": "当前:{stage}",
+154 -4
View File
@@ -1961,13 +1961,17 @@
"shortageCount": "缺口行 {count}",
"waveSelect": "波次",
"partNumber": "料號",
"requiredQty": "需求數量",
"availableQty": "可用數量",
"reservationId": "預約單號",
"partUnrecognized": "未識別",
"qty": "需求/可用",
"shortage": "缺口",
"status": "狀態",
"actions": "操作",
"waitInventory": "等待補貨",
"fulfillNow": "完整行先行",
"closeLine": "關閉",
"closeLine": "關閉該明細",
"confirmWave": "確認波次({count} 行)",
"waving": "建立波次中…",
"waveSuccess": "履約波次已建立",
@@ -1983,8 +1987,81 @@
"task_created": "已建單",
"fulfilled": "已履約",
"reopened": "已重開"
},
"userLineStatus": {
"shortage": "庫存不足 · 等待庫存更新",
"inventory_pending": "庫存處理中",
"acquiring_inventory": "獲取庫存中",
"inventory_file_missing": "庫存檔案未準備",
"inventory_file_expired": "庫存檔案已過期",
"inventory_match_failed": "庫存匹配失敗",
"inventory_source_unrecognized": "庫存源未識別",
"inventory_matched": "庫存匹配成功",
"source_conflict": "庫存源衝突",
"invalid": "資料不完整",
"auto_fulfilling": "自動履約中",
"wave_created": "已加入履約波次",
"fulfilled": "已完成",
"closed": "已關閉",
"auto_fulfill_failed": "自動履約失敗",
"pending_decision": "待決定",
"ready_to_fulfill": "可完整履約"
}
},
"lineOps": {
"decideFulfillment": "決定履約",
"viewInventory": "查看庫存處理",
"resolveSource": "處理庫存來源",
"changeSource": "更換庫存源",
"viewFulfillment": "查看履約詳情",
"recheck": "重新校驗",
"availablePending": "待確認",
"inventoryProcessing": "庫存處理",
"inventoryPending": "庫存處理中",
"noSourceOptions": "暫無可用庫存源",
"retryRpa": "重試取得庫存",
"retryRpaSubmitted": "已提交庫存 RPA 重試",
"retryRpaFailed": "庫存 RPA 重試失敗",
"retryRpaUnavailable": "目前庫存處理狀態不支援重試",
"retryPreparation": "重試獲取庫存",
"retryMatching": "重新匹配庫存",
"moreActions": "更多操作",
"inventorySource": "庫存源",
"inventorySourceStatus": {
"resolved": "已解析",
"resolving": "解析中",
"unrecognized": "未識別",
"conflict": "存在衝突",
"unavailable": "庫存源不可用"
}
},
"lineFulfillmentDetail": {
"title": "行履約摘要",
"wave": "履約波次",
"task": "正式任務",
"snapshotId": "庫存快照 ID",
"matchedAt": "匹配校驗時間",
"decisionSource": "決定來源",
"decisionSourceValue": {
"system": "系統自動",
"user": "人工",
"unknown": "未知"
},
"failureReason": "自動履約失敗原因",
"noFailure": "無",
"openAudit": "打開稽核",
"close": "收起"
},
"lineFulfillmentAggregate": {
"title": "履約進度摘要",
"hint": "同時展示系統進度與人工待辦;明細操作請在訂單表右側欄處理。",
"autoProgress": "系統處理中 {count} 行",
"manualPending": "待人工處理 {count} 行",
"inventoryPending": "庫存處理中 {count} 行",
"systemFailed": "自動履約失敗 {count} 行",
"enterInventory": "進入庫存/履約處理",
"viewLines": "查看訂單明細"
},
"closeFulfillment": {
"titleSelected": "關閉所選行({count})",
"titleAll": "關閉剩餘開放行",
@@ -2045,6 +2122,62 @@
"skipped": "已跳過"
}
},
"automation": {
"waitingPreOt": "等待系統啟動自動建單",
"waitingPostOt": "等待系統啟動"
},
"currentProcessing": {
"title": "目前處理",
"status": "狀態",
"formalOt": "正式 OT",
"waitingStart": "等待系統啟動",
"taskMissing": "正式任務關聯異常",
"taskMissingHint": "正式任務關聯異常,請聯絡管理員",
"adminDiagnosisTitle": "管理員診斷",
"confirmedTaskId": "confirmed_task_id:{id}",
"adminDiagnosisStatus": "狀態:task_missing",
"adminDiagnosisHint": "請透過任務審計/資料修復流程處理;本頁不提供自動恢復。",
"stateInconsistent": "狀態同步中 / 狀態資料不一致",
"statusRunning": "系統處理中",
"statusFailedRetryable": "失敗可重試",
"statusCompleted": "已完成",
"statusIdle": "待機",
"statusTaskMissing": "關聯異常",
"stages": {
"waiting_to_start": "等待系統啟動",
"waiting_system_start": "等待系統啟動",
"order_creating": "等待系統啟動",
"order_review": "訂單覆核",
"inventory_fetching": "取得庫存",
"fetching_inventory": "取得庫存",
"inventory_matching": "庫存匹配",
"excel_generating": "Excel 產生",
"task_missing": "正式任務關聯異常",
"state_inconsistent": "狀態資料不一致"
}
},
"completedChecks": {
"title": "已完成檢查({count})",
"codes": {
"document_available": "文件可用",
"pdf_layout_parsed": "PDF 解析",
"profile_routed": "範本路由",
"fields_extracted": "欄位抽取",
"field_completeness": "必填欄位校驗",
"customer_resolved": "客戶識別",
"duplicate_checked": "重複偵測",
"field_conflicts_resolved": "欄位衝突",
"order_review_completed": "訂單覆核",
"formal_ot_created": "正式 OT 建立"
}
},
"fieldCompleteness": {
"title": "欄位完整性",
"subtitle": "校驗建單必填欄位是否齊全;與範本匹配相互獨立。",
"blocked": "未通過",
"ready": "已通過",
"unknownField": "未知欄位"
},
"fieldConflict": {
"title": "欄位衝突待裁決({count})",
"subtitle": "多來源取值不一致時不會自動寫入。請選用一方或填寫人工值後再建單。",
@@ -2110,14 +2243,16 @@
"score": "得分 {score}",
"reselectHint": "若範本不對或版面漂移,請使用頂部「重新識別此 PDF」;門禁重路由見下方恢復卡片。",
"status": {
"matched": "已匹配",
"unmatched": "未匹配",
"ambiguous": "多個候選",
"unknown": "未知",
"unique_match": "唯一命中",
"selected_by_score": "按得分選定",
"no_special_profile_feature": "無專用範本特徵",
"no_match": "未命中",
"ambiguous": "多個候選",
"layout_drift": "版面漂移",
"evidence_insufficient": "證據不足",
"unknown": "未知"
"evidence_insufficient": "證據不足"
},
"reasons": {
"profile_ambiguous": "多個範本候選分差不足",
@@ -2256,6 +2391,18 @@
"missing_order_table": "缺少訂單表格",
"other": "其他(須填寫說明)"
}
},
"inventoryFallback": {
"title": "庫存處理問題",
"affectedLines": "影響範圍:約 {count} 行訂單明細",
"kinds": {
"inventory_file_missing": "庫存檔案未準備",
"inventory_source_unavailable": "庫存源不可用",
"inventory_preparation_failed": "庫存準備失敗",
"inventory_rpa_timeout": "庫存 RPA 逾時",
"inventory_rpa_export_failed": "庫存匯出失敗",
"inventory_file_empty": "庫存檔案為空"
}
}
},
"shippingOrderExtractionElapsed": "已用時 {elapsed}",
@@ -2357,6 +2504,9 @@
"freight_uploading": "上傳貨代",
"completed": "已完成"
},
"stageLabel": {
"waiting_system_start": "等待系統啟動"
},
"progress": {
"completedOfTotal": "已完成 {done} / {total}",
"currentStage": "目前:{stage}",
+1190 -113
View File
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
<#
.SYNOPSIS
为同一 Windows 用户下的 RPA Worker 创建当前用户可解密的 Secret 文件。
.DESCRIPTION
Secret 文件使用 PowerShell SecureString/Windows DPAPI 保存,不能被其他用户直接解密。
启动脚本只在 Worker 子进程中设置 Process 级环境变量,不写入 User/Machine 环境变量。
Secret 文件应保存在仓库之外,例如 C:\HxopsRpaSecrets\test.xml。
DSV/Crane 登录地址、账号和密码不在本文件中保存;它们由 HXOPS RPA Profile
配置并随加密 credential_envelope 进入 trigger,Worker 使用 CredentialKey 解密。
#>
param(
[Parameter(Mandatory = $true)]
[ValidateSet("test", "prod")]
[string]$Environment,
[string]$OutputRoot = "C:\HxopsRpaSecrets"
)
$ErrorActionPreference = "Stop"
$secretPath = Join-Path $OutputRoot ("{0}.xml" -f $Environment)
New-Item -ItemType Directory -Force -Path $OutputRoot | Out-Null
function Read-RequiredSecret {
param([Parameter(Mandatory = $true)][string]$Prompt)
$value = Read-Host $Prompt -AsSecureString
if (-not $value -or $value.Length -eq 0) {
throw "$Prompt 不能为空"
}
return $value
}
$record = [pscustomobject]@{
ToolApiKey = Read-RequiredSecret "请输入 $Environment 环境 SHIPPING_NOTICE_TOOL_API_KEY"
CredentialKey = Read-RequiredSecret "请输入 $Environment 环境 SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"
}
$record | Export-Clixml -LiteralPath $secretPath
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
icacls $secretPath /inheritance:r /grant:r "${currentUser}:F" | Out-Null
Write-Host "Secret 文件已创建:$secretPath"
Write-Host "仅当前 Windows 用户可解密;不要复制到其他账号、提交 Git 或写入日志。"
-162
View File
@@ -1,162 +0,0 @@
<#
.SYNOPSIS
为货代库存 RPA Worker 写入 Windows 用户级永久环境变量(含共享 scope 与心跳)。
.DESCRIPTION
test/prod 部署时必须配置 SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID,与 Ubuntu 后端
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID 一致,否则 Worker 不会写哨兵文件,
后端就绪检查将报 shared_sentinel_missing。
RPA Profile 凭据解密还要求 Windows Worker 与对应环境后端使用同一个
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY。脚本通过 SecureString 交互读取该密钥,
不接收明文命令行参数,也不会在控制台显示密钥。
用法(以管理员或 RPA 专用账号登录后执行一次):
.\scripts\rpa\set_rpa_worker_env.ps1 -Environment test -ApiBase "http://192.168.1.20:8890" -ToolApiKey "<密钥>"
.\scripts\rpa\set_rpa_worker_env.ps1 -Environment prod -ApiBase "http://生产地址:端口" -ToolApiKey "<密钥>"
执行后请关闭并重新打开 PowerShell,再运行 freight_rpa_worker.py。
完整说明见 docs/features/shipping-notice/technical.md §1.5.5a / §1.5.10。
#>
param(
[Parameter(Mandatory = $true)]
[ValidateSet("test", "prod")]
[string]$Environment,
[Parameter(Mandatory = $true)]
[string]$ApiBase,
[Parameter(Mandatory = $true)]
[string]$ToolApiKey,
[SecureString]$CredentialKey,
[string]$DsvUsername = "",
[string]$DsvPassword = "",
[string]$CraneUsername = "",
[string]$CranePassword = ""
)
$ErrorActionPreference = "Stop"
function ConvertTo-PlainText {
param([Parameter(Mandatory = $true)][SecureString]$Value)
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Value)
try {
return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer)
} finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer)
}
}
if (-not $CredentialKey) {
$CredentialKey = Read-Host `
"请输入与 $Environment 后端一致的 SHIPPING_NOTICE_RPA_CREDENTIAL_KEY" `
-AsSecureString
}
$CredentialKeyPlainText = ConvertTo-PlainText -Value $CredentialKey
try {
$credentialKeyBytes = [Convert]::FromBase64String(
$CredentialKeyPlainText.Replace('-', '+').Replace('_', '/')
)
} catch {
throw "SHIPPING_NOTICE_RPA_CREDENTIAL_KEY 必须是有效的 Fernet URL-safe Base64 密钥"
}
if ($credentialKeyBytes.Length -ne 32) {
throw "SHIPPING_NOTICE_RPA_CREDENTIAL_KEY 解码后必须为 32 字节"
}
if ($Environment -eq "test") {
$Root = "C:\HxopsRpaTest"
$ScopeId = "hxops-rpa-test-data"
} else {
$Root = "C:\HxopsRpaProd"
$ScopeId = "hxops-rpa-prod-data"
}
$DataRoot = Join-Path $Root "data"
$Vars = [ordered]@{
"HXOPS_API_BASE" = $ApiBase
"SHIPPING_NOTICE_TOOL_API_KEY" = $ToolApiKey
"SHIPPING_NOTICE_RPA_CREDENTIAL_KEY" = $CredentialKeyPlainText
"SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT" = $Environment
"SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID" = $ScopeId
"SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS" = "20"
"SHIPPING_NOTICE_RPA_WORKER_MOCK" = "false"
"SHIPPING_NOTICE_RPA_WORKER_HEADLESS" = "false"
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL" = "msedge"
"SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS" = "3"
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR" = Join-Path $DataRoot "inventory_triggers"
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR" = Join-Path $DataRoot "inventory_drop"
"SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR" = Join-Path $DataRoot "upload_triggers"
"SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR" = Join-Path $DataRoot "upload_queue"
# 上传站点配置通过受控环境变量单独注入;部署脚本永远不默认开启浏览器提交。
"SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED" = "false"
"SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT" = "false"
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR" = Join-Path $DataRoot "browser_profile"
"SHIPPING_NOTICE_RPA_WORKER_LOG_FILE" = Join-Path $DataRoot "logs\worker.log"
"SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES" = "10485760"
"SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT" = "5"
}
if ($DsvUsername) { $Vars["SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME"] = $DsvUsername }
if ($DsvPassword) { $Vars["SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD"] = $DsvPassword }
if ($CraneUsername) { $Vars["SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME"] = $CraneUsername }
if ($CranePassword) { $Vars["SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD"] = $CranePassword }
$SensitiveKeys = @(
"SHIPPING_NOTICE_TOOL_API_KEY",
"SHIPPING_NOTICE_RPA_CREDENTIAL_KEY",
"SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD",
"SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD"
)
$UsernameKeys = @(
"SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME",
"SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME"
)
function Get-MaskedUsername {
param([string]$Value)
if (-not $Value) { return $Value }
if ($Value -match '^([^@]+)@(.+)$') {
$local = $Matches[1]
$domain = $Matches[2]
if ($local.Length -le 3) {
return "***@$domain"
}
return ($local.Substring(0, 3) + "***@" + $domain)
}
if ($Value.Length -le 3) {
return "***"
}
return ($Value.Substring(0, 3) + "***")
}
function Get-DisplayValue {
param(
[string]$Key,
[string]$Value
)
if ($SensitiveKeys -contains $Key -and $Value) {
return "******"
}
if ($UsernameKeys -contains $Key -and $Value) {
return Get-MaskedUsername -Value $Value
}
return $Value
}
foreach ($entry in $Vars.GetEnumerator()) {
[Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, "User")
$display = Get-DisplayValue -Key $entry.Key -Value ([string]$entry.Value)
Write-Host ("[ok] {0}={1}" -f $entry.Key, $display)
}
$CredentialKeyPlainText = $null
Write-Host ""
Write-Host "Environment=$Environment scope_id=$ScopeId root=$Root"
Write-Host "请关闭并重新打开 PowerShell,然后验证:"
Write-Host " echo `$env:SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"
Write-Host " cd $Root"
Write-Host " python scripts\rpa\freight_rpa_worker.py"
+99
View File
@@ -0,0 +1,99 @@
<#
.SYNOPSIS
在当前 PowerShell 进程树中启动指定环境的 RPA Worker。
.DESCRIPTION
该脚本只写入 Process 级环境变量,绝不调用 User/Machine 环境变量 API。
test/prod 可由同一 Windows 用户、同一交互式桌面、两个独立计划任务同时运行。
每个环境必须有独立 root、scope、共享目录、browser profile、日志和 DPAPI Secret 文件。
DSV/Crane 登录地址、账号和密码来自 HXOPS trigger 的 credential_envelope,
不从本机 Secret 文件读取。
#>
param(
[Parameter(Mandatory = $true)]
[ValidateSet("test", "prod")]
[string]$Environment,
[Parameter(Mandatory = $true)]
[string]$ApiBase,
[Parameter(Mandatory = $true)]
[string]$WorkerRoot,
[Parameter(Mandatory = $true)]
[string]$SecretFile,
[string]$PythonExe = "python.exe",
[switch]$Mock,
[switch]$Headless
)
$ErrorActionPreference = "Stop"
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) {
throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。"
}
$workerScript = Join-Path $WorkerRoot "scripts\rpa\freight_rpa_worker.py"
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) {
throw "Worker 不存在:$workerScript"
}
if ($Environment -eq "test") {
$scopeId = "hxops-rpa-test-data"
} else {
$scopeId = "hxops-rpa-prod-data"
}
$dataRoot = Join-Path $WorkerRoot "data"
function ConvertTo-PlainText {
param([Parameter(Mandatory = $true)][System.Security.SecureString]$Value)
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Value)
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
}
$secret = Import-Clixml -LiteralPath $SecretFile
foreach ($required in @("ToolApiKey", "CredentialKey")) {
if (-not ($secret.PSObject.Properties.Name -contains $required)) {
throw "Secret 文件缺少字段:$required"
}
}
# 只设置当前 launcher 及其 Worker 子进程可见的环境变量;不写 User/Machine 持久配置。
$processVars = [ordered]@{
HXOPS_API_BASE = $ApiBase
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = $Environment
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = $scopeId
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20"
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" })
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge"
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $dataRoot "inventory_triggers"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $dataRoot "inventory_drop"
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $dataRoot "upload_triggers"
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $dataRoot "upload_queue"
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $dataRoot "browser_profile"
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot "logs\worker.log"
SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760"
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5"
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED = "false"
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT = "false"
}
foreach ($entry in $processVars.GetEnumerator()) {
[Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, "Process")
}
Write-Host "Starting RPA Worker: environment=$Environment scope=$scopeId root=$WorkerRoot"
try {
& $PythonExe $workerScript
exit $LASTEXITCODE
}
finally {
foreach ($entry in $processVars.GetEnumerator()) {
[Environment]::SetEnvironmentVariable($entry.Key, $null, "Process")
}
}