fix(shipping-notice): 修复订单解析签名与库存 RPA 导出流程
- 修正订单提取运行与模板签名处理 - 优化库存 RPA 归档及报表导出逻辑 - 补充库存参数、归档、运行与签名测试 - 更新 Shipping Notice 技术文档
This commit is contained in:
1 parent
dabf140e41
commit
2bb7822247
10 files changed
+300
-43
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: 排程执行记录。
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -165,6 +165,45 @@ def test_dsv_report_inventory_rows_returns_false_when_no_data_within_deadline(mo
|
||||
assert worker._wait_dsv_report_inventory_rows(page=object(), timeout_ms=2_500) is False
|
||||
|
||||
|
||||
def test_ensure_dsv_inventory_rows_retries_view_report_then_allows_export_fallback(monkeypatch):
|
||||
"""DOM 无行时重试 View Report;仍无行不得抛空,应继续导出由 Excel 判空。"""
|
||||
worker = _load_dsv_report_export()
|
||||
clicks: list[str] = []
|
||||
waits: list[int] = []
|
||||
row_outcomes = iter([False, False])
|
||||
|
||||
monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_wait_dsv_report_inventory_rows",
|
||||
lambda page_arg, timeout_ms: (waits.append(timeout_ms) or next(row_outcomes, False)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_click_dsv_view_report",
|
||||
lambda page_arg: clicks.append("view"),
|
||||
)
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms: None)
|
||||
|
||||
worker._ensure_dsv_inventory_rows_or_export_fallback(page=object(), report_name="On Hand Inventory by Location")
|
||||
|
||||
assert clicks == ["view"]
|
||||
assert waits == [5_000, 5_000]
|
||||
|
||||
|
||||
def test_ensure_dsv_inventory_rows_skips_retry_when_rows_already_visible(monkeypatch):
|
||||
"""首次轮询已有明细行时不得再点 View Report。"""
|
||||
worker = _load_dsv_report_export()
|
||||
clicks: list[str] = []
|
||||
monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000)
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_inventory_rows", lambda page_arg, timeout_ms: True)
|
||||
monkeypatch.setattr(worker, "_click_dsv_view_report", lambda page_arg: clicks.append("view"))
|
||||
|
||||
worker._ensure_dsv_inventory_rows_or_export_fallback(page=object(), report_name="On Hand Inventory by Location")
|
||||
|
||||
assert clicks == []
|
||||
|
||||
|
||||
def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
|
||||
"""单票 DSV 导出应走与批量相同的 session + export 函数。"""
|
||||
worker = _load_worker()
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
@@ -28,6 +29,7 @@ from app.services.schedule.scheduler_service import (
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import (
|
||||
inventory_raw_zip_available_from_summary,
|
||||
inventory_raw_zip_download_name,
|
||||
inventory_rpa_attachment_stem,
|
||||
inventory_rpa_result_excel_name,
|
||||
persist_inventory_rpa_raw_zip_archive,
|
||||
resolve_inventory_raw_zip_download,
|
||||
@@ -544,6 +546,23 @@ def test_build_zip_entry_name_prefers_source_code():
|
||||
) == "003_AWSSG.xlsx"
|
||||
|
||||
|
||||
def test_inventory_rpa_attachment_stem_converts_utc_to_schedule_timezone(app):
|
||||
"""展示名 HHmm 必须用业务时区,不能直接用库内 UTC naive / run_no 内嵌时刻。"""
|
||||
with app.app_context():
|
||||
run = _make_inventory_run_with_created(
|
||||
schedule_no="ARCH-TZ-STEM",
|
||||
username="arch_tz_stem",
|
||||
created=[],
|
||||
)
|
||||
# UTC 06:27 → Asia/Shanghai 14:27
|
||||
run.started_at = datetime(2026, 9, 9, 6, 27, 17)
|
||||
run.task.schedule_timezone = "Asia/Shanghai"
|
||||
db.session.commit()
|
||||
assert inventory_rpa_attachment_stem(run) == "库存RPA-20260909-1427"
|
||||
assert inventory_rpa_result_excel_name(run) == "库存RPA-20260909-1427-结果.xlsx"
|
||||
assert inventory_raw_zip_download_name(run) == "库存RPA-20260909-1427-库存.zip"
|
||||
|
||||
|
||||
def test_get_inventory_raw_zip_returns_404_when_archive_unavailable(
|
||||
client,
|
||||
app,
|
||||
|
||||
@@ -786,7 +786,10 @@ def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app):
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 1
|
||||
db.session.refresh(run)
|
||||
first_job_id = run.current_job_id
|
||||
assert db.session.get(Job, first_job_id) is not None
|
||||
first_job = db.session.get(Job, first_job_id)
|
||||
assert first_job is not None
|
||||
# 关键断言:抬高 priority,避免被同队列剩余 layout FIFO 堵住。
|
||||
assert int(first_job.priority or 0) >= 10
|
||||
assert run.phase == 'waiting_layout'
|
||||
|
||||
layouts[1].status = 'ready'
|
||||
@@ -799,6 +802,7 @@ def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app):
|
||||
assert run.phase == 'queued'
|
||||
assert job is not None
|
||||
assert job.job_type == 'shipping_order_extraction'
|
||||
assert int(job.priority or 0) >= 10
|
||||
|
||||
|
||||
def test_pdf_without_ready_coordinate_layout_is_a_prerequisite_failure(app):
|
||||
|
||||
@@ -74,6 +74,67 @@ def test_same_input_produces_same_checksum():
|
||||
assert signature_checksum(first['signature']) == first['signature_checksum']
|
||||
|
||||
|
||||
def test_layout_signature_excludes_line_field_supplement_table_patterns():
|
||||
"""
|
||||
补充表不得进入匹配签名 table_patterns。
|
||||
|
||||
关键断言:即便补充区样本含料号行文案,签名 identity 也只保留 business_lines,
|
||||
避免 line_field_supplement 污染表头原子硬互斥。
|
||||
"""
|
||||
definition = _minimal_definition()
|
||||
definition['table_regions'][0]['region_role'] = 'business_lines'
|
||||
definition['table_regions'][0]['region'] = {'x0': 0, 'y0': 0.2, 'x1': 1, 'y1': 0.55}
|
||||
definition['table_regions'][0]['line_layouts'][0]['region'] = {
|
||||
'x0': 0, 'y0': 0.35, 'x1': 1, 'y1': 0.55,
|
||||
}
|
||||
definition['table_regions'].append({
|
||||
'region_id': 'line_supplement',
|
||||
'region_role': 'line_field_supplement',
|
||||
'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9},
|
||||
'line_layouts': [{
|
||||
'layout_id': 'supp_main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{
|
||||
'field_id': 'supp-ln',
|
||||
'field_code': 'customer_po_line_no',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0.05, 'y0': 0.1, 'x1': 0.2, 'y1': 0.4},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'supp-pn',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0.25, 'y0': 0.1, 'x1': 0.8, 'y1': 0.4},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
],
|
||||
}],
|
||||
})
|
||||
layout = _sample_layout(header_text='ITEM NO QTY')
|
||||
# 补充表区高度内放入料号正文,模拟 HYVE 脏表头污染场景。
|
||||
dirty = 'WTP-B3-A08AR11000001 CN,TH,JP'
|
||||
for index, char in enumerate(dirty):
|
||||
layout['coordinate_evidence']['page_glyphs']['1'].append({
|
||||
'text': char,
|
||||
'bbox': {'x0': 10 + index * 3, 'y0': 190, 'x1': 12 + index * 3, 'y1': 202},
|
||||
})
|
||||
|
||||
snapshot = build_layout_signature(definition=definition, sample_layouts=[layout])
|
||||
patterns = snapshot['signature']['table_patterns']
|
||||
region_ids = [item.get('region_id') for item in patterns]
|
||||
assert region_ids == ['lines']
|
||||
joined = ' '.join(
|
||||
str(token)
|
||||
for pattern in patterns
|
||||
for token in (pattern.get('header_tokens') or [])
|
||||
).upper()
|
||||
assert 'WTP-B3-A08AR11000001' not in joined
|
||||
assert 'CN,TH,JP' not in joined
|
||||
|
||||
|
||||
|
||||
def test_different_samples_produce_different_checksum():
|
||||
"""不同表头样本应产生不同 checksum。"""
|
||||
definition = _minimal_definition()
|
||||
|
||||
Reference in new issue
Block a user