feat(shipping-notice): 收敛复核阶段同源投影与 OT 后履约推进
统一 Case/Progress 阶段 label_key、修复 Job 成功未推进 OT 的可重试失败投影与写路径,并落地 OT 后行级匹配/波次履约与版面诊断开关。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
74270adc22
commit
fd6a23f870
100 files changed
+12138
-1017
No files matched your search
@@ -134,6 +134,9 @@ def _register_builtin_platform_jobs() -> None:
|
||||
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
|
||||
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
|
||||
run_shipping_post_ot_auto_fulfill_compensation_schedule,
|
||||
)
|
||||
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-order-extraction-progress-cleanup",
|
||||
@@ -144,6 +147,19 @@ def _register_builtin_platform_jobs() -> None:
|
||||
params_schema=({"key": "limit", "type": "number", "label": "单批上限", "required": False, "default": 1000},),
|
||||
defaults={"limit": 1000},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-post-ot-auto-fulfill-compensation",
|
||||
label="OT 后行级自动履约补偿",
|
||||
handler=run_shipping_post_ot_auto_fulfill_compensation_schedule,
|
||||
description=(
|
||||
"每 15 分钟扫描正式 OT 上尚未入波次且匹配 ready 的行,"
|
||||
"复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。"
|
||||
"SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false 时空跑。"
|
||||
),
|
||||
category="shipping",
|
||||
params_schema=({"key": "limit", "type": "number", "label": "单批 Case 上限", "required": False, "default": 50},),
|
||||
defaults={"limit": 50},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-audit-retention",
|
||||
label="货代审计到期清理与哈希校验",
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""
|
||||
services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py
|
||||
|
||||
用途:OT 后行级自动履约补偿轮询(每 15 分钟)——补齐 matching/ot_created 事件丢失。
|
||||
依赖:line_auto_fulfill_coordinator、ShippingOrderReviewCase、list_eligible_post_ot_line_keys。
|
||||
逻辑:platform_api_path=shipping-post-ot-auto-fulfill-compensation;flag 关闭时 no-op;
|
||||
仅扫描有正式 OT 且存在 eligible 行的 Case,复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingOrderReviewCase
|
||||
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
|
||||
coordinate_post_ot_auto_fulfill,
|
||||
enqueue_post_ot_auto_fulfill_job,
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
|
||||
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
|
||||
list_eligible_post_ot_line_keys,
|
||||
)
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
|
||||
def run_post_ot_auto_fulfill_compensation(*, limit: int = 50) -> dict[str, Any]:
|
||||
"""
|
||||
扫描可补偿的正式 OT Case 并入队/协调自动履约。
|
||||
|
||||
Args:
|
||||
limit: 单批最多处理的 Case 数。
|
||||
|
||||
Returns:
|
||||
scanned / enqueued / coordinated / skipped / details。
|
||||
"""
|
||||
if not line_auto_fulfill_enabled():
|
||||
return {
|
||||
'scanned': 0,
|
||||
'enqueued': 0,
|
||||
'coordinated': 0,
|
||||
'skipped': 0,
|
||||
'reason': 'line_auto_fulfill_disabled',
|
||||
'details': [],
|
||||
}
|
||||
|
||||
safe_limit = min(200, max(1, int(limit or 50)))
|
||||
cases = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter(ShippingOrderReviewCase.confirmed_task_id.isnot(None))
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.limit(safe_limit * 3)
|
||||
.all()
|
||||
)
|
||||
|
||||
scanned = 0
|
||||
enqueued = 0
|
||||
coordinated = 0
|
||||
skipped = 0
|
||||
details: list[dict[str, Any]] = []
|
||||
|
||||
for case in cases:
|
||||
if scanned >= safe_limit:
|
||||
break
|
||||
scanned += 1
|
||||
eligible = list_eligible_post_ot_line_keys(case)
|
||||
if not eligible:
|
||||
skipped += 1
|
||||
continue
|
||||
task_no = str(getattr(case, 'confirmed_task_no', None) or '').strip()
|
||||
if not task_no and case.confirmed_task_id is not None:
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
task = db.session.get(ShippingNotice, int(case.confirmed_task_id))
|
||||
task_no = str(getattr(task, 'task_no', '') or '').strip() if task else ''
|
||||
if not task_no:
|
||||
skipped += 1
|
||||
details.append({'case_no': case.case_no, 'status': 'skipped', 'reason': 'missing_task_no'})
|
||||
continue
|
||||
|
||||
job_id = enqueue_post_ot_auto_fulfill_job(
|
||||
task_no=task_no,
|
||||
trigger='compensation',
|
||||
commit=True,
|
||||
)
|
||||
if job_id is not None:
|
||||
enqueued += 1
|
||||
details.append({
|
||||
'case_no': case.case_no,
|
||||
'task_no': task_no,
|
||||
'status': 'enqueued',
|
||||
'job_id': int(job_id),
|
||||
'eligible_count': len(eligible),
|
||||
})
|
||||
continue
|
||||
|
||||
# 入队失败时同步协调一次(仍受幂等键保护)
|
||||
result = coordinate_post_ot_auto_fulfill(case=case, trigger='compensation')
|
||||
coordinated += 1
|
||||
details.append({
|
||||
'case_no': case.case_no,
|
||||
'task_no': task_no,
|
||||
'status': str(result.get('status') or 'coordinated'),
|
||||
'eligible_count': len(eligible),
|
||||
})
|
||||
|
||||
return {
|
||||
'scanned': scanned,
|
||||
'enqueued': enqueued,
|
||||
'coordinated': coordinated,
|
||||
'skipped': skipped,
|
||||
'details': details[:50],
|
||||
}
|
||||
|
||||
|
||||
def run_shipping_post_ot_auto_fulfill_compensation_schedule(
|
||||
task: ScheduleTask,
|
||||
run: ScheduleRun,
|
||||
) -> ScheduleExecuteResult:
|
||||
"""
|
||||
平台排程入口:每 15 分钟补偿扫描。
|
||||
|
||||
Returns:
|
||||
ScheduleExecuteResult 七元组。
|
||||
"""
|
||||
_ = run
|
||||
params = getattr(task, 'job_params', None) or {}
|
||||
result = run_post_ot_auto_fulfill_compensation(limit=int(params.get('limit') or 50))
|
||||
enqueued = int(result.get('enqueued') or 0)
|
||||
coordinated = int(result.get('coordinated') or 0)
|
||||
skipped = int(result.get('skipped') or 0)
|
||||
scanned = int(result.get('scanned') or 0)
|
||||
success = enqueued + coordinated
|
||||
details = list(result.get('details') or [])
|
||||
warnings: list[str] = []
|
||||
if result.get('reason') == 'line_auto_fulfill_disabled':
|
||||
warnings.append('line_auto_fulfill_disabled')
|
||||
return success, 0, skipped, scanned, details, warnings, []
|
||||
@@ -53,6 +53,7 @@ from app.services.shipping_notice.document_layout.text_cell_alignment import (
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
NativePdfPage,
|
||||
attach_native_pdf_page_images,
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
extract_native_pdf_pages,
|
||||
@@ -64,6 +65,8 @@ from app.services.shipping_notice.document_layout.ocr_pdf import (
|
||||
OcrTableEvidence,
|
||||
build_ocr_table_evidence,
|
||||
extract_ocr_lines,
|
||||
extract_table_crop_ocr_lines,
|
||||
get_page_ocr_lines,
|
||||
page_bbox_to_normalized,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.schema_mapping import (
|
||||
@@ -98,6 +101,7 @@ __all__ = [
|
||||
'NativePdfPage',
|
||||
'build_native_pdf_layout_candidate',
|
||||
'build_native_pdf_text_table_fallbacks',
|
||||
'attach_native_pdf_page_images',
|
||||
'extract_native_pdf_pages',
|
||||
'build_html_layout_candidate',
|
||||
'OcrCellEvidence',
|
||||
@@ -105,6 +109,8 @@ __all__ = [
|
||||
'OcrTableEvidence',
|
||||
'build_ocr_table_evidence',
|
||||
'extract_ocr_lines',
|
||||
'extract_table_crop_ocr_lines',
|
||||
'get_page_ocr_lines',
|
||||
'page_bbox_to_normalized',
|
||||
'layout_table_to_grid',
|
||||
'map_layout_document_to_schema',
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/layout_diagnostics.py
|
||||
|
||||
用途:Layout Job 脱敏阶段计时与计数契约(PR-0~PR-3);仅写入 Job result / worker 日志。
|
||||
依赖:time.perf_counter;可选读取 ocr_pdf._ocr_engine 的 lru_cache 状态。
|
||||
逻辑:由 shipping_document_layout handler 初始化;runtime / native_pdf / ocr_pdf / opencv_table 累加;
|
||||
PR-1 持有页面 OCR 缓存;PR-2 持有 OpenCV geometry 缓存;PR-3 持有表格裁剪 OCR 缓存;
|
||||
均不进 snapshot、不跨 Job;禁止把 timings/counts 写入 layout snapshot。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from time import perf_counter
|
||||
from typing import Any
|
||||
|
||||
|
||||
LAYOUT_DIAGNOSTIC_TIMING_KEYS: tuple[str, ...] = (
|
||||
'queue_wait_ms',
|
||||
'asset_read_ms',
|
||||
'xfa_analysis_ms',
|
||||
'mineru_wait_ms',
|
||||
'mineru_result_parse_ms',
|
||||
'native_pdf_extract_ms',
|
||||
'native_layout_build_ms',
|
||||
'native_text_alignment_ms',
|
||||
'opencv_geometry_ms',
|
||||
'opencv_validation_ms',
|
||||
'ocr_engine_init_ms',
|
||||
'ocr_inference_ms',
|
||||
'layout_assembly_ms',
|
||||
'layout_serialize_ms',
|
||||
'coordinate_evidence_ms',
|
||||
'snapshot_build_ms',
|
||||
'total_handler_ms',
|
||||
)
|
||||
|
||||
LAYOUT_DIAGNOSTIC_COUNT_KEYS: tuple[str, ...] = (
|
||||
'page_count',
|
||||
'mineru_table_count',
|
||||
'resolved_table_count',
|
||||
'partial_alignment_table_count',
|
||||
'opencv_attempt_count',
|
||||
'opencv_geometry_cache_hit',
|
||||
'opencv_geometry_cache_miss',
|
||||
'ocr_attempt_count',
|
||||
'ocr_call_count',
|
||||
'ocr_page_count',
|
||||
'ocr_table_count',
|
||||
'ocr_page_cache_hit',
|
||||
'ocr_page_cache_miss',
|
||||
'ocr_crop_count',
|
||||
'pdfium_page_image_attach_count',
|
||||
'native_token_count',
|
||||
'layout_cell_count',
|
||||
'ocr_engine_warm',
|
||||
)
|
||||
|
||||
# 页面 OCR 缓存失败哨兵:与空行列表区分,表示引擎不可用。
|
||||
OCR_PAGE_CACHE_UNAVAILABLE = object()
|
||||
OCR_TABLE_CROP_CACHE_UNAVAILABLE = object()
|
||||
|
||||
|
||||
def empty_layout_timings() -> dict[str, int]:
|
||||
"""
|
||||
构造 PR-0 全量 timing 键,未执行阶段统一为 0。
|
||||
|
||||
Returns:
|
||||
可就地累加的 timing 字典。
|
||||
"""
|
||||
return {key: 0 for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS}
|
||||
|
||||
|
||||
def empty_layout_counts() -> dict[str, Any]:
|
||||
"""
|
||||
构造 PR-0 全量 count 键;数值计数为 0,`ocr_engine_warm` 默认为 False。
|
||||
|
||||
Returns:
|
||||
可就地累加的 counts 字典。
|
||||
"""
|
||||
counts: dict[str, Any] = {
|
||||
key: 0 for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS if key != 'ocr_engine_warm'
|
||||
}
|
||||
counts['ocr_engine_warm'] = False
|
||||
return counts
|
||||
|
||||
|
||||
def ensure_layout_timings(timings: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
补齐缺失 timing 键为 0,不删除调用方已写入的额外键(如 native_table_detect_ms)。
|
||||
|
||||
Args:
|
||||
timings: 既有 timing 字典;None 时返回新建空字典。
|
||||
|
||||
Returns:
|
||||
保证含全部 PR-0 timing 键的字典。
|
||||
"""
|
||||
target = timings if timings is not None else {}
|
||||
for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS:
|
||||
if key not in target:
|
||||
target[key] = 0
|
||||
return target
|
||||
|
||||
|
||||
def ensure_layout_counts(counts: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
补齐缺失 count 键;`ocr_engine_warm` 缺失时为 False。
|
||||
|
||||
Args:
|
||||
counts: 既有 counts 字典;None 时返回新建空字典。
|
||||
|
||||
Returns:
|
||||
保证含全部 PR-0 count 键的字典。
|
||||
"""
|
||||
target = counts if counts is not None else {}
|
||||
for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS:
|
||||
if key not in target:
|
||||
target[key] = False if key == 'ocr_engine_warm' else 0
|
||||
return target
|
||||
|
||||
|
||||
def ocr_engine_is_warm() -> bool:
|
||||
"""
|
||||
判断当前 Worker 进程是否已持有 RapidOCR 引擎实例。
|
||||
|
||||
核心逻辑:读取 `_ocr_engine` 的 lru_cache;无真实 cache_info(测试 mock)时视为未 warm,
|
||||
避免把 mock 调用计入初始化。
|
||||
|
||||
Returns:
|
||||
True 表示进程内已有引擎;False 表示尚未初始化或无法判定。
|
||||
"""
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import _ocr_engine
|
||||
|
||||
cache_info = getattr(_ocr_engine, 'cache_info', None)
|
||||
if not callable(cache_info):
|
||||
return False
|
||||
currsize = getattr(cache_info(), 'currsize', None)
|
||||
return isinstance(currsize, int) and currsize > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def freeze_layout_diagnostics(
|
||||
timings: dict[str, Any] | None,
|
||||
counts: dict[str, Any] | None,
|
||||
) -> tuple[dict[str, int], dict[str, Any]]:
|
||||
"""
|
||||
在 finish_job 前规范化 result 载荷:timing 全为 int,counts 数值为 int,warm 为 bool。
|
||||
|
||||
Args:
|
||||
timings/counts: Job 内累加后的诊断字典。
|
||||
|
||||
Returns:
|
||||
(timings, counts) 可直接写入 Job result 的副本。
|
||||
"""
|
||||
raw_timings = ensure_layout_timings(dict(timings or {}))
|
||||
raw_counts = ensure_layout_counts(dict(counts or {}))
|
||||
frozen_timings = {key: int(raw_timings.get(key) or 0) for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS}
|
||||
# 保留已有额外 timing(如 native_table_detect_ms),但不强制进契约列表。
|
||||
for key, value in raw_timings.items():
|
||||
if key not in frozen_timings:
|
||||
try:
|
||||
frozen_timings[key] = int(value or 0)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
frozen_counts: dict[str, Any] = {}
|
||||
for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS:
|
||||
if key == 'ocr_engine_warm':
|
||||
frozen_counts[key] = bool(raw_counts.get(key))
|
||||
else:
|
||||
frozen_counts[key] = int(raw_counts.get(key) or 0)
|
||||
return frozen_timings, frozen_counts
|
||||
|
||||
|
||||
@dataclass
|
||||
class LayoutJobDiagnostics:
|
||||
"""
|
||||
单次 Layout Job 内存诊断上下文;生命周期仅限当前 Job。
|
||||
|
||||
Attributes:
|
||||
timings: 阶段耗时(毫秒),允许嵌套墙钟,不可简单求和。
|
||||
counts: 计数与 ocr_engine_warm 标志。
|
||||
ocr_pages: 已执行 RapidOCR 的去重页号,用于 ocr_page_count。
|
||||
ocr_page_cache: PR-1 整页 OCR 结果;键为 (page_no, image_width, image_height)。
|
||||
ocr_table_crop_cache: PR-3 表格裁剪 OCR 结果;键含页号、圆整 bbox 与图尺寸。
|
||||
opencv_geometry_cache: PR-2 同表同图 geometry 结果缓存。
|
||||
"""
|
||||
|
||||
timings: dict[str, Any] = field(default_factory=empty_layout_timings)
|
||||
counts: dict[str, Any] = field(default_factory=empty_layout_counts)
|
||||
ocr_pages: set[int] = field(default_factory=set)
|
||||
ocr_page_cache: dict[tuple[int, int, int], Any] = field(default_factory=dict)
|
||||
ocr_table_crop_cache: dict[tuple[Any, ...], Any] = field(default_factory=dict)
|
||||
opencv_geometry_cache: dict[tuple[Any, ...], Any] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""确保 timings/counts 含全量契约键。"""
|
||||
ensure_layout_timings(self.timings)
|
||||
ensure_layout_counts(self.counts)
|
||||
|
||||
@staticmethod
|
||||
def page_ocr_cache_key(page_no: int, image: Any) -> tuple[int, int, int]:
|
||||
"""
|
||||
构造 Job 内页面 OCR 缓存键。
|
||||
|
||||
Args:
|
||||
page_no: PDF 页号。
|
||||
image: 渲染页图;用像素宽高区分不同 render_scale。
|
||||
|
||||
Returns:
|
||||
(page_no, image_width, image_height)。
|
||||
"""
|
||||
height, width = image.shape[:2]
|
||||
return (int(page_no), int(width), int(height))
|
||||
|
||||
def add_ms(self, key: str, started: float) -> None:
|
||||
"""
|
||||
将 started 至今的墙钟毫秒累加到指定 timing 键。
|
||||
|
||||
Args:
|
||||
key: LAYOUT_DIAGNOSTIC_TIMING_KEYS 中的键或额外诊断键。
|
||||
started: perf_counter() 起点。
|
||||
"""
|
||||
elapsed = round((perf_counter() - started) * 1000)
|
||||
self.timings[key] = int(self.timings.get(key) or 0) + max(elapsed, 0)
|
||||
|
||||
def set_ms(self, key: str, started: float) -> None:
|
||||
"""
|
||||
用 started 至今的墙钟毫秒覆盖写入(用于包围计时,如 native_layout_build_ms)。
|
||||
|
||||
Args:
|
||||
key: timing 键。
|
||||
started: perf_counter() 起点。
|
||||
"""
|
||||
self.timings[key] = max(round((perf_counter() - started) * 1000), 0)
|
||||
|
||||
def incr(self, key: str, amount: int = 1) -> None:
|
||||
"""
|
||||
累加数值型 count。
|
||||
|
||||
Args:
|
||||
key: count 键(不得用于 ocr_engine_warm)。
|
||||
amount: 增量,默认 1。
|
||||
"""
|
||||
if key == 'ocr_engine_warm':
|
||||
return
|
||||
self.counts[key] = int(self.counts.get(key) or 0) + int(amount)
|
||||
|
||||
def record_ocr_call(self, *, page_no: int | None = None) -> None:
|
||||
"""
|
||||
记录一次实际 RapidOCR 推理,并按页去重更新 ocr_page_count。
|
||||
|
||||
Args:
|
||||
page_no: 页面号;缺失时只增加 ocr_call_count。
|
||||
"""
|
||||
self.incr('ocr_call_count')
|
||||
if page_no is None:
|
||||
return
|
||||
page = int(page_no)
|
||||
if page in self.ocr_pages:
|
||||
return
|
||||
self.ocr_pages.add(page)
|
||||
self.counts['ocr_page_count'] = len(self.ocr_pages)
|
||||
|
||||
def record_layout_document_stats(self, layout: Any) -> None:
|
||||
"""
|
||||
从最终 LayoutDocument 回填 resolved/partial/token/cell 计数。
|
||||
|
||||
Args:
|
||||
layout: contracts.LayoutDocument 或兼容对象。
|
||||
"""
|
||||
pages = list(getattr(layout, 'pages', None) or [])
|
||||
if not self.counts.get('page_count'):
|
||||
self.counts['page_count'] = len(pages)
|
||||
resolved = 0
|
||||
native_tokens = 0
|
||||
cells = 0
|
||||
for page in pages:
|
||||
for table in list(getattr(page, 'tables', None) or []):
|
||||
table_cells = [
|
||||
cell
|
||||
for row in list(getattr(table, 'rows', None) or [])
|
||||
for cell in list(getattr(row, 'cells', None) or [])
|
||||
]
|
||||
if table_cells:
|
||||
resolved += 1
|
||||
cells += len(table_cells)
|
||||
for token in list(getattr(page, 'tokens', None) or []):
|
||||
if str(getattr(token, 'source', '') or '') == 'native_text':
|
||||
native_tokens += 1
|
||||
# partial_alignment 由 native_pdf 在方法 issue 处累加;此处只回填终态统计。
|
||||
self.counts['resolved_table_count'] = resolved
|
||||
self.counts['native_token_count'] = native_tokens
|
||||
self.counts['layout_cell_count'] = cells
|
||||
@@ -2,15 +2,18 @@
|
||||
backend/app/services/shipping_notice/document_layout/native_pdf.py
|
||||
|
||||
用途:用项目既有 PDFium 提取原生 PDF 字符坐标、页面渲染,并组装保守的 layout.v1 表格候选。
|
||||
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐和布局契约。
|
||||
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐、布局契约、layout_diagnostics。
|
||||
逻辑:MinerU 提供整表与 HTML;PDFium 提供独立字符/图像证据;阶段 1 优先唯一 glyph
|
||||
对齐写入真实 cell bbox/token;部分唯一匹配可落盘;整体 layout 仍可 needs_review。
|
||||
PR-0 可选累加 Job 级脱敏计时/计数,不改变候选算法。
|
||||
PR-2:`attach_native_pdf_page_images` 在复用开关开启时仅补齐缺图页,禁止二次字符枚举。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from html import escape
|
||||
from time import perf_counter
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
@@ -31,9 +34,10 @@ from app.services.shipping_notice.document_layout.contracts import (
|
||||
stable_layout_id,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.layout_diagnostics import LayoutJobDiagnostics
|
||||
from app.services.shipping_notice.document_layout.mineru import MinerUParseCandidate
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
reconstruct_opencv_table_geometry,
|
||||
cached_reconstruct_opencv_table_geometry,
|
||||
validate_opencv_cell_text,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import build_ocr_table_evidence
|
||||
@@ -142,6 +146,72 @@ def extract_native_pdf_pages(
|
||||
return pages
|
||||
|
||||
|
||||
def layout_native_page_reuse_enabled() -> bool:
|
||||
"""
|
||||
读取 PR-2 PDFium 页面字符复用 / 按需补图开关。
|
||||
|
||||
Returns:
|
||||
True 时复用前置轻量预读字符并仅补齐页面图,避免二次枚举字符层。
|
||||
"""
|
||||
try:
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
if not has_app_context():
|
||||
return False
|
||||
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED', False))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def attach_native_pdf_page_images(
|
||||
content: bytes,
|
||||
pages: list[NativePdfPage],
|
||||
*,
|
||||
render_scale: float = 2.0,
|
||||
) -> list[NativePdfPage]:
|
||||
"""
|
||||
在已有字符页列表上按需补齐渲染图,不重复枚举 PDF 字符层。
|
||||
|
||||
核心逻辑:仅打开 PDFium 渲染缺图页面;已有 image 的页原样保留;Job 结束后由调用方释放。
|
||||
|
||||
Args:
|
||||
content: 原始 PDF 字节。
|
||||
pages: 前置 `render_images=False` 提取的页面。
|
||||
render_scale: 渲染倍率,须与增强链一致。
|
||||
|
||||
Returns:
|
||||
与输入同序的页面列表;缺图页替换为带 image 的新 NativePdfPage。
|
||||
|
||||
Raises:
|
||||
ValueError: 内容为空、倍率非法或页号越界。
|
||||
"""
|
||||
if not content or render_scale <= 0:
|
||||
raise ValueError('native PDF content and positive render scale are required')
|
||||
if not pages:
|
||||
return []
|
||||
if all(page.image is not None for page in pages):
|
||||
return list(pages)
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
attached: list[NativePdfPage] = []
|
||||
for page in pages:
|
||||
if page.image is not None:
|
||||
attached.append(page)
|
||||
continue
|
||||
index = int(page.page_no) - 1
|
||||
if index < 0 or index >= len(pdf):
|
||||
raise ValueError('native PDF page_no is out of range for image attach')
|
||||
image = np.asarray(pdf[index].render(scale=render_scale).to_numpy()).copy()
|
||||
attached.append(NativePdfPage(
|
||||
page_no=page.page_no,
|
||||
width=page.width,
|
||||
height=page.height,
|
||||
rotation=page.rotation,
|
||||
characters=page.characters,
|
||||
image=image,
|
||||
))
|
||||
return attached
|
||||
|
||||
|
||||
def build_native_pdf_text_table_fallbacks(
|
||||
content: bytes,
|
||||
*,
|
||||
@@ -326,6 +396,7 @@ def build_native_pdf_layout_candidate(
|
||||
content: bytes,
|
||||
mineru: MinerUParseCandidate,
|
||||
native_pages: list[NativePdfPage] | None = None,
|
||||
diagnostics: LayoutJobDiagnostics | None = None,
|
||||
) -> LayoutDocument:
|
||||
"""
|
||||
组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。
|
||||
@@ -336,10 +407,16 @@ def build_native_pdf_layout_candidate(
|
||||
content: 原始 PDF 字节。
|
||||
mineru: 同一文件的 MinerU pipeline 候选。
|
||||
native_pages: 可复用的 PDFium 页面;未传入时由本函数提取。
|
||||
diagnostics: 可选 Job 级诊断上下文;None 时不做计时/计数。
|
||||
Returns:
|
||||
通过完整布局契约校验的候选;没有可证 cell 时保留空表和 blocking issue。
|
||||
"""
|
||||
resolved_pages = native_pages if native_pages is not None else extract_native_pdf_pages(content)
|
||||
if diagnostics is not None:
|
||||
diagnostics.counts['page_count'] = len(resolved_pages)
|
||||
diagnostics.counts['mineru_table_count'] = sum(
|
||||
len(page.tables) for page in mineru.pages
|
||||
)
|
||||
mineru_pages = {item.page_no: item for item in mineru.pages}
|
||||
issues: list[LayoutIssue] = [LayoutIssue(
|
||||
code='document_cell_truth_deferred', severity='blocking',
|
||||
@@ -353,7 +430,10 @@ def build_native_pdf_layout_candidate(
|
||||
try:
|
||||
grid = parse_html_grid(table_candidate.html, table_id=table_candidate.candidate_id)
|
||||
cells, method_issues = _candidate_cells(
|
||||
native=native, grid=grid, table_bbox=table_candidate.bbox,
|
||||
native=native,
|
||||
grid=grid,
|
||||
table_bbox=table_candidate.bbox,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
except Exception:
|
||||
issues.append(LayoutIssue(
|
||||
@@ -361,6 +441,8 @@ def build_native_pdf_layout_candidate(
|
||||
table_id=table_candidate.candidate_id,
|
||||
))
|
||||
continue
|
||||
if diagnostics is not None and 'native_pdf_cells_from_partial_unique_text' in method_issues:
|
||||
diagnostics.incr('partial_alignment_table_count')
|
||||
for code in method_issues:
|
||||
issues.append(LayoutIssue(
|
||||
code=code, severity='blocking', page_no=native.page_no,
|
||||
@@ -369,6 +451,7 @@ def build_native_pdf_layout_candidate(
|
||||
if not cells:
|
||||
continue
|
||||
try:
|
||||
assembly_started = perf_counter()
|
||||
layout_table = _layout_table(
|
||||
native=native,
|
||||
grid=grid,
|
||||
@@ -378,6 +461,8 @@ def build_native_pdf_layout_candidate(
|
||||
cells=cells,
|
||||
page_tokens=page_tokens,
|
||||
)
|
||||
if diagnostics is not None:
|
||||
diagnostics.add_ms('layout_assembly_ms', assembly_started)
|
||||
except Exception:
|
||||
issues.append(LayoutIssue(
|
||||
code='native_pdf_layout_table_invalid', severity='blocking',
|
||||
@@ -389,15 +474,19 @@ def build_native_pdf_layout_candidate(
|
||||
issues.append(LayoutIssue(
|
||||
code='native_pdf_table_cells_unresolved', severity='blocking', page_no=native.page_no,
|
||||
))
|
||||
assembly_started = perf_counter()
|
||||
pages.append(LayoutPage(
|
||||
page_no=native.page_no, width=native.width, height=native.height,
|
||||
rotation=native.rotation,
|
||||
tokens=[page_tokens[token_id] for token_id in sorted(page_tokens)],
|
||||
tables=tables,
|
||||
))
|
||||
if diagnostics is not None:
|
||||
diagnostics.add_ms('layout_assembly_ms', assembly_started)
|
||||
if not any(page.tables for page in pages):
|
||||
issues.append(LayoutIssue(code='native_pdf_no_resolved_tables', severity='blocking'))
|
||||
return LayoutDocument(
|
||||
assembly_started = perf_counter()
|
||||
layout = LayoutDocument(
|
||||
document_id=document_id,
|
||||
content_hash=content_hash,
|
||||
parser=LayoutParserInfo(
|
||||
@@ -407,6 +496,10 @@ def build_native_pdf_layout_candidate(
|
||||
pages=pages,
|
||||
quality=LayoutQuality(status='needs_review', confidence=0, issues=issues),
|
||||
)
|
||||
if diagnostics is not None:
|
||||
diagnostics.add_ms('layout_assembly_ms', assembly_started)
|
||||
diagnostics.record_layout_document_stats(layout)
|
||||
return layout
|
||||
|
||||
|
||||
def _cells_from_text_alignment(
|
||||
@@ -430,17 +523,29 @@ def _cells_from_text_alignment(
|
||||
|
||||
|
||||
def _candidate_cells(
|
||||
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox,
|
||||
*,
|
||||
native: NativePdfPage,
|
||||
grid: HtmlGrid,
|
||||
table_bbox: LayoutBBox,
|
||||
diagnostics: LayoutJobDiagnostics | None = None,
|
||||
) -> tuple[dict[str, dict[str, Any]], list[str]]:
|
||||
"""
|
||||
优先唯一文本对齐;完整失败时有框表才走 OpenCV;快速路径允许部分唯一匹配落盘。
|
||||
|
||||
核心逻辑:禁止在多候选重复文本上猜第 N 个;OpenCV 全表失败时回退已对齐的部分 native cell。
|
||||
PR-0:在既有分支累加 alignment/OpenCV/OCR 诊断,不改变返回的 cells 与 issues。
|
||||
|
||||
Args:
|
||||
native/grid/table_bbox: 既有表格候选输入。
|
||||
diagnostics: 可选 Job 级诊断上下文。
|
||||
"""
|
||||
alignment_started = perf_counter()
|
||||
alignment = align_html_cells_from_positioned_text(
|
||||
grid, characters=native.characters, table_bbox=table_bbox,
|
||||
page_width=native.width, page_height=native.height,
|
||||
)
|
||||
if diagnostics is not None:
|
||||
diagnostics.add_ms('native_text_alignment_ms', alignment_started)
|
||||
text_cells = _cells_from_text_alignment(native=native, alignment=alignment)
|
||||
if alignment.complete and text_cells:
|
||||
return text_cells, ['native_pdf_cells_from_unique_text_candidate']
|
||||
@@ -451,20 +556,30 @@ def _candidate_cells(
|
||||
list(alignment.issues) + ['native_pdf_cells_from_partial_unique_text'],
|
||||
))
|
||||
return {}, sorted(set(alignment.issues + ['native_pdf_render_deferred']))
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
geometry_started = perf_counter()
|
||||
geometry = cached_reconstruct_opencv_table_geometry(
|
||||
native.image, page_width=native.width, page_height=native.height,
|
||||
table_bbox=table_bbox, grid=grid,
|
||||
diagnostics=diagnostics, page_no=native.page_no,
|
||||
)
|
||||
if diagnostics is not None:
|
||||
diagnostics.add_ms('opencv_geometry_ms', geometry_started)
|
||||
diagnostics.incr('opencv_attempt_count')
|
||||
validation_started = perf_counter()
|
||||
validation = validate_opencv_cell_text(
|
||||
geometry, grid=grid,
|
||||
bounded_text_reader=lambda bbox: _text_within(native.characters, bbox),
|
||||
minimum_match_rate=1.0,
|
||||
required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()},
|
||||
)
|
||||
if diagnostics is not None:
|
||||
diagnostics.add_ms('opencv_validation_ms', validation_started)
|
||||
if not validation.accepted:
|
||||
ocr = build_ocr_table_evidence(
|
||||
image=native.image, page_width=native.width, page_height=native.height,
|
||||
table_bbox=table_bbox, grid=grid,
|
||||
diagnostics=diagnostics,
|
||||
page_no=native.page_no,
|
||||
)
|
||||
if not ocr.ready:
|
||||
if text_cells:
|
||||
|
||||
@@ -2,22 +2,29 @@
|
||||
backend/app/services/shipping_notice/document_layout/ocr_pdf.py
|
||||
|
||||
用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选(阶段 2)。
|
||||
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约;高亮质量对齐 field_highlight_contract。
|
||||
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约、layout_diagnostics、Flask 配置;高亮质量对齐 field_highlight_contract。
|
||||
逻辑:OCR 只提供独立文本坐标与 candidate 级高亮;必须与多参数有框网格及全部非空 cell
|
||||
文本一致才输出;OCR 结果不得自动升为 verified。
|
||||
文本一致才输出;OCR 结果不得自动升为 verified。PR-0 可选写入 Job 级脱敏计时/计数;
|
||||
PR-1 经 get_page_ocr_lines 在同 Job 内复用整页 OCR(含失败结果);
|
||||
PR-3 表格 cell 路径可裁剪 OCR(安全边距),订单级 page_glyphs 仍走整页。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from time import perf_counter
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox, normalize_layout_text
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
|
||||
from app.services.shipping_notice.document_layout.layout_diagnostics import (
|
||||
OCR_PAGE_CACHE_UNAVAILABLE,
|
||||
LayoutJobDiagnostics,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
reconstruct_opencv_table_geometry,
|
||||
cached_reconstruct_opencv_table_geometry,
|
||||
validate_opencv_cell_text,
|
||||
)
|
||||
|
||||
@@ -76,17 +83,33 @@ def _ocr_engine() -> Any:
|
||||
|
||||
|
||||
def extract_ocr_lines(
|
||||
image: Any, *, page_width: float, page_height: float, minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
|
||||
image: Any,
|
||||
*,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
|
||||
diagnostics: LayoutJobDiagnostics | None = None,
|
||||
page_no: int | None = None,
|
||||
image_origin_x: float = 0.0,
|
||||
image_origin_y: float = 0.0,
|
||||
full_image_width: int | None = None,
|
||||
full_image_height: int | None = None,
|
||||
) -> list[OcrLine]:
|
||||
"""
|
||||
将 RapidOCR 图像像素多边形映射为 PDF 页面坐标。
|
||||
|
||||
核心逻辑:像素坐标 → 页面坐标(按渲染宽高比例);低置信度行丢弃;保留 polygon 供审计。
|
||||
PR-0:可选拆分引擎初始化与推理墙钟,不改变行过滤与坐标映射结果。
|
||||
PR-3:裁剪 OCR 时通过 origin + full_image_* 把 crop 像素加回整页再映射。
|
||||
|
||||
Args:
|
||||
image: PDFium 渲染的页面 ndarray。
|
||||
image: PDFium 渲染的页面或表格裁剪 ndarray。
|
||||
page_width/page_height: PDF 页面单位尺寸。
|
||||
minimum_confidence: OCR 行最低可信度;低于阈值完全丢弃。
|
||||
diagnostics: 可选 Job 级诊断上下文;None 时不做计时/计数。
|
||||
page_no: 可选页号,用于 ocr_page_count 去重。
|
||||
image_origin_x/image_origin_y: 裁剪图在整页渲染图中的像素原点。
|
||||
full_image_width/full_image_height: 整页渲染尺寸;裁剪路径必填。
|
||||
|
||||
Returns:
|
||||
保持 OCR 返回顺序的文本行坐标。
|
||||
@@ -96,7 +119,30 @@ def extract_ocr_lines(
|
||||
height, width = image.shape[:2]
|
||||
if width <= 0 or height <= 0 or page_width <= 0 or page_height <= 0:
|
||||
raise ValueError('OCR page dimensions must be positive')
|
||||
result, _elapsed = _ocr_engine()(image)
|
||||
ref_width = int(full_image_width) if full_image_width is not None else int(width)
|
||||
ref_height = int(full_image_height) if full_image_height is not None else int(height)
|
||||
if ref_width <= 0 or ref_height <= 0:
|
||||
raise ValueError('OCR full image dimensions must be positive')
|
||||
# [STEP 1] 拆分引擎获取与推理,避免把模型加载混进 ocr_inference_ms。
|
||||
cache_info = getattr(_ocr_engine, 'cache_info', None)
|
||||
warm_before = False
|
||||
has_real_cache = False
|
||||
if callable(cache_info):
|
||||
try:
|
||||
currsize = getattr(cache_info(), 'currsize', None)
|
||||
has_real_cache = isinstance(currsize, int)
|
||||
warm_before = has_real_cache and currsize > 0
|
||||
except Exception:
|
||||
has_real_cache = False
|
||||
init_started = perf_counter()
|
||||
engine = _ocr_engine()
|
||||
if diagnostics is not None and has_real_cache and not warm_before:
|
||||
diagnostics.add_ms('ocr_engine_init_ms', init_started)
|
||||
infer_started = perf_counter()
|
||||
result, _elapsed = engine(image)
|
||||
if diagnostics is not None:
|
||||
diagnostics.add_ms('ocr_inference_ms', infer_started)
|
||||
diagnostics.record_ocr_call(page_no=page_no)
|
||||
lines: list[OcrLine] = []
|
||||
for index, item in enumerate(result or []):
|
||||
if len(item) < 3:
|
||||
@@ -110,14 +156,14 @@ def extract_ocr_lines(
|
||||
continue
|
||||
try:
|
||||
points = [[float(point[0]), float(point[1])] for point in polygon]
|
||||
xs = [point[0] for point in points]
|
||||
ys = [point[1] for point in points]
|
||||
# 像素 → 页面坐标;不做额外平移猜测
|
||||
xs = [point[0] + float(image_origin_x) for point in points]
|
||||
ys = [point[1] + float(image_origin_y) for point in points]
|
||||
# 像素 → 页面坐标;裁剪路径使用整页尺寸做比例换算
|
||||
bbox = LayoutBBox(
|
||||
x0=min(xs) * page_width / width,
|
||||
y0=min(ys) * page_height / height,
|
||||
x1=max(xs) * page_width / width,
|
||||
y1=max(ys) * page_height / height,
|
||||
x0=min(xs) * page_width / ref_width,
|
||||
y0=min(ys) * page_height / ref_height,
|
||||
x1=max(xs) * page_width / ref_width,
|
||||
y1=max(ys) * page_height / ref_height,
|
||||
)
|
||||
if bbox.x1 > page_width or bbox.y1 > page_height:
|
||||
continue
|
||||
@@ -126,15 +172,223 @@ def extract_ocr_lines(
|
||||
bbox=bbox,
|
||||
confidence=confidence,
|
||||
line_id=f'ocr-line-{index}',
|
||||
polygon=points,
|
||||
image_width=int(width),
|
||||
image_height=int(height),
|
||||
polygon=[[x, y] for x, y in zip(xs, ys)],
|
||||
image_width=ref_width,
|
||||
image_height=ref_height,
|
||||
))
|
||||
except (TypeError, ValueError, IndexError):
|
||||
continue
|
||||
return lines
|
||||
|
||||
|
||||
def layout_ocr_page_cache_enabled() -> bool:
|
||||
"""
|
||||
读取 PR-1 页面 OCR 缓存开关。
|
||||
|
||||
核心逻辑:优先 Flask config;无应用上下文时默认关闭,避免测试/脚本意外复用。
|
||||
|
||||
Returns:
|
||||
True 表示同 Job 内复用整页 OcrLine 结果。
|
||||
"""
|
||||
try:
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
if not has_app_context():
|
||||
return False
|
||||
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED', False))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def layout_ocr_crop_enabled() -> bool:
|
||||
"""
|
||||
读取 PR-3 表格裁剪 OCR 开关。
|
||||
|
||||
Returns:
|
||||
True 时表格 cell 候选优先裁剪识别;订单级 page_glyphs 仍用整页 OCR。
|
||||
"""
|
||||
try:
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
if not has_app_context():
|
||||
return False
|
||||
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED', False))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _ocr_crop_margin_ratio() -> float:
|
||||
"""读取表格裁剪安全边距比例,默认 3%,夹在 [0.02, 0.05]。"""
|
||||
default = 0.03
|
||||
try:
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
if not has_app_context():
|
||||
return default
|
||||
raw = float(current_app.config.get('SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO', default))
|
||||
except Exception:
|
||||
return default
|
||||
return min(max(raw, 0.02), 0.05)
|
||||
|
||||
|
||||
def _expanded_table_bbox(
|
||||
table_bbox: LayoutBBox, *, page_width: float, page_height: float, margin_ratio: float,
|
||||
) -> LayoutBBox:
|
||||
"""按页面尺寸扩展表格 bbox 安全边距,并裁剪到页面范围。"""
|
||||
pad_x = page_width * margin_ratio
|
||||
pad_y = page_height * margin_ratio
|
||||
return LayoutBBox(
|
||||
x0=max(0.0, float(table_bbox.x0) - pad_x),
|
||||
y0=max(0.0, float(table_bbox.y0) - pad_y),
|
||||
x1=min(page_width, float(table_bbox.x1) + pad_x),
|
||||
y1=min(page_height, float(table_bbox.y1) + pad_y),
|
||||
)
|
||||
|
||||
|
||||
def extract_table_crop_ocr_lines(
|
||||
image: Any,
|
||||
*,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
table_bbox: LayoutBBox,
|
||||
minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
|
||||
diagnostics: LayoutJobDiagnostics | None = None,
|
||||
page_no: int | None = None,
|
||||
use_cache: bool | None = None,
|
||||
) -> list[OcrLine]:
|
||||
"""
|
||||
对表格区域(含安全边距)裁剪后 OCR,坐标映射回整页页面单位。
|
||||
|
||||
核心逻辑:仅服务表格 cell 候选;失败结果按表 bbox 缓存。订单级字段仍应走整页 OCR。
|
||||
|
||||
Args:
|
||||
image: 整页渲染图。
|
||||
page_width/page_height/table_bbox: 页面与表格坐标。
|
||||
diagnostics/page_no/use_cache: 诊断与缓存控制。
|
||||
|
||||
Returns:
|
||||
映射回整页的 OcrLine 列表。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.layout_diagnostics import (
|
||||
OCR_TABLE_CROP_CACHE_UNAVAILABLE,
|
||||
)
|
||||
|
||||
cache_on = layout_ocr_crop_enabled() if use_cache is None else bool(use_cache)
|
||||
margin = _ocr_crop_margin_ratio()
|
||||
expanded = _expanded_table_bbox(
|
||||
table_bbox, page_width=page_width, page_height=page_height, margin_ratio=margin,
|
||||
)
|
||||
full_height, full_width = image.shape[:2]
|
||||
x0 = max(0, int(expanded.x0 * full_width / page_width))
|
||||
y0 = max(0, int(expanded.y0 * full_height / page_height))
|
||||
x1 = min(full_width, max(x0 + 1, int(expanded.x1 * full_width / page_width + 0.999)))
|
||||
y1 = min(full_height, max(y0 + 1, int(expanded.y1 * full_height / page_height + 0.999)))
|
||||
cache_key = None
|
||||
if cache_on and diagnostics is not None and page_no is not None:
|
||||
cache_key = (
|
||||
int(page_no), round(expanded.x0, 2), round(expanded.y0, 2),
|
||||
round(expanded.x1, 2), round(expanded.y1, 2), int(full_width), int(full_height),
|
||||
)
|
||||
if cache_key in diagnostics.ocr_table_crop_cache:
|
||||
diagnostics.incr('ocr_page_cache_hit')
|
||||
cached = diagnostics.ocr_table_crop_cache[cache_key]
|
||||
if cached is OCR_TABLE_CROP_CACHE_UNAVAILABLE:
|
||||
raise RuntimeError('ocr_engine_unavailable')
|
||||
return list(cached)
|
||||
diagnostics.incr('ocr_page_cache_miss')
|
||||
|
||||
crop = image[y0:y1, x0:x1]
|
||||
if crop.size == 0:
|
||||
raise ValueError('OCR table crop is empty')
|
||||
if diagnostics is not None:
|
||||
diagnostics.incr('ocr_crop_count')
|
||||
try:
|
||||
lines = extract_ocr_lines(
|
||||
crop,
|
||||
page_width=page_width,
|
||||
page_height=page_height,
|
||||
minimum_confidence=minimum_confidence,
|
||||
diagnostics=diagnostics,
|
||||
page_no=page_no,
|
||||
image_origin_x=float(x0),
|
||||
image_origin_y=float(y0),
|
||||
full_image_width=int(full_width),
|
||||
full_image_height=int(full_height),
|
||||
)
|
||||
except Exception:
|
||||
if cache_key is not None and diagnostics is not None:
|
||||
diagnostics.ocr_table_crop_cache[cache_key] = OCR_TABLE_CROP_CACHE_UNAVAILABLE
|
||||
raise
|
||||
if cache_key is not None and diagnostics is not None:
|
||||
diagnostics.ocr_table_crop_cache[cache_key] = list(lines)
|
||||
return lines
|
||||
|
||||
|
||||
def get_page_ocr_lines(
|
||||
image: Any,
|
||||
*,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
|
||||
diagnostics: LayoutJobDiagnostics | None = None,
|
||||
page_no: int | None = None,
|
||||
use_cache: bool | None = None,
|
||||
) -> list[OcrLine]:
|
||||
"""
|
||||
获取整页 OCR 行;PR-1 可在同 Job 内按页缓存(含失败结果)。
|
||||
|
||||
核心逻辑:缓存键为 (page_no, image_width, image_height);命中则不再调用 RapidOCR;
|
||||
引擎不可用缓存为哨兵并再次抛出受控异常,供调用方映射 ocr_engine_unavailable。
|
||||
|
||||
Args:
|
||||
image/page_width/page_height/minimum_confidence: 同 extract_ocr_lines。
|
||||
diagnostics: Job 诊断上下文;提供时才可写入/读取页面缓存。
|
||||
page_no: 页号;缺失时不做页面缓存(仍可直接推理)。
|
||||
use_cache: 显式覆盖开关;None 时读取配置。
|
||||
|
||||
Returns:
|
||||
OCR 行列表(可能为空)。
|
||||
|
||||
Raises:
|
||||
Exception: 与 extract_ocr_lines 相同;缓存命中 unavailable 时抛 RuntimeError。
|
||||
"""
|
||||
cache_on = layout_ocr_page_cache_enabled() if use_cache is None else bool(use_cache)
|
||||
cache_key = None
|
||||
if (
|
||||
cache_on
|
||||
and diagnostics is not None
|
||||
and page_no is not None
|
||||
and image is not None
|
||||
):
|
||||
cache_key = LayoutJobDiagnostics.page_ocr_cache_key(int(page_no), image)
|
||||
if cache_key in diagnostics.ocr_page_cache:
|
||||
diagnostics.incr('ocr_page_cache_hit')
|
||||
cached = diagnostics.ocr_page_cache[cache_key]
|
||||
if cached is OCR_PAGE_CACHE_UNAVAILABLE:
|
||||
raise RuntimeError('ocr_engine_unavailable')
|
||||
return list(cached)
|
||||
|
||||
if cache_key is not None and diagnostics is not None:
|
||||
diagnostics.incr('ocr_page_cache_miss')
|
||||
try:
|
||||
lines = extract_ocr_lines(
|
||||
image,
|
||||
page_width=page_width,
|
||||
page_height=page_height,
|
||||
minimum_confidence=minimum_confidence,
|
||||
diagnostics=diagnostics,
|
||||
page_no=page_no,
|
||||
)
|
||||
except Exception:
|
||||
if cache_key is not None and diagnostics is not None:
|
||||
diagnostics.ocr_page_cache[cache_key] = OCR_PAGE_CACHE_UNAVAILABLE
|
||||
raise
|
||||
if cache_key is not None and diagnostics is not None:
|
||||
# 失败空结果也缓存,避免同页多表重复打引擎。
|
||||
diagnostics.ocr_page_cache[cache_key] = list(lines)
|
||||
return lines
|
||||
|
||||
|
||||
def page_bbox_to_normalized(bbox: LayoutBBox, *, page_width: float, page_height: float) -> LayoutBBox:
|
||||
"""
|
||||
将页面坐标转为 0..1 归一化 bbox,供 PDF.js viewport 绘制。
|
||||
@@ -163,17 +417,54 @@ def page_bbox_to_normalized(bbox: LayoutBBox, *, page_width: float, page_height:
|
||||
|
||||
|
||||
def build_ocr_table_evidence(
|
||||
*, image: Any, page_width: float, page_height: float,
|
||||
table_bbox: LayoutBBox, grid: HtmlGrid,
|
||||
*,
|
||||
image: Any,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
table_bbox: LayoutBBox,
|
||||
grid: HtmlGrid,
|
||||
diagnostics: LayoutJobDiagnostics | None = None,
|
||||
page_no: int | None = None,
|
||||
ocr_lines: list[OcrLine] | None = None,
|
||||
) -> OcrTableEvidence:
|
||||
"""
|
||||
对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。
|
||||
|
||||
核心逻辑:通过后 cell.status 固定为 candidate;置信度不足/多候选/文本不一致不准入。
|
||||
PR-0:进入本函数即计 ocr_attempt/ocr_table;OpenCV 子耗时累加到 diagnostics。
|
||||
PR-1:ocr_lines 已提供时不再推理;否则经 get_page_ocr_lines 走页面缓存。
|
||||
PR-3:开启裁剪 OCR 且未预传 ocr_lines 时,对表格区域裁剪识别(订单级仍用整页)。
|
||||
|
||||
Args:
|
||||
image/page_width/page_height/table_bbox/grid: 既有扫描表门禁输入。
|
||||
diagnostics: 可选 Job 级诊断上下文。
|
||||
page_no: 可选页号,传给页面 OCR 缓存与去重计数。
|
||||
ocr_lines: 可选预计算整页 OCR 行;提供时跳过推理。
|
||||
"""
|
||||
if diagnostics is not None:
|
||||
diagnostics.incr('ocr_attempt_count')
|
||||
diagnostics.incr('ocr_table_count')
|
||||
try:
|
||||
height, width = image.shape[:2]
|
||||
lines = extract_ocr_lines(image, page_width=page_width, page_height=page_height)
|
||||
if ocr_lines is not None:
|
||||
lines = list(ocr_lines)
|
||||
elif layout_ocr_crop_enabled():
|
||||
lines = extract_table_crop_ocr_lines(
|
||||
image,
|
||||
page_width=page_width,
|
||||
page_height=page_height,
|
||||
table_bbox=table_bbox,
|
||||
diagnostics=diagnostics,
|
||||
page_no=page_no,
|
||||
)
|
||||
else:
|
||||
lines = get_page_ocr_lines(
|
||||
image,
|
||||
page_width=page_width,
|
||||
page_height=page_height,
|
||||
diagnostics=diagnostics,
|
||||
page_no=page_no,
|
||||
)
|
||||
except Exception:
|
||||
return OcrTableEvidence(ready=False, issues=['ocr_engine_unavailable'])
|
||||
if not lines:
|
||||
@@ -183,16 +474,24 @@ def build_ocr_table_evidence(
|
||||
image_width=int(width) if width else None,
|
||||
image_height=int(height) if height else None,
|
||||
)
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
geometry_started = perf_counter()
|
||||
geometry = cached_reconstruct_opencv_table_geometry(
|
||||
image, page_width=page_width, page_height=page_height,
|
||||
table_bbox=table_bbox, grid=grid,
|
||||
diagnostics=diagnostics, page_no=page_no,
|
||||
)
|
||||
if diagnostics is not None:
|
||||
diagnostics.add_ms('opencv_geometry_ms', geometry_started)
|
||||
diagnostics.incr('opencv_attempt_count')
|
||||
validation_started = perf_counter()
|
||||
validation = validate_opencv_cell_text(
|
||||
geometry, grid=grid,
|
||||
bounded_text_reader=lambda bbox: _text_within(lines, bbox),
|
||||
minimum_match_rate=1,
|
||||
required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()},
|
||||
)
|
||||
if diagnostics is not None:
|
||||
diagnostics.add_ms('opencv_validation_ms', validation_started)
|
||||
if not validation.accepted:
|
||||
return OcrTableEvidence(
|
||||
ready=False,
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
backend/app/services/shipping_notice/document_layout/opencv_table.py
|
||||
|
||||
用途:在 MinerU 整表区域内用 OpenCV 恢复严格有框表网格,生成待评测的 HTML cell 几何候选。
|
||||
依赖:opencv-python-headless、numpy、document_layout.html_table/contracts。
|
||||
依赖:opencv-python-headless、numpy、document_layout.html_table/contracts、layout_diagnostics。
|
||||
逻辑:多组形态学参数独立检测 cell 轮廓;仅当至少两组结果与 HTML 网格完全一致且边界
|
||||
共识稳定时输出 ready;还必须经独立 PDF 文本验收,不得仅凭几何轮廓接受 cell(阶段 3)。
|
||||
PR-2:`cached_reconstruct_opencv_table_geometry` 在同 Job 内按页/表/网格签名缓存
|
||||
(含失败),不减少多配置共识组数、不改变门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -115,6 +117,13 @@ def reconstruct_opencv_table_geometry(
|
||||
"""
|
||||
if cv2 is None:
|
||||
return _not_ready(grid, 'opencv_unavailable')
|
||||
# 快速退出:无效网格/空图/非法 bbox,避免无意义的多配置扫描。
|
||||
if grid.row_count <= 0 or grid.column_count <= 0:
|
||||
return _not_ready(grid, 'opencv_table_grid_not_detected')
|
||||
if float(table_bbox.x1) <= float(table_bbox.x0) or float(table_bbox.y1) <= float(table_bbox.y0):
|
||||
return _not_ready(grid, 'opencv_table_crop_invalid')
|
||||
if page_image is None or getattr(page_image, 'size', 0) <= 0:
|
||||
return _not_ready(grid, 'opencv_unavailable')
|
||||
if min_consensus < 2 or len(configs) < min_consensus:
|
||||
raise ValueError('OpenCV grid reconstruction requires at least two configurations')
|
||||
image = _grayscale_page(page_image)
|
||||
@@ -164,6 +173,64 @@ def reconstruct_opencv_table_geometry(
|
||||
)
|
||||
|
||||
|
||||
def cached_reconstruct_opencv_table_geometry(
|
||||
page_image: np.ndarray,
|
||||
*,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
table_bbox: LayoutBBox,
|
||||
grid: HtmlGrid,
|
||||
diagnostics: Any | None = None,
|
||||
page_no: int | None = None,
|
||||
configs: tuple[OpenCVGridConfig, ...] = DEFAULT_GRID_CONFIGS,
|
||||
min_consensus: int = 2,
|
||||
boundary_tolerance_pixels: int = 8,
|
||||
) -> OpenCVTableGeometryResult:
|
||||
"""
|
||||
同 Job 内复用相同 page/table/grid 的 OpenCV geometry 结果(含失败)。
|
||||
|
||||
核心逻辑:缓存键含页号、圆整 bbox、行列数与 rowspan/colspan 签名;不改变多配置共识门禁。
|
||||
|
||||
Args:
|
||||
同 reconstruct_opencv_table_geometry,另加 diagnostics/page_no。
|
||||
|
||||
Returns:
|
||||
OpenCVTableGeometryResult;命中缓存时直接返回同一对象。
|
||||
"""
|
||||
if diagnostics is None:
|
||||
return reconstruct_opencv_table_geometry(
|
||||
page_image, page_width=page_width, page_height=page_height,
|
||||
table_bbox=table_bbox, grid=grid, configs=configs,
|
||||
min_consensus=min_consensus,
|
||||
boundary_tolerance_pixels=boundary_tolerance_pixels,
|
||||
)
|
||||
height, width = page_image.shape[:2]
|
||||
span_sig = tuple(
|
||||
(int(cell.row_index), int(cell.column_index), int(cell.row_span), int(cell.column_span))
|
||||
for cell in grid.cells
|
||||
)
|
||||
cache_key = (
|
||||
int(page_no or 0),
|
||||
round(float(table_bbox.x0), 2), round(float(table_bbox.y0), 2),
|
||||
round(float(table_bbox.x1), 2), round(float(table_bbox.y1), 2),
|
||||
int(grid.row_count), int(grid.column_count), span_sig,
|
||||
int(width), int(height), int(min_consensus), int(boundary_tolerance_pixels),
|
||||
)
|
||||
cached = diagnostics.opencv_geometry_cache.get(cache_key)
|
||||
if cached is not None:
|
||||
diagnostics.incr('opencv_geometry_cache_hit')
|
||||
return cached
|
||||
diagnostics.incr('opencv_geometry_cache_miss')
|
||||
result = reconstruct_opencv_table_geometry(
|
||||
page_image, page_width=page_width, page_height=page_height,
|
||||
table_bbox=table_bbox, grid=grid, configs=configs,
|
||||
min_consensus=min_consensus,
|
||||
boundary_tolerance_pixels=boundary_tolerance_pixels,
|
||||
)
|
||||
diagnostics.opencv_geometry_cache[cache_key] = result
|
||||
return result
|
||||
|
||||
|
||||
def validate_opencv_cell_text(
|
||||
geometry: OpenCVTableGeometryResult,
|
||||
*,
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
backend/app/services/shipping_notice/document_layout/runtime.py
|
||||
|
||||
用途:在独立布局 Job 中调用 MinerU,并生成可持久化的紧凑文本、表格及原生 PDF 候选快照。
|
||||
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf。
|
||||
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf、layout_diagnostics。
|
||||
逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;阶段 1 在
|
||||
layout_candidate 写入真实 cell bbox 后回填 capability.cell_bbox_count,禁止长期假报 0。
|
||||
PR-0 将细分 timings/counts 写入传入诊断字典,永不进入持久化快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +18,11 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.shipping_notice.document_layout.layout_diagnostics import (
|
||||
LayoutJobDiagnostics,
|
||||
ensure_layout_counts,
|
||||
ensure_layout_timings,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MINERU_SUPPORTED_EXTENSIONS,
|
||||
MinerUClient,
|
||||
@@ -97,6 +103,7 @@ def build_mineru_table_snapshot(
|
||||
document_id: int | None = None,
|
||||
content_hash: str | None = None,
|
||||
timings: dict[str, int] | None = None,
|
||||
counts: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
为一个受支持附件生成紧凑 MinerU 文本与表格快照。
|
||||
@@ -109,9 +116,11 @@ def build_mineru_table_snapshot(
|
||||
content: 原始文件字节;不写数据库和日志。
|
||||
document_id/content_hash: PDF 的版本化 Document 身份;两者齐全时生成 layout.v1 候选。
|
||||
timings: 可选运维耗时字典;只写阶段毫秒数,不进入持久化快照。
|
||||
counts: 可选运维计数字典;与 timings 平级写入 Job result,不进入快照。
|
||||
Returns:
|
||||
关闭/不支持时返回 None;成功或 Provider 降级均返回受控的版本化状态对象。
|
||||
"""
|
||||
diagnostics = _diagnostics_from_maps(timings=timings, counts=counts)
|
||||
extension = Path(str(filename or '')).suffix.lower()
|
||||
if not mineru_layout_capture_enabled(filename) or not content:
|
||||
return None
|
||||
@@ -123,6 +132,7 @@ def build_mineru_table_snapshot(
|
||||
timings=timings,
|
||||
)
|
||||
if xfa_snapshot is not None:
|
||||
_record_xfa_page_count(xfa_snapshot, diagnostics=diagnostics)
|
||||
return xfa_snapshot
|
||||
native_pages: list[Any] | None = None
|
||||
if extension == '.pdf' and document_id and content_hash:
|
||||
@@ -131,7 +141,10 @@ def build_mineru_table_snapshot(
|
||||
|
||||
native_started = perf_counter()
|
||||
native_pages = extract_native_pdf_pages(content, render_images=False)
|
||||
if timings is not None:
|
||||
if diagnostics is not None:
|
||||
diagnostics.set_ms('native_pdf_extract_ms', native_started)
|
||||
diagnostics.counts['page_count'] = len(native_pages)
|
||||
elif timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
except Exception:
|
||||
native_pages = None
|
||||
@@ -139,7 +152,7 @@ def build_mineru_table_snapshot(
|
||||
if not base_url:
|
||||
fallback = _native_pdf_fallback_snapshot(
|
||||
content=content, document_id=document_id, content_hash=content_hash,
|
||||
native_pages=native_pages, timings=timings,
|
||||
native_pages=native_pages, timings=timings, diagnostics=diagnostics,
|
||||
provider_issue='mineru_base_url_missing',
|
||||
)
|
||||
if fallback is not None:
|
||||
@@ -175,7 +188,7 @@ def build_mineru_table_snapshot(
|
||||
except AppError as exc:
|
||||
fallback = _native_pdf_fallback_snapshot(
|
||||
content=content, document_id=document_id, content_hash=content_hash,
|
||||
native_pages=native_pages, timings=timings,
|
||||
native_pages=native_pages, timings=timings, diagnostics=diagnostics,
|
||||
provider_issue=str(exc.code),
|
||||
)
|
||||
if fallback is not None:
|
||||
@@ -191,7 +204,7 @@ def build_mineru_table_snapshot(
|
||||
except (TypeError, ValueError):
|
||||
fallback = _native_pdf_fallback_snapshot(
|
||||
content=content, document_id=document_id, content_hash=content_hash,
|
||||
native_pages=native_pages, timings=timings,
|
||||
native_pages=native_pages, timings=timings, diagnostics=diagnostics,
|
||||
provider_issue='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
if fallback is not None:
|
||||
@@ -268,16 +281,34 @@ def build_mineru_table_snapshot(
|
||||
if extension == '.pdf' and document_id and content_hash:
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
attach_native_pdf_page_images,
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
extract_native_pdf_pages,
|
||||
layout_native_page_reuse_enabled,
|
||||
)
|
||||
|
||||
# MinerU 成功后进入坐标增强链;此时按需补齐页面图,供严格 OpenCV/OCR 门禁使用。
|
||||
# 前置轻量预读只缓存字符,不得因为已有无图页面而跳过必要的增强证据。
|
||||
# PR-2:开启复用时保留前置字符预读,仅渲染缺图页,禁止二次字符枚举。
|
||||
native_started = perf_counter()
|
||||
native_pages = extract_native_pdf_pages(content)
|
||||
if timings is not None:
|
||||
reuse = layout_native_page_reuse_enabled() and native_pages is not None
|
||||
if reuse:
|
||||
attached = 0
|
||||
before = list(native_pages)
|
||||
native_pages = attach_native_pdf_page_images(content, before)
|
||||
attached = sum(
|
||||
1 for old, new in zip(before, native_pages)
|
||||
if old.image is None and new.image is not None
|
||||
)
|
||||
if diagnostics is not None:
|
||||
diagnostics.incr('pdfium_page_image_attach_count', attached)
|
||||
else:
|
||||
native_pages = extract_native_pdf_pages(content)
|
||||
if diagnostics is not None:
|
||||
# 第二次提取/补图覆盖前置轻量预读耗时(既有语义:增强链提取为准)。
|
||||
diagnostics.set_ms('native_pdf_extract_ms', native_started)
|
||||
diagnostics.counts['page_count'] = len(native_pages)
|
||||
elif timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
|
||||
layout_source_candidate = candidate
|
||||
@@ -308,23 +339,33 @@ def build_mineru_table_snapshot(
|
||||
'native_pdf_text_table_fallback_used',
|
||||
})
|
||||
|
||||
if diagnostics is not None:
|
||||
diagnostics.counts['mineru_table_count'] = len(tables)
|
||||
layout_started = perf_counter()
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=int(document_id), content_hash=str(content_hash),
|
||||
content=content, mineru=layout_source_candidate, native_pages=native_pages,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
if timings is not None:
|
||||
if diagnostics is not None:
|
||||
diagnostics.set_ms('native_layout_build_ms', layout_started)
|
||||
elif timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
serialize_started = perf_counter()
|
||||
snapshot['layout_candidate'] = layout.model_dump(mode='json')
|
||||
if diagnostics is not None:
|
||||
diagnostics.set_ms('layout_serialize_ms', serialize_started)
|
||||
snapshot['capability'] = _capability_with_layout_cells(
|
||||
snapshot.get('capability'), layout_payload=snapshot['layout_candidate'],
|
||||
)
|
||||
# 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。
|
||||
evidence_started = perf_counter()
|
||||
snapshot['coordinate_evidence'] = _table_coordinate_evidence(
|
||||
pages=native_pages, tables=tables,
|
||||
pages=native_pages, tables=tables, diagnostics=diagnostics,
|
||||
)
|
||||
if timings is not None:
|
||||
if diagnostics is not None:
|
||||
diagnostics.set_ms('coordinate_evidence_ms', evidence_started)
|
||||
elif timings is not None:
|
||||
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
|
||||
except Exception:
|
||||
snapshot['issues'] = sorted(set(
|
||||
@@ -337,10 +378,67 @@ def build_mineru_table_snapshot(
|
||||
return snapshot
|
||||
|
||||
|
||||
def _diagnostics_from_maps(
|
||||
*,
|
||||
timings: dict[str, Any] | None,
|
||||
counts: dict[str, Any] | None,
|
||||
) -> LayoutJobDiagnostics | None:
|
||||
"""
|
||||
将 handler 传入的 timings/counts 字典包装为共享诊断上下文。
|
||||
|
||||
核心逻辑:任一侧非 None 即启用诊断,并保证契约键齐全;两边引用同一字典以便就地累加。
|
||||
|
||||
Args:
|
||||
timings/counts: Job handler 持有的可变字典。
|
||||
|
||||
Returns:
|
||||
LayoutJobDiagnostics;两者皆缺失时返回 None。
|
||||
"""
|
||||
if timings is None and counts is None:
|
||||
return None
|
||||
ensured_timings = ensure_layout_timings(timings if timings is not None else {})
|
||||
ensured_counts = ensure_layout_counts(counts if counts is not None else {})
|
||||
if timings is not None and timings is not ensured_timings:
|
||||
timings.update(ensured_timings)
|
||||
if counts is not None and counts is not ensured_counts:
|
||||
counts.update(ensured_counts)
|
||||
return LayoutJobDiagnostics(
|
||||
timings=timings if timings is not None else ensured_timings,
|
||||
counts=counts if counts is not None else ensured_counts,
|
||||
)
|
||||
|
||||
|
||||
def _record_xfa_page_count(
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
diagnostics: LayoutJobDiagnostics | None,
|
||||
) -> None:
|
||||
"""
|
||||
XFA 早退路径仅回填可安全取得的 page_count,不引入 OCR/OpenCV 逻辑。
|
||||
|
||||
Args:
|
||||
snapshot: XFA layout 快照。
|
||||
diagnostics: 可选诊断上下文。
|
||||
"""
|
||||
if diagnostics is None:
|
||||
return
|
||||
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
|
||||
page_count = capability.get('page_count')
|
||||
if page_count is None:
|
||||
pages = snapshot.get('pages')
|
||||
if isinstance(pages, list):
|
||||
page_count = len(pages)
|
||||
try:
|
||||
diagnostics.counts['page_count'] = int(page_count or 0)
|
||||
except (TypeError, ValueError):
|
||||
diagnostics.counts['page_count'] = 0
|
||||
|
||||
|
||||
def _native_pdf_fallback_snapshot(
|
||||
*, content: bytes, document_id: int | None, content_hash: str | None,
|
||||
native_pages: list[Any] | None, timings: dict[str, int] | None,
|
||||
provider_issue: str,
|
||||
diagnostics: LayoutJobDiagnostics | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
在 MinerU 不可用时,用严格原生文字表格证据生成降级布局快照。
|
||||
@@ -355,6 +453,7 @@ def _native_pdf_fallback_snapshot(
|
||||
native_pages: MinerU 调用前已轻量预读的 PDFium 页面;缺失时禁止降级。
|
||||
timings: 可选运维阶段耗时,不进入快照。
|
||||
provider_issue: 触发降级的 MinerU 稳定问题码。
|
||||
diagnostics: 可选 Job 级诊断上下文。
|
||||
|
||||
Returns:
|
||||
证据充分时返回带 Provider 失败原因的 ready 降级快照;否则返回 None。
|
||||
@@ -369,7 +468,11 @@ def _native_pdf_fallback_snapshot(
|
||||
|
||||
fallback_started = perf_counter()
|
||||
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
|
||||
if timings is not None:
|
||||
if diagnostics is not None:
|
||||
diagnostics.set_ms('native_table_detect_ms', fallback_started)
|
||||
diagnostics.counts['page_count'] = len(native_pages)
|
||||
diagnostics.counts['mineru_table_count'] = len(tables)
|
||||
elif timings is not None:
|
||||
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
|
||||
if not tables:
|
||||
return None
|
||||
@@ -382,10 +485,16 @@ def _native_pdf_fallback_snapshot(
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=int(document_id), content_hash=str(content_hash),
|
||||
content=content, mineru=candidate, native_pages=native_pages,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
if timings is not None:
|
||||
if diagnostics is not None:
|
||||
diagnostics.set_ms('native_layout_build_ms', layout_started)
|
||||
elif timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
serialize_started = perf_counter()
|
||||
layout_payload_preview = layout.model_dump(mode='json')
|
||||
if diagnostics is not None:
|
||||
diagnostics.set_ms('layout_serialize_ms', serialize_started)
|
||||
capability = _capability_with_layout_cells(
|
||||
candidate.capability.model_dump(mode='json'),
|
||||
layout_payload=layout_payload_preview,
|
||||
@@ -395,8 +504,11 @@ def _native_pdf_fallback_snapshot(
|
||||
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
|
||||
evidence = _table_coordinate_evidence(
|
||||
pages=native_pages, tables=tables, include_page_glyphs=False,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
if timings is not None:
|
||||
if diagnostics is not None:
|
||||
diagnostics.set_ms('coordinate_evidence_ms', evidence_started)
|
||||
elif timings is not None:
|
||||
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
@@ -454,7 +566,11 @@ def _native_pdf_candidate_from_tables(
|
||||
|
||||
|
||||
def _table_coordinate_evidence(
|
||||
*, pages: list[Any], tables: list[dict[str, Any]], include_page_glyphs: bool = True,
|
||||
*,
|
||||
pages: list[Any],
|
||||
tables: list[dict[str, Any]],
|
||||
include_page_glyphs: bool = True,
|
||||
diagnostics: LayoutJobDiagnostics | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
从已提取页面保存表内及整页字符证据,避免同一 PDF 重复解析和渲染。
|
||||
@@ -463,6 +579,7 @@ def _table_coordinate_evidence(
|
||||
pages: 本轮已提取的 NativePdfPage 列表。
|
||||
tables: MinerU 或原生文字回退生成的表格摘要。
|
||||
include_page_glyphs: 是否保留表格外整页字符证据;fallback 只保留表内证据。
|
||||
diagnostics: 可选 Job 级诊断;页级 OCR 计入 ocr_*(嵌套于 coordinate_evidence_ms)。
|
||||
Returns:
|
||||
供明细重建与订单字段重放的坐标证据。
|
||||
"""
|
||||
@@ -498,9 +615,16 @@ def _table_coordinate_evidence(
|
||||
# Only scanned pages without a usable native text layer trigger OCR. OCR failure
|
||||
# intentionally leaves this page without order-field evidence rather than guessing.
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import get_page_ocr_lines
|
||||
|
||||
ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
|
||||
# PR-1:与 layout 构建共享同一页面 OCR 缓存,禁止同页整页重复推理。
|
||||
ocr_lines = get_page_ocr_lines(
|
||||
page.image,
|
||||
page_width=page.width,
|
||||
page_height=page.height,
|
||||
diagnostics=diagnostics,
|
||||
page_no=int(page_no),
|
||||
)
|
||||
ocr_glyphs = _ocr_page_characters(ocr_lines)
|
||||
except Exception:
|
||||
ocr_glyphs = []
|
||||
|
||||
@@ -865,6 +865,13 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
order_line['__required_qty'] = purpose_line.get('quantity')
|
||||
order_line['__display_part_number'] = purpose_line.get('part_number')
|
||||
order_line['__display_reservation_id'] = purpose_line.get('reservation_id')
|
||||
# BE-6:单位为可选匹配键;优先行字典 uom/unit。
|
||||
order_line['__display_uom'] = (
|
||||
purpose_line.get('uom')
|
||||
or purpose_line.get('unit')
|
||||
or order_line.get('uom')
|
||||
or order_line.get('unit')
|
||||
)
|
||||
total_notice_lines = len(order_field_lines)
|
||||
_sync_workflow_stage(
|
||||
task,
|
||||
@@ -927,6 +934,17 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'__required_qty': purpose_line.get('quantity'),
|
||||
'__display_part_number': purpose_line.get('part_number'),
|
||||
'__display_reservation_id': purpose_line.get('reservation_id'),
|
||||
'__display_uom': (
|
||||
purpose_line.get('uom')
|
||||
or purpose_line.get('unit')
|
||||
or (order_field_lines[index] if index < len(order_field_lines) else {}).get('__display_uom')
|
||||
or (order_field_lines[index] if index < len(order_field_lines) else {}).get('uom')
|
||||
),
|
||||
'uom': (
|
||||
purpose_line.get('uom')
|
||||
or purpose_line.get('unit')
|
||||
or (order_field_lines[index] if index < len(order_field_lines) else {}).get('__display_uom')
|
||||
),
|
||||
'line_key': (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key'),
|
||||
})
|
||||
match_payload = match_order_lines_across_candidates(
|
||||
@@ -935,6 +953,18 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
header_reservation_id=header_reservation,
|
||||
)
|
||||
apply_line_inventory_resolutions(task, match_payload)
|
||||
# [STEP] Slice 1:持久化 OT 行匹配事实(ready+not_found=0;缺键→invalid_key)
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||
persist_line_inventory_match_facts,
|
||||
)
|
||||
persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload=match_payload,
|
||||
inventory_snapshot_id=(
|
||||
int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None
|
||||
),
|
||||
matching_rule_version='stp_line_v2',
|
||||
)
|
||||
match_status = str(match_payload.get('match_status') or 'unfulfillable')
|
||||
line_results = list(match_payload.get('line_results') or [])
|
||||
from app.services.shipping_notice.reservation_service import record_inventory_verification
|
||||
@@ -973,6 +1003,15 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
actor_id=actor_id,
|
||||
source='workspace_api' if actor_id else 'system',
|
||||
)
|
||||
# [STEP] Slice 3:匹配 ready 后入队自动履约协调(flag 关则 no-op)
|
||||
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
|
||||
enqueue_post_ot_auto_fulfill_job,
|
||||
)
|
||||
enqueue_post_ot_auto_fulfill_job(
|
||||
task_no=str(task.task_no),
|
||||
trigger='inventory_ready',
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
match_result = tool_response(
|
||||
status="ok",
|
||||
@@ -989,6 +1028,15 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
actor_id=actor_id,
|
||||
source='workspace_api' if actor_id else 'system',
|
||||
)
|
||||
# 部分短缺时仍可能有 eligible 行;协调器按事实筛选。
|
||||
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
|
||||
enqueue_post_ot_auto_fulfill_job,
|
||||
)
|
||||
enqueue_post_ot_auto_fulfill_job(
|
||||
task_no=str(task.task_no),
|
||||
trigger='inventory_ready',
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""
|
||||
services/shipping_notice/line_auto_fulfill_coordinator.py
|
||||
|
||||
用途:OT 后行级自动履约幂等协调器——统一 matching ready / OT 回调 / 补偿入口。
|
||||
依赖:line_auto_fulfill_enabled、post_ot_fulfillment_wave_service、post_ot_wave_progress_service、
|
||||
ShippingNoticeLineInventoryMatch / LineDecision snapshot。
|
||||
逻辑:flag 关闭时 skipped;开启时整波创建+专用推进;失败整波回滚后独立写 auto_fulfill_failed 列;
|
||||
不创建 wait_inventory 半成品决定;trigger=ot_created|compensation 由确认/STP/补偿排程接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision,
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import resolve_review_case_for_task
|
||||
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
|
||||
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
|
||||
create_post_ot_fulfillment_wave,
|
||||
list_eligible_post_ot_line_keys,
|
||||
)
|
||||
from app.services.shipping_notice.post_ot_wave_progress_service import schedule_post_ot_wave_progress
|
||||
|
||||
|
||||
def _mark_auto_fulfill_failed(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
line_keys: list[str],
|
||||
error_code: str,
|
||||
message: str,
|
||||
) -> None:
|
||||
"""
|
||||
独立事务内写入失败事实:匹配事实表列优先;活动决定仅补 snapshot,不新建 wait_inventory。
|
||||
|
||||
核心逻辑:写 ShippingNoticeLineInventoryMatch.auto_fulfill_failed* 列;可选同步 snapshot。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
formal_task_id = getattr(case, 'confirmed_task_id', None)
|
||||
for key in line_keys:
|
||||
key_s = str(key)
|
||||
if formal_task_id is not None:
|
||||
fact = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(formal_task_id), line_key=key_s, is_current=True)
|
||||
.first()
|
||||
)
|
||||
if fact is not None:
|
||||
fact.auto_fulfill_failed = True
|
||||
fact.auto_fulfill_error_code = str(error_code)[:128]
|
||||
fact.auto_fulfill_error_message = str(message)[:1000]
|
||||
fact.auto_fulfill_failed_at = now
|
||||
detail = dict(fact.detail_json or {})
|
||||
detail['auto_fulfill_failed'] = True
|
||||
detail['auto_fulfill_error_code'] = str(error_code)[:128]
|
||||
detail['auto_fulfill_error_message'] = str(message)[:1000]
|
||||
detail['auto_fulfill_failed_at'] = now.isoformat() + 'Z'
|
||||
fact.detail_json = detail
|
||||
fact.updated_at = now
|
||||
|
||||
row = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.filter_by(review_case_id=int(case.id), line_key=key_s, is_active=True)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
continue
|
||||
payload = dict(row.snapshot_json or {})
|
||||
payload['auto_fulfill_failed'] = True
|
||||
payload['auto_fulfill_error_code'] = str(error_code)[:128]
|
||||
payload['auto_fulfill_error_message'] = str(message)[:1000]
|
||||
payload['auto_fulfill_failed_at'] = now.isoformat() + 'Z'
|
||||
row.snapshot_json = payload
|
||||
row.updated_at = now
|
||||
|
||||
|
||||
def coordinate_post_ot_auto_fulfill(
|
||||
*,
|
||||
task: ShippingNotice | None = None,
|
||||
case: ShippingOrderReviewCase | None = None,
|
||||
trigger: str = 'inventory_ready',
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
幂等协调:收集 eligible 行并批量创建 post-OT wave,再调度本 wave 推进。
|
||||
|
||||
Args:
|
||||
task: 正式 OT;与 case 至少提供一个。
|
||||
case: 复核 Case。
|
||||
trigger: inventory_ready | ot_created | compensation。
|
||||
|
||||
Returns:
|
||||
status / accepted / skipped / reason。
|
||||
"""
|
||||
case_no_hint = None
|
||||
if case is None and task is not None:
|
||||
case = resolve_review_case_for_task(task)
|
||||
if case is not None:
|
||||
case_no_hint = str(case.case_no)
|
||||
if case is None:
|
||||
return {'status': 'skipped', 'reason': 'review_case_not_found', 'trigger': trigger}
|
||||
|
||||
if not line_auto_fulfill_enabled():
|
||||
return {
|
||||
'status': 'skipped',
|
||||
'reason': 'line_auto_fulfill_disabled',
|
||||
'trigger': trigger,
|
||||
'case_no': case.case_no,
|
||||
}
|
||||
|
||||
eligible = list_eligible_post_ot_line_keys(case)
|
||||
if not eligible:
|
||||
return {
|
||||
'status': 'idle',
|
||||
'reason': 'no_eligible_lines',
|
||||
'trigger': trigger,
|
||||
'case_no': case.case_no,
|
||||
'accepted_line_keys': [],
|
||||
}
|
||||
|
||||
idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}'
|
||||
try:
|
||||
# [STEP 1] 整波创建(失败则整波回滚)
|
||||
result = create_post_ot_fulfillment_wave(
|
||||
case_no=str(case.case_no),
|
||||
line_keys=eligible,
|
||||
decision_source='system',
|
||||
actor_user_id=None,
|
||||
reason=f'auto_fulfill:{trigger}',
|
||||
idempotency_key=idem_key,
|
||||
)
|
||||
# [STEP 2] 仅调度本 wave 推进(禁止 confirm 专用推进)
|
||||
progress = schedule_post_ot_wave_progress(
|
||||
task_no=str(result.get('task_no') or ''),
|
||||
wave_no=result.get('wave_no'),
|
||||
line_keys=list(result.get('accepted_line_keys') or eligible),
|
||||
review_case_id=int(result.get('review_case_id') or case.id),
|
||||
idempotency_row_id=result.get('idempotency_row_id'),
|
||||
request_idempotency_key=str(result.get('idempotency_key') or idem_key),
|
||||
commit=False,
|
||||
)
|
||||
db.session.flush()
|
||||
return {
|
||||
'status': 'ok',
|
||||
'trigger': trigger,
|
||||
'case_no': case.case_no,
|
||||
'wave_progress': progress,
|
||||
**{k: result.get(k) for k in (
|
||||
'task_no', 'wave_no', 'accepted_line_keys', 'skipped_line_keys',
|
||||
'idempotency_row_id', 'idempotent_replay',
|
||||
)},
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# [STEP 3] 整波回滚,再独立写失败事实
|
||||
db.session.rollback()
|
||||
refreshed = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=str(case_no_hint or ''))
|
||||
.first()
|
||||
)
|
||||
if refreshed is not None:
|
||||
_mark_auto_fulfill_failed(
|
||||
refreshed,
|
||||
line_keys=eligible,
|
||||
error_code=getattr(exc, 'code', None) or 'SHIPPING.AUTO_FULFILL_FAILED',
|
||||
message=str(exc)[:1000],
|
||||
)
|
||||
db.session.flush()
|
||||
return {
|
||||
'status': 'failed',
|
||||
'trigger': trigger,
|
||||
'case_no': case_no_hint,
|
||||
'error': str(exc)[:500],
|
||||
'eligible_line_keys': eligible,
|
||||
}
|
||||
|
||||
|
||||
def enqueue_post_ot_auto_fulfill_job(
|
||||
*,
|
||||
task_no: str,
|
||||
trigger: str = 'inventory_ready',
|
||||
commit: bool = False,
|
||||
) -> int | None:
|
||||
"""
|
||||
入队自动履约协调 Job;flag 关闭时不入队。
|
||||
|
||||
Returns:
|
||||
job_id 或 None。
|
||||
"""
|
||||
if not line_auto_fulfill_enabled():
|
||||
return None
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
|
||||
|
||||
normalized = str(task_no or '').strip().upper()
|
||||
if not normalized:
|
||||
return None
|
||||
return enqueue(
|
||||
JobType.SHIPPING_LINE_AUTO_FULFILL,
|
||||
{'task_no': normalized, 'trigger': str(trigger or 'inventory_ready')},
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
business_ref=normalized,
|
||||
message='OT 后行级自动履约协调',
|
||||
max_attempts=3,
|
||||
commit=commit,
|
||||
)
|
||||
@@ -0,0 +1,258 @@
|
||||
"""
|
||||
services/shipping_notice/line_inventory_match_persistence.py
|
||||
|
||||
用途:inventory_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。
|
||||
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
|
||||
逻辑:由 fulfillment_workflow.match_inventory 调用;按 draft line_key(行序)落库;
|
||||
新快照新增行并切换 is_current;不覆盖历史快照事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderReviewCase,
|
||||
)
|
||||
|
||||
|
||||
def _draft_line_keys_by_index(case: ShippingOrderReviewCase | None) -> dict[int, str]:
|
||||
"""Case 草稿行序 → line_key。"""
|
||||
if case is None or case.current_draft is None:
|
||||
return {}
|
||||
out: dict[int, str] = {}
|
||||
for idx, line in enumerate(list(case.current_draft.lines_json or [])):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}'
|
||||
out[idx] = key
|
||||
return out
|
||||
|
||||
|
||||
def resolve_review_case_for_task(task: ShippingNotice) -> ShippingOrderReviewCase | None:
|
||||
"""
|
||||
反查确认到该 OT 的 Review Case。
|
||||
|
||||
Args:
|
||||
task: 正式 ShippingNotice。
|
||||
|
||||
Returns:
|
||||
Case 或 None。
|
||||
"""
|
||||
return (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(confirmed_task_id=int(task.id))
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def map_disposition_to_match_codes(
|
||||
*,
|
||||
disposition: str,
|
||||
part_number: Any,
|
||||
reservation_id: Any,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
将 STP disposition 映射为 match_result + inventory_status。
|
||||
|
||||
核心逻辑:缺料号/预约单 → invalid_key;multi_file_conflict → source_conflict;
|
||||
not_found(键完整)→ ready+not_found;ok/shortage → ready+matched。
|
||||
"""
|
||||
disp = str(disposition or '').strip()
|
||||
part = str(part_number or '').strip()
|
||||
res = str(reservation_id or '').strip()
|
||||
if disp == 'multi_file_conflict':
|
||||
return 'source_conflict', 'source_conflict'
|
||||
if not part or not res:
|
||||
return 'invalid_key', 'invalid_key'
|
||||
if disp == 'not_found':
|
||||
return 'not_found', 'ready'
|
||||
if disp in {'ok', 'shortage'}:
|
||||
return 'matched', 'ready'
|
||||
return 'result_missing', 'unavailable'
|
||||
|
||||
|
||||
def persist_line_inventory_match_facts(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
match_payload: dict[str, Any],
|
||||
inventory_snapshot_id: int | None = None,
|
||||
matching_rule_version: str | None = 'stp_line_v2',
|
||||
) -> list[ShippingNoticeLineInventoryMatch]:
|
||||
"""
|
||||
将 match_order_lines_across_candidates 结果持久化为当前事实。
|
||||
|
||||
核心逻辑:按 line_index 解析 draft line_key;同快照幂等更新;否则新增并切换 is_current;
|
||||
无 inventory_snapshot_id 时禁止写入 ready/not_found;单位写入事实列。
|
||||
"""
|
||||
case = resolve_review_case_for_task(task)
|
||||
keys_by_index = _draft_line_keys_by_index(case)
|
||||
snap_id = inventory_snapshot_id
|
||||
if snap_id is None and getattr(task, 'inventory_snapshot_id', None) is not None:
|
||||
snap_id = int(task.inventory_snapshot_id)
|
||||
|
||||
line_results = [
|
||||
item for item in list(match_payload.get('line_results') or []) if isinstance(item, dict)
|
||||
]
|
||||
resolutions = [
|
||||
item for item in list(match_payload.get('resolutions') or []) if isinstance(item, dict)
|
||||
]
|
||||
res_by_index = {
|
||||
int(item.get('line_index')): item
|
||||
for item in resolutions
|
||||
if item.get('line_index') is not None
|
||||
}
|
||||
|
||||
written: list[ShippingNoticeLineInventoryMatch] = []
|
||||
now = datetime.utcnow()
|
||||
|
||||
for result in line_results:
|
||||
try:
|
||||
index = int(result.get('line_index'))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
res = res_by_index.get(index) or {}
|
||||
line_key = str(
|
||||
res.get('line_key')
|
||||
or keys_by_index.get(index)
|
||||
or f'line-{index + 1}'
|
||||
).strip()
|
||||
if not line_key:
|
||||
continue
|
||||
|
||||
match_result, inventory_status = map_disposition_to_match_codes(
|
||||
disposition=str(result.get('disposition') or res.get('disposition') or ''),
|
||||
part_number=result.get('part_number') or res.get('part_number'),
|
||||
reservation_id=result.get('reservation_id') or res.get('effective_reservation_id'),
|
||||
)
|
||||
|
||||
required = result.get('required_qty')
|
||||
available = result.get('available_qty')
|
||||
shortage = result.get('shortage_qty')
|
||||
|
||||
# [STEP] BE-5:无库存快照时禁止 ready/not_found(不得规范为 0)
|
||||
if snap_id is None and (
|
||||
inventory_status == 'ready'
|
||||
or match_result in {'matched', 'not_found'}
|
||||
):
|
||||
match_result, inventory_status = 'result_missing', 'unavailable'
|
||||
available = None
|
||||
shortage = None
|
||||
|
||||
# [STEP] ready+not_found:强制 available=0(与投影契约一致)
|
||||
if match_result == 'not_found' and inventory_status == 'ready':
|
||||
available = 0
|
||||
if required is not None:
|
||||
shortage = required
|
||||
|
||||
unit_raw = (
|
||||
result.get('unit')
|
||||
or result.get('uom')
|
||||
or res.get('unit')
|
||||
or res.get('uom')
|
||||
)
|
||||
unit_value = str(unit_raw or '').strip()[:32] or None
|
||||
|
||||
# [STEP] 同 OT+行+快照:更新;否则新建并撤销旧 current
|
||||
existing = None
|
||||
if snap_id is not None:
|
||||
existing = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(
|
||||
task_id=int(task.id),
|
||||
line_key=line_key,
|
||||
inventory_snapshot_id=int(snap_id),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing is None and snap_id is None:
|
||||
existing = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
|
||||
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id.is_(None))
|
||||
.first()
|
||||
)
|
||||
|
||||
if existing is None:
|
||||
(
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
|
||||
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
row = ShippingNoticeLineInventoryMatch(
|
||||
task_id=int(task.id),
|
||||
review_case_id=int(case.id) if case is not None else None,
|
||||
line_key=line_key,
|
||||
line_index=index,
|
||||
inventory_snapshot_id=int(snap_id) if snap_id is not None else None,
|
||||
match_result=match_result,
|
||||
inventory_status=inventory_status,
|
||||
required_qty=str(required) if required is not None else None,
|
||||
available_qty=str(available) if available is not None else None,
|
||||
shortage_qty=str(shortage) if shortage is not None else None,
|
||||
reservation_id=str(result.get('reservation_id') or '')[:128] or None,
|
||||
part_number=str(result.get('part_number') or '')[:128] or None,
|
||||
unit=unit_value,
|
||||
matching_rule_version=str(matching_rule_version or '')[:64] or None,
|
||||
inventory_source_code=(
|
||||
str(result.get('resolved_inventory_source_code') or '')[:64] or None
|
||||
),
|
||||
is_current=True,
|
||||
matched_at=now,
|
||||
detail_json={
|
||||
'disposition': result.get('disposition'),
|
||||
'line_status': result.get('line_status'),
|
||||
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
|
||||
'inventory_file_no': result.get('inventory_file_no'),
|
||||
'inventory_row_ref': result.get('inventory_row_ref'),
|
||||
'snapshot_missing': snap_id is None,
|
||||
},
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(row)
|
||||
written.append(row)
|
||||
else:
|
||||
existing.match_result = match_result
|
||||
existing.inventory_status = inventory_status
|
||||
existing.required_qty = str(required) if required is not None else None
|
||||
existing.available_qty = str(available) if available is not None else None
|
||||
existing.shortage_qty = str(shortage) if shortage is not None else None
|
||||
existing.reservation_id = str(result.get('reservation_id') or '')[:128] or None
|
||||
existing.part_number = str(result.get('part_number') or '')[:128] or None
|
||||
existing.unit = unit_value
|
||||
existing.matching_rule_version = str(matching_rule_version or '')[:64] or None
|
||||
existing.inventory_source_code = (
|
||||
str(result.get('resolved_inventory_source_code') or '')[:64] or None
|
||||
)
|
||||
existing.is_current = True
|
||||
existing.matched_at = now
|
||||
existing.updated_at = now
|
||||
existing.detail_json = {
|
||||
'disposition': result.get('disposition'),
|
||||
'line_status': result.get('line_status'),
|
||||
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
|
||||
'inventory_file_no': result.get('inventory_file_no'),
|
||||
'inventory_row_ref': result.get('inventory_row_ref'),
|
||||
'snapshot_missing': snap_id is None,
|
||||
}
|
||||
# 确保同 task+line 仅本条 current
|
||||
(
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.line_key == line_key,
|
||||
ShippingNoticeLineInventoryMatch.id != int(existing.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
)
|
||||
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
written.append(existing)
|
||||
|
||||
db.session.flush()
|
||||
return written
|
||||
@@ -0,0 +1,562 @@
|
||||
"""
|
||||
services/shipping_notice/line_inventory_match_projection.py
|
||||
|
||||
用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。
|
||||
依赖:ShippingNoticeLineInventoryMatch、Config 自动履约开关。
|
||||
逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用;
|
||||
ready+not_found→available=0;result_missing 不得转 0;
|
||||
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
|
||||
|
||||
MATCH_NOT_FOUND = 'not_found'
|
||||
MATCH_MATCHED = 'matched'
|
||||
MATCH_RESULT_MISSING = 'result_missing'
|
||||
MATCH_PREPARING = 'preparing'
|
||||
MATCH_SOURCE_CONFLICT = 'source_conflict'
|
||||
MATCH_INVALID_KEY = 'invalid_key'
|
||||
MATCH_MAPPING_FAILED = 'mapping_failed'
|
||||
MATCH_UNAVAILABLE = 'unavailable'
|
||||
|
||||
STATUS_READY = 'ready'
|
||||
STATUS_PREPARING = 'preparing'
|
||||
STATUS_MAPPING_FAILED = 'mapping_failed'
|
||||
STATUS_SOURCE_CONFLICT = 'source_conflict'
|
||||
STATUS_UNAVAILABLE = 'unavailable'
|
||||
STATUS_INVALID_KEY = 'invalid_key'
|
||||
|
||||
ACTION_RETRY_PREPARATION = 'retry_inventory_preparation'
|
||||
ACTION_RETRY_MATCHING = 'retry_inventory_matching'
|
||||
ACTION_CLOSE = 'close_unfulfillable'
|
||||
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail'
|
||||
|
||||
SOURCE_STATUS_RESOLVED = 'resolved'
|
||||
SOURCE_STATUS_RESOLVING = 'resolving'
|
||||
SOURCE_STATUS_UNRECOGNIZED = 'unrecognized'
|
||||
SOURCE_STATUS_CONFLICT = 'conflict'
|
||||
SOURCE_STATUS_UNAVAILABLE = 'unavailable'
|
||||
|
||||
|
||||
def line_auto_fulfill_enabled() -> bool:
|
||||
"""读取行级自动履约总闸;默认关闭。"""
|
||||
try:
|
||||
from flask import current_app
|
||||
|
||||
return bool(current_app.config.get('SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED', False))
|
||||
except Exception:
|
||||
from app.core.config.settings import Config
|
||||
|
||||
return bool(getattr(Config, 'SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED', False))
|
||||
|
||||
|
||||
def _parse_qty(value: Any) -> Decimal | None:
|
||||
"""解析数量;空/非法返回 None。"""
|
||||
text = str(value if value is not None else '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return Decimal(text)
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def normalize_match_quantities(
|
||||
*,
|
||||
match_result: str | None,
|
||||
inventory_status: str | None,
|
||||
required_qty: Any,
|
||||
available_qty: Any,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按冻结语义规范 available/shortage。
|
||||
|
||||
核心逻辑:仅 ready+not_found 将 available 规范为 0;result_missing 保持 null 且不标短缺。
|
||||
"""
|
||||
req = _parse_qty(required_qty)
|
||||
status = str(inventory_status or '').strip() or None
|
||||
result = str(match_result or '').strip() or None
|
||||
|
||||
if status != STATUS_READY:
|
||||
return {
|
||||
'available_qty': None,
|
||||
'shortage_qty': None,
|
||||
'is_shortage': False,
|
||||
'display_available': 'pending',
|
||||
}
|
||||
|
||||
if result == MATCH_NOT_FOUND:
|
||||
return {
|
||||
'available_qty': '0',
|
||||
'shortage_qty': str(req) if req is not None else None,
|
||||
'is_shortage': req is not None and req > 0,
|
||||
'display_available': 'number',
|
||||
}
|
||||
|
||||
if result in {
|
||||
MATCH_RESULT_MISSING,
|
||||
MATCH_PREPARING,
|
||||
MATCH_SOURCE_CONFLICT,
|
||||
MATCH_INVALID_KEY,
|
||||
MATCH_MAPPING_FAILED,
|
||||
MATCH_UNAVAILABLE,
|
||||
None,
|
||||
'',
|
||||
}:
|
||||
return {
|
||||
'available_qty': None,
|
||||
'shortage_qty': None,
|
||||
'is_shortage': False,
|
||||
'display_available': 'pending',
|
||||
}
|
||||
|
||||
avail = _parse_qty(available_qty)
|
||||
if avail is None:
|
||||
return {
|
||||
'available_qty': None,
|
||||
'shortage_qty': None,
|
||||
'is_shortage': False,
|
||||
'display_available': 'pending',
|
||||
}
|
||||
shortage = None
|
||||
is_shortage = False
|
||||
if req is not None:
|
||||
diff = req - avail
|
||||
if diff > 0:
|
||||
shortage = str(diff)
|
||||
is_shortage = True
|
||||
else:
|
||||
shortage = '0'
|
||||
return {
|
||||
'available_qty': str(avail),
|
||||
'shortage_qty': shortage,
|
||||
'is_shortage': is_shortage,
|
||||
'display_available': 'number',
|
||||
}
|
||||
|
||||
|
||||
def project_inventory_source(
|
||||
*,
|
||||
inventory_status: str | None,
|
||||
match_result: str | None,
|
||||
source_code: str | None,
|
||||
source_labels: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
投影只读库存源对象;前端不得自行推断。
|
||||
|
||||
Returns:
|
||||
code / label / status / source。
|
||||
"""
|
||||
code = str(source_code or '').strip() or None
|
||||
labels = source_labels or {}
|
||||
label = str(labels.get(code) or '').strip() if code else ''
|
||||
status = str(inventory_status or '').strip()
|
||||
result = str(match_result or '').strip()
|
||||
|
||||
if status == STATUS_SOURCE_CONFLICT or result == MATCH_SOURCE_CONFLICT:
|
||||
source_status = SOURCE_STATUS_CONFLICT
|
||||
elif status == STATUS_INVALID_KEY or result == MATCH_INVALID_KEY:
|
||||
source_status = SOURCE_STATUS_UNRECOGNIZED
|
||||
elif status == STATUS_UNAVAILABLE or result == MATCH_UNAVAILABLE:
|
||||
source_status = SOURCE_STATUS_UNAVAILABLE
|
||||
elif status == STATUS_PREPARING or result == MATCH_PREPARING or not code:
|
||||
source_status = SOURCE_STATUS_RESOLVING if not code else (
|
||||
SOURCE_STATUS_RESOLVED if code else SOURCE_STATUS_RESOLVING
|
||||
)
|
||||
if not code and status in {STATUS_PREPARING, ''} and result in {MATCH_PREPARING, ''}:
|
||||
source_status = SOURCE_STATUS_RESOLVING
|
||||
elif not code:
|
||||
source_status = SOURCE_STATUS_UNRECOGNIZED
|
||||
else:
|
||||
source_status = SOURCE_STATUS_RESOLVED if code else SOURCE_STATUS_UNRECOGNIZED
|
||||
|
||||
if code and source_status == SOURCE_STATUS_RESOLVING and status == STATUS_READY:
|
||||
source_status = SOURCE_STATUS_RESOLVED
|
||||
|
||||
return {
|
||||
'code': code,
|
||||
'label': label or None,
|
||||
'status': source_status,
|
||||
'source': 'inventory_source_clue',
|
||||
}
|
||||
|
||||
|
||||
def project_user_line_status(
|
||||
*,
|
||||
inventory_status: str | None,
|
||||
match_result: str | None,
|
||||
is_shortage: bool,
|
||||
stored_line_status: str | None,
|
||||
decision_source: str | None = None,
|
||||
auto_fulfill_failed: bool = False,
|
||||
inventory_rpa_running: bool = False,
|
||||
file_expired: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
将存储态 + 库存事实投影为用户态状态码(文案由前端 i18n 映射)。
|
||||
|
||||
Returns:
|
||||
acquiring_inventory / inventory_file_missing / inventory_file_expired /
|
||||
inventory_match_failed / inventory_source_unrecognized / source_conflict /
|
||||
shortage / inventory_matched / auto_fulfilling / wave_created / fulfilled /
|
||||
closed / auto_fulfill_failed 等。
|
||||
"""
|
||||
if auto_fulfill_failed:
|
||||
return 'auto_fulfill_failed'
|
||||
stored = str(stored_line_status or '').strip()
|
||||
if stored in {'closed_unfulfillable'}:
|
||||
return 'closed'
|
||||
if stored in {'fulfilled'}:
|
||||
return 'fulfilled'
|
||||
if stored in {'task_created'}:
|
||||
return 'wave_created'
|
||||
if stored in {'ready_to_fulfill'} and decision_source == 'system':
|
||||
return 'auto_fulfilling'
|
||||
|
||||
status = str(inventory_status or '').strip()
|
||||
result = str(match_result or '').strip()
|
||||
# [STEP] RPA 运行中才标「获取库存中」;否则 preparing 按文件未准备(可重试)。
|
||||
if inventory_rpa_running:
|
||||
return 'acquiring_inventory'
|
||||
if file_expired:
|
||||
return 'inventory_file_expired'
|
||||
if status == STATUS_SOURCE_CONFLICT or result == MATCH_SOURCE_CONFLICT:
|
||||
return 'source_conflict'
|
||||
if status == STATUS_INVALID_KEY or result == MATCH_INVALID_KEY:
|
||||
return 'inventory_source_unrecognized'
|
||||
if status == STATUS_MAPPING_FAILED or result == MATCH_MAPPING_FAILED:
|
||||
return 'inventory_match_failed'
|
||||
if status in {STATUS_UNAVAILABLE, STATUS_PREPARING} or result in {
|
||||
MATCH_UNAVAILABLE, MATCH_RESULT_MISSING, MATCH_PREPARING,
|
||||
}:
|
||||
return 'inventory_file_missing'
|
||||
if is_shortage or result == MATCH_NOT_FOUND:
|
||||
return 'shortage'
|
||||
if status == STATUS_READY and result == MATCH_MATCHED:
|
||||
return 'inventory_matched'
|
||||
if stored in {'ready_to_fulfill'}:
|
||||
return 'auto_fulfilling' if decision_source == 'system' else 'inventory_matched'
|
||||
if stored in {'waiting_inventory'}:
|
||||
return 'shortage'
|
||||
return stored or 'acquiring_inventory'
|
||||
|
||||
|
||||
def resolve_inventory_allowed_actions(
|
||||
*,
|
||||
has_formal_ot: bool,
|
||||
inventory_status: str | None,
|
||||
match_result: str | None,
|
||||
is_shortage: bool,
|
||||
stored_line_status: str | None,
|
||||
user_line_status: str | None,
|
||||
inventory_rpa_running: bool = False,
|
||||
has_usable_snapshot: bool = False,
|
||||
) -> list[str]:
|
||||
"""
|
||||
仅下发库存获取/匹配动作;禁止 wait/change_source/view_inventory。
|
||||
|
||||
矩阵:RPA 运行中→空;成功/终态→空;文件问题→preparation;
|
||||
文件有效匹配失败→preparation+matching;短缺→preparation。
|
||||
"""
|
||||
stored = str(stored_line_status or '').strip()
|
||||
user_status = str(user_line_status or '').strip()
|
||||
if not has_formal_ot:
|
||||
return []
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed',
|
||||
}:
|
||||
return []
|
||||
if inventory_rpa_running or user_status == 'acquiring_inventory':
|
||||
return []
|
||||
|
||||
status = str(inventory_status or '').strip()
|
||||
result = str(match_result or '').strip()
|
||||
|
||||
if user_status == 'inventory_matched' and not is_shortage:
|
||||
return []
|
||||
if status == STATUS_READY and result == MATCH_MATCHED and not is_shortage:
|
||||
return []
|
||||
|
||||
if is_shortage or result == MATCH_NOT_FOUND or user_status == 'shortage':
|
||||
return [ACTION_RETRY_PREPARATION]
|
||||
|
||||
if (
|
||||
status == STATUS_MAPPING_FAILED
|
||||
or result == MATCH_MAPPING_FAILED
|
||||
or user_status == 'inventory_match_failed'
|
||||
):
|
||||
actions = [ACTION_RETRY_PREPARATION]
|
||||
if has_usable_snapshot:
|
||||
actions.append(ACTION_RETRY_MATCHING)
|
||||
return actions
|
||||
|
||||
if user_status in {
|
||||
'inventory_file_missing',
|
||||
'inventory_file_expired',
|
||||
'inventory_source_unrecognized',
|
||||
} or status in {STATUS_UNAVAILABLE, STATUS_PREPARING, STATUS_INVALID_KEY} or result in {
|
||||
MATCH_UNAVAILABLE,
|
||||
MATCH_PREPARING,
|
||||
MATCH_RESULT_MISSING,
|
||||
MATCH_INVALID_KEY,
|
||||
}:
|
||||
return [ACTION_RETRY_PREPARATION]
|
||||
|
||||
if status == STATUS_SOURCE_CONFLICT or result == MATCH_SOURCE_CONFLICT:
|
||||
# 客户指定源冲突:只展示状态,不开放换源;可重试获取以刷新。
|
||||
return [ACTION_RETRY_PREPARATION]
|
||||
|
||||
if user_status == 'auto_fulfill_failed':
|
||||
return [ACTION_RETRY_PREPARATION, ACTION_RETRY_MATCHING]
|
||||
|
||||
return []
|
||||
|
||||
|
||||
def resolve_line_allowed_actions(
|
||||
*,
|
||||
has_formal_ot: bool,
|
||||
stored_line_status: str | None,
|
||||
user_line_status: str | None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
行生命周期动作;本轮仅 close_unfulfillable(已完成/已关闭不展示)。
|
||||
"""
|
||||
if not has_formal_ot:
|
||||
return []
|
||||
stored = str(stored_line_status or '').strip()
|
||||
user_status = str(user_line_status or '').strip()
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed',
|
||||
}:
|
||||
if user_status in {'wave_created', 'fulfilled'}:
|
||||
return [ACTION_VIEW_FULFILLMENT] if user_status != 'closed' else []
|
||||
return []
|
||||
return [ACTION_CLOSE]
|
||||
|
||||
|
||||
def resolve_allowed_actions(
|
||||
*,
|
||||
has_formal_ot: bool,
|
||||
inventory_status: str | None,
|
||||
match_result: str | None,
|
||||
is_shortage: bool,
|
||||
stored_line_status: str | None,
|
||||
user_line_status: str | None,
|
||||
can_manual_fulfill: bool,
|
||||
inventory_rpa_running: bool = False,
|
||||
has_usable_snapshot: bool = False,
|
||||
) -> list[str]:
|
||||
"""
|
||||
兼容旧单一 allowed_actions:合并 inventory + line 域(测试/旧调用方)。
|
||||
|
||||
新前端应读 inventory_allowed_actions / line_allowed_actions。
|
||||
"""
|
||||
inv = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=has_formal_ot,
|
||||
inventory_status=inventory_status,
|
||||
match_result=match_result,
|
||||
is_shortage=is_shortage,
|
||||
stored_line_status=stored_line_status,
|
||||
user_line_status=user_line_status,
|
||||
inventory_rpa_running=inventory_rpa_running,
|
||||
has_usable_snapshot=has_usable_snapshot,
|
||||
)
|
||||
line = resolve_line_allowed_actions(
|
||||
has_formal_ot=has_formal_ot,
|
||||
stored_line_status=stored_line_status,
|
||||
user_line_status=user_line_status,
|
||||
)
|
||||
# can_manual_fulfill 保留参数兼容,本轮不开放 fulfill 按钮。
|
||||
_ = can_manual_fulfill
|
||||
return [*inv, *line]
|
||||
|
||||
|
||||
def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str, Any]]:
|
||||
"""加载 OT 当前行匹配事实,键为 line_key。"""
|
||||
if task_id is None:
|
||||
return {}
|
||||
rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task_id), is_current=True)
|
||||
.all()
|
||||
)
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for row in rows:
|
||||
key = str(row.line_key or '').strip()
|
||||
if not key:
|
||||
continue
|
||||
out[key] = serialize_match_fact(row)
|
||||
return out
|
||||
|
||||
|
||||
def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]:
|
||||
"""将 ORM 行序列化为投影输入。"""
|
||||
return {
|
||||
'id': int(row.id),
|
||||
'task_id': int(row.task_id),
|
||||
'review_case_id': int(row.review_case_id) if row.review_case_id is not None else None,
|
||||
'line_key': str(row.line_key),
|
||||
'line_index': row.line_index,
|
||||
'inventory_snapshot_id': (
|
||||
int(row.inventory_snapshot_id) if row.inventory_snapshot_id is not None else None
|
||||
),
|
||||
'match_result': str(row.match_result or ''),
|
||||
'inventory_status': str(row.inventory_status or ''),
|
||||
'required_qty': row.required_qty,
|
||||
'available_qty': row.available_qty,
|
||||
'shortage_qty': row.shortage_qty,
|
||||
'reservation_id': row.reservation_id,
|
||||
'part_number': row.part_number,
|
||||
'unit': row.unit,
|
||||
'matching_rule_version': row.matching_rule_version,
|
||||
'inventory_source_code': row.inventory_source_code,
|
||||
'matched_at': row.matched_at.isoformat() if row.matched_at else None,
|
||||
'is_current': bool(row.is_current),
|
||||
'detail_json': dict(row.detail_json or {}),
|
||||
'auto_fulfill_failed': bool(getattr(row, 'auto_fulfill_failed', False)),
|
||||
'auto_fulfill_error_code': getattr(row, 'auto_fulfill_error_code', None),
|
||||
'auto_fulfill_error_message': getattr(row, 'auto_fulfill_error_message', None),
|
||||
'auto_fulfill_failed_at': (
|
||||
row.auto_fulfill_failed_at.isoformat()
|
||||
if getattr(row, 'auto_fulfill_failed_at', None)
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def project_line_inventory_view(
|
||||
*,
|
||||
has_formal_ot: bool,
|
||||
fact: dict[str, Any] | None,
|
||||
required_qty: Any,
|
||||
stored_line_status: str | None,
|
||||
decision_source: str | None,
|
||||
can_fulfill_complete_line: bool,
|
||||
auto_fulfill_failed: bool = False,
|
||||
auto_fulfill_error_message: str | None = None,
|
||||
inventory_rpa_running: bool = False,
|
||||
source_labels: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单行库存+履约用户投影。
|
||||
|
||||
Returns:
|
||||
inventory_* / inventory_source / inventory_allowed_actions /
|
||||
line_allowed_actions / user_line_status 等。
|
||||
"""
|
||||
if not has_formal_ot:
|
||||
user_status = project_user_line_status(
|
||||
inventory_status=None,
|
||||
match_result=None,
|
||||
is_shortage=False,
|
||||
stored_line_status=stored_line_status,
|
||||
decision_source=decision_source,
|
||||
auto_fulfill_failed=False,
|
||||
)
|
||||
return {
|
||||
'inventory_status': None,
|
||||
'match_result': None,
|
||||
'available_qty': None,
|
||||
'shortage_qty': None,
|
||||
'is_shortage': False,
|
||||
'display_available': 'pending',
|
||||
'inventory_snapshot_id': None,
|
||||
'inventory_checked_at': None,
|
||||
'inventory_source': {
|
||||
'code': None,
|
||||
'label': None,
|
||||
'status': SOURCE_STATUS_RESOLVING,
|
||||
'source': 'inventory_source_clue',
|
||||
},
|
||||
'user_line_status': user_status,
|
||||
'decision_source': decision_source,
|
||||
'inventory_allowed_actions': [],
|
||||
'line_allowed_actions': [],
|
||||
'allowed_actions': [],
|
||||
'auto_fulfill_error_message': None,
|
||||
}
|
||||
|
||||
if not isinstance(fact, dict):
|
||||
fact = {
|
||||
'match_result': MATCH_PREPARING,
|
||||
'inventory_status': STATUS_PREPARING,
|
||||
'available_qty': None,
|
||||
'inventory_snapshot_id': None,
|
||||
'matched_at': None,
|
||||
'inventory_source_code': None,
|
||||
'detail_json': {},
|
||||
}
|
||||
|
||||
match_result = str(fact.get('match_result') or MATCH_RESULT_MISSING)
|
||||
inventory_status = str(fact.get('inventory_status') or STATUS_PREPARING)
|
||||
detail = dict(fact.get('detail_json') or {}) if isinstance(fact.get('detail_json'), dict) else {}
|
||||
file_expired = bool(detail.get('file_expired') or detail.get('snapshot_expired'))
|
||||
has_usable_snapshot = fact.get('inventory_snapshot_id') is not None and not file_expired
|
||||
|
||||
qty = normalize_match_quantities(
|
||||
match_result=match_result,
|
||||
inventory_status=inventory_status,
|
||||
required_qty=required_qty if required_qty is not None else fact.get('required_qty'),
|
||||
available_qty=fact.get('available_qty'),
|
||||
)
|
||||
user_status = project_user_line_status(
|
||||
inventory_status=inventory_status,
|
||||
match_result=match_result,
|
||||
is_shortage=bool(qty['is_shortage']),
|
||||
stored_line_status=stored_line_status,
|
||||
decision_source=decision_source,
|
||||
auto_fulfill_failed=bool(auto_fulfill_failed),
|
||||
inventory_rpa_running=bool(inventory_rpa_running),
|
||||
file_expired=file_expired,
|
||||
)
|
||||
can_manual = bool(can_fulfill_complete_line) and inventory_status == STATUS_READY and not qty['is_shortage']
|
||||
inv_actions = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
inventory_status=inventory_status,
|
||||
match_result=match_result,
|
||||
is_shortage=bool(qty['is_shortage']),
|
||||
stored_line_status=stored_line_status,
|
||||
user_line_status=user_status,
|
||||
inventory_rpa_running=bool(inventory_rpa_running),
|
||||
has_usable_snapshot=has_usable_snapshot,
|
||||
)
|
||||
line_actions = resolve_line_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
stored_line_status=stored_line_status,
|
||||
user_line_status=user_status,
|
||||
)
|
||||
source = project_inventory_source(
|
||||
inventory_status=inventory_status,
|
||||
match_result=match_result,
|
||||
source_code=fact.get('inventory_source_code'),
|
||||
source_labels=source_labels,
|
||||
)
|
||||
return {
|
||||
'inventory_status': inventory_status,
|
||||
'match_result': match_result,
|
||||
'available_qty': qty['available_qty'],
|
||||
'shortage_qty': qty['shortage_qty'],
|
||||
'is_shortage': bool(qty['is_shortage']),
|
||||
'display_available': qty['display_available'],
|
||||
'inventory_snapshot_id': fact.get('inventory_snapshot_id'),
|
||||
'inventory_checked_at': fact.get('matched_at'),
|
||||
'inventory_source_code': fact.get('inventory_source_code'),
|
||||
'inventory_source': source,
|
||||
'matching_rule_version': fact.get('matching_rule_version'),
|
||||
'user_line_status': user_status,
|
||||
'decision_source': decision_source,
|
||||
'inventory_allowed_actions': inv_actions,
|
||||
'line_allowed_actions': line_actions,
|
||||
'allowed_actions': [*inv_actions, *line_actions],
|
||||
'auto_fulfill_error_message': (
|
||||
str(auto_fulfill_error_message)[:1000] if auto_fulfill_error_message else None
|
||||
),
|
||||
'_can_manual_fulfill': can_manual,
|
||||
}
|
||||
@@ -1529,7 +1529,9 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
|
||||
"""
|
||||
判断确认建单后的任务是否仍需自动推进。
|
||||
|
||||
核心逻辑:仍为 created 且已挂正式 Extraction,视为尚未被 auto_progress 消费的悬挂态。
|
||||
核心逻辑:已挂正式 Extraction,且仍停在确认后早期态(created / parsed)。
|
||||
确认路径会先 CONFIRM_PARSE→parsed,故不得仅认 created,否则永远不会入队。
|
||||
重复调度依赖 enqueue 幂等(同 business_ref 有效 Job 不重复入队)。
|
||||
|
||||
Args:
|
||||
task: 发货任务;None 视为不需要。
|
||||
@@ -1539,10 +1541,11 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
|
||||
"""
|
||||
if task is None:
|
||||
return False
|
||||
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
|
||||
if process_status != 'created':
|
||||
if not getattr(task, 'current_order_extraction_id', None):
|
||||
return False
|
||||
return bool(getattr(task, 'current_order_extraction_id', None))
|
||||
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
|
||||
# created:尚未 CONFIRM_PARSE;parsed:刚确认仍待库存推进。
|
||||
return process_status in {'', 'created', 'parsed'}
|
||||
|
||||
|
||||
def resolve_confirm_outcome(progress: dict[str, Any] | None) -> str:
|
||||
|
||||
+313
-17
@@ -1,13 +1,14 @@
|
||||
"""
|
||||
services/shipping_notice/order_review_fulfillment_decision_service.py
|
||||
|
||||
用途:建单前行级履约决定(等待补货 / 完整行先行 / 关闭 / 重开)与履约波次创建。
|
||||
用途:行级履约决定(等待补货 / 完整行先行 / 关闭 / 重开)与履约波次投影。
|
||||
依赖:ShippingOrderReviewLineDecision、order_review_confirmation_service、
|
||||
order_review_draft_service.validate_draft、fulfillment_audit、
|
||||
order_review_draft_service、order_review_workbench_projection、
|
||||
line_inventory_match_projection(OT 行匹配事实)、fulfillment_audit、
|
||||
order_review_resume_service。
|
||||
逻辑:禁止拆分数量;活动决定版本化;波次 Task 仅含选中完整行;
|
||||
fulfill / 建波次均 fail-closed 校验最新库存与 Reservation;
|
||||
task_created/fulfilled 不可 reopen;仅 closed_unfulfillable 可由管理员重开。
|
||||
逻辑:禁止拆分数量;活动决定版本化;投影叠加 inventory_status/match_result/allowed_actions;
|
||||
订单级聚合计数供侧栏主卡;旧 create_fulfillment_wave 仍走 confirm(BE-8 兼容);
|
||||
OT 后自动 wave 另服务;履约「料号」= Schema part_number(内部料号),禁止 reservation 回填。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -97,18 +98,61 @@ def _parse_qty(value: Any) -> Decimal | None:
|
||||
|
||||
|
||||
def _line_reservation_id(draft_line: dict[str, Any], proj: dict[str, Any]) -> str | None:
|
||||
"""解析行有效 Reservation。"""
|
||||
"""解析行有效 Reservation(履约表权威字段 reservation_id)。"""
|
||||
value = str(
|
||||
draft_line.get('reservation_id')
|
||||
or proj.get('reservation_id')
|
||||
or proj.get('effective_reservation_id')
|
||||
or ''
|
||||
).strip()
|
||||
return value or None
|
||||
|
||||
|
||||
def _line_part_number(
|
||||
draft_line: dict[str, Any],
|
||||
proj: dict[str, Any],
|
||||
*,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
解析标准料号(内部料号 / field_code=part_number);禁止用 reservation_id 回填。
|
||||
|
||||
核心逻辑:委托 extract_line_part_number,并传入冻结 Schema 以解析 values[field_id]。
|
||||
"""
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
extract_line_part_number,
|
||||
sanitize_part_number_vs_reservation,
|
||||
)
|
||||
|
||||
part = extract_line_part_number(draft_line, proj, schema_fields=schema_fields)
|
||||
reservation = _line_reservation_id(draft_line, proj)
|
||||
return sanitize_part_number_vs_reservation(
|
||||
part_number=part,
|
||||
reservation_id=reservation,
|
||||
)
|
||||
|
||||
|
||||
def _line_required_qty(
|
||||
draft_line: dict[str, Any],
|
||||
proj: dict[str, Any],
|
||||
*,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> Any:
|
||||
"""
|
||||
解析需求数量(field_code=qty/quantity),与订单明细同源。
|
||||
"""
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
extract_line_required_qty,
|
||||
)
|
||||
|
||||
return extract_line_required_qty(draft_line, proj, schema_fields=schema_fields)
|
||||
|
||||
|
||||
def _assess_line_fulfill_complete(
|
||||
draft_line: dict[str, Any],
|
||||
proj: dict[str, Any],
|
||||
*,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> tuple[bool, str | None, Decimal | None, Decimal | None]:
|
||||
"""
|
||||
判断完整明细行是否可先行履约(fail-closed)。
|
||||
@@ -116,7 +160,7 @@ def _assess_line_fulfill_complete(
|
||||
Returns:
|
||||
(can_fulfill, block_code, required_qty, available_qty)
|
||||
"""
|
||||
req = _parse_qty(draft_line.get('qty') or draft_line.get('quantity') or proj.get('required_qty'))
|
||||
req = _parse_qty(_line_required_qty(draft_line, proj, schema_fields=schema_fields))
|
||||
avail = _parse_qty(proj.get('available_qty'))
|
||||
if req is None:
|
||||
return False, 'SHIPPING.REVIEW_LINE_QTY_REQUIRED', None, avail
|
||||
@@ -137,6 +181,7 @@ def _assert_line_can_fulfill_complete(
|
||||
line_key: str,
|
||||
draft_line: dict[str, Any],
|
||||
proj: dict[str, Any],
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> tuple[Decimal, Decimal]:
|
||||
"""
|
||||
强制完整行可履约;否则抛业务错误。
|
||||
@@ -144,7 +189,11 @@ def _assert_line_can_fulfill_complete(
|
||||
Returns:
|
||||
(required_qty, available_qty)
|
||||
"""
|
||||
ok, code, req, avail = _assess_line_fulfill_complete(draft_line, proj)
|
||||
ok, code, req, avail = _assess_line_fulfill_complete(
|
||||
draft_line,
|
||||
proj,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if not ok or req is None or avail is None:
|
||||
raise ConflictError(
|
||||
'Line cannot fulfill complete quantity with current inventory',
|
||||
@@ -218,6 +267,7 @@ def _serialize_decision(row: ShippingOrderReviewLineDecision) -> dict[str, Any]:
|
||||
'line_index': row.line_index,
|
||||
'decision_version': int(row.decision_version),
|
||||
'decision_code': row.decision_code,
|
||||
'decision_source': getattr(row, 'decision_source', None),
|
||||
'line_status': row.line_status,
|
||||
'is_active': bool(row.is_active),
|
||||
'reason': row.reason,
|
||||
@@ -231,18 +281,123 @@ def _serialize_decision(row: ShippingOrderReviewLineDecision) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def project_review_case_line_decisions(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
def _normalize_schema_fields_map(
|
||||
schema_fields: dict[str, dict[str, Any]] | list[dict[str, Any]] | None,
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
将 list/dict 形态的 Schema 字段统一为 field_id → 定义。
|
||||
|
||||
Args:
|
||||
schema_fields: serialize_review_case 的 fields 列表,或 draft_service 字典。
|
||||
|
||||
Returns:
|
||||
field_id → 字段定义;非法输入返回空 dict。
|
||||
"""
|
||||
if isinstance(schema_fields, dict):
|
||||
return {
|
||||
str(field_id): dict(field)
|
||||
for field_id, field in schema_fields.items()
|
||||
if field_id and isinstance(field, dict)
|
||||
}
|
||||
if isinstance(schema_fields, list):
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for raw in schema_fields:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
field_id = str(raw.get('field_id') or '').strip()
|
||||
if field_id:
|
||||
out[field_id] = dict(raw)
|
||||
return out
|
||||
return {}
|
||||
|
||||
|
||||
def _aggregate_line_fulfillment_counts(lines_out: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""
|
||||
按用户态汇总订单级履约计数(侧栏聚合卡)。
|
||||
|
||||
核心逻辑:系统进度与人工待办分列;短缺与失败不得被「处理中」吞掉。
|
||||
|
||||
Args:
|
||||
lines_out: project_review_case_line_decisions 已投影的行列表。
|
||||
|
||||
Returns:
|
||||
auto_progress_count / manual_pending_count / system_failed_count /
|
||||
inventory_pending_count。
|
||||
"""
|
||||
auto_progress_count = 0
|
||||
manual_pending_count = 0
|
||||
system_failed_count = 0
|
||||
inventory_pending_count = 0
|
||||
for item in lines_out:
|
||||
user_status = str(item.get('user_line_status') or '').strip()
|
||||
if user_status == 'auto_fulfill_failed':
|
||||
system_failed_count += 1
|
||||
elif user_status in {'auto_fulfilling', 'wave_created'}:
|
||||
auto_progress_count += 1
|
||||
elif user_status in {'inventory_pending', 'source_conflict', 'invalid'}:
|
||||
inventory_pending_count += 1
|
||||
elif user_status in {'shortage', 'pending_decision'} or item.get('is_shortage'):
|
||||
manual_pending_count += 1
|
||||
elif user_status == 'ready_to_fulfill' and item.get('line_status') not in _TERMINAL_ACTIVE:
|
||||
# flag 关时仍可能有可履约但未入波次的行,计入人工待办以便侧栏提示。
|
||||
manual_pending_count += 1
|
||||
return {
|
||||
'auto_progress_count': auto_progress_count,
|
||||
'manual_pending_count': manual_pending_count,
|
||||
'system_failed_count': system_failed_count,
|
||||
'inventory_pending_count': inventory_pending_count,
|
||||
}
|
||||
|
||||
|
||||
def project_review_case_line_decisions(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
schema_fields: dict[str, dict[str, Any]] | list[dict[str, Any]] | None = None,
|
||||
inventory_rpa_running: bool = False,
|
||||
source_labels: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
投影 Case 行级履约决定与库存缺口摘要。
|
||||
|
||||
核心逻辑:料号/数量按冻结 Schema field_code 从草稿 values 解析;
|
||||
OT 后叠加行库存匹配事实投影;分域下发 inventory/line_allowed_actions;
|
||||
ready+not_found 才规范 available=0,禁止把结果缺失当零库存。
|
||||
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
schema_fields: 可选;优先使用 serialize_review_case 已解析的字段列表。
|
||||
inventory_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。
|
||||
source_labels: code→显示名映射。
|
||||
|
||||
Returns:
|
||||
lines / open_count / ready_count / has_open_lines。
|
||||
lines(含 inventory_source / 分域 actions)与聚合计数。
|
||||
"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
line_auto_fulfill_enabled,
|
||||
load_current_match_facts_by_task,
|
||||
project_line_inventory_view,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
resolve_formal_ot,
|
||||
schema_fields_from_case,
|
||||
)
|
||||
|
||||
draft_lines = _draft_line_map(case)
|
||||
projections = _line_projection_map(case)
|
||||
schema_fields = _normalize_schema_fields_map(schema_fields) or schema_fields_from_case(case)
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
has_formal_ot = bool(formal_ot.get('has_formal_ot'))
|
||||
match_facts = load_current_match_facts_by_task(formal_ot.get('task_id'))
|
||||
labels = dict(source_labels or {})
|
||||
if not labels:
|
||||
draft = getattr(case, 'current_draft', None)
|
||||
raw_labels = (
|
||||
(getattr(draft, 'validation_result_json', None) or {}).get('inventory_source_labels')
|
||||
if draft is not None
|
||||
else None
|
||||
)
|
||||
if isinstance(raw_labels, dict):
|
||||
labels = {str(k): str(v) for k, v in raw_labels.items() if k}
|
||||
active_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.filter_by(review_case_id=int(case.id), is_active=True)
|
||||
@@ -255,10 +410,18 @@ def project_review_case_line_decisions(case: ShippingOrderReviewCase) -> dict[st
|
||||
for key, draft_line in draft_lines.items():
|
||||
proj = projections.get(key) or {}
|
||||
decision = by_key.get(key)
|
||||
can_fulfill, _block, rq, aq = _assess_line_fulfill_complete(draft_line, proj)
|
||||
required = str(rq) if rq is not None else (
|
||||
str(draft_line.get('qty') or draft_line.get('quantity') or '').strip() or None
|
||||
can_fulfill, _block, rq, aq = _assess_line_fulfill_complete(
|
||||
draft_line,
|
||||
proj,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
required = str(rq) if rq is not None else (
|
||||
str(
|
||||
_line_required_qty(draft_line, proj, schema_fields=schema_fields) or ''
|
||||
).strip()
|
||||
or None
|
||||
)
|
||||
# 兼容旧 path:无 OT 事实时仍可读 line_projections;有事实后以事实为准。
|
||||
available = str(aq) if aq is not None else (
|
||||
str(proj.get('available_qty') or '').strip() or None
|
||||
)
|
||||
@@ -270,16 +433,67 @@ def project_review_case_line_decisions(case: ShippingOrderReviewCase) -> dict[st
|
||||
status = decision.line_status if decision is not None else (
|
||||
'ready_to_fulfill' if can_fulfill else 'pending_decision'
|
||||
)
|
||||
decision_source = (
|
||||
getattr(decision, 'decision_source', None) if decision is not None else None
|
||||
)
|
||||
decision_snap = dict(decision.snapshot_json or {}) if decision is not None else {}
|
||||
fact = match_facts.get(key)
|
||||
fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {}
|
||||
auto_failed = bool(
|
||||
decision_snap.get('auto_fulfill_failed')
|
||||
or (fact or {}).get('auto_fulfill_failed')
|
||||
or fact_detail.get('auto_fulfill_failed')
|
||||
)
|
||||
auto_err = (
|
||||
decision_snap.get('auto_fulfill_error_message')
|
||||
or (fact or {}).get('auto_fulfill_error_message')
|
||||
or fact_detail.get('auto_fulfill_error_message')
|
||||
)
|
||||
inv_view = project_line_inventory_view(
|
||||
has_formal_ot=has_formal_ot,
|
||||
fact=fact,
|
||||
required_qty=required,
|
||||
stored_line_status=status,
|
||||
decision_source=decision_source,
|
||||
can_fulfill_complete_line=can_fulfill,
|
||||
auto_fulfill_failed=auto_failed,
|
||||
auto_fulfill_error_message=auto_err,
|
||||
inventory_rpa_running=bool(inventory_rpa_running),
|
||||
source_labels=labels,
|
||||
)
|
||||
# [STEP] OT 后数量以匹配事实投影覆盖(含 not_found→0 / result_missing→null)
|
||||
if has_formal_ot:
|
||||
available = inv_view.get('available_qty')
|
||||
shortage = inv_view.get('shortage_qty')
|
||||
lines_out.append({
|
||||
'line_key': key,
|
||||
'line_index': draft_line.get('_line_index'),
|
||||
'reservation_id': _line_reservation_id(draft_line, proj),
|
||||
'part_number': str(draft_line.get('part_number') or '').strip() or None,
|
||||
'part_number': _line_part_number(
|
||||
draft_line,
|
||||
proj,
|
||||
schema_fields=schema_fields,
|
||||
),
|
||||
'required_qty': required,
|
||||
'available_qty': available,
|
||||
'shortage_qty': shortage,
|
||||
'can_fulfill_complete_line': can_fulfill,
|
||||
'line_status': status,
|
||||
'user_line_status': inv_view.get('user_line_status'),
|
||||
'inventory_status': inv_view.get('inventory_status'),
|
||||
'match_result': inv_view.get('match_result'),
|
||||
'is_shortage': bool(inv_view.get('is_shortage')),
|
||||
'display_available': inv_view.get('display_available'),
|
||||
'inventory_snapshot_id': inv_view.get('inventory_snapshot_id'),
|
||||
'inventory_checked_at': inv_view.get('inventory_checked_at'),
|
||||
'inventory_source_code': inv_view.get('inventory_source_code'),
|
||||
'inventory_source': inv_view.get('inventory_source'),
|
||||
'decision_source': inv_view.get('decision_source'),
|
||||
'inventory_allowed_actions': list(inv_view.get('inventory_allowed_actions') or []),
|
||||
'line_allowed_actions': list(inv_view.get('line_allowed_actions') or []),
|
||||
'allowed_actions': list(inv_view.get('allowed_actions') or []),
|
||||
'auto_fulfill_error_message': inv_view.get('auto_fulfill_error_message'),
|
||||
'auto_fulfill_failed': bool(auto_failed),
|
||||
'decision': _serialize_decision(decision) if decision is not None else None,
|
||||
'block_reason': proj.get('block_reason'),
|
||||
})
|
||||
@@ -296,12 +510,76 @@ def project_review_case_line_decisions(case: ShippingOrderReviewCase) -> dict[st
|
||||
and item.get('line_status') not in _TERMINAL_ACTIVE
|
||||
)
|
||||
]
|
||||
aggregates = _aggregate_line_fulfillment_counts(lines_out)
|
||||
return {
|
||||
'lines': lines_out,
|
||||
'open_count': len(open_lines),
|
||||
'ready_count': len(ready),
|
||||
'has_open_lines': bool(open_lines),
|
||||
'has_shortage': any(item.get('shortage_qty') for item in lines_out),
|
||||
'has_shortage': any(
|
||||
item.get('is_shortage') or item.get('shortage_qty') for item in lines_out
|
||||
),
|
||||
**aggregates,
|
||||
'line_auto_fulfill_enabled': bool(line_auto_fulfill_enabled()),
|
||||
'has_line_inventory_projection': bool(has_formal_ot and lines_out),
|
||||
}
|
||||
|
||||
|
||||
def build_inventory_issue_fallback(
|
||||
*,
|
||||
has_formal_ot: bool,
|
||||
line_fulfillment: dict[str, Any] | None,
|
||||
process_gate: dict[str, Any] | None,
|
||||
automation: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
Case 级库存兜底:仅无有效行投影且库存系统失败时返回。
|
||||
|
||||
核心逻辑:有行投影→None;系统等待/RPA 运行中→None;失败时最多下发
|
||||
retry_inventory_preparation。
|
||||
|
||||
Returns:
|
||||
fallback 字典或 None。
|
||||
"""
|
||||
if not has_formal_ot:
|
||||
return None
|
||||
lf = line_fulfillment if isinstance(line_fulfillment, dict) else {}
|
||||
lines = list(lf.get('lines') or [])
|
||||
if lines:
|
||||
# 存在有效行投影:库存动作只在行上,不展示 Case 卡。
|
||||
return None
|
||||
|
||||
auto = automation if isinstance(automation, dict) else {}
|
||||
auto_status = str(auto.get('status') or '').strip().lower()
|
||||
if auto_status in {'processing', 'queued', 'automating', 'waiting', 'waiting_to_start'}:
|
||||
return None
|
||||
gate = process_gate if isinstance(process_gate, dict) else {}
|
||||
if gate.get('technical_auto_only') and auto_status not in {'failed', 'error'}:
|
||||
return None
|
||||
|
||||
reason = str(
|
||||
(gate.get('current_blocking_gate') or {}).get('blocking_reason_code')
|
||||
or gate.get('blocking_reason_code')
|
||||
or ''
|
||||
).strip()
|
||||
failed_reasons = {
|
||||
'inventory_file_missing',
|
||||
'inventory_source_unavailable',
|
||||
'inventory_preparation_failed',
|
||||
'inventory_rpa_timeout',
|
||||
'inventory_rpa_export_failed',
|
||||
'inventory_file_empty',
|
||||
}
|
||||
if auto_status not in {'failed', 'error'} and reason not in failed_reasons:
|
||||
return None
|
||||
|
||||
kind = reason if reason in failed_reasons else 'inventory_file_missing'
|
||||
return {
|
||||
'kind': kind,
|
||||
'reason_label_key': kind,
|
||||
'affected_line_count': 0,
|
||||
'file_count': 0,
|
||||
'allowed_actions': ['retry_inventory_preparation'],
|
||||
}
|
||||
|
||||
|
||||
@@ -391,13 +669,19 @@ def decide_review_line_fulfillment(
|
||||
draft_line = lines[key]
|
||||
projections = _line_projection_map(case)
|
||||
proj = projections.get(key) or {}
|
||||
req_qty = _parse_qty(draft_line.get('qty') or draft_line.get('quantity'))
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
schema_fields_from_case,
|
||||
)
|
||||
|
||||
schema_fields = schema_fields_from_case(case)
|
||||
req_qty = _parse_qty(_line_required_qty(draft_line, proj, schema_fields=schema_fields))
|
||||
avail_qty = _parse_qty(proj.get('available_qty'))
|
||||
if code == DECISION_FULFILL:
|
||||
req_qty, avail_qty = _assert_line_can_fulfill_complete(
|
||||
line_key=key,
|
||||
draft_line=draft_line,
|
||||
proj=proj,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
|
||||
# [STEP 1] 停用旧活动决定
|
||||
@@ -412,6 +696,7 @@ def decide_review_line_fulfillment(
|
||||
line_index=draft_line.get('_line_index'),
|
||||
decision_version=_next_version(case, key),
|
||||
decision_code=code,
|
||||
decision_source='user',
|
||||
line_status=status,
|
||||
is_active=True,
|
||||
reason=str(reason or '').strip()[:2000] or None,
|
||||
@@ -420,10 +705,15 @@ def decide_review_line_fulfillment(
|
||||
str(proj.get('available_qty') or '').strip() or None
|
||||
),
|
||||
reservation_id=_line_reservation_id(draft_line, proj),
|
||||
part_number=str(draft_line.get('part_number') or '').strip() or None,
|
||||
part_number=_line_part_number(
|
||||
draft_line,
|
||||
proj,
|
||||
schema_fields=schema_fields,
|
||||
),
|
||||
actor_user_id=int(user_id),
|
||||
snapshot_json={
|
||||
'decision_code': code,
|
||||
'decision_source': 'user',
|
||||
'required_qty': str(req_qty) if req_qty is not None else None,
|
||||
'available_qty': str(avail_qty) if avail_qty is not None else None,
|
||||
'line_key': key,
|
||||
@@ -531,8 +821,13 @@ def create_fulfillment_wave(
|
||||
if case is None:
|
||||
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
schema_fields_from_case,
|
||||
)
|
||||
|
||||
draft_lines = _draft_line_map(case)
|
||||
projections = _line_projection_map(case)
|
||||
schema_fields = schema_fields_from_case(case)
|
||||
for key in keys:
|
||||
if key not in draft_lines:
|
||||
raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
|
||||
@@ -553,6 +848,7 @@ def create_fulfillment_wave(
|
||||
line_key=key,
|
||||
draft_line=draft_lines[key],
|
||||
proj=projections.get(key) or {},
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
# 禁止拆分:决定中的 required_qty 必须等于草稿整行数量
|
||||
if decision.required_qty and _parse_qty(decision.required_qty) != req:
|
||||
|
||||
@@ -9,16 +9,23 @@ backend/app/services/shipping_notice/order_review_projection.py
|
||||
order_review_duplicate_service.project_review_case_duplicate、
|
||||
order_review_profile_match_service.project_review_case_profile_match、
|
||||
order_review_reservation_service.project_review_case_reservation、
|
||||
order_review_fulfillment_decision_service.project_review_case_line_decisions、
|
||||
order_review_fulfillment_decision_service.project_review_case_line_decisions /
|
||||
build_inventory_issue_fallback、
|
||||
order_review_workbench_projection(正式 OT / completed_checks / field_completeness)、
|
||||
order_task_service.resolve_order_task_for_candidate、
|
||||
schema_edit_policy.list_editable_formal_field_ids、
|
||||
workflow_ledger_service.find_item_by_current_case、ShippingNotice(确认后推进态)。
|
||||
逻辑:只返回工作台展示所需的字段定义、机器/人工草稿值、问题、建单资格与行级库存候选;
|
||||
固定投影 customer_resolution / field_conflicts / duplicate / profile_match /
|
||||
reservation / line_fulfillment / automation;
|
||||
profile_match 按 is_admin 裁剪(普通用户仅 admin_only 占位);
|
||||
automation 区分 waiting_to_start / queued / running / manual_fallback,禁止资格冒充正在推进;
|
||||
管理员另附 technical_progress(如 document_materialization pending);
|
||||
field_completeness / completed_checks / current_stage / reservation /
|
||||
line_fulfillment(分域 inventory/line_allowed_actions)/ inventory_issue_fallback /
|
||||
automation;
|
||||
profile_match:普通用户四态裁剪,管理员保留完整审计;
|
||||
automation 区分 pre_ot_stp / post_ot_progress 与 owner_type,禁止资格冒充正在推进;
|
||||
正式 OT automation/needs_retry 同源绑定 shipping_notice_run Job;
|
||||
current_stage 与 Progress 共用 project_stage_for_task;
|
||||
正式 OT 后 process_gate 清除建单前阻断;管理员另附 technical_progress;
|
||||
task_missing 时 available_actions=view/contact_admin 且 recovery_available=false;
|
||||
Case 级暴露 candidate_id / order_task_no(Candidate 一对一 OT,禁止前端回退 Run 根号);
|
||||
为每行/表头投影 field_meta(value_source / locked / override_reason);
|
||||
已确认 Case 附带 confirmed_task_no 与 post_confirm_auto_progress,供刷新后恢复「已建单待推进」;
|
||||
@@ -48,44 +55,70 @@ def _safe_filename(value: Any) -> str | None:
|
||||
|
||||
def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[str, Any] | None:
|
||||
"""
|
||||
投影已确认 Case 的任务号与「是否仍需自动推进」态,供前端刷新后恢复重试入口。
|
||||
投影已绑定正式 OT 的任务号与自动推进态(与 automation 同源 Job 判定)。
|
||||
|
||||
核心逻辑:与 schedule_auto_progress_after_review_confirm 同一判定
|
||||
(process_status=created 且已挂 Extraction);未确认则不投影。
|
||||
核心逻辑:委托 project_post_ot_automation_from_job(shipping_notice_run);
|
||||
needs_retry 与 automation.status=failed 必须同源;无 confirmed_task_id 则不投影。
|
||||
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
|
||||
Returns:
|
||||
含 task_no / needs_retry / status / message 的摘要;未确认时为 None。
|
||||
含 task_no / needs_retry / status / job_id / message 的摘要;无正式 OT 绑定时为 None。
|
||||
"""
|
||||
if str(case.status or '') != 'confirmed' or not case.confirmed_task_id:
|
||||
if not case.confirmed_task_id:
|
||||
return None
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
_task_needs_post_confirm_auto_progress,
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
project_post_ot_automation_from_job,
|
||||
resolve_formal_ot,
|
||||
)
|
||||
|
||||
task = db.session.get(ShippingNotice, int(case.confirmed_task_id))
|
||||
if task is None:
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
if formal_ot.get('task_missing'):
|
||||
return {
|
||||
'task_no': None,
|
||||
'needs_retry': False,
|
||||
'status': 'task_missing',
|
||||
'message': '已确认但关联任务不可用',
|
||||
'message': '正式任务关联异常,请联系管理员',
|
||||
'task_process_status': None,
|
||||
'job_id': None,
|
||||
'error_code': 'task_missing',
|
||||
'recovery_available': False,
|
||||
}
|
||||
needs_retry = bool(_task_needs_post_confirm_auto_progress(task))
|
||||
if not formal_ot.get('has_formal_ot'):
|
||||
return None
|
||||
|
||||
auto = project_post_ot_automation_from_job(formal_ot.get('task'))
|
||||
needs_retry = bool(auto.get('needs_retry'))
|
||||
status = str(auto.get('status') or '')
|
||||
# needs_retry 时保留 manual_fallback;其余可重试统一 needs_retry 供旧消费方。
|
||||
if needs_retry and status == 'manual_fallback':
|
||||
mapped_status = 'manual_fallback'
|
||||
elif needs_retry:
|
||||
mapped_status = 'needs_retry'
|
||||
else:
|
||||
mapped_status = status
|
||||
return {
|
||||
'task_no': str(task.task_no or ''),
|
||||
'task_no': auto.get('task_no') or formal_ot.get('task_no'),
|
||||
'needs_retry': needs_retry,
|
||||
'status': 'needs_retry' if needs_retry else 'advanced_or_idle',
|
||||
'status': mapped_status,
|
||||
'message': (
|
||||
'已建单但任务仍停在待推进,可重试自动推进'
|
||||
'自动推进失败,可重试'
|
||||
if needs_retry
|
||||
else '任务已离开待推进态或不需推进'
|
||||
else (
|
||||
'已建单,等待系统启动自动推进'
|
||||
if status == 'waiting_to_start'
|
||||
else '任务自动推进进行中或已完成'
|
||||
)
|
||||
),
|
||||
'task_process_status': str(getattr(task, 'process_status', None) or ''),
|
||||
'task_process_status': auto.get('task_process_status'),
|
||||
'job_id': auto.get('job_id'),
|
||||
'error_code': auto.get('error_code'),
|
||||
'reason_code': auto.get('reason_code'),
|
||||
'attempts': auto.get('attempts'),
|
||||
'max_attempts': auto.get('max_attempts'),
|
||||
'completed_at': auto.get('completed_at'),
|
||||
'recovery_available': False if formal_ot.get('task_missing') else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -124,18 +157,18 @@ def _project_case_automation_status(
|
||||
投影用户可见的自动建单/推进状态;资格达标不等于正在推进。
|
||||
|
||||
核心逻辑:
|
||||
- confirmed + needs_retry → failed(可重试)
|
||||
- confirmed + 已有 Task 且非 retry → queued/running/completed
|
||||
- 存在 STP Job queued/running → 对应状态
|
||||
- STP Job failed → failed(可重试)
|
||||
- can_auto_create 且未入队 → waiting_to_start;超时无 Job → manual_fallback
|
||||
- 其余 → idle
|
||||
- 已有正式 OT:只消费 post_confirm / OT process_status(禁止再读 STP 主态)
|
||||
- post_confirm needs_retry → failed(可重试)
|
||||
- 正式 OT + process_status created/空 → waiting_to_start(无 Job)或 queued
|
||||
- 无正式 OT:查 STP Job queued/running/failed;can_auto_create 未入队 → waiting_to_start
|
||||
- phase / owner_type 由 enrich_automation_status 在 serialize 时补齐
|
||||
|
||||
Returns:
|
||||
status / retryable / task_no / can_auto_create / job_id。
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
build_stp_idempotency_key,
|
||||
find_active_stp_job,
|
||||
@@ -144,37 +177,90 @@ def _project_case_automation_status(
|
||||
|
||||
can_auto = bool((validation or {}).get('can_auto_create'))
|
||||
can_build = bool((validation or {}).get('can_build'))
|
||||
task_no = None
|
||||
if isinstance(post_confirm, dict):
|
||||
task_no = str(post_confirm.get('task_no') or '').strip() or None
|
||||
if post_confirm.get('needs_retry'):
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
|
||||
# [STEP 1] 正式 OT:与 post_confirm 共用 project_post_ot_automation_from_job,禁止只读 process_status。
|
||||
if formal_ot.get('has_formal_ot') or formal_ot.get('task_missing') or (
|
||||
isinstance(post_confirm, dict) and (
|
||||
post_confirm.get('task_no') or str(post_confirm.get('status') or '') == 'task_missing'
|
||||
)
|
||||
):
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
project_post_ot_automation_from_job,
|
||||
)
|
||||
|
||||
# 优先复用 post_confirm:needs_retry 可操作态优先于 task_missing 诊断。
|
||||
if isinstance(post_confirm, dict) and post_confirm.get('needs_retry'):
|
||||
raw_status = str(post_confirm.get('status') or '').strip().lower()
|
||||
out_status = 'manual_fallback' if raw_status == 'manual_fallback' else 'failed'
|
||||
return {
|
||||
'status': 'failed',
|
||||
'status': out_status,
|
||||
'retryable': True,
|
||||
'task_no': task_no,
|
||||
'task_no': post_confirm.get('task_no') or formal_ot.get('task_no'),
|
||||
'can_auto_create': can_auto,
|
||||
'can_build': can_build,
|
||||
'job_id': None,
|
||||
'reason_code': 'post_confirm_auto_progress_failed',
|
||||
}
|
||||
if task_no:
|
||||
process_status = str(post_confirm.get('task_process_status') or '').strip().lower()
|
||||
if process_status in {'created', ''}:
|
||||
status = 'queued'
|
||||
elif process_status in {'completed', 'closed', 'done'}:
|
||||
status = 'completed'
|
||||
else:
|
||||
status = 'running'
|
||||
return {
|
||||
'status': status,
|
||||
'retryable': False,
|
||||
'task_no': task_no,
|
||||
'can_auto_create': can_auto,
|
||||
'can_build': can_build,
|
||||
'job_id': None,
|
||||
'job_id': post_confirm.get('job_id'),
|
||||
'error_code': post_confirm.get('error_code'),
|
||||
'reason_code': (
|
||||
post_confirm.get('reason_code')
|
||||
or post_confirm.get('error_code')
|
||||
or 'post_confirm_auto_progress_failed'
|
||||
),
|
||||
'attempts': post_confirm.get('attempts'),
|
||||
'max_attempts': post_confirm.get('max_attempts'),
|
||||
'completed_at': post_confirm.get('completed_at'),
|
||||
}
|
||||
|
||||
# [STEP] 查当前有效 STP Job;无有效 Job 时再看最新历史(failed → 可重试)。
|
||||
if formal_ot.get('task_missing') or (
|
||||
isinstance(post_confirm, dict)
|
||||
and str(post_confirm.get('status') or '') == 'task_missing'
|
||||
):
|
||||
return {
|
||||
'status': 'failed',
|
||||
'retryable': False,
|
||||
'task_no': None,
|
||||
'can_auto_create': can_auto,
|
||||
'can_build': can_build,
|
||||
'job_id': None,
|
||||
'reason_code': 'task_missing',
|
||||
'error_code': 'task_missing',
|
||||
}
|
||||
|
||||
# 复用已算好的 post_confirm(同源);缺省时再查 Job。
|
||||
if isinstance(post_confirm, dict) and post_confirm.get('status') not in (None, ''):
|
||||
status = str(post_confirm.get('status') or '').strip().lower()
|
||||
if status == 'needs_retry':
|
||||
status = 'failed'
|
||||
return {
|
||||
'status': status,
|
||||
'retryable': bool(post_confirm.get('needs_retry') or status in {'failed', 'manual_fallback'}),
|
||||
'task_no': post_confirm.get('task_no') or formal_ot.get('task_no'),
|
||||
'can_auto_create': can_auto,
|
||||
'can_build': can_build,
|
||||
'job_id': post_confirm.get('job_id'),
|
||||
'error_code': post_confirm.get('error_code'),
|
||||
'reason_code': post_confirm.get('reason_code') or post_confirm.get('error_code'),
|
||||
'attempts': post_confirm.get('attempts'),
|
||||
'max_attempts': post_confirm.get('max_attempts'),
|
||||
'completed_at': post_confirm.get('completed_at'),
|
||||
}
|
||||
|
||||
auto = project_post_ot_automation_from_job(formal_ot.get('task'))
|
||||
return {
|
||||
'status': auto.get('status') or 'waiting_to_start',
|
||||
'retryable': bool(auto.get('retryable')),
|
||||
'task_no': auto.get('task_no') or formal_ot.get('task_no'),
|
||||
'can_auto_create': can_auto,
|
||||
'can_build': can_build,
|
||||
'job_id': auto.get('job_id'),
|
||||
'error_code': auto.get('error_code'),
|
||||
'reason_code': auto.get('reason_code') or auto.get('error_code'),
|
||||
'attempts': auto.get('attempts'),
|
||||
'max_attempts': auto.get('max_attempts'),
|
||||
'completed_at': auto.get('completed_at'),
|
||||
}
|
||||
|
||||
# [STEP 2] 建单前:查当前有效 STP Job;无有效 Job 时再看最新历史(failed → 可重试)。
|
||||
job = None
|
||||
latest = None
|
||||
draft = getattr(case, 'current_draft', None)
|
||||
@@ -466,13 +552,22 @@ def serialize_review_case(
|
||||
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
is_admin: 为 True 时返回完整 profile_match 审计;普通用户仅返回
|
||||
``{available: false, visibility: admin_only}``,禁止下发模板 ID/分数/内部原因码。
|
||||
is_admin: 为 True 时返回完整 profile_match 审计;普通用户仅四态裁剪,
|
||||
禁止下发模板 ID/分数/内部原因码。
|
||||
"""
|
||||
from app.services.shipping_notice.schema_edit_policy import (
|
||||
is_excel_ready_for_task,
|
||||
list_editable_formal_field_ids,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
apply_post_ot_gate_rules,
|
||||
enrich_automation_status,
|
||||
project_completed_checks,
|
||||
project_field_completeness,
|
||||
project_stage_for_task,
|
||||
project_user_profile_match,
|
||||
resolve_formal_ot,
|
||||
)
|
||||
|
||||
run = case.run
|
||||
draft = case.current_draft
|
||||
@@ -533,6 +628,8 @@ def serialize_review_case(
|
||||
.all()
|
||||
)
|
||||
llm_suggestions = [serialize_suggestion(row) for row in rows]
|
||||
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
process_gate = None
|
||||
technical_progress = None
|
||||
from app.models import ShippingProcessExecution
|
||||
@@ -548,7 +645,10 @@ def serialize_review_case(
|
||||
.first()
|
||||
)
|
||||
if execution is not None:
|
||||
process_gate = project_user_gate_summary(execution)
|
||||
process_gate = apply_post_ot_gate_rules(
|
||||
project_user_gate_summary(execution),
|
||||
has_formal_ot=bool(formal_ot.get('has_formal_ot')),
|
||||
)
|
||||
# [STEP] 管理员 technical_progress:如实投影当前技术 Gate(含 pending),不经用户态过滤。
|
||||
if is_admin:
|
||||
full_exec = serialize_process_execution(execution, include_diagnostics=False)
|
||||
@@ -559,15 +659,33 @@ def serialize_review_case(
|
||||
'status': str(current.get('status') or ''),
|
||||
'blocking_reason_code': current.get('blocking_reason_code'),
|
||||
}
|
||||
elif formal_ot.get('has_formal_ot') or formal_ot.get('task_missing'):
|
||||
# 无 Execution 时仍给出 OT 后系统自动态,避免前端回退到人工待办。
|
||||
process_gate = {
|
||||
'execution_no': None,
|
||||
'status': 'running' if formal_ot.get('has_formal_ot') else 'failed',
|
||||
'current_blocking_gate': None,
|
||||
'technical_auto_only': True,
|
||||
'owner_type': 'system' if formal_ot.get('has_formal_ot') else 'unknown',
|
||||
'available_actions': [],
|
||||
'gates_track': [],
|
||||
}
|
||||
|
||||
post_confirm = _project_post_confirm_auto_progress(case)
|
||||
confirmed_task_no = None
|
||||
if isinstance(post_confirm, dict) and post_confirm.get('task_no'):
|
||||
if formal_ot.get('has_formal_ot'):
|
||||
confirmed_task_no = formal_ot.get('task_no')
|
||||
elif isinstance(post_confirm, dict) and post_confirm.get('task_no'):
|
||||
confirmed_task_no = str(post_confirm.get('task_no') or '')
|
||||
validation_snapshot = dict(draft.validation_result_json or {}) if draft is not None else None
|
||||
automation = _project_case_automation_status(
|
||||
case,
|
||||
validation=validation_snapshot,
|
||||
post_confirm=post_confirm if isinstance(post_confirm, dict) else None,
|
||||
automation = enrich_automation_status(
|
||||
_project_case_automation_status(
|
||||
case,
|
||||
validation=validation_snapshot,
|
||||
post_confirm=post_confirm if isinstance(post_confirm, dict) else None,
|
||||
),
|
||||
formal_ot=formal_ot,
|
||||
is_admin=is_admin,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_customer_service import (
|
||||
project_review_case_customer_resolution,
|
||||
@@ -585,25 +703,53 @@ def serialize_review_case(
|
||||
project_review_case_reservation,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
build_inventory_issue_fallback,
|
||||
project_review_case_line_decisions,
|
||||
)
|
||||
from app.services.shipping_notice.order_task_service import resolve_order_task_for_candidate
|
||||
|
||||
# [STEP] 模板匹配属审计信息:普通用户不得收到模板 ID / 候选分 / 内部原因码。
|
||||
# [STEP] 模板匹配:管理员完整审计;普通用户仅四态。
|
||||
admin_profile_match = project_review_case_profile_match(case)
|
||||
if is_admin:
|
||||
profile_match = project_review_case_profile_match(case)
|
||||
profile_match = dict(admin_profile_match)
|
||||
profile_match['visibility'] = 'admin'
|
||||
profile_match['raw_status'] = profile_match.get('status')
|
||||
profile_match['status'] = project_user_profile_match(admin_profile_match)['status']
|
||||
else:
|
||||
profile_match = {
|
||||
'available': False,
|
||||
'visibility': 'admin_only',
|
||||
'status': 'hidden',
|
||||
'candidates': [],
|
||||
'fallback_reason_codes': [],
|
||||
'needs_review': False,
|
||||
'selected_profile': None,
|
||||
'execution_mode': None,
|
||||
'route_type': None,
|
||||
profile_match = project_user_profile_match(admin_profile_match)
|
||||
|
||||
customer_resolution = project_review_case_customer_resolution(case)
|
||||
field_conflicts = project_review_case_field_conflicts(case)
|
||||
duplicate = project_review_case_duplicate(case)
|
||||
field_completeness = project_field_completeness(
|
||||
validation=validation_snapshot,
|
||||
has_formal_ot=bool(formal_ot.get('has_formal_ot')),
|
||||
)
|
||||
completed_checks = project_completed_checks(
|
||||
case=case,
|
||||
process_gate=process_gate,
|
||||
customer_resolution=customer_resolution,
|
||||
duplicate=duplicate,
|
||||
field_conflicts=field_conflicts if isinstance(field_conflicts, list) else [],
|
||||
field_completeness=field_completeness,
|
||||
profile_match=profile_match,
|
||||
formal_ot=formal_ot,
|
||||
)
|
||||
if formal_ot.get('task_missing'):
|
||||
current_stage = {
|
||||
'code': 'task_missing',
|
||||
'label_key': 'task_missing',
|
||||
'source': 'formal_ot',
|
||||
'inconsistent': True,
|
||||
'process_status': None,
|
||||
'current_step': None,
|
||||
'stage_node': None,
|
||||
}
|
||||
elif formal_ot.get('has_formal_ot'):
|
||||
current_stage = project_stage_for_task(formal_ot.get('task'))
|
||||
else:
|
||||
# 建单前:固定 order_review;STP 入队态只走 automation,不冒充库存阶段。
|
||||
current_stage = project_stage_for_task(None, default_code='order_review')
|
||||
|
||||
# [UI-03] Case 级暴露 Candidate 绑定的 OT,禁止前端回退 Run 根号。
|
||||
linked_order_task = resolve_order_task_for_candidate(
|
||||
@@ -614,13 +760,52 @@ def serialize_review_case(
|
||||
)
|
||||
|
||||
order_data_version = None
|
||||
confirmed_notice = None
|
||||
if str(case.status or '') == 'confirmed' and case.confirmed_task_id:
|
||||
from app.models import ShippingNotice
|
||||
confirmed_notice = formal_ot.get('task') if formal_ot.get('has_formal_ot') else None
|
||||
if confirmed_notice is not None:
|
||||
order_data_version = int(confirmed_notice.order_data_version or 1)
|
||||
|
||||
confirmed_notice = db.session.get(ShippingNotice, int(case.confirmed_task_id))
|
||||
if confirmed_notice is not None:
|
||||
order_data_version = int(confirmed_notice.order_data_version or 1)
|
||||
if is_admin and formal_ot.get('task_missing'):
|
||||
technical_progress = {
|
||||
'gate_code': (technical_progress or {}).get('gate_code'),
|
||||
'status': 'task_missing',
|
||||
'blocking_reason_code': 'task_missing',
|
||||
'enqueue_status': 'task_missing',
|
||||
'confirmed_task_id': formal_ot.get('task_id') or (
|
||||
int(case.confirmed_task_id) if case.confirmed_task_id else None
|
||||
),
|
||||
'recovery_available': False,
|
||||
}
|
||||
|
||||
# task_missing:禁止 confirm;无恢复 API 时明确 view + contact_admin。
|
||||
available_actions = _allowed_actions(case)
|
||||
if formal_ot.get('task_missing') or formal_ot.get('has_formal_ot'):
|
||||
available_actions = [a for a in available_actions if a != 'confirm']
|
||||
if formal_ot.get('task_missing'):
|
||||
available_actions = ['view', 'contact_admin']
|
||||
|
||||
# [STEP] 行履约投影依赖 automation / labels;Case 兜底仅无行投影且系统失败。
|
||||
# waiting_to_start / waiting = 尚未真正跑库存 RPA,禁止当成 running 清空行动作。
|
||||
auto_status = str((automation or {}).get('status') or '').strip().lower()
|
||||
inventory_rpa_running = auto_status in {
|
||||
'processing', 'queued', 'automating', 'running',
|
||||
}
|
||||
source_labels: dict[str, str] = {}
|
||||
if isinstance(validation_snapshot, dict):
|
||||
raw_labels = validation_snapshot.get('inventory_source_labels') or {}
|
||||
if isinstance(raw_labels, dict):
|
||||
source_labels = {str(k): str(v) for k, v in raw_labels.items() if k}
|
||||
line_fulfillment = project_review_case_line_decisions(
|
||||
case,
|
||||
schema_fields=schema_fields,
|
||||
inventory_rpa_running=inventory_rpa_running,
|
||||
source_labels=source_labels,
|
||||
)
|
||||
inventory_issue_fallback = build_inventory_issue_fallback(
|
||||
has_formal_ot=bool(formal_ot.get('has_formal_ot')),
|
||||
line_fulfillment=line_fulfillment,
|
||||
process_gate=process_gate if isinstance(process_gate, dict) else None,
|
||||
automation=automation if isinstance(automation, dict) else None,
|
||||
)
|
||||
|
||||
return {
|
||||
'case_no': case.case_no,
|
||||
@@ -632,8 +817,14 @@ def serialize_review_case(
|
||||
'disposition': case.disposition,
|
||||
'confirmed_task_id': int(case.confirmed_task_id) if case.confirmed_task_id else None,
|
||||
'confirmed_task_no': confirmed_task_no,
|
||||
'has_formal_ot': bool(formal_ot.get('has_formal_ot')),
|
||||
'task_missing': bool(formal_ot.get('task_missing')),
|
||||
'recovery_available': False if formal_ot.get('task_missing') else None,
|
||||
'post_confirm_auto_progress': post_confirm,
|
||||
'automation': automation,
|
||||
'current_stage': current_stage,
|
||||
'completed_checks': completed_checks,
|
||||
'field_completeness': field_completeness,
|
||||
'technical_progress': technical_progress,
|
||||
'candidate': {
|
||||
'id': int(candidate.id),
|
||||
@@ -641,17 +832,16 @@ def serialize_review_case(
|
||||
'validation_status': candidate.validation_status,
|
||||
'po_number': candidate.po_number,
|
||||
} if candidate is not None else None,
|
||||
'customer_resolution': project_review_case_customer_resolution(case),
|
||||
'field_conflicts': project_review_case_field_conflicts(case),
|
||||
'duplicate': project_review_case_duplicate(case),
|
||||
'customer_resolution': customer_resolution,
|
||||
'field_conflicts': field_conflicts,
|
||||
'duplicate': duplicate,
|
||||
'profile_match': profile_match,
|
||||
'reservation': project_review_case_reservation(case),
|
||||
'line_fulfillment': project_review_case_line_decisions(case),
|
||||
'line_fulfillment': line_fulfillment,
|
||||
'schema': {'schema_version_id': int(run.schema_version_id), 'fields': schema_fields},
|
||||
'draft': projected_draft,
|
||||
'llm_suggestions': llm_suggestions,
|
||||
'available_actions': _allowed_actions(case),
|
||||
# 正式任务可编辑字段(默认空;仅 Schema task_edit_policy 放行;Excel ready 后全空)。
|
||||
'available_actions': available_actions,
|
||||
'formal_editable_field_ids': (
|
||||
list_editable_formal_field_ids(
|
||||
schema_fields,
|
||||
@@ -662,6 +852,7 @@ def serialize_review_case(
|
||||
),
|
||||
'order_data_version': order_data_version,
|
||||
'process_gate': process_gate,
|
||||
'inventory_issue_fallback': inventory_issue_fallback,
|
||||
}
|
||||
|
||||
|
||||
@@ -683,7 +874,6 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
})
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
# 已被新版识别替代的 Run 不可继续编辑,前端据此跳转而非渲染空白旧 Case。
|
||||
'superseded_by_run_no': run.superseding_run.run_no if run.superseding_run is not None else None,
|
||||
'summary': counts,
|
||||
'items': items,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -56,17 +56,17 @@ def compute_effective_reservation_id(
|
||||
|
||||
def default_derivation_rules() -> list[dict[str, Any]]:
|
||||
"""
|
||||
返回新草稿默认派生规则(关闭状态)。
|
||||
返回新草稿默认派生规则(启用状态)。
|
||||
|
||||
核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=False,
|
||||
避免未评审规则自动改写内部项次。
|
||||
核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=True,
|
||||
内部项次为空时自动从客户 PO 行号派生;人工已锁定或目标有值时不覆盖。
|
||||
|
||||
Returns:
|
||||
可写入 definition_json.derivation_rules 的规则列表。
|
||||
"""
|
||||
return [{
|
||||
'rule_id': DEFAULT_DERIVATION_RULE_ID,
|
||||
'enabled': False,
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
|
||||
@@ -841,6 +841,16 @@ def execute_stp_auto_create_job(*, payload: dict[str, Any], job_id: int) -> dict
|
||||
created_by_id=int(owner_id),
|
||||
commit=False,
|
||||
)
|
||||
# [STEP] BE-4:STP 建 OT 成功后补触发自动履约协调(flag 关时 no-op)
|
||||
if created.get('task_no') and not created.get('idempotent_replay'):
|
||||
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
|
||||
enqueue_post_ot_auto_fulfill_job,
|
||||
)
|
||||
enqueue_post_ot_auto_fulfill_job(
|
||||
task_no=str(created.get('task_no')),
|
||||
trigger='ot_created',
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
progress = finalize_sync_auto_progress_after_commit(progress)
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
"""
|
||||
services/shipping_notice/post_ot_fulfillment_wave_service.py
|
||||
|
||||
用途:正式 OT 已存在后的行级履约波次(create_post_ot_fulfillment_wave);禁止再走 confirm_review_case。
|
||||
依赖:ShippingOrderReviewWaveLine、ShippingOrderReviewWaveIdempotency、LineDecision、
|
||||
line_inventory_match 事实、fulfillment_audit、post_ot_wave_progress_service。
|
||||
逻辑:服务端按匹配事实重校验;独立幂等表强约束;同 key 参数冲突 409;
|
||||
成功后由调用方 schedule_post_ot_wave_progress(本模块不调用 confirm 推进)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision,
|
||||
ShippingOrderReviewWaveIdempotency,
|
||||
ShippingOrderReviewWaveLine,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
DECISION_FULFILL,
|
||||
_STATUS_BY_DECISION,
|
||||
_active_decision,
|
||||
_draft_line_map,
|
||||
_next_version,
|
||||
project_review_case_line_decisions,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
assert_case_is_current_workflow_version,
|
||||
)
|
||||
|
||||
|
||||
def _parse_qty(value: Any) -> Decimal | None:
|
||||
"""解析数量。"""
|
||||
text = str(value if value is not None else '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return Decimal(text)
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]:
|
||||
"""
|
||||
按匹配事实 fail-closed 校验可完整履约。
|
||||
|
||||
Raises:
|
||||
ConflictError: 事实未 ready、短缺、或数量无效。
|
||||
"""
|
||||
if str(line.get('inventory_status') or '') != 'ready':
|
||||
raise ConflictError(
|
||||
'Inventory not ready for post-OT wave',
|
||||
code='SHIPPING.REVIEW_LINE_INVENTORY_NOT_READY',
|
||||
details={'line_key': line.get('line_key'), 'inventory_status': line.get('inventory_status')},
|
||||
)
|
||||
if str(line.get('match_result') or '') != 'matched':
|
||||
raise ConflictError(
|
||||
'Line match result does not allow fulfill',
|
||||
code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE',
|
||||
details={'line_key': line.get('line_key'), 'match_result': line.get('match_result')},
|
||||
)
|
||||
if line.get('is_shortage'):
|
||||
raise ConflictError(
|
||||
'Line has inventory shortage',
|
||||
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
|
||||
details={'line_key': line.get('line_key')},
|
||||
)
|
||||
req = _parse_qty(line.get('required_qty'))
|
||||
avail = _parse_qty(line.get('available_qty'))
|
||||
if req is None or avail is None or avail < req:
|
||||
raise ConflictError(
|
||||
'Line cannot fulfill complete quantity with current inventory facts',
|
||||
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
|
||||
details={'line_key': line.get('line_key')},
|
||||
)
|
||||
return req, avail
|
||||
|
||||
|
||||
def _stable_line_keys(keys: list[str]) -> list[str]:
|
||||
"""稳定排序行键。"""
|
||||
return sorted({str(k).strip() for k in keys if str(k).strip()})
|
||||
|
||||
|
||||
def _line_keys_hash(keys: list[str]) -> str:
|
||||
"""行集合指纹。"""
|
||||
payload = json.dumps(_stable_line_keys(keys), ensure_ascii=False, separators=(',', ':'))
|
||||
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _snapshot_fingerprint(lines: list[dict[str, Any]], keys: list[str]) -> tuple[int | None, str]:
|
||||
"""
|
||||
从行投影提取库存快照指纹。
|
||||
|
||||
Returns:
|
||||
(单一 snapshot_id 或 None, fingerprint 字符串)。
|
||||
"""
|
||||
ids: list[int] = []
|
||||
by_key = {str(item.get('line_key') or ''): item for item in lines}
|
||||
for key in keys:
|
||||
item = by_key.get(key) or {}
|
||||
raw = item.get('inventory_snapshot_id')
|
||||
if raw is None or raw == '':
|
||||
continue
|
||||
try:
|
||||
ids.append(int(raw))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
unique = sorted(set(ids))
|
||||
fingerprint = ','.join(str(i) for i in unique) if unique else 'none'
|
||||
single = unique[0] if len(unique) == 1 else None
|
||||
return single, fingerprint
|
||||
|
||||
|
||||
def _params_conflict(
|
||||
row: ShippingOrderReviewWaveIdempotency,
|
||||
*,
|
||||
line_keys: list[str],
|
||||
fingerprint: str,
|
||||
decision_source: str,
|
||||
) -> bool:
|
||||
"""同 key 参数是否与已存记录冲突。"""
|
||||
if str(row.decision_source or '') != str(decision_source):
|
||||
return True
|
||||
if str(row.line_keys_hash or '') != _line_keys_hash(line_keys):
|
||||
return True
|
||||
if str(row.inventory_snapshot_fingerprint or '') != str(fingerprint):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def create_post_ot_fulfillment_wave(
|
||||
*,
|
||||
case_no: str,
|
||||
line_keys: list[str],
|
||||
decision_source: str = 'system',
|
||||
actor_user_id: int | None = None,
|
||||
reason: str | None = None,
|
||||
idempotency_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
在已有正式 OT 上为选中行创建履约波次(不调用 confirm_review_case)。
|
||||
|
||||
核心逻辑:要求 has_formal_ot;按 line_fulfillment 事实重校验;独立幂等表回放/409;
|
||||
新行写入 wave_lines 并更新决定为 task_created。
|
||||
|
||||
Args:
|
||||
case_no: Case 编号。
|
||||
line_keys: 本波次行键。
|
||||
decision_source: system | user。
|
||||
actor_user_id: 人工操作人;系统可为 None。
|
||||
reason: 备注。
|
||||
idempotency_key: 可选幂等键(独立表强约束)。
|
||||
|
||||
Returns:
|
||||
wave_no / task_no / accepted_line_keys / skipped_line_keys / line_fulfillment /
|
||||
idempotency_row_id / idempotent_replay。
|
||||
"""
|
||||
keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()]
|
||||
if not keys:
|
||||
raise ValidationError('line_keys required', code='SHIPPING.REVIEW_LINE_WAVE_EMPTY')
|
||||
if len(keys) != len(set(keys)):
|
||||
raise ValidationError('Duplicate line_keys', code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE')
|
||||
source = str(decision_source or 'system').strip()
|
||||
if source not in {'system', 'user'}:
|
||||
raise ValidationError('Invalid decision_source', code='SHIPPING.REVIEW_DECISION_SOURCE_INVALID')
|
||||
idem_key = str(idempotency_key or '').strip()[:191] or None
|
||||
|
||||
# [STEP 1] 加载 Case 与正式 OT
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=str(case_no or '').strip())
|
||||
.first()
|
||||
)
|
||||
if case is None:
|
||||
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
assert_case_is_current_workflow_version(case=case)
|
||||
formal = resolve_formal_ot(case)
|
||||
if not formal.get('has_formal_ot') or formal.get('task') is None:
|
||||
raise ConflictError(
|
||||
'Formal OT required for post-OT fulfillment wave',
|
||||
code='SHIPPING.REVIEW_POST_OT_WAVE_REQUIRES_OT',
|
||||
)
|
||||
task: ShippingNotice = formal['task']
|
||||
|
||||
projected = project_review_case_line_decisions(case)
|
||||
projected_lines = [item for item in list(projected.get('lines') or []) if isinstance(item, dict)]
|
||||
by_key = {
|
||||
str(item.get('line_key') or ''): item
|
||||
for item in projected_lines
|
||||
}
|
||||
snap_id, snap_fp = _snapshot_fingerprint(projected_lines, keys)
|
||||
|
||||
# [STEP 1b] 幂等回放 / 参数冲突 409
|
||||
if idem_key:
|
||||
existing = (
|
||||
ShippingOrderReviewWaveIdempotency.query
|
||||
.filter_by(idempotency_key=idem_key)
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
if _params_conflict(
|
||||
existing,
|
||||
line_keys=keys,
|
||||
fingerprint=snap_fp,
|
||||
decision_source=source,
|
||||
):
|
||||
raise ConflictError(
|
||||
'Idempotency key reuse with conflicting wave parameters',
|
||||
code='SHIPPING.REVIEW_POST_OT_WAVE_IDEMPOTENCY_CONFLICT',
|
||||
details={
|
||||
'idempotency_key': idem_key,
|
||||
'existing_line_keys_hash': existing.line_keys_hash,
|
||||
'existing_snapshot_fingerprint': existing.inventory_snapshot_fingerprint,
|
||||
'existing_decision_source': existing.decision_source,
|
||||
},
|
||||
)
|
||||
replay = dict(existing.result_json or {})
|
||||
replay['idempotent_replay'] = True
|
||||
replay['idempotency_row_id'] = int(existing.id)
|
||||
replay['line_fulfillment'] = project_review_case_line_decisions(case)
|
||||
return replay
|
||||
|
||||
assigned = {
|
||||
str(row.line_key)
|
||||
for row in ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(case.id)).all()
|
||||
}
|
||||
|
||||
accepted: list[str] = []
|
||||
skipped: list[str] = []
|
||||
for key in keys:
|
||||
if key in assigned:
|
||||
skipped.append(key)
|
||||
continue
|
||||
line = by_key.get(key)
|
||||
if line is None:
|
||||
raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
|
||||
if str(line.get('line_status') or '') == 'closed_unfulfillable':
|
||||
raise ConflictError(
|
||||
'Closed line cannot enter wave',
|
||||
code='SHIPPING.REVIEW_LINE_CLOSED',
|
||||
details={'line_key': key},
|
||||
)
|
||||
_assert_fact_allows_fulfill(line)
|
||||
accepted.append(key)
|
||||
|
||||
wave_no = None
|
||||
if accepted:
|
||||
max_wave = (
|
||||
db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no))
|
||||
.filter(ShippingOrderReviewWaveLine.review_case_id == int(case.id))
|
||||
.scalar()
|
||||
)
|
||||
wave_no = int(max_wave or 0) + 1
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
_persist_wave_lines_for_task,
|
||||
)
|
||||
_persist_wave_lines_for_task(
|
||||
case=case,
|
||||
task=task,
|
||||
line_keys=accepted,
|
||||
wave_no=wave_no,
|
||||
revision_id=None,
|
||||
)
|
||||
|
||||
# [STEP 2] 写入/推进履约决定(含已在 wave 的幂等行)
|
||||
draft_lines = _draft_line_map(case)
|
||||
now = datetime.utcnow()
|
||||
for key in keys:
|
||||
line = by_key.get(key) or {}
|
||||
current = _active_decision(case, key)
|
||||
if current is not None and current.line_status in {'task_created', 'fulfilled'}:
|
||||
continue
|
||||
if current is not None:
|
||||
current.is_active = False
|
||||
current.updated_at = now
|
||||
req = str(line.get('required_qty') or '') or None
|
||||
avail = str(line.get('available_qty') or '') or None
|
||||
row = ShippingOrderReviewLineDecision(
|
||||
review_case_id=int(case.id),
|
||||
line_key=key,
|
||||
line_index=(draft_lines.get(key) or {}).get('_line_index'),
|
||||
decision_version=_next_version(case, key),
|
||||
decision_code=DECISION_FULFILL,
|
||||
decision_source=source,
|
||||
line_status='task_created' if key in assigned or key in accepted else _STATUS_BY_DECISION[DECISION_FULFILL],
|
||||
is_active=True,
|
||||
reason=str(reason or '').strip()[:2000] or None,
|
||||
required_qty=req,
|
||||
available_qty=avail,
|
||||
reservation_id=line.get('reservation_id'),
|
||||
part_number=line.get('part_number'),
|
||||
task_id=int(task.id),
|
||||
wave_no=wave_no if key in accepted else (
|
||||
int(current.wave_no) if current is not None and current.wave_no is not None else None
|
||||
),
|
||||
actor_user_id=int(actor_user_id) if actor_user_id is not None else None,
|
||||
snapshot_json={
|
||||
'decision_code': DECISION_FULFILL,
|
||||
'decision_source': source,
|
||||
'idempotency_key': idem_key,
|
||||
'inventory_snapshot_id': line.get('inventory_snapshot_id'),
|
||||
'match_result': line.get('match_result'),
|
||||
},
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
if key in accepted:
|
||||
row.line_status = 'task_created'
|
||||
row.wave_no = wave_no
|
||||
elif key in assigned:
|
||||
row.line_status = 'task_created'
|
||||
existing_wave = (
|
||||
ShippingOrderReviewWaveLine.query
|
||||
.filter_by(review_case_id=int(case.id), line_key=key)
|
||||
.first()
|
||||
)
|
||||
if existing_wave is not None:
|
||||
row.wave_no = int(existing_wave.wave_no)
|
||||
db.session.add(row)
|
||||
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
record_fulfillment_audit(
|
||||
event_type='review_post_ot_fulfillment_wave',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
action='create_post_ot_fulfillment_wave',
|
||||
actor_type='system' if source == 'system' else 'user',
|
||||
actor_id=int(actor_user_id) if actor_user_id is not None else None,
|
||||
review_case_no=str(case.case_no),
|
||||
run_no=str(case.run.run_no) if case.run is not None else None,
|
||||
task_no=str(task.task_no),
|
||||
before_json={'line_keys': keys},
|
||||
after_json={
|
||||
'wave_no': wave_no,
|
||||
'accepted_line_keys': accepted,
|
||||
'skipped_line_keys': skipped,
|
||||
'decision_source': source,
|
||||
'idempotency_key': idem_key,
|
||||
},
|
||||
)
|
||||
|
||||
result = {
|
||||
'case_no': case.case_no,
|
||||
'task_no': task.task_no,
|
||||
'task_id': int(task.id),
|
||||
'review_case_id': int(case.id),
|
||||
'wave_no': wave_no,
|
||||
'accepted_line_keys': accepted,
|
||||
'skipped_line_keys': skipped,
|
||||
'decision_source': source,
|
||||
'idempotent_replay': False,
|
||||
'line_fulfillment': project_review_case_line_decisions(case),
|
||||
}
|
||||
|
||||
# [STEP 3] 持久化幂等记录(无显式 key 时用 UUID,避免误撞自然键)
|
||||
import uuid
|
||||
persist_key = idem_key or f'post-ot-wave:{uuid.uuid4().hex}'[:191]
|
||||
idem_row = ShippingOrderReviewWaveIdempotency(
|
||||
idempotency_key=persist_key,
|
||||
review_case_id=int(case.id),
|
||||
task_id=int(task.id),
|
||||
task_no=str(task.task_no),
|
||||
wave_no=wave_no,
|
||||
decision_source=source,
|
||||
line_keys_json=_stable_line_keys(keys),
|
||||
line_keys_hash=_line_keys_hash(keys),
|
||||
inventory_snapshot_id=snap_id,
|
||||
inventory_snapshot_fingerprint=snap_fp,
|
||||
status='succeeded',
|
||||
result_json={k: v for k, v in result.items() if k != 'line_fulfillment'},
|
||||
progress_status='pending',
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(idem_row)
|
||||
db.session.flush()
|
||||
result['idempotency_row_id'] = int(idem_row.id)
|
||||
result['idempotency_key'] = persist_key
|
||||
idem_row.result_json = {k: v for k, v in result.items() if k != 'line_fulfillment'}
|
||||
db.session.flush()
|
||||
return result
|
||||
|
||||
|
||||
def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
|
||||
"""
|
||||
列出可自动/人工完整履约的行(ready+matched+非短缺+未关闭+未终态)。
|
||||
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
|
||||
Returns:
|
||||
line_key 列表。
|
||||
"""
|
||||
projected = project_review_case_line_decisions(case)
|
||||
out: list[str] = []
|
||||
for item in list(projected.get('lines') or []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if str(item.get('line_status') or '') in {'closed_unfulfillable', 'fulfilled', 'task_created'}:
|
||||
continue
|
||||
if str(item.get('inventory_status') or '') != 'ready':
|
||||
continue
|
||||
if str(item.get('match_result') or '') != 'matched':
|
||||
continue
|
||||
if item.get('is_shortage'):
|
||||
continue
|
||||
if item.get('user_line_status') == 'auto_fulfill_failed':
|
||||
continue
|
||||
if item.get('auto_fulfill_failed'):
|
||||
continue
|
||||
req = _parse_qty(item.get('required_qty'))
|
||||
avail = _parse_qty(item.get('available_qty'))
|
||||
if req is None or avail is None or avail < req:
|
||||
continue
|
||||
out.append(str(item.get('line_key') or ''))
|
||||
return [k for k in out if k]
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
services/shipping_notice/post_ot_wave_progress_service.py
|
||||
|
||||
用途:正式 OT 后履约 wave 的专用推进调度(Excel/RPA),禁止复用 confirm 后整单推进。
|
||||
依赖:Job 队列、ShippingOrderReviewWaveIdempotency、fulfillment_workflow.generate_excel。
|
||||
逻辑:create_post_ot_fulfillment_wave 成功后调用;幂等键含 wave_no;下游失败只标 progress_failed,不回滚 wave。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import ShippingOrderReviewWaveIdempotency
|
||||
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
|
||||
|
||||
|
||||
def _progress_idempotency_key(
|
||||
*,
|
||||
task_no: str,
|
||||
wave_no: int | None,
|
||||
request_key: str | None,
|
||||
) -> str:
|
||||
"""构造 wave 推进幂等键(含 wave_no)。"""
|
||||
wave_token = f'w{int(wave_no)}' if wave_no is not None else 'w0'
|
||||
base = str(request_key or '').strip() or 'anon'
|
||||
return f'post-ot-wave-progress:{str(task_no).strip().upper()}:{wave_token}:{base}'[:191]
|
||||
|
||||
|
||||
def schedule_post_ot_wave_progress(
|
||||
*,
|
||||
task_no: str,
|
||||
wave_no: int | None,
|
||||
line_keys: list[str],
|
||||
review_case_id: int | None = None,
|
||||
idempotency_row_id: int | None = None,
|
||||
request_idempotency_key: str | None = None,
|
||||
created_by_id: int | None = None,
|
||||
commit: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为本 wave 入队 Excel/RPA 推进 Job;不得调用 schedule_auto_progress_after_review_confirm。
|
||||
|
||||
核心逻辑:幂等键含 task_no+wave_no;同进度键已有 Job 则复用;仅推进本 wave 上下文。
|
||||
|
||||
Args:
|
||||
task_no: 正式 OT 编号。
|
||||
wave_no: 本波次号;可为 None(仅跳过行时)。
|
||||
line_keys: 本波行键。
|
||||
review_case_id: 复核 Case id。
|
||||
idempotency_row_id: wave 幂等行 id(用于回写 progress_*)。
|
||||
request_idempotency_key: 原始 wave 请求幂等键。
|
||||
created_by_id: 操作人(审计)。
|
||||
commit: 是否自行提交入队。
|
||||
|
||||
Returns:
|
||||
调度摘要(progress_status / job_id / progress_idempotency_key)。
|
||||
"""
|
||||
_ = created_by_id
|
||||
normalized = str(task_no or '').strip().upper()
|
||||
keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()]
|
||||
if not normalized:
|
||||
return {
|
||||
'auto_progress_started': False,
|
||||
'status': 'not_scheduled',
|
||||
'reason': 'missing_task_no',
|
||||
'wave_no': wave_no,
|
||||
}
|
||||
if wave_no is None and not keys:
|
||||
return {
|
||||
'auto_progress_started': False,
|
||||
'status': 'skipped',
|
||||
'reason': 'no_new_wave_lines',
|
||||
'wave_no': None,
|
||||
}
|
||||
|
||||
progress_key = _progress_idempotency_key(
|
||||
task_no=normalized,
|
||||
wave_no=wave_no,
|
||||
request_key=request_idempotency_key,
|
||||
)
|
||||
|
||||
# [STEP 1] 同进度键已调度则幂等返回
|
||||
existing = (
|
||||
ShippingOrderReviewWaveIdempotency.query
|
||||
.filter_by(progress_idempotency_key=progress_key)
|
||||
.first()
|
||||
)
|
||||
if existing is not None and existing.progress_job_id is not None:
|
||||
return {
|
||||
'auto_progress_started': True,
|
||||
'status': 'idempotent_replay',
|
||||
'wave_no': existing.wave_no,
|
||||
'progress_status': existing.progress_status,
|
||||
'progress_job_id': int(existing.progress_job_id),
|
||||
'progress_idempotency_key': progress_key,
|
||||
}
|
||||
|
||||
# [STEP 2] 入队本 wave 推进 Job
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_POST_OT_WAVE_PROGRESS,
|
||||
{
|
||||
'task_no': normalized,
|
||||
'wave_no': int(wave_no) if wave_no is not None else None,
|
||||
'line_keys': keys,
|
||||
'review_case_id': int(review_case_id) if review_case_id is not None else None,
|
||||
'idempotency_row_id': int(idempotency_row_id) if idempotency_row_id is not None else None,
|
||||
'progress_idempotency_key': progress_key,
|
||||
},
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
business_ref=normalized,
|
||||
message=f'post-OT wave={wave_no} Excel/RPA 推进',
|
||||
max_attempts=3,
|
||||
commit=commit,
|
||||
)
|
||||
|
||||
row = None
|
||||
if idempotency_row_id is not None:
|
||||
row = db.session.get(ShippingOrderReviewWaveIdempotency, int(idempotency_row_id))
|
||||
if row is None and review_case_id is not None and wave_no is not None:
|
||||
row = (
|
||||
ShippingOrderReviewWaveIdempotency.query
|
||||
.filter_by(review_case_id=int(review_case_id), wave_no=int(wave_no))
|
||||
.order_by(ShippingOrderReviewWaveIdempotency.id.desc())
|
||||
.first()
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
if row is not None:
|
||||
row.progress_status = 'scheduled'
|
||||
row.progress_job_id = int(job_id) if job_id is not None else None
|
||||
row.progress_idempotency_key = progress_key
|
||||
row.progress_error = None
|
||||
row.updated_at = now
|
||||
db.session.flush()
|
||||
|
||||
return {
|
||||
'auto_progress_started': job_id is not None,
|
||||
'status': 'queued' if job_id is not None else 'enqueue_failed',
|
||||
'wave_no': wave_no,
|
||||
'progress_status': 'scheduled' if job_id is not None else 'failed',
|
||||
'progress_job_id': int(job_id) if job_id is not None else None,
|
||||
'progress_idempotency_key': progress_key,
|
||||
'line_keys': keys,
|
||||
}
|
||||
|
||||
|
||||
def mark_post_ot_wave_progress_result(
|
||||
*,
|
||||
idempotency_row_id: int | None,
|
||||
progress_idempotency_key: str | None,
|
||||
ok: bool,
|
||||
error: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
回写本 wave 推进结果;失败只更新 progress_*,不删除 wave_lines。
|
||||
|
||||
Args:
|
||||
idempotency_row_id: 幂等行主键。
|
||||
progress_idempotency_key: 推进幂等键。
|
||||
ok: 是否成功。
|
||||
error: 失败原因。
|
||||
"""
|
||||
row = None
|
||||
if idempotency_row_id is not None:
|
||||
row = db.session.get(ShippingOrderReviewWaveIdempotency, int(idempotency_row_id))
|
||||
if row is None and progress_idempotency_key:
|
||||
row = (
|
||||
ShippingOrderReviewWaveIdempotency.query
|
||||
.filter_by(progress_idempotency_key=str(progress_idempotency_key))
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
return
|
||||
row.progress_status = 'succeeded' if ok else 'failed'
|
||||
row.progress_error = (str(error)[:2000] if error and not ok else None)
|
||||
row.updated_at = datetime.utcnow()
|
||||
@@ -6,6 +6,7 @@ services/shipping_notice/process_gate_projection.py
|
||||
error_explainability_contract(统一 explainability / request_id)。
|
||||
逻辑:Chat、复核台与任务中心读取用户安全投影;管理员诊断中心读取完整投影;
|
||||
用户端同一时间最多一个阻断 + 一个主要恢复动作;诊断 Finding 不进入用户阻断;
|
||||
pending/queued/running 不冒充人工待办,但保留 execution_status 供观测;
|
||||
explainability.details 仅白名单业务事实;request_id 仅真实 HTTP 请求号,
|
||||
execution_no 写入 details;blocking_message 为中文兜底,前端优先 i18n。
|
||||
"""
|
||||
@@ -270,9 +271,11 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
|
||||
核心逻辑:技术 Gate(system/worker)的 POST 重试动作不对业务用户投影;
|
||||
仅保留导航至复核工作台的业务动作。业务用户看到「系统自动处理中」只读态。
|
||||
正式 OT 创建后的建单前 Gate 清除、owner_type 分层由
|
||||
order_review_workbench_projection.apply_post_ot_gate_rules 在 Case 序列化时叠加。
|
||||
|
||||
Returns:
|
||||
current_blocking_gate、reason、next_action、diagnostic_hint(可选非阻断提示)。
|
||||
current_blocking_gate、reason、next_action、diagnostic_hint、technical_auto_only。
|
||||
"""
|
||||
full = serialize_process_execution(execution, include_diagnostics=False)
|
||||
current = full.get('current_gate')
|
||||
@@ -281,14 +284,23 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated',
|
||||
}:
|
||||
blocking = current
|
||||
# [STEP] 已通过的客户确认不得再成为用户当前阻断;pending/queued 技术 Gate 也不冒充人工优先处理。
|
||||
# [STEP] 已通过的客户确认不得再成为用户当前阻断;pending/queued/running 不冒充人工待办,
|
||||
# 但保留 execution_status 供 OT 后观测(系统等待 ≠ 无 Gate)。
|
||||
execution_status = None
|
||||
if blocking:
|
||||
gate_code = str(blocking.get('gate_code') or '').strip().lower()
|
||||
gate_status = str(blocking.get('status') or '').strip().lower()
|
||||
if gate_code in {'customer_resolution', 'customer_confirmed'} and gate_status == 'passed':
|
||||
blocking = None
|
||||
elif gate_status in {'pending', 'queued', 'running', 'passed', 'skipped'}:
|
||||
elif gate_status in {'pending', 'queued', 'running'}:
|
||||
execution_status = gate_status
|
||||
blocking = None
|
||||
elif gate_status in {'passed', 'skipped'}:
|
||||
blocking = None
|
||||
if execution_status is None:
|
||||
full_status = str(full.get('status') or '').strip().lower()
|
||||
if full_status in {'pending', 'queued', 'running'}:
|
||||
execution_status = full_status
|
||||
diagnostic_hint = None
|
||||
for gate in full.get('gates') or []:
|
||||
for finding in gate.get('findings') or []:
|
||||
@@ -337,12 +349,17 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
|
||||
return {
|
||||
'execution_no': full.get('execution_no'),
|
||||
'status': full.get('status'),
|
||||
'execution_status': execution_status,
|
||||
'current_blocking_gate': blocking,
|
||||
'blocking_reason_code': reason_code,
|
||||
'blocking_message': _user_facing_blocking_message(reason_code),
|
||||
'explainability': explainability,
|
||||
'next_action_code': next_action,
|
||||
'technical_auto_only': technical_auto_only,
|
||||
'owner_type': (
|
||||
'system' if technical_auto_only or execution_status
|
||||
else ('human' if blocking and next_action else ('unknown' if blocking else 'system'))
|
||||
),
|
||||
'responsible_party': (
|
||||
(explainability or {}).get('responsible_party')
|
||||
or full.get('responsible_party')
|
||||
|
||||
@@ -165,7 +165,8 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
|
||||
【触发时机】写状态机回写 OT、投影组装 order_task 工作项。
|
||||
|
||||
核心逻辑:上传完成 → completed;上传中/待上传 → freight_uploading;
|
||||
导出/Excel → excel_generating;匹配 → inventory_matching;建单/拉库存细分。
|
||||
导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching;
|
||||
matching/inventory_ready/matched → inventory_matching;建单中 → order_creating。
|
||||
领域映射唯一来源,禁止写状态机反向依赖投影私有函数。
|
||||
|
||||
Args:
|
||||
@@ -191,15 +192,19 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
|
||||
if ps == 'matched' and export_path:
|
||||
return ('automating', 'excel_generating')
|
||||
|
||||
if ps in {'matching', 'inventory_ready', 'waiting_inventory', 'matched', 'parsed'} or 'match' in step:
|
||||
if ps in {'matching', 'inventory_ready', 'matched'} or 'match' in step:
|
||||
return ('automating', 'inventory_matching')
|
||||
|
||||
# 正式建单后的库存获取:waiting_inventory / parsed → 获取库存(禁止仍映射到 matching)。
|
||||
if ps in {'waiting_inventory', 'parsed'} or 'fetch' in step or step.startswith('step4'):
|
||||
return ('automating', 'inventory_fetching')
|
||||
|
||||
if ps == 'pending_review':
|
||||
return ('waiting_review', 'waiting_review')
|
||||
|
||||
if ps in {'creating', 'order_creating', 'confirming'} or 'create' in step or step.startswith('step3'):
|
||||
return ('automating', 'order_creating')
|
||||
if ps in {'fetching_inventory', 'inventory_fetching'} or 'fetch' in step or step.startswith('step4'):
|
||||
if ps in {'fetching_inventory', 'inventory_fetching'}:
|
||||
return ('automating', 'inventory_fetching')
|
||||
if ps in {'parsing', 'parsed_pending'}:
|
||||
return ('automating', 'order_creating')
|
||||
|
||||
@@ -231,12 +231,20 @@ def claim_next_shipping_notice_job() -> Job | None:
|
||||
JobType.SHIPPING_PROCESS_GATE,
|
||||
JobType.SHIPPING_XFA_OCR_AUTOMARK,
|
||||
JobType.SHIPPING_STP_AUTO_CREATE,
|
||||
JobType.SHIPPING_LINE_AUTO_FULFILL,
|
||||
JobType.SHIPPING_POST_OT_WAVE_PROGRESS,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | None = None) -> tuple[bool, str]:
|
||||
"""执行单票发货任务;既可被通用 Job handler 调用,也可被 sync enqueue 直调。"""
|
||||
"""
|
||||
执行单票发货任务;既可被通用 Job handler 调用,也可被 sync enqueue 直调。
|
||||
|
||||
核心逻辑:委托 batch_orchestrator._run_single_task;若 Job 软成功但
|
||||
OT 仍停在 created(已挂 Extraction),则 fail_job 并带
|
||||
auto_progress_job_succeeded_but_task_not_advanced,供幂等重试直至 max_attempts。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_orchestrator import _run_single_task
|
||||
|
||||
raw_job_id = payload.get('job_id')
|
||||
@@ -265,6 +273,26 @@ def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | No
|
||||
status = str(result.get('status') or '').strip().lower()
|
||||
success = status in {'ok', 'running', 'needs_human', 'skipped'}
|
||||
|
||||
# [STEP] 正式 OT 已挂 Extraction 却仍停在 created:软成功不得 finish Job,须 fail/重试。
|
||||
# 根因:orchestrator 对 created+extraction 调 auto_progress 后若未推进,旧逻辑仍会 finish_job。
|
||||
refreshed = get_task_by_ref(task_no)
|
||||
hang_created = bool(
|
||||
refreshed is not None
|
||||
and getattr(refreshed, 'current_order_extraction_id', None)
|
||||
and str(getattr(refreshed, 'process_status', None) or '').strip().lower() in {'', 'created'}
|
||||
and status in {'ok', 'needs_human', 'skipped'}
|
||||
)
|
||||
if hang_created:
|
||||
success = False
|
||||
status = 'failed'
|
||||
result = {
|
||||
**dict(result or {}),
|
||||
'status': 'failed',
|
||||
'error_code': 'auto_progress_job_succeeded_but_task_not_advanced',
|
||||
'message': str(result.get('message') or '')
|
||||
or '自动推进 Job 结束但正式 OT 仍停在 created,将按幂等重试',
|
||||
}
|
||||
|
||||
if job_id is not None:
|
||||
job = db.session.get(Job, job_id)
|
||||
if job is not None:
|
||||
|
||||
@@ -12,6 +12,7 @@ services/shipping_notice/shipping_processing_projection.py
|
||||
Intake/OT 均填充 current_gate(优先真实 ProcessExecution)与 source_summary;
|
||||
输出前 reconcile status/stage/gate/action,并结合 Notice 失效起点 / Excel Artifact
|
||||
写入 stage_nodes 与 available_actions;stage/status 以 OT 已写入值为准(BE-07,禁止 Notice 覆盖);
|
||||
已挂正式 Notice 时 stage/stage_label_key 与 Case.current_stage 同源(project_stage_for_task);
|
||||
**只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert);已建 Notice 时填 shipping_notice_no;
|
||||
work_items 构建后由 _conversation_processing_from_work_items 重建兼容 conversation_processing。
|
||||
"""
|
||||
@@ -967,6 +968,22 @@ def _project_order_task_work_item(
|
||||
)
|
||||
if stage not in SHIPPING_PROCESSING_STAGES:
|
||||
stage = map_run_to_processing_stage(run, source_type=source_type)
|
||||
# [BE-02] 已挂正式 Notice 时与 Case.current_stage 同源(project_stage_for_task)。
|
||||
stage_label_key = None
|
||||
if order_task.shipping_notice_id:
|
||||
notice_for_stage = db.session.get(ShippingNotice, int(order_task.shipping_notice_id))
|
||||
if notice_for_stage is not None:
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
project_stage_for_task,
|
||||
)
|
||||
shared = project_stage_for_task(notice_for_stage)
|
||||
shared_code = str(shared.get('code') or '').strip().lower()
|
||||
if shared_code in SHIPPING_PROCESSING_STAGES:
|
||||
stage = shared_code
|
||||
stage_label_key = str(shared.get('label_key') or '').strip() or None
|
||||
# order_creating 无共享投影时仍统一用户文案键。
|
||||
if not stage_label_key and stage == 'order_creating':
|
||||
stage_label_key = 'waiting_system_start'
|
||||
raw_status = str(getattr(order_task, 'status', None) or '').strip().lower()
|
||||
if raw_status in SHIPPING_PROCESSING_STATUSES:
|
||||
status = raw_status
|
||||
@@ -1047,6 +1064,10 @@ def _project_order_task_work_item(
|
||||
'intake_no': _first_intake_no_for_run(run),
|
||||
'status': status,
|
||||
'stage': stage,
|
||||
# 与 Case.current_stage.label_key 同源;前端禁止用 stage 码直接当用户文案。
|
||||
'stage_label_key': stage_label_key or (
|
||||
'waiting_system_start' if stage == 'order_creating' else stage
|
||||
),
|
||||
'progress_version': int(
|
||||
getattr(order_task, 'progress_version', None)
|
||||
or getattr(run, 'progress_version', None)
|
||||
|
||||
@@ -649,6 +649,7 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N
|
||||
将命名状态迁移写入 ShippingNotice 的 process_status / review_status / pending_human_reason。
|
||||
|
||||
核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。
|
||||
库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → inventory_fetching 等)。
|
||||
|
||||
Args:
|
||||
task: 待更新的 ShippingNotice 实例(尚未 commit)。
|
||||
@@ -663,3 +664,12 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N
|
||||
task.pending_human_reason = spec.pending_human_reason
|
||||
if spec.clear_error_message:
|
||||
task.error_message = None
|
||||
|
||||
# [STEP] 履约态变更后回写 OT stage,避免进度条卡在 order_creating。
|
||||
try:
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_notice,
|
||||
)
|
||||
sync_order_task_stage_for_notice(task)
|
||||
except Exception: # noqa: BLE001 — 无 OT / 无 Flask 上下文时跳过,不阻断主迁移
|
||||
pass
|
||||
@@ -33,6 +33,11 @@ def _norm_part(value: Any) -> str:
|
||||
return str(value or '').strip().upper()
|
||||
|
||||
|
||||
def _norm_unit(value: Any) -> str:
|
||||
"""单位匹配键:去空白并大写;空串表示未配置单位。"""
|
||||
return str(value or '').strip().upper()
|
||||
|
||||
|
||||
def _qty(value: Any) -> Decimal:
|
||||
"""解析数量;非法视为 0。"""
|
||||
try:
|
||||
@@ -41,19 +46,20 @@ def _qty(value: Any) -> Decimal:
|
||||
return Decimal('0')
|
||||
|
||||
|
||||
def _inventory_row_key(row: dict[str, Any]) -> tuple[str, str] | None:
|
||||
def _inventory_row_key(row: dict[str, Any]) -> tuple[str, str, str] | None:
|
||||
"""
|
||||
从库存行提取 Reservation + Part Number 键。
|
||||
从库存行提取 Reservation + Part Number + Unit 键。
|
||||
|
||||
核心逻辑:优先标准键名,兼容常见别名;不做数值归一化 Reservation。
|
||||
核心逻辑:优先标准键名,兼容常见别名;单位缺省为空串(与订单侧对齐后参与匹配)。
|
||||
"""
|
||||
reservation = validated_reservation_id(
|
||||
row.get('reservation_id') or row.get('Reservation ID') or row.get('reservation')
|
||||
)
|
||||
part = _norm_part(row.get('part_number') or row.get('Part Number') or row.get('mpn') or row.get('sku'))
|
||||
unit = _norm_unit(row.get('uom') or row.get('unit') or row.get('UOM') or row.get('Unit'))
|
||||
if not reservation or not part:
|
||||
return None
|
||||
return reservation, part
|
||||
return reservation, part, unit
|
||||
|
||||
|
||||
def _inventory_row_qty(row: dict[str, Any]) -> Decimal:
|
||||
@@ -205,18 +211,18 @@ def match_order_lines_across_candidates(
|
||||
header_reservation_id: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
跨候选库存行按有效 Reservation + Part Number 匹配。
|
||||
跨候选库存行按有效 Reservation + Part Number + Unit 匹配。
|
||||
|
||||
Args:
|
||||
order_lines: 含 part_number / reservation_id / quantity(或 qty)的订单行。
|
||||
order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。
|
||||
inventory_lines: 已打 ``__source_code`` 的库存行。
|
||||
header_reservation_id: 头级 Reservation,用于行级回退。
|
||||
|
||||
Returns:
|
||||
match_status、line_results、shortage_json、resolutions。
|
||||
"""
|
||||
# [STEP 1] 按 (reservation, part, source) 聚合可用量与样例行。
|
||||
buckets: dict[tuple[str, str, str], dict[str, Any]] = {}
|
||||
# [STEP 1] 按 (reservation, part, unit, source) 聚合可用量与样例行。
|
||||
buckets: dict[tuple[str, str, str, str], dict[str, Any]] = {}
|
||||
for row in inventory_lines:
|
||||
key = _inventory_row_key(row)
|
||||
if key is None:
|
||||
@@ -224,7 +230,7 @@ def match_order_lines_across_candidates(
|
||||
source = str(row.get('__source_code') or '').strip().upper()
|
||||
if not source:
|
||||
continue
|
||||
bucket_key = (key[0], key[1], source)
|
||||
bucket_key = (key[0], key[1], key[2], source)
|
||||
bucket = buckets.get(bucket_key)
|
||||
if bucket is None:
|
||||
bucket = {'available_qty': Decimal('0'), 'sample_row': row, 'source_code': source}
|
||||
@@ -239,15 +245,23 @@ def match_order_lines_across_candidates(
|
||||
|
||||
for index, line in enumerate(order_lines):
|
||||
part = _norm_part(line.get('part_number') or line.get('__display_part_number'))
|
||||
unit = _norm_unit(
|
||||
line.get('uom')
|
||||
or line.get('unit')
|
||||
or line.get('__display_uom')
|
||||
)
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=line.get('reservation_id') or line.get('__display_reservation_id'),
|
||||
header_reservation_id=header_reservation_id,
|
||||
)
|
||||
required = _qty(line.get('quantity') if line.get('quantity') is not None else line.get('__required_qty', line.get('qty')))
|
||||
# [STEP] 订单带单位时只命中同单位库存;双方皆空则退化为料号+预约单。
|
||||
source_hits = [
|
||||
buckets[key]
|
||||
for key in buckets
|
||||
if key[0] == (effective or '') and key[1] == part
|
||||
if key[0] == (effective or '')
|
||||
and key[1] == part
|
||||
and key[2] == unit
|
||||
] if effective and part else []
|
||||
|
||||
if not effective or not part:
|
||||
@@ -256,6 +270,7 @@ def match_order_lines_across_candidates(
|
||||
'line_index': index,
|
||||
'part_number': part or None,
|
||||
'reservation_id': effective,
|
||||
'unit': unit or None,
|
||||
'required_qty': float(required),
|
||||
'available_qty': 0.0,
|
||||
'shortage_qty': float(required),
|
||||
@@ -270,6 +285,7 @@ def match_order_lines_across_candidates(
|
||||
'line_index': index,
|
||||
'part_number': part,
|
||||
'reservation_id': effective,
|
||||
'unit': unit or None,
|
||||
'required_qty': float(required),
|
||||
'available_qty': float(sum(item['available_qty'] for item in source_hits)),
|
||||
'shortage_qty': 0.0,
|
||||
@@ -285,6 +301,7 @@ def match_order_lines_across_candidates(
|
||||
'line_index': index,
|
||||
'part_number': part,
|
||||
'reservation_id': effective,
|
||||
'unit': unit or None,
|
||||
'required_qty': float(required),
|
||||
'available_qty': 0.0,
|
||||
'shortage_qty': float(required),
|
||||
@@ -303,6 +320,7 @@ def match_order_lines_across_candidates(
|
||||
'line_index': index,
|
||||
'part_number': part,
|
||||
'reservation_id': effective,
|
||||
'unit': unit or None,
|
||||
'required_qty': float(required),
|
||||
'available_qty': float(available),
|
||||
'shortage_qty': 0.0,
|
||||
@@ -313,6 +331,7 @@ def match_order_lines_across_candidates(
|
||||
'inventory_row_ref': {
|
||||
'reservation_id': effective,
|
||||
'part_number': part,
|
||||
'unit': unit or None,
|
||||
'source_code': hit['source_code'],
|
||||
},
|
||||
}
|
||||
@@ -323,6 +342,7 @@ def match_order_lines_across_candidates(
|
||||
'line_index': index,
|
||||
'part_number': part,
|
||||
'reservation_id': effective,
|
||||
'unit': unit or None,
|
||||
'required_qty': float(required),
|
||||
'available_qty': float(available),
|
||||
'shortage_qty': float(max(required - available, Decimal('0'))),
|
||||
@@ -339,6 +359,7 @@ def match_order_lines_across_candidates(
|
||||
'disposition': result['disposition'],
|
||||
'effective_reservation_id': effective,
|
||||
'part_number': part or None,
|
||||
'unit': unit or None,
|
||||
'resolved_inventory_source_code': result.get('resolved_inventory_source_code'),
|
||||
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
|
||||
'inventory_file_no': result.get('inventory_file_no'),
|
||||
|
||||
@@ -3,12 +3,14 @@ services/shipping_notice/ui_state.py
|
||||
|
||||
用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。
|
||||
依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、
|
||||
process_gate_projection(统一 Gate 用户摘要)。
|
||||
process_gate_projection(统一 Gate 用户摘要)、
|
||||
order_review_workbench_projection.apply_post_ot_gate_rules。
|
||||
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
|
||||
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
|
||||
stp_facts、progress_nodes);
|
||||
若存在 ProcessExecution:阻断时清空 action_buttons;非阻断时仅保留
|
||||
download_excel / mark_manual_uploaded / refresh(恢复动作仅由 process_gate 驱动);
|
||||
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办);
|
||||
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
|
||||
"""
|
||||
|
||||
@@ -615,10 +617,16 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
|
||||
"""
|
||||
按 Task 查找活动 Execution 的用户 Gate 摘要。
|
||||
|
||||
核心逻辑:Task 本身即正式 OT,套用 apply_post_ot_gate_rules,
|
||||
使 inventory_preparation 等系统等待不进入 current_blocking_gate。
|
||||
|
||||
Returns:
|
||||
project_user_gate_summary;无 Execution 时 None。
|
||||
用户态 Gate 摘要;无 Execution 时 None。
|
||||
"""
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
apply_post_ot_gate_rules,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
task_id = getattr(task, 'id', None)
|
||||
@@ -636,7 +644,10 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
return project_user_gate_summary(execution)
|
||||
return apply_post_ot_gate_rules(
|
||||
project_user_gate_summary(execution),
|
||||
has_formal_ot=True,
|
||||
)
|
||||
|
||||
|
||||
def build_batch_ui_state(batch: Any) -> dict[str, Any]:
|
||||
|
||||
Reference in new issue
Block a user