Merge branch 'hugo-shipping-notice' into dev

This commit is contained in:
hugo committed 2026-09-10 09:58:43 +08:00
commit 93b8c68256
23 files changed
+1356 -129

No files matched your search

@@ -13,7 +13,7 @@ from __future__ import annotations
import json
import re
import zipfile
from datetime import datetime
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -23,6 +23,7 @@ from app import db
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingInventoryFile
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
@@ -52,26 +53,38 @@ def get_inventory_archive_dir() -> str:
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
"""
推导企微/下载展示名中的时刻。
推导企微/下载展示名中的当地时刻。
核心逻辑:优先 started_at → created_at → finished_at;再尝试解析 RUN{yyyyMMddHHmmss}*;
最后回退 utcnow。完整 run_no 仍留在卡片与磁盘归档键,不塞进展示名。
核心逻辑:started_at → created_at → finished_at → 解析 RUN{yyyyMMddHHmmss}* → utcnow;
上述时刻在库内均为 UTC naive(含 run_no 时间戳),格式化前转到任务
schedule_timezone(缺省 Asia/Shanghai)。完整 run_no 仍留在卡片与磁盘归档键。
"""
when_utc: datetime | None = None
for value in (run.started_at, run.created_at, run.finished_at):
if isinstance(value, datetime):
return value
match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip())
if match:
try:
return datetime.strptime(match.group(1), "%Y%m%d%H%M%S")
except ValueError:
pass
return datetime.utcnow()
when_utc = value
break
if when_utc is None:
match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip())
if match:
try:
when_utc = datetime.strptime(match.group(1), "%Y%m%d%H%M%S")
except ValueError:
when_utc = None
if when_utc is None:
when_utc = datetime.now(timezone.utc).replace(tzinfo=None)
task = getattr(run, "task", None)
tz_name = getattr(task, "schedule_timezone", None) if task is not None else None
tz = resolve_schedule_tzinfo(tz_name)
if when_utc.tzinfo is None:
when_utc = when_utc.replace(tzinfo=timezone.utc)
return when_utc.astimezone(tz)
def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}。
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
Args:
run: 排程执行记录。
@@ -5,6 +5,9 @@ services/shipping_notice/document_layout/order_profile_matcher.py
依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠;
无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient;
身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
@@ -46,6 +49,8 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义,
# 避免无意义的版本兼容分支。
LAYOUT_MATCHING_FEATURES_VERSION = 'v1'
# 多表时签名表头原子交集占比达到该阈值才优先于纯 bbox 重叠选主表。
_PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM = 0.5
def _anchor_comparable_text(value: Any) -> str:
@@ -286,7 +291,12 @@ def match_frozen_coordinate_profiles(
candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6)
if not hard_valid:
if any('profile_coordinate_evidence_unavailable' in item.reason_codes for item in rendered):
# [STEP] 仅当全部候选都缺关键坐标结构时才抬升 evidence_insufficient;
# 禁止无关远亲候选的坐标码掩盖近亲模板的真实 header/topology 冲突。
if rendered and all(
'profile_coordinate_evidence_unavailable' in item.reason_codes
for item in rendered
):
return ProfileMatchResult(
status='evidence_insufficient', candidates=rendered,
top1_score=top1_score, top2_score=top2_score, margin=margin,
@@ -1006,6 +1016,7 @@ def _score_header_semantic_position(
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
_HEADER_ATOM_MIN_LEN = 3
_HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]')
def _sanitize_signature_table_identity(
@@ -1069,14 +1080,16 @@ def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
"""
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
核心逻辑:去撇号后按非字母数字切分;过滤过短词与虚词,避免 Q'TY/No. 噪声。
核心逻辑:先拼接 token 再去掉括号注记(通用印刷 gloss,跨 token 空格切开时
仍可剥除),再去撇号并按非字母数字切分;过滤过短词与虚词。签名侧与运行时共用。
"""
joined = ' '.join(str(token) for token in tokens)
normalized = _HEADER_PAREN_GLOSS.sub(' ', joined.casefold())
normalized = re.sub(r"['’]", '', normalized)
atoms: set[str] = set()
for token in tokens:
normalized = re.sub(r"['’]", '', str(token).casefold())
for part in re.split(r'[^a-z0-9]+', normalized):
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
atoms.add(part)
for part in re.split(r'[^a-z0-9]+', normalized):
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
atoms.add(part)
return frozenset(atoms)
@@ -1321,10 +1334,11 @@ def _observe_layout_features(
if width > 0 and height > 0:
aspect_ratio = width / height
# [STEP 1] 与签名生成一致,按签名表区选择实际业务表;MinerU 的 tables[0]
# 可能是抬头/元数据表,不能作为运行时默认主表。
# [STEP 1] 与签名生成一致,按签名表头亲和度与表区选择实际业务表;MinerU 的
# tables[0] 可能是抬头/元数据 KV 表,不能作为运行时默认主表。
primary_bbox = _select_signature_primary_table_bbox(
tables=tables, pages=pages, signature=signature,
page_glyphs=page_glyphs, glyph_tables=glyph_tables,
)
# [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。
primary_bbox = _clip_observed_primary_table_bbox(
@@ -1470,9 +1484,21 @@ def _select_persisted_header_candidate(
def _select_signature_primary_table_bbox(
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
*,
tables: list[dict[str, Any]],
pages: dict[str, Any],
signature: dict[str, Any] | None,
page_glyphs: dict[str, Any] | None = None,
glyph_tables: dict[str, Any] | None = None,
) -> list[float] | None:
"""按签名表区选取重叠最大的实际表;无可用签名时才保持首表兼容行为。"""
"""
选取运行时主表框:签名表头亲和度优先,其次表区重叠;无签名时首表兼容。
核心逻辑:MinerU 常把右上角 ORDER DATE/NO 等 KV 块拆成独立表且排在 tables[0];
仅靠 bbox 重叠在全页 glyphs 场景下仍可能读错表头。对每个候选表顶部观测 header
atoms,与签名 identity header 算交集占比;占比 ≥ 阈值时优先该表,并列再比
table_patterns.bbox.median 重叠。
"""
normalized_tables: list[list[float]] = []
for table in tables:
page = pages.get(str(table.get('page_no') or 1)) or pages.get(table.get('page_no') or 1)
@@ -1498,22 +1524,99 @@ def _select_signature_primary_table_bbox(
and isinstance(item['bbox'].get('median'), list)
and len(item['bbox']['median']) == 4
]
if not patterns:
return normalized_tables[0]
best_bbox = normalized_tables[0]
best_overlap = -1.0
for candidate in normalized_tables:
expected_atoms = _header_token_atoms(_signature_identity_header_tokens(signature))
glyph_pages = page_glyphs if isinstance(page_glyphs, dict) else {}
table_glyph_map = glyph_tables if isinstance(glyph_tables, dict) else {}
def _best_pattern_overlap(candidate: list[float]) -> float:
best = -1.0
for pattern in patterns:
try:
expected = [float(value) for value in pattern['bbox']['median']]
except (TypeError, ValueError):
continue
overlap = _bbox_overlap(expected, candidate)
if overlap > best_overlap:
best_overlap, best_bbox = overlap, candidate
best = max(best, _bbox_overlap(expected, candidate))
return best
if expected_atoms and (glyph_pages or table_glyph_map):
affinity_scored: list[tuple[float, float, list[float]]] = []
for candidate in normalized_tables:
tokens = _header_tokens_for_table_bbox(
bbox=candidate,
tables=tables,
pages=pages,
page_glyphs=glyph_pages,
glyph_tables=table_glyph_map,
)
observed_atoms = _header_token_atoms(tokens)
affinity = (
len(observed_atoms & expected_atoms) / len(expected_atoms)
if expected_atoms else 0.0
)
affinity_scored.append((affinity, _best_pattern_overlap(candidate), candidate))
affinity_scored.sort(key=lambda item: (item[0], item[1]))
best_affinity, best_overlap, best_bbox = affinity_scored[-1]
if best_affinity >= _PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM:
return best_bbox
if not patterns:
return best_bbox if best_affinity > 0 else normalized_tables[0]
if not patterns:
return normalized_tables[0]
best_bbox = normalized_tables[0]
best_overlap = -1.0
for candidate in normalized_tables:
overlap = _best_pattern_overlap(candidate)
if overlap > best_overlap:
best_overlap, best_bbox = overlap, candidate
return best_bbox
def _header_tokens_for_table_bbox(
*,
bbox: list[float],
tables: list[dict[str, Any]],
pages: dict[str, Any],
page_glyphs: dict[str, Any],
glyph_tables: dict[str, Any],
) -> list[str]:
"""
在候选表顶部条带观测表头 token,供主表亲和度打分。
核心逻辑:取相对坐标表框顶边向下 max(6%, 18% 表高) 的条带,用页级 glyphs
(不足时回退 table glyphs)拼 token;不做折行合并,仅服务选表。
"""
if not isinstance(bbox, list) or len(bbox) != 4:
return []
page_no, page = _page_for_primary_table_bbox(bbox, tables=tables, pages=pages)
if not isinstance(page, dict):
return []
glyphs = None
if page_no is not None:
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
if not isinstance(glyphs, list) or not glyphs:
glyphs = page_glyphs.get('1') or page_glyphs.get(1) or []
if not isinstance(glyphs, list) or not glyphs:
glyphs = []
for table_glyphs in glyph_tables.values():
if isinstance(table_glyphs, list):
glyphs.extend(table_glyphs)
if not glyphs:
return []
region = {
'x0': float(bbox[0]),
'y0': float(bbox[1]),
'x1': float(bbox[2]),
'y1': float(bbox[1]) + max(0.06, (float(bbox[3]) - float(bbox[1])) * 0.18),
}
header_glyphs = _glyphs_in_relative_region(glyphs, page=page, region=region)
spans = [
item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False)
if _usable_observed_header_token(str(item.get('text') or ''))
][:32]
return [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
def _clip_observed_primary_table_bbox(
primary_bbox: list[float] | None,
*,
@@ -1616,21 +1719,62 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float:
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
def _band_headers_match_signature(
*, band_tokens: list[str], signature: dict[str, Any] | None,
) -> bool:
"""判断冻结表头带读到的 token 是否足以代表签名表头。
def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None:
"""读取签名首个可用 table_patterns.bbox.median(归一化四点)。"""
for pattern in (signature or {}).get('table_patterns') or []:
if not isinstance(pattern, dict):
continue
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
if not isinstance(bbox, dict):
continue
median = bbox.get('median')
if isinstance(median, list) and len(median) == 4:
try:
return [float(item) for item in median]
except (TypeError, ValueError):
continue
return None
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
需要回退到表体顶部的结构搜索。期望侧先截断折行副标签污染。
def _align_signature_header_bbox_to_primary(
*,
signature: dict[str, Any] | None,
primary_bbox: list[float],
) -> list[float] | None:
"""
expected = [str(token).casefold() for token in _signature_identity_header_tokens(signature)]
if not expected or not band_tokens:
return False
observed = [str(token).casefold() for token in band_tokens]
matched = sum(1 for token in expected if token in observed)
return matched / len(expected) >= 0.5
将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。
核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0
平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。
"""
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
return None
header_bbox = _signature_header_bbox(signature)
if header_bbox is None:
return None
table_median = _signature_table_bbox_median(signature)
try:
hx0, hy0, hx1, hy1 = (float(header_bbox[i]) for i in range(4))
py0, py1 = float(primary_bbox[1]), float(primary_bbox[3])
except (TypeError, ValueError, IndexError):
return None
if hy1 <= hy0 or py1 <= py0:
return None
delta_y = 0.0
if table_median is not None:
try:
delta_y = py0 - float(table_median[1])
except (TypeError, ValueError, IndexError):
delta_y = 0.0
aligned_y0 = hy0 + delta_y
aligned_y1 = hy1 + delta_y
# [STEP] 夹在主表内;保持最小可读高度。
height = max(0.02, aligned_y1 - aligned_y0)
clipped_y0 = min(max(aligned_y0, py0), max(py0, py1 - height))
clipped_y1 = min(clipped_y0 + height, py1)
if clipped_y1 <= clipped_y0:
return None
return [hx0, clipped_y0, hx1, clipped_y1]
def _observe_primary_table_header(
@@ -1641,10 +1785,12 @@ def _observe_primary_table_header(
primary_bbox: list[float] | None,
signature: dict[str, Any] | None,
) -> tuple[list[str], list[float], list[float]]:
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
"""
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用。
若固定带失准,则基于表体顶部做表头行搜索。单逻辑表头时把折行副标签按 x 并入所属列。
核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框
时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行
宽带搜索,避免印刷括号注记污染身份原子。
"""
if not primary_bbox or len(primary_bbox) != 4:
return [], [], []
@@ -1657,14 +1803,23 @@ def _observe_primary_table_header(
page = pages.get('1') or pages.get(1)
if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict):
return [], [], []
header_bbox = _signature_header_bbox(signature)
region = (
{'x0': header_bbox[0], 'y0': header_bbox[1], 'x1': header_bbox[2], 'y1': header_bbox[3]}
if header_bbox is not None else {
'x0': primary_bbox[0], 'y0': primary_bbox[1], 'x1': primary_bbox[2],
'y1': primary_bbox[1] + max(0.06, (primary_bbox[3] - primary_bbox[1]) * 0.18),
}
aligned = _align_signature_header_bbox_to_primary(
signature=signature, primary_bbox=primary_bbox,
)
if aligned is not None:
region = {
'x0': float(aligned[0]), 'y0': float(aligned[1]),
'x1': float(aligned[2]), 'y1': float(aligned[3]),
}
else:
region = {
'x0': float(primary_bbox[0]),
'y0': float(primary_bbox[1]),
'x1': float(primary_bbox[2]),
'y1': float(primary_bbox[1]) + max(
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
),
}
width = float(page.get('width') or 0)
if width <= 0:
return [], [], []
@@ -1675,38 +1830,19 @@ def _observe_primary_table_header(
][:32]
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001)
band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
single_logical = _signature_single_logical_header(signature)
if single_logical:
table_span = max(float(primary_bbox[2]) - float(primary_bbox[0]), 0.0001)
band_widths = [
round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans
]
if _signature_single_logical_header(signature):
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
band_tokens, band_centers, band_widths,
)
band_tokens = [str(item).casefold() for item in merged_tokens]
band_centers = list(merged_centers or [])
band_widths = list(merged_widths or [])
# 固定带有效 → 直接沿用。
if _band_headers_match_signature(band_tokens=band_tokens, signature=signature):
return band_tokens, band_centers, band_widths
# 固定带失准 → 表体顶部候选行;单逻辑表头时把下一视觉行折行副标签并入。
header_candidates = _observe_header_candidates(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
)
selected = _select_persisted_header_candidate(
candidates=[{'bbox': primary_bbox, 'header_candidates': header_candidates}],
signature=signature,
)
if selected is not None:
header, _ = selected
tokens = [str(token).casefold() for token in header['header_tokens']]
centers = list(header['column_centers'])
widths = list(header['column_width_ratios'])
if single_logical:
tokens, centers, widths = _merge_following_wrap_candidate(
header=header,
header_candidates=header_candidates,
)
return tokens, centers, widths
return (
[str(item).casefold() for item in merged_tokens],
list(merged_centers or []),
list(merged_widths or []),
)
return band_tokens, band_centers, band_widths
@@ -6,6 +6,7 @@ services/shipping_notice/document_layout/order_profile_signature.py
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
单逻辑表头行将格内折行副标签按 x 并入所属列,保留文案、不拆成新身份列。
table_patterns 仅纳入 business_lines;line_field_supplement 不进匹配身份。
"""
from __future__ import annotations
@@ -198,8 +199,9 @@ def build_layout_signature(
"""
生成版面签名快照;相同输入必须得到相同 checksum。
核心逻辑:解析模板表区/表头/字段关系 → 从样本区域读取固定文字 → 多样本聚合
中位数与容差 → 过滤动态值与单样本噪声 → 计算稳定 checksum。
核心逻辑:解析模板表区/表头/字段关系 → 仅对 business_lines 建 table_patterns →
从样本区域读取固定文字 → 多样本聚合中位数与容差 → 过滤动态值与单样本噪声 →
计算稳定 checksum。line_field_supplement 只服务按 LN 补料号,不进匹配身份。
Args:
definition: 当前草稿或冻结 Profile 定义 JSON。
@@ -225,11 +227,15 @@ def build_layout_signature(
order_field_layouts=definition.get('order_field_layouts') or [],
)
# [STEP 2] 页面与表区几何模式
# [STEP 2] 页面与主表明细几何模式(排除 line_field_supplement)
page_patterns = _build_page_patterns(sample_layouts=sample_layouts)
matching_tables = [
table for table in profile.table_regions
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
]
table_patterns = [
_build_table_pattern(table=table, sample_layouts=sample_layouts)
for table in profile.table_regions
for table in matching_tables
]
field_relation_graph = _build_field_relation_graph(profile, sample_layouts=sample_layouts)
evidence_quality = _build_evidence_quality(
@@ -356,8 +356,20 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow()
db.session.commit()
return _payload(run)
path = Path(str(payload.get('file_path') or ''))
if not path.is_file():
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
# SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
raw_file_path = str(payload.get('file_path') or '').strip()
path: Path | None = None
from app.services.shipping_notice.rpa import inventory_drop_dir
from app.services.shipping_notice.inventory_rpa_workflow import _resolve_shared_inventory_drop_file
drop_root = inventory_drop_dir()
if drop_root is not None:
path = _resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root)
if path is None:
candidate = Path(raw_file_path)
if candidate.is_file():
path = candidate
if path is None or not path.is_file():
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
db.session.commit()
return _payload(run)
@@ -1204,6 +1204,43 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool:
_EXTRACT_DONE_UNIT_STATUSES = frozenset({
'candidate_ready', 'review_required', 'failed', 'cancelled',
})
# layout 与 extraction 共 shipping 队列且默认 priority=0;resume 抬高后才能插队,
# 否则「单文件版式完成」的 extraction 仍排在剩余 layout FIFO 之后。
_ORDER_EXTRACTION_READY_PRIORITY = 10
def _enqueue_ready_order_extraction_job(
run: ShippingOrderProcessingRun, *, message: str,
) -> int:
"""
为已有 ready 活的 Run 入队(或复用)extraction Job,并抬高 queued 优先级以便插队。
核心逻辑:enqueue 去重可能返回仍在排队的早建 Job;必须把其 priority 提到
_ORDER_EXTRACTION_READY_PRIORITY,否则 claim 仍按 created_at 先消化 layout。
"""
from app.jobs.queue import enqueue
from app.jobs.types import JobType
job_id = enqueue(
JobType.SHIPPING_ORDER_EXTRACTION,
{'run_no': run.run_no},
domain='shipping_notice',
business_ref=run.run_no,
created_by_id=run.user_id,
priority=_ORDER_EXTRACTION_READY_PRIORITY,
max_attempts=3,
message=message,
commit=False,
)
job = db.session.get(Job, int(job_id))
if (
job is not None
and str(job.status or '') == 'queued'
and int(job.priority or 0) < _ORDER_EXTRACTION_READY_PRIORITY
):
job.priority = _ORDER_EXTRACTION_READY_PRIORITY
job.message = message
return int(job_id)
def order_extraction_ready_document_ids(run: ShippingOrderProcessingRun) -> set[int]:
@@ -1360,12 +1397,9 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
单份附件布局完成后唤醒仍等待版式的 Run。
核心逻辑:不再要求 Run 内全部 PDF 版式就绪;只要存在可抽取的 ready Document,
即入队(或复用活跃)shipping_order_extraction。无 ready 活且无 pending、仅有失败版式、
且尚未抽出任何 Unit 时,整 Run 失败收口。
即以抬高 priority 入队(或复用活跃)shipping_order_extraction,避免被剩余 layout
FIFO 堵住。无 ready 活且无 pending、仅有失败版式、且尚未抽出任何 Unit 时整 Run 失败。
"""
from app.jobs.queue import enqueue
from app.jobs.types import JobType
resumed = 0
# processing + waiting_layout:部分 Unit 已抽完、仍等兄弟文件版式。
runs = (
@@ -1380,11 +1414,8 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
if int(document_id) not in _run_snapshot_document_ids(run):
continue
if order_extraction_has_extractable_ready_work(run):
job_id = enqueue(
JobType.SHIPPING_ORDER_EXTRACTION,
{'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no,
created_by_id=run.user_id, max_attempts=3,
message='附件解析完成,等待订单识别', commit=False,
job_id = _enqueue_ready_order_extraction_job(
run, message='附件解析完成,等待订单识别',
)
run.current_job_id = job_id
# 仍有兄弟 layout pending 时保持 waiting_layout,便于再次 resume;
@@ -1410,11 +1441,8 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
)
if progressed:
# 已有 Unit 成功/复核:再入队一次让 Worker 收口,禁止整 Run 抹掉部分成果。
job_id = enqueue(
JobType.SHIPPING_ORDER_EXTRACTION,
{'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no,
created_by_id=run.user_id, max_attempts=3,
message='部分附件版式失败,等待订单识别收口', commit=False,
job_id = _enqueue_ready_order_extraction_job(
run, message='部分附件版式失败,等待订单识别收口',
)
run.current_job_id = job_id
run.phase = 'queued'