diff --git a/.env.dev b/.env.dev index 2e329956..2c7fa88e 100644 --- a/.env.dev +++ b/.env.dev @@ -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) diff --git a/.env.prod b/.env.prod index 7528fabe..51a6dc86 100644 --- a/.env.prod +++ b/.env.prod @@ -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 diff --git a/.env.shared b/.env.shared index 54be5454..e02b1b76 100644 --- a/.env.shared +++ b/.env.shared @@ -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。 diff --git a/.env.test b/.env.test index d8df0810..49729674 100644 --- a/.env.test +++ b/.env.test @@ -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 diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index f467d493..1a1584fd 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -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) diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index d47eafc6..901898a6 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -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')) diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index 37fc7377..34c06d0a 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -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, ) diff --git a/backend/app/jobs/handlers/shipping_document_layout.py b/backend/app/jobs/handlers/shipping_document_layout.py index 462ca994..0bd08fbc 100644 --- a/backend/app/jobs/handlers/shipping_document_layout.py +++ b/backend/app/jobs/handlers/shipping_document_layout.py @@ -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() diff --git a/backend/app/jobs/handlers/shipping_line_auto_fulfill.py b/backend/app/jobs/handlers/shipping_line_auto_fulfill.py new file mode 100644 index 00000000..749688b3 --- /dev/null +++ b/backend/app/jobs/handlers/shipping_line_auto_fulfill.py @@ -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 diff --git a/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py b/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py new file mode 100644 index 00000000..365c0df7 --- /dev/null +++ b/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py @@ -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 diff --git a/backend/app/jobs/handlers/shipping_stp_auto_create.py b/backend/app/jobs/handlers/shipping_stp_auto_create.py index 71e50985..428d797e 100644 --- a/backend/app/jobs/handlers/shipping_stp_auto_create.py +++ b/backend/app/jobs/handlers/shipping_stp_auto_create.py @@ -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 diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index fec9182c..efdb502a 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -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', }), } diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index f44e1545..6e4959c7 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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', diff --git a/backend/app/models/shipping_notice_line_inventory_match.py b/backend/app/models/shipping_notice_line_inventory_match.py new file mode 100644 index 00000000..c75a7887 --- /dev/null +++ b/backend/app/models/shipping_notice_line_inventory_match.py @@ -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, + ) diff --git a/backend/app/models/shipping_order_review_line_decision.py b/backend/app/models/shipping_order_review_line_decision.py index 65769b1f..cb79c31d 100644 --- a/backend/app/models/shipping_order_review_line_decision.py +++ b/backend/app/models/shipping_order_review_line_decision.py @@ -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) diff --git a/backend/app/models/shipping_order_review_wave_idempotency.py b/backend/app/models/shipping_order_review_wave_idempotency.py new file mode 100644 index 00000000..9ba9ccf3 --- /dev/null +++ b/backend/app/models/shipping_order_review_wave_idempotency.py @@ -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, + ) diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index bb0fd7ba..f21187f8 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -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="货代审计到期清理与哈希校验", diff --git a/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py new file mode 100644 index 00000000..eb24344d --- /dev/null +++ b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py @@ -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, [] diff --git a/backend/app/services/shipping_notice/document_layout/__init__.py b/backend/app/services/shipping_notice/document_layout/__init__.py index fafb4a66..fce79f47 100644 --- a/backend/app/services/shipping_notice/document_layout/__init__.py +++ b/backend/app/services/shipping_notice/document_layout/__init__.py @@ -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', diff --git a/backend/app/services/shipping_notice/document_layout/layout_diagnostics.py b/backend/app/services/shipping_notice/document_layout/layout_diagnostics.py new file mode 100644 index 00000000..6a1e9760 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/layout_diagnostics.py @@ -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 diff --git a/backend/app/services/shipping_notice/document_layout/native_pdf.py b/backend/app/services/shipping_notice/document_layout/native_pdf.py index e97db791..da7b1f96 100644 --- a/backend/app/services/shipping_notice/document_layout/native_pdf.py +++ b/backend/app/services/shipping_notice/document_layout/native_pdf.py @@ -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: diff --git a/backend/app/services/shipping_notice/document_layout/ocr_pdf.py b/backend/app/services/shipping_notice/document_layout/ocr_pdf.py index c62b6220..df418c85 100644 --- a/backend/app/services/shipping_notice/document_layout/ocr_pdf.py +++ b/backend/app/services/shipping_notice/document_layout/ocr_pdf.py @@ -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, diff --git a/backend/app/services/shipping_notice/document_layout/opencv_table.py b/backend/app/services/shipping_notice/document_layout/opencv_table.py index 96293cac..306d5302 100644 --- a/backend/app/services/shipping_notice/document_layout/opencv_table.py +++ b/backend/app/services/shipping_notice/document_layout/opencv_table.py @@ -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, *, diff --git a/backend/app/services/shipping_notice/document_layout/runtime.py b/backend/app/services/shipping_notice/document_layout/runtime.py index b5e13015..1527c76f 100644 --- a/backend/app/services/shipping_notice/document_layout/runtime.py +++ b/backend/app/services/shipping_notice/document_layout/runtime.py @@ -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 = [] diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index ffa3c7ec..196064e4 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -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", diff --git a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py new file mode 100644 index 00000000..8cf9316f --- /dev/null +++ b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py @@ -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, + ) diff --git a/backend/app/services/shipping_notice/line_inventory_match_persistence.py b/backend/app/services/shipping_notice/line_inventory_match_persistence.py new file mode 100644 index 00000000..74f5a8c0 --- /dev/null +++ b/backend/app/services/shipping_notice/line_inventory_match_persistence.py @@ -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 diff --git a/backend/app/services/shipping_notice/line_inventory_match_projection.py b/backend/app/services/shipping_notice/line_inventory_match_projection.py new file mode 100644 index 00000000..bfd0bc51 --- /dev/null +++ b/backend/app/services/shipping_notice/line_inventory_match_projection.py @@ -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, + } diff --git a/backend/app/services/shipping_notice/order_review_confirmation_service.py b/backend/app/services/shipping_notice/order_review_confirmation_service.py index 62ba173c..bb284804 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -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: diff --git a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py index 2c523c5b..48d33032 100644 --- a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py +++ b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py @@ -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: diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index db4a11cb..9aea3bc9 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -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, diff --git a/backend/app/services/shipping_notice/order_review_workbench_projection.py b/backend/app/services/shipping_notice/order_review_workbench_projection.py new file mode 100644 index 00000000..88e874ab --- /dev/null +++ b/backend/app/services/shipping_notice/order_review_workbench_projection.py @@ -0,0 +1,1024 @@ +""" +backend/app/services/shipping_notice/order_review_workbench_projection.py + +用途:复核工作台 Case 投影的阶段分层辅助——正式 OT 判定、用户态 profile_match、 + field_completeness、completed_checks、OT 当前阶段与 automation 责任方; + 以及草稿行 field_code(如 part_number/qty)解析,供履约表与订单明细对齐。 +依赖:ShippingNotice、ShippingOrderReviewCase、Job、order_review_draft_service._current_value、 + process_gate_contract、processing_projection_invariants、queue_service 域常量。 +逻辑:由 order_review_projection.serialize_review_case / shipping_processing_projection / + order_review_fulfillment_decision_service 调用;不新建状态模型; + project_stage_for_task 与 project_post_ot_automation_from_job 为 Case/Progress 同源; + 禁止前端自行拼接里程碑。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.models import ShippingNotice, ShippingOrderReviewCase + +# 正式 OT 创建后不得再作为「当前人工阻断」的建单前 Gate。 +_PRE_OT_BLOCKING_GATE_CODES: frozenset[str] = frozenset({ + 'document_materialization', + 'document_layout_parsing', + 'document_profile_routing', + 'order_field_extraction', + 'field_completeness', + 'customer_resolution', + 'customer_confirmed', + 'duplicate_detection', + 'field_conflict_resolution', + 'order_freeze_readiness', + 'order_review', + 'build_eligibility', +}) + +# Worker 等待类库存准备:即使存在 Gate 行,也不得投影为人工待办。 +_SYSTEM_WAIT_INVENTORY_GATES: frozenset[str] = frozenset({ + 'inventory_preparation', +}) + +# 库存/履约域(正式 OT 后允许在 owner_type=human 时成为当前阻断)。 +_POST_OT_INVENTORY_FULFILLMENT_GATES: frozenset[str] = frozenset({ + 'inventory_source_routing', + 'reservation_validation', + 'inventory_field_mapping', + 'inventory_matching', + 'inventory_sufficiency', + 'line_fulfillment', + 'shortage_review', + 'fulfillment_decision', +}) + +_USER_PROFILE_MATCH_STATUSES: frozenset[str] = frozenset({ + 'matched', + 'unmatched', + 'ambiguous', + 'unknown', +}) + + +def resolve_formal_ot(case: ShippingOrderReviewCase) -> dict[str, Any]: + """ + 判定 Case 是否已绑定可读的正式 OT。 + + 核心逻辑:唯一判据为 confirmed_task_id 指向存在且 task_no 有效的 ShippingNotice; + Case.status=confirmed 不能单独证明 OT 存在。 + + Args: + case: 复核 Case。 + + Returns: + { + has_formal_ot: bool, + task_missing: bool, + task: ShippingNotice | None, + task_no: str | None, + task_id: int | None, + } + """ + task_id = getattr(case, 'confirmed_task_id', None) + if task_id is None: + return { + 'has_formal_ot': False, + 'task_missing': False, + 'task': None, + 'task_no': None, + 'task_id': None, + } + task = db.session.get(ShippingNotice, int(task_id)) + if task is None: + return { + 'has_formal_ot': False, + 'task_missing': True, + 'task': None, + 'task_no': None, + 'task_id': int(task_id), + } + task_no = str(getattr(task, 'task_no', None) or '').strip() or None + if not task_no: + return { + 'has_formal_ot': False, + 'task_missing': True, + 'task': task, + 'task_no': None, + 'task_id': int(task_id), + } + return { + 'has_formal_ot': True, + 'task_missing': False, + 'task': task, + 'task_no': task_no, + 'task_id': int(task_id), + } + + +def map_profile_match_user_status( + raw_status: str | None, + *, + candidates: list[Any] | None = None, + needs_review: bool = False, +) -> str: + """ + 将路由原始状态映射为普通用户四态:matched|unmatched|ambiguous|unknown。 + + Args: + raw_status: 路由 match_status 原值。 + candidates: 候选列表;用于 needs_review 歧义判定。 + needs_review: 是否需人工裁决。 + + Returns: + 用户态四态之一。 + """ + status = str(raw_status or '').strip().lower() + if status in {'matched', 'selected'}: + return 'matched' + if status in {'not_matched', 'no_match', 'unmatched'}: + return 'unmatched' + if status in {'ambiguous', 'layout_drift'}: + return 'ambiguous' + if status == 'needs_review' or (needs_review and status in {'', 'unknown'}): + if candidates: + return 'ambiguous' + return 'unknown' + if status in {'evidence_insufficient', 'unknown', ''}: + return 'unknown' + if status in _USER_PROFILE_MATCH_STATUSES: + return status + # 未识别原值:保守为 unknown,禁止伪装成 unmatched。 + if needs_review and candidates: + return 'ambiguous' + return 'unknown' + + +def project_user_profile_match(admin_payload: dict[str, Any] | None) -> dict[str, Any]: + """ + 普通用户模板匹配裁剪:仅四态 + 是否需关注;不含 Profile ID/分数/原因链。 + + Args: + admin_payload: 管理员完整 profile_match;None 时返回 unknown。 + + Returns: + 用户可读 profile_match。 + """ + payload = dict(admin_payload or {}) + if not payload.get('available', True) and str(payload.get('status') or '') in {'hidden', ''}: + # 尚无路由决策时仍给用户四态,避免「模板匹配区」整块消失导致无法区分 unknown。 + return { + 'available': True, + 'visibility': 'user', + 'status': 'unknown', + 'needs_review': False, + 'candidates': [], + 'fallback_reason_codes': [], + 'selected_profile': None, + 'execution_mode': None, + 'route_type': None, + } + raw = str(payload.get('status') or '') + candidates = list(payload.get('candidates') or []) + needs_review = bool(payload.get('needs_review')) + user_status = map_profile_match_user_status( + raw, + candidates=candidates, + needs_review=needs_review, + ) + selected = payload.get('selected_profile') if isinstance(payload.get('selected_profile'), dict) else None + selected_user = None + if selected and user_status == 'matched': + # 仅展示名,不带 profile id / checksum。 + selected_user = { + 'display_name': str(selected.get('display_name') or selected.get('profile_code') or '').strip() or None, + } + return { + 'available': True, + 'visibility': 'user', + 'status': user_status, + 'needs_review': needs_review and user_status in {'ambiguous', 'unmatched', 'unknown'}, + 'candidates': [], + 'fallback_reason_codes': [], + 'selected_profile': selected_user, + 'execution_mode': None, + 'route_type': None, + } + + +def project_field_completeness( + *, + validation: dict[str, Any] | None, + has_formal_ot: bool, +) -> dict[str, Any]: + """ + 投影 Case.field_completeness(与 Process Gate field_completeness 同源校验事实)。 + + 核心逻辑:从 Draft validation issues / failed_gates 提取 required_field_missing; + 正式 OT 已创建后强制 status=ready(可供已完成检查),不再作为当前阻断。 + + Args: + validation: Draft.validation_result_json。 + has_formal_ot: 是否已有正式 OT。 + + Returns: + {status: ready|blocked, issues: [...]} + """ + issues: list[dict[str, Any]] = [] + source = validation if isinstance(validation, dict) else {} + for item in list(source.get('issues') or []): + if not isinstance(item, dict): + continue + code = str(item.get('code') or item.get('reason') or item.get('reason_code') or '').strip() + owning = str(item.get('owning_gate_code') or '').strip() + if code == 'required_field_missing' or owning == 'field_completeness': + if code != 'required_field_missing' and owning != 'field_completeness': + continue + issues.append({ + 'code': code or 'required_field_missing', + 'field_id': item.get('field_id'), + 'field_code': item.get('field_code'), + 'line_index': item.get('line_index'), + 'message': item.get('message'), + }) + failed_gates = {str(g).strip() for g in (source.get('failed_gates') or []) if g} + gate_blocked = 'field_completeness' in failed_gates + status = 'blocked' if (issues or gate_blocked) else 'ready' + if has_formal_ot: + status = 'ready' + return { + 'status': status, + 'issues': [] if has_formal_ot else issues, + } + + +def _iso_or_none(value: Any) -> str | None: + """将 datetime / ISO 字符串规范为 ISO 文本。""" + if value is None: + return None + if isinstance(value, datetime): + return value.isoformat() + text = str(value).strip() + return text or None + + +def project_completed_checks( + *, + case: ShippingOrderReviewCase, + process_gate: dict[str, Any] | None, + customer_resolution: dict[str, Any] | None, + duplicate: dict[str, Any] | None, + field_conflicts: list[Any] | None, + field_completeness: dict[str, Any] | None, + profile_match: dict[str, Any] | None, + formal_ot: dict[str, Any], +) -> list[dict[str, Any]]: + """ + 组装已完成检查列表;仅已通过项进入,前端禁止自行拼接。 + + Returns: + [{code, status: passed, completed_at?}, ...] + """ + checks: list[dict[str, Any]] = [] + track = list((process_gate or {}).get('gates_track') or []) + track_by_code = { + str(item.get('gate_code') or '').strip(): item + for item in track + if isinstance(item, dict) and item.get('gate_code') + } + + def _append_if_passed(code: str, *, ok: bool, completed_at: Any = None) -> None: + if not ok: + return + checks.append({ + 'code': code, + 'status': 'passed', + 'completed_at': _iso_or_none(completed_at), + }) + + # [STEP 1] 从 Gate track 映射稳定里程碑(有则展示、无则省略)。 + gate_to_check = { + 'document_materialization': 'document_available', + 'document_layout_parsing': 'pdf_layout_parsed', + 'document_profile_routing': 'profile_routed', + 'order_field_extraction': 'fields_extracted', + 'field_completeness': 'field_completeness', + 'customer_resolution': 'customer_resolved', + 'duplicate_detection': 'duplicate_checked', + 'field_conflict_resolution': 'field_conflicts_resolved', + 'order_freeze_readiness': 'order_review_completed', + } + for gate_code, check_code in gate_to_check.items(): + item = track_by_code.get(gate_code) + if item is None: + continue + if str(item.get('status') or '').strip().lower() in {'passed', 'skipped'}: + _append_if_passed(check_code, ok=True) + + # [STEP 2] 业务侧补充(Gate track 缺失时用 Case 摘要兜底,仍只记「已通过」)。 + existing = {item['code'] for item in checks} + if 'field_completeness' not in existing and str((field_completeness or {}).get('status') or '') == 'ready': + _append_if_passed('field_completeness', ok=True) + if 'customer_resolved' not in existing and bool((customer_resolution or {}).get('resolved')): + _append_if_passed('customer_resolved', ok=True) + if 'duplicate_checked' not in existing and not bool((duplicate or {}).get('needs_adjudication')): + # 仅当 duplicate 投影明确不需要裁决时记完成;缺投影则省略。 + if duplicate is not None: + _append_if_passed('duplicate_checked', ok=True) + if 'field_conflicts_resolved' not in existing: + open_conflicts = [ + c for c in (field_conflicts or []) + if isinstance(c, dict) and str(c.get('status') or '').lower() not in {'resolved', 'accepted', 'dismissed'} + ] + if field_conflicts is not None and not open_conflicts: + _append_if_passed('field_conflicts_resolved', ok=True) + if 'profile_routed' not in existing and str((profile_match or {}).get('status') or '') == 'matched': + _append_if_passed('profile_routed', ok=True) + + # [STEP 3] 正式 OT 里程碑。 + if formal_ot.get('has_formal_ot'): + if 'order_review_completed' not in {item['code'] for item in checks}: + _append_if_passed('order_review_completed', ok=True) + completed_at = getattr(formal_ot.get('task'), 'created_at', None) or getattr(case, 'updated_at', None) + _append_if_passed('formal_ot_created', ok=True, completed_at=completed_at) + + return checks + + +def find_active_shipping_notice_run_job(*, task_no: str): + """ + 按 task_no / business_ref 查找当前有效 shipping_notice_run Job(queued|running)。 + + Args: + task_no: 正式 OT 任务号。 + + Returns: + Job 或 None。 + """ + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + key = str(task_no or '').strip().upper() + if not key: + return None + return ( + Job.query + .filter( + Job.domain == SHIPPING_NOTICE_JOB_DOMAIN, + Job.job_type == JobType.SHIPPING_NOTICE_RUN.value, + Job.business_ref == key, + Job.status.in_(('queued', 'running')), + ) + .order_by(Job.id.desc()) + .first() + ) + + +def find_latest_shipping_notice_run_job(*, task_no: str): + """ + 按 task_no 查找最近一条 shipping_notice_run Job(含 failed,供投影/重试)。 + + Args: + task_no: 正式 OT 任务号。 + + Returns: + Job 或 None。 + """ + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN + + key = str(task_no or '').strip().upper() + if not key: + return None + return ( + Job.query + .filter( + Job.domain == SHIPPING_NOTICE_JOB_DOMAIN, + Job.job_type == JobType.SHIPPING_NOTICE_RUN.value, + Job.business_ref == key, + ) + .order_by(Job.id.desc()) + .first() + ) + + +def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str, Any]: + """ + 正式 OT 后 Automation / needs_retry 的唯一判定:绑定 shipping_notice_run Job。 + + 优先级:有效 Job failed > running > queued; + Job success/succeeded 但 OT 仍 created → failed + retryable(保留 job_id); + 达到 max_attempts / dead → manual_fallback; + 无 Job + created → waiting_to_start。 + + Args: + task: 正式 ShippingNotice;None 时返回空闲态。 + + Returns: + status / retryable / job_id / error_code / needs_retry / reason_code / + task_no / task_process_status / completed_at。 + """ + if task is None: + return { + 'status': 'idle', + 'retryable': False, + 'needs_retry': False, + 'job_id': None, + 'error_code': None, + 'task_no': None, + 'task_process_status': None, + 'attempts': None, + 'max_attempts': None, + 'completed_at': None, + 'reason_code': None, + } + + task_no = str(getattr(task, 'task_no', None) or '').strip().upper() or None + process_status = str(getattr(task, 'process_status', None) or '').strip().lower() + active = find_active_shipping_notice_run_job(task_no=task_no or '') + latest = active or find_latest_shipping_notice_run_job(task_no=task_no or '') + + def _iso(value: Any) -> str | None: + if value is None: + return None + try: + return value.isoformat() if hasattr(value, 'isoformat') else str(value) + except Exception: # noqa: BLE001 + return None + + def _job_fields(job) -> dict[str, Any]: + if job is None: + return { + 'job_id': None, + 'error_code': None, + 'attempts': None, + 'max_attempts': None, + 'completed_at': None, + } + result = job.result_json if isinstance(job.result_json, dict) else {} + error_code = ( + str(result.get('error_code') or '').strip() + or str(getattr(job, 'error_message', None) or '').strip() + or None + ) + return { + 'job_id': int(job.id), + 'error_code': error_code, + 'attempts': int(job.attempts or 0), + 'max_attempts': int(job.max_attempts or 0) or None, + 'completed_at': _iso(getattr(job, 'finished_at', None)), + } + + def _attempts_exhausted(job) -> bool: + job_status = str(getattr(job, 'status', None) or '').strip().lower() + if job_status == 'dead': + return True + attempts = int(getattr(job, 'attempts', None) or 0) + max_attempts = int(getattr(job, 'max_attempts', None) or 1) or 1 + return attempts >= max_attempts + + # [STEP 1] 有效 queued/running 优先。 + if active is not None: + job_status = str(active.status or '').strip().lower() + mapped = 'queued' if job_status == 'queued' else 'running' + return { + 'status': mapped, + 'retryable': False, + 'needs_retry': False, + 'task_no': task_no, + 'task_process_status': process_status, + 'reason_code': None, + **_job_fields(active), + } + + # [STEP 2] 最近 Job:failed/dead,或 success 但 OT 未推进。 + if latest is not None: + latest_status = str(latest.status or '').strip().lower() + fields = _job_fields(latest) + if latest_status in {'failed', 'dead'}: + exhausted = _attempts_exhausted(latest) + return { + 'status': 'manual_fallback' if exhausted else 'failed', + 'retryable': True, + 'needs_retry': True, + 'task_no': task_no, + 'task_process_status': process_status, + 'reason_code': fields.get('error_code') or 'auto_progress_job_failed', + **fields, + } + if latest_status in {'succeeded', 'success', 'completed'}: + # Job 标成功但 OT 仍 created:业务故障,不得伪装 waiting / 抹掉 job_id。 + if process_status in {'', 'created'}: + exhausted = _attempts_exhausted(latest) + reason = 'auto_progress_job_succeeded_but_task_not_advanced' + return { + 'status': 'manual_fallback' if exhausted else 'failed', + 'retryable': True, + 'needs_retry': True, + 'task_no': task_no, + 'task_process_status': process_status, + 'reason_code': reason, + 'error_code': reason, + 'job_id': fields['job_id'], + 'attempts': fields['attempts'], + 'max_attempts': fields['max_attempts'], + 'completed_at': fields['completed_at'], + } + return { + 'status': 'completed', + 'retryable': False, + 'needs_retry': False, + 'task_no': task_no, + 'task_process_status': process_status, + 'reason_code': None, + **fields, + } + + # [STEP 3] 无 Job:created → waiting_to_start;其余按 OT 态,禁止仅凭 process_status 伪装 running。 + if process_status in {'', 'created'}: + return { + 'status': 'waiting_to_start', + 'retryable': False, + 'needs_retry': False, + 'task_no': task_no, + 'task_process_status': process_status, + 'reason_code': 'auto_progress_not_enqueued_yet', + **_job_fields(None), + } + if process_status in {'completed', 'closed', 'done', 'uploaded'}: + return { + 'status': 'completed', + 'retryable': False, + 'needs_retry': False, + 'task_no': task_no, + 'task_process_status': process_status, + 'reason_code': None, + **_job_fields(None), + } + # OT 已离开 created 但无 Job:投影 waiting_to_start(no_job),禁止猜 running。 + return { + 'status': 'waiting_to_start', + 'retryable': False, + 'needs_retry': False, + 'task_no': task_no, + 'task_process_status': process_status, + 'reason_code': 'auto_progress_not_enqueued_yet', + **_job_fields(None), + } + + +def project_stage_for_task( + task: ShippingNotice | None, + *, + default_code: str = 'order_review', +) -> dict[str, Any]: + """ + Case API 与统一 Progress API 共用的正式 OT 阶段投影。 + + 核心逻辑:优先读取已挂接 ShippingOrderTask.stage(与 Progress 写路径同源); + 否则 created → order_creating;再否则 map_notice_to_processing_status_stage。 + 凡 code=order_creating,用户文案键统一 label_key=waiting_system_start(禁止用码当文案)。 + + Args: + task: 正式 ShippingNotice;可为 None。 + default_code: 无 OT 时的阶段码。 + + Returns: + {code, label_key, source, inconsistent, process_status, current_step, stage_node} + """ + if task is None: + return { + 'code': default_code, + 'label_key': default_code, + 'source': 'fallback', + 'inconsistent': False, + 'process_status': None, + 'current_step': None, + 'stage_node': None, + } + + from app.models import ShippingOrderTask + from app.services.shipping_notice.progress_audit_contract import SHIPPING_PROCESSING_STAGES + from app.services.shipping_notice.processing_projection_invariants import ( + map_notice_to_processing_status_stage, + ) + + process_status = str(getattr(task, 'process_status', None) or '').strip().lower() or None + current_step = str(getattr(task, 'current_step', None) or '').strip() or None + + def _with_label(code: str, *, source: str) -> dict[str, Any]: + # order_creating 技术阶段码保留;用户可见文案键固定 waiting_system_start。 + label_key = 'waiting_system_start' if code == 'order_creating' else code + return { + 'code': code, + 'label_key': label_key, + 'source': source, + 'inconsistent': False, + 'process_status': process_status, + 'current_step': current_step, + 'stage_node': None, + } + + # [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。 + order_task = None + try: + from flask import has_app_context + if has_app_context(): + if getattr(task, 'order_task_id', None): + order_task = db.session.get(ShippingOrderTask, int(task.order_task_id)) + if order_task is None and getattr(task, 'id', None): + order_task = ( + ShippingOrderTask.query.filter_by(shipping_notice_id=int(task.id)) + .order_by(ShippingOrderTask.id.desc()) + .first() + ) + except Exception: # noqa: BLE001 — 单元测试无 Flask 上下文时跳过 OT 查询 + order_task = None + ot_stage = str(getattr(order_task, 'stage', None) or '').strip().lower() if order_task else '' + if ot_stage and ot_stage in SHIPPING_PROCESSING_STAGES: + # [STEP 1b] 正式 OT 已创建但 stage 仍停在 order_creating:业务上已进入获取库存。 + # Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。 + if ot_stage == 'order_creating': + if process_status in {'waiting_inventory', 'parsed', 'fetching_inventory', 'inventory_fetching'}: + return _with_label('inventory_fetching', source='notice_inventory') + if process_status in {'inventory_ready', 'matching', 'matched'}: + _status, mapped = map_notice_to_processing_status_stage(task) + code = str(mapped or 'inventory_matching').strip() or 'inventory_matching' + return _with_label(code, source='notice_map') + if process_status in {None, '', 'created'}: + return _with_label('inventory_fetching', source='post_ot_inventory') + return _with_label(ot_stage, source='order_task') + + # [STEP 2] Notice 尚停在 created:统一 order_creating(与 Progress 词典同源,禁止冒充库存匹配)。 + if process_status in {None, '', 'created'}: + return _with_label('order_creating', source='process_status') + + # [STEP 3] 领域映射(与 sync_order_task_stage_for_notice 同源)。 + _status, stage = map_notice_to_processing_status_stage(task) + code = str(stage or 'waiting_review').strip() or 'waiting_review' + return _with_label(code, source='notice_map') + + +def project_ot_current_stage(task: ShippingNotice | None) -> dict[str, Any]: + """ + 兼容别名:委托 project_stage_for_task(正式 OT 默认 waiting_to_start)。 + + Returns: + 与 project_stage_for_task 相同结构。 + """ + return project_stage_for_task(task, default_code='waiting_to_start') + + +def enrich_automation_status( + automation: dict[str, Any], + *, + formal_ot: dict[str, Any], + is_admin: bool = False, +) -> dict[str, Any]: + """ + 为 automation 补充 phase / owner_type;建单后禁止 STP 主态,并附管理员 enqueue 诊断。 + + Args: + automation: _project_case_automation_status 原始结果。 + formal_ot: resolve_formal_ot 结果。 + is_admin: 管理员时附加 technical enqueue 字段。 + + Returns: + 增强后的 automation 字典。 + """ + result = dict(automation or {}) + has_ot = bool(formal_ot.get('has_formal_ot')) + task_missing = bool(formal_ot.get('task_missing')) + result['phase'] = 'post_ot_progress' if (has_ot or task_missing) else 'pre_ot_stp' + status = str(result.get('status') or '').strip().lower() + + if task_missing: + result['status'] = 'failed' + result['retryable'] = False + result['reason_code'] = 'task_missing' + result['owner_type'] = 'unknown' + if is_admin: + result['technical'] = { + 'enqueue_status': 'task_missing', + 'task_id': formal_ot.get('task_id'), + } + return result + + if has_ot: + # 建单后:禁止再读 STP 作为主状态;无 Job 时 waiting_to_start + enqueue_status=no_job。 + if status in {'idle', ''} and formal_ot.get('task_no'): + result['status'] = 'waiting_to_start' + status = 'waiting_to_start' + result['reason_code'] = result.get('reason_code') or 'auto_progress_not_enqueued_yet' + result['task_no'] = formal_ot.get('task_no') or result.get('task_no') + if status in {'waiting_to_start', 'queued', 'running', 'completed'}: + result['owner_type'] = 'system' + elif status in {'failed', 'manual_fallback'}: + result['owner_type'] = 'human' if status == 'manual_fallback' else 'system' + else: + result['owner_type'] = 'system' + if is_admin and status == 'waiting_to_start' and not result.get('job_id'): + result['technical'] = { + 'enqueue_status': 'no_job', + } + return result + + # 建单前 STP + if status in {'waiting_to_start', 'queued', 'running', 'completed'}: + result['owner_type'] = 'system' + elif status in {'failed', 'manual_fallback'}: + result['owner_type'] = 'human' if status == 'manual_fallback' else 'system' + else: + result['owner_type'] = 'unknown' + return result + + +def apply_post_ot_gate_rules( + summary: dict[str, Any], + *, + has_formal_ot: bool, +) -> dict[str, Any]: + """ + 正式 OT 创建后清除建单前 Gate 当前阻断;系统等待库存准备不得冒充人工待办。 + + Args: + summary: project_user_gate_summary 原始结果。 + has_formal_ot: 是否已有正式 OT。 + + Returns: + 调整后的 process_gate 摘要(含 owner_type)。 + """ + result = dict(summary or {}) + blocking = result.get('current_blocking_gate') + gate_code = '' + if isinstance(blocking, dict): + gate_code = str(blocking.get('gate_code') or '').strip().lower() + + # [STEP] 保留运行态只读字段(pending/queued/running),不渲染人工待办。 + raw_gate_status = '' + if isinstance(blocking, dict): + raw_gate_status = str(blocking.get('status') or '').strip().lower() + elif isinstance(result.get('current_gate_status'), str): + raw_gate_status = str(result.get('current_gate_status') or '').strip().lower() + if result.get('execution_status') is None: + if raw_gate_status in {'pending', 'queued', 'running'}: + result['execution_status'] = raw_gate_status + elif str(result.get('status') or '').strip().lower() in {'pending', 'queued', 'running'}: + result['execution_status'] = str(result.get('status') or '').strip().lower() + + if not has_formal_ot: + # 建单前:技术自动则 system;有人工动作则 human。 + if result.get('technical_auto_only'): + result['owner_type'] = 'system' + elif blocking and result.get('next_action_code'): + result['owner_type'] = 'human' + elif blocking: + result['owner_type'] = 'unknown' + else: + result['owner_type'] = 'system' + return result + + # [STEP] OT 后:清除建单前阻断。 + if gate_code in _PRE_OT_BLOCKING_GATE_CODES: + result['current_blocking_gate'] = None + result['blocking_reason_code'] = None + result['blocking_message'] = None + result['explainability'] = None + result['next_action_code'] = None + result['navigation'] = None + blocking = None + gate_code = '' + + # inventory_preparation(Worker 等待)→ 技术自动,无人工卡。 + if gate_code in _SYSTEM_WAIT_INVENTORY_GATES: + result['current_blocking_gate'] = None + result['blocking_reason_code'] = None + result['blocking_message'] = None + result['explainability'] = None + result['next_action_code'] = None + result['navigation'] = None + result['technical_auto_only'] = True + result['owner_type'] = 'system' + result['available_actions'] = [] + return result + + if result.get('current_blocking_gate') is None: + # OT 已创建且无人工阻断:系统自动态。 + result['technical_auto_only'] = True + result['owner_type'] = 'system' + result['available_actions'] = [] + return result + + # 库存/履约域 + human + 有动作 → 保留人工阻断(显式集合优先;前缀仅作必要兼容)。 + next_action = str(result.get('next_action_code') or '').strip() + in_domain = gate_code in _POST_OT_INVENTORY_FULFILLMENT_GATES or ( + gate_code.startswith('inventory_') or gate_code.startswith('fulfill') + ) + if in_domain and next_action and not result.get('technical_auto_only'): + result['owner_type'] = 'human' + result['technical_auto_only'] = False + return result + + # 其余 OT 后 Gate:降级为技术自动,不展示人工待办。 + result['current_blocking_gate'] = None + result['blocking_reason_code'] = None + result['blocking_message'] = None + result['explainability'] = None + result['next_action_code'] = None + result['navigation'] = None + result['technical_auto_only'] = True + result['owner_type'] = 'system' + result['available_actions'] = [] + return result + + +def resolve_draft_line_field_values( + draft_line: dict[str, Any], + *, + schema_fields: dict[str, dict[str, Any]] | None = None, +) -> dict[str, Any]: + """ + 将草稿行投影为 field_code → 当前值,与 validate_draft / 订单明细同源。 + + 核心逻辑:优先用冻结 Schema 的 field_id 经 `_current_value`(values 人工层 → + machine_fields)取值;无 Schema 时回退顶层键。UUID field_id 不能靠 key 名猜料号。 + + Args: + draft_line: 草稿行(含 values / machine_fields)。 + schema_fields: field_id → Schema 字段定义;scope=line 才会写入。 + + Returns: + field_code → 原始值(可能为空串以外的 falsy;调用方自行 strip)。 + """ + out: dict[str, Any] = {} + # [STEP 1] 顶层便捷键(兼容扁平测试夹具) + for key in ('part_number', 'qty', 'quantity', 'reservation_id', 'mpn', 'sku'): + if draft_line.get(key) not in (None, ''): + out[key] = draft_line.get(key) + + fields = schema_fields if isinstance(schema_fields, dict) else {} + if not fields: + return out + + # [STEP 2] Schema field_code 权威解析(内部料号 = part_number) + from app.services.shipping_notice.order_review_draft_service import _current_value + + for field_id, field in fields.items(): + if not isinstance(field, dict): + continue + if str(field.get('scope') or '') != 'line': + continue + code = str(field.get('field_code') or field_id or '').strip() + if not code: + continue + value = _current_value(draft_line, str(field_id)) + if value not in (None, ''): + out[code] = value + return out + + +def schema_fields_from_case(case: ShippingOrderReviewCase | None) -> dict[str, dict[str, Any]]: + """ + 从 Case 冻结 Schema 读取 field_id → 字段定义;失败返回空 dict。 + + 核心逻辑:委托 draft_service._schema_fields;Run/快照缺失时吞掉异常,避免投影崩溃。 + """ + if case is None: + return {} + try: + from app.services.shipping_notice.order_review_draft_service import _schema_fields + + return dict(_schema_fields(case) or {}) + except Exception: + return {} + + +def extract_line_part_number( + draft_line: dict[str, Any], + proj: dict[str, Any] | None = None, + *, + schema_fields: dict[str, dict[str, Any]] | None = None, +) -> str | None: + """ + 从草稿行提取标准料号(Schema field_code=part_number,UI 常称「内部料号」); + 禁止用 reservation_id / 库存引用回填。 + + 核心逻辑:经 resolve_draft_line_field_values 读 part_number/mpn/sku; + 与预约单号相等的候选丢弃。 + + Args: + draft_line: 草稿行(可含顶层 part_number 或 values[field_id])。 + proj: 行级 eligibility 投影。 + schema_fields: 可选冻结 Schema;有则按 field_id 解析内部料号。 + + Returns: + 料号字符串或 None(前端显示「未识别」)。 + """ + proj = proj if isinstance(proj, dict) else {} + field_values = resolve_draft_line_field_values(draft_line, schema_fields=schema_fields) + reservation = str( + field_values.get('reservation_id') + or draft_line.get('reservation_id') + or proj.get('effective_reservation_id') + or proj.get('reservation_id') + or '' + ).strip() + + candidates: list[str] = [] + for code in ('part_number', 'mpn', 'sku'): + text = str(field_values.get(code) or '').strip() + if text: + candidates.append(text) + proj_part = str(proj.get('part_number') or '').strip() + if proj_part: + candidates.append(proj_part) + + # 无 Schema 时:仅当 values 的 key 本身是 part_number 等才扫(UUID 无法猜测) + if not schema_fields: + values = draft_line.get('values') if isinstance(draft_line.get('values'), dict) else {} + for key, entry in values.items(): + key_l = str(key or '').strip().lower() + if 'reservation' in key_l: + continue + if key_l in {'part_number', 'mpn', 'sku'} or key_l.endswith('part_number'): + if isinstance(entry, dict) and 'value' in entry: + text = str(entry.get('value') or '').strip() + else: + text = str(entry or '').strip() + if text: + candidates.append(text) + + for text in candidates: + if reservation and text == reservation: + # 禁止料号等于预约单号。 + continue + return text + return None + + +def extract_line_required_qty( + draft_line: dict[str, Any], + proj: dict[str, Any] | None = None, + *, + schema_fields: dict[str, dict[str, Any]] | None = None, +) -> Any: + """ + 从草稿行提取需求数量(field_code=qty/quantity),与订单明细同源。 + + Args: + draft_line: 草稿行。 + proj: 行级 eligibility 投影(可含 required_qty)。 + schema_fields: 可选冻结 Schema。 + + Returns: + 原始数量值或 None。 + """ + proj = proj if isinstance(proj, dict) else {} + field_values = resolve_draft_line_field_values(draft_line, schema_fields=schema_fields) + for key in ('qty', 'quantity'): + if field_values.get(key) not in (None, ''): + return field_values.get(key) + if proj.get('required_qty') not in (None, ''): + return proj.get('required_qty') + return None + + +def assert_part_number_not_reservation( + *, + part_number: str | None, + reservation_id: str | None, +) -> None: + """ + 回归断言:料号不得等于预约单号(测试硬失败)。 + + Raises: + AssertionError: 两字段非空且相等。 + """ + part = str(part_number or '').strip() + res = str(reservation_id or '').strip() + if part and res and part == res: + raise AssertionError('part_number must not equal reservation_id') + + +def sanitize_part_number_vs_reservation( + *, + part_number: str | None, + reservation_id: str | None, +) -> str | None: + """ + 生产投影 fail-closed:料号等于预约单号时丢弃料号,禁止串位进入用户 DTO。 + + Args: + part_number: 候选料号。 + reservation_id: 预约单号。 + + Returns: + 安全料号;串位时返回 None。 + """ + part = str(part_number or '').strip() or None + res = str(reservation_id or '').strip() or None + if part and res and part == res: + return None + return part diff --git a/backend/app/services/shipping_notice/order_schema/field_rules.py b/backend/app/services/shipping_notice/order_schema/field_rules.py index 3c035188..d41e7af2 100644 --- a/backend/app/services/shipping_notice/order_schema/field_rules.py +++ b/backend/app/services/shipping_notice/order_schema/field_rules.py @@ -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', diff --git a/backend/app/services/shipping_notice/order_stp_auto_create_service.py b/backend/app/services/shipping_notice/order_stp_auto_create_service.py index 46b64ffe..cdd9907d 100644 --- a/backend/app/services/shipping_notice/order_stp_auto_create_service.py +++ b/backend/app/services/shipping_notice/order_stp_auto_create_service.py @@ -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 { diff --git a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py new file mode 100644 index 00000000..6e9e4202 --- /dev/null +++ b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py @@ -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] diff --git a/backend/app/services/shipping_notice/post_ot_wave_progress_service.py b/backend/app/services/shipping_notice/post_ot_wave_progress_service.py new file mode 100644 index 00000000..122d6ae3 --- /dev/null +++ b/backend/app/services/shipping_notice/post_ot_wave_progress_service.py @@ -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() diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 4c686ee5..6d058ea5 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -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') diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 047b0c27..0f658943 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -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') diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index d9e9c7b2..9b40c956 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -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: diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index eb4535f7..985db8c6 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -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) diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index c3f78f59..dcbf9d1e 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -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 diff --git a/backend/app/services/shipping_notice/stp_line_inventory_match.py b/backend/app/services/shipping_notice/stp_line_inventory_match.py index db3d93af..0c3a52c1 100644 --- a/backend/app/services/shipping_notice/stp_line_inventory_match.py +++ b/backend/app/services/shipping_notice/stp_line_inventory_match.py @@ -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'), diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 2737c248..33b99f77 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -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]: diff --git a/backend/migrations/versions/cr2b3c4d5e6f_add_shipping_notice_line_inventory_matches.py b/backend/migrations/versions/cr2b3c4d5e6f_add_shipping_notice_line_inventory_matches.py new file mode 100644 index 00000000..af4119f3 --- /dev/null +++ b/backend/migrations/versions/cr2b3c4d5e6f_add_shipping_notice_line_inventory_matches.py @@ -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') diff --git a/backend/migrations/versions/cs3c4d5e6f7a_add_shipping_review_wave_idempotency.py b/backend/migrations/versions/cs3c4d5e6f7a_add_shipping_review_wave_idempotency.py new file mode 100644 index 00000000..410747bb --- /dev/null +++ b/backend/migrations/versions/cs3c4d5e6f7a_add_shipping_review_wave_idempotency.py @@ -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') diff --git a/backend/migrations/versions/ct4d5e6f7a8b_post_ot_auto_fulfill_p1.py b/backend/migrations/versions/ct4d5e6f7a8b_post_ot_auto_fulfill_p1.py new file mode 100644 index 00000000..8099832d --- /dev/null +++ b/backend/migrations/versions/ct4d5e6f7a8b_post_ot_auto_fulfill_p1.py @@ -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') diff --git a/backend/tests/test_line_inventory_allowed_actions.py b/backend/tests/test_line_inventory_allowed_actions.py new file mode 100644 index 00000000..a8cdc511 --- /dev/null +++ b/backend/tests/test_line_inventory_allowed_actions.py @@ -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' diff --git a/backend/tests/test_line_inventory_match_persistence.py b/backend/tests/test_line_inventory_match_persistence.py new file mode 100644 index 00000000..b1fbb997 --- /dev/null +++ b/backend/tests/test_line_inventory_match_persistence.py @@ -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') diff --git a/backend/tests/test_line_inventory_match_projection.py b/backend/tests/test_line_inventory_match_projection.py new file mode 100644 index 00000000..529b84d1 --- /dev/null +++ b/backend/tests/test_line_inventory_match_projection.py @@ -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' diff --git a/backend/tests/test_post_ot_auto_fulfill_p1.py b/backend/tests/test_post_ot_auto_fulfill_p1.py new file mode 100644 index 00000000..9e07015d --- /dev/null +++ b/backend/tests/test_post_ot_auto_fulfill_p1.py @@ -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 diff --git a/backend/tests/test_post_ot_fulfillment_wave_p0.py b/backend/tests/test_post_ot_fulfillment_wave_p0.py new file mode 100644 index 00000000..36578fe0 --- /dev/null +++ b/backend/tests/test_post_ot_fulfillment_wave_p0.py @@ -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 diff --git a/backend/tests/test_shipping_document_layout_diagnostics.py b/backend/tests/test_shipping_document_layout_diagnostics.py new file mode 100644 index 00000000..a066384d --- /dev/null +++ b/backend/tests/test_shipping_document_layout_diagnostics.py @@ -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'] diff --git a/backend/tests/test_shipping_document_layout_job.py b/backend/tests/test_shipping_document_layout_job.py index 12f0e912..9af3bd4d 100644 --- a/backend/tests/test_shipping_document_layout_job.py +++ b/backend/tests/test_shipping_document_layout_job.py @@ -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): diff --git a/backend/tests/test_shipping_document_layout_native_pdf.py b/backend/tests/test_shipping_document_layout_native_pdf.py index 4f92ee19..822a018d 100644 --- a/backend/tests/test_shipping_document_layout_native_pdf.py +++ b/backend/tests/test_shipping_document_layout_native_pdf.py @@ -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( diff --git a/backend/tests/test_shipping_document_layout_ocr_pdf.py b/backend/tests/test_shipping_document_layout_ocr_pdf.py index 2fe06f91..53dfc25b 100644 --- a/backend/tests/test_shipping_document_layout_ocr_pdf.py +++ b/backend/tests/test_shipping_document_layout_ocr_pdf.py @@ -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('
| A |
| A | B |
|---|---|
| C | D |
+ {{ stageLabel }} +
++ {{ t('chat.shippingOrderReview.currentProcessing.taskMissingHint') }} +
+ + + + +{{ t('chat.shippingOrderReview.fieldCompleteness.subtitle') }}
+- {{ t('chat.shippingOrderReview.fulfillmentDecision.railHint') }} -
-+ {{ reasonLabel }} +
++ {{ t('chat.shippingOrderReview.inventoryFallback.affectedLines', { + count: fallback?.affected_line_count || 0, + }) }} +
+ ++ {{ t('chat.shippingOrderReview.lineFulfillmentAggregate.hint') }} +
++ {{ t('chat.shippingOrderReview.lineFulfillmentDetail.title') }} +
+- {{ item.reason_codes.join(', ') }} -
- - - -- {{ t('chat.shippingOrderReview.profileMatch.reselectHint') }} -
+{{ t('chat.shippingProcessing.progress.stageNodesUnavailable') }}
- +{{ t('chat.shippingProcessing.progress.completedOfTotal', { @@ -196,25 +266,5 @@ function nodeShortLabel(stage: string): string { }) }}
-- {{ t('chat.shippingProcessing.progress.currentNeedLabel') }} - {{ currentNeed }} -
- -