feat(shipping-notice): 升级货代发货流程为五阶段,完善业务校验

将货代发货流程从四阶段扩展为五阶段,拆分上传相关逻辑至独立的货代上传阶段;
统一多语言文案修正客户状态语义,将"客户尚未识别"调整为符合业务的"客户尚未确认";
新增严格的上传成功验证谓词,需同时满足任务状态、全部预约单上传成功、存在有效成功上传尝试三个条件方可标记为完成;
新增坐标取值模型配置,支持Legacy冻结绝对坐标和锚点框架受限平移两种模式;
更新全链路相关文档、前端组件、后端服务与测试用例,确保业务逻辑对齐新业务规则。
This commit is contained in:
hugo committed 2026-08-21 09:20:47 +08:00
1 parent 1b6483a4ea
commit 935bf26fa6
86 files changed
+2743 -311

No files matched your search

+5 -7
View File
@@ -1808,26 +1808,24 @@ def workspace_delete_shipping_order_review_line(case_no: str, line_key: str):
def workspace_validate_shipping_order_review_draft(case_no: str):
"""显式重跑当前草稿校验,并触发统一恢复协调器(可 auto_gate)。"""
user = _require_user()
from app.services.shipping_notice.order_review_draft_service import validate_draft
from app.services.shipping_notice.order_review_resume_service import (
attach_resume_outcome,
resume_after_review_change,
)
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='draft_validated')
result = validate_draft(
user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'),
)
db.session.commit()
# 保存校验必须由统一恢复协调器编排:唯一客户候选自动确认 → Draft 校验 →
# Gate/资格/STP。若先独立校验,会在同一次点击中把 unique_candidate 误判为未确认。
resume = resume_after_review_change(
user_id=user.id,
case_no=case_no,
trigger='draft_validated',
change_type=None,
skip_validate=True,
skip_validate=False,
allow_auto_create=True,
expected_draft_version=payload.get('expected_draft_version'),
)
return _ok(attach_resume_outcome({'case': result}, resume))
return _ok(attach_resume_outcome({'case': resume.get('case')}, resume))
@workspace_shipping_notice_bp.route(
@@ -8,6 +8,8 @@
from __future__ import annotations
from copy import deepcopy
import math
import re
from statistics import median
from typing import Any, Literal
@@ -269,6 +271,7 @@ def reconstruct_coordinate_profile_rows(
line_start_field_code: str | None = None,
include_unanchored_rows: bool = False,
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows',
coordinate_transform: dict[str, Any] | None = None,
) -> list[CoordinateProfileLogicalRow]:
"""
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
@@ -279,7 +282,22 @@ def reconstruct_coordinate_profile_rows(
才是已授权的删除证据;未授权删除文字会被忽略。``include_deleted`` 仅供标注预览
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启
``include_unanchored_rows``,在没有任何有效起行值时返回待复核的主行字段,不能用于正式解析。
``coordinate_transform`` 只能接收共同 matcher 已确认的 ``status=applied`` 平移;
它只在当前调用的内存副本投影表区、物理行和字段区域,绝不修改冻结 Profile。
"""
projected = _project_coordinate_profile_regions(
table_region=table_region,
line_layouts=line_layouts,
termination_rules=termination_rules,
exclusion_regions=exclusion_regions,
coordinate_transform=coordinate_transform,
)
if projected is None:
return []
table_region = projected['table_region']
line_layouts = projected['line_layouts']
termination_rules = projected['termination_rules']
exclusion_regions = projected['exclusion_regions']
start_field_code = resolve_line_start_field_code(line_start_field_code)
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1))
@@ -451,6 +469,81 @@ def reconstruct_coordinate_profile_rows(
return results if include_deleted else [row for row in results if row.role != 'deleted']
def _project_coordinate_profile_regions(
*,
table_region: dict[str, Any] | None,
line_layouts: list[dict[str, Any]],
termination_rules: list[dict[str, Any]] | None,
exclusion_regions: list[dict[str, Any]] | None,
coordinate_transform: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""对当前重建调用复制并投影受 matcher 证明的相对坐标平移。
未传变换时保留 legacy 行为。传入变换必须是有限、页面内的 ``applied``
变换;任何伪造、过界或未知状态都返回 ``None``,由调用方保持 Review,
不能静默回退到旧绝对坐标。
"""
if coordinate_transform is None:
return {
'table_region': table_region,
'line_layouts': line_layouts,
'termination_rules': termination_rules,
'exclusion_regions': exclusion_regions,
}
if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied':
return None
try:
translate_x = float(coordinate_transform['translate_x'])
translate_y = float(coordinate_transform['translate_y'])
except (KeyError, TypeError, ValueError):
return None
if not math.isfinite(translate_x) or not math.isfinite(translate_y):
return None
def translate_region(region: Any) -> bool:
if not isinstance(region, dict):
return False
try:
x0, y0 = float(region['x0']) + translate_x, float(region['y0']) + translate_y
x1, y1 = float(region['x1']) + translate_x, float(region['y1']) + translate_y
except (KeyError, TypeError, ValueError):
return False
if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
return False
region.update({'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1})
return True
projected_table = deepcopy(table_region) if table_region is not None else None
projected_layouts = deepcopy(line_layouts)
projected_terminations = deepcopy(termination_rules) if termination_rules is not None else None
projected_exclusions = deepcopy(exclusion_regions) if exclusion_regions is not None else None
if projected_table is not None and not translate_region(projected_table):
return None
for layout in projected_layouts:
if not isinstance(layout, dict):
return None
region = layout.get('region')
if region is not None and not translate_region(region):
return None
for field in layout.get('field_regions') or []:
if not isinstance(field, dict) or not translate_region(field.get('region')):
return None
for rule in projected_terminations or []:
anchor = rule.get('anchor') if isinstance(rule, dict) else None
region = anchor.get('region') if isinstance(anchor, dict) else None
if region is not None and not translate_region(region):
return None
for region in projected_exclusions or []:
if not translate_region(region):
return None
return {
'table_region': projected_table,
'line_layouts': projected_layouts,
'termination_rules': projected_terminations,
'exclusion_regions': projected_exclusions,
}
def _reconstruct_adaptive_record_columns_profile_rows(
*,
glyphs: list[tuple[int, PositionedCharacter]],
@@ -188,6 +188,13 @@ def _fit_layout_payload_to_budget(
coordinate_evidence = candidate.get('coordinate_evidence')
if isinstance(coordinate_evidence, dict):
# [STEP] 仅在即将删除逐字符坐标时固定模板身份特征,避免改变未压缩快照的
# checksum;后续 matcher 只能读取此投影,不能退化为页面/表框高分猜测。
if coordinate_evidence.get('page_glyphs') is not None or coordinate_evidence.get('tables') is not None:
from app.services.shipping_notice.document_layout.order_profile_matcher import (
build_layout_matching_features,
)
candidate['matching_features'] = build_layout_matching_features(layout=candidate)
if coordinate_evidence.pop('page_glyphs', None) is not None:
issues.append('shipping_document_layout_page_glyphs_compacted')
if coordinate_evidence.pop('tables', None) is not None:
@@ -44,8 +44,24 @@ def ensure_on_demand_coordinate_evidence(
sources = _coordinate_mapping(evidence.get('sources'))
source_pages = _coordinate_mapping(sources.get('pages'))
tables = _coordinate_mapping(evidence.get('tables'))
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
return layout
available_page_nos = {
int(page_no) for page_no, glyphs in page_glyphs.items()
if str(page_no).isdigit() and isinstance(glyphs, list) and glyphs
}
if page_nos is not None and page_nos.issubset(available_page_nos):
# 当前 Layout 可能补齐了 Run 冻结快照中已被压缩的坐标证据。必须返回
# 合并后的运行期 Layout;返回原 layout 会让调用方重新丢失这些字符坐标,
# 从而使同版式 PDF 因快照压缩路径不同进入不同的匹配分支。
next_layout = dict(layout)
merged_evidence = {**evidence, 'pages': pages}
if page_glyphs:
merged_evidence['page_glyphs'] = page_glyphs
if tables:
merged_evidence['tables'] = tables
if sources or source_pages:
merged_evidence['sources'] = {**sources, 'pages': source_pages}
next_layout['coordinate_evidence'] = merged_evidence
return next_layout
tables_by_page: dict[int, list[dict[str, Any]]] = {}
for raw_table in layout.get('tables') or []:
if not isinstance(raw_table, dict):
@@ -108,8 +124,12 @@ def ensure_on_demand_coordinate_evidence(
if table_id and chars:
tables[table_id] = chars
next_layout = dict(layout)
next_layout['coordinate_evidence'] = {
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
'tables': tables, 'sources': {**sources, 'pages': source_pages},
}
merged_evidence = {**evidence, 'pages': pages}
if page_glyphs:
merged_evidence['page_glyphs'] = page_glyphs
if tables:
merged_evidence['tables'] = tables
if sources or source_pages:
merged_evidence['sources'] = {**sources, 'pages': source_pages}
next_layout['coordinate_evidence'] = merged_evidence
return next_layout
@@ -49,6 +49,7 @@ class OrderFieldExtraction(BaseModel):
def extract_order_fields(
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False,
coordinate_transform: dict[str, Any] | None = None,
) -> list[OrderFieldExtraction]:
"""
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
@@ -63,6 +64,12 @@ def extract_order_fields(
Returns:
每个已绑定布局对应一个候选,按模板声明顺序返回。
"""
effective_profile = _project_coordinate_transform(profile, coordinate_transform)
if effective_profile is None:
return [
_unavailable(layout, 'order_field_coordinate_transform_invalid')
for layout in profile.order_field_layouts
]
return [
_extract_layout(
layout=layout,
@@ -70,10 +77,49 @@ def extract_order_fields(
coordinate_evidence=coordinate_evidence,
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
)
for layout in profile.order_field_layouts
for layout in effective_profile.order_field_layouts
]
def _project_coordinate_transform(
profile: OrderCoordinateProfile, coordinate_transform: dict[str, Any] | None,
) -> OrderCoordinateProfile | None:
"""把 matcher 唯一确认的平移一次性投影到订单头布局,禁止二次估算。"""
if coordinate_transform is None:
return profile
if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied':
return None
try:
dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y'])
except (KeyError, TypeError, ValueError):
return None
if not all(value == value and abs(value) != float('inf') for value in (dx, dy)):
return None
payload = profile.model_dump(mode='python')
for layout in payload.get('order_field_layouts') or []:
if not isinstance(layout, dict):
continue
for key in ('absolute_value_region', 'fallback_value_region'):
region = layout.get(key)
if isinstance(region, dict):
_translate_region_dict(region, dx=dx, dy=dy)
anchor = layout.get('anchor')
if isinstance(anchor, dict) and isinstance(anchor.get('region'), dict):
_translate_region_dict(anchor['region'], dx=dx, dy=dy)
try:
return OrderCoordinateProfile.model_validate(payload)
except Exception:
return None
def _translate_region_dict(region: dict[str, Any], *, dx: float, dy: float) -> None:
"""原地平移归一化区域并拒绝越界;调用方随后重新校验 Profile。"""
region['x0'] = float(region['x0']) + dx
region['x1'] = float(region['x1']) + dx
region['y0'] = float(region['y0']) + dy
region['y1'] = float(region['y1']) + dy
def _extract_layout(
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
allow_ocr_preview_fallback: bool = False,
@@ -427,6 +427,46 @@ class DocumentMatchProfile(OrderProfileModel):
return self
class AnchorFrameCoordinateModel(OrderProfileModel):
"""声明以稳定静态文字建立运行时平移坐标框架的 Profile 能力。"""
type: Literal['anchor_frame']
anchors: list[AnchorRule] = Field(min_length=1, max_length=4)
max_translate_x: float = Field(default=.03, ge=0, le=.15)
max_translate_y: float = Field(default=.06, ge=0, le=.20)
@model_validator(mode='after')
def validate_anchor_frame(self) -> 'AnchorFrameCoordinateModel':
"""要求每个框架锚点都有基线区域且身份唯一,避免运行时从全文猜测基准。"""
if any(anchor.region is None for anchor in self.anchors):
raise ValueError('anchor frame anchors require baseline regions')
ids = [anchor.anchor_id for anchor in self.anchors]
if len(ids) != len(set(ids)):
raise ValueError('anchor frame anchor ids must be unique')
return self
class CoordinateModel(OrderProfileModel):
"""定义坐标模板是否启用锚点框架;legacy 保持既有绝对坐标行为。"""
type: Literal['legacy', 'anchor_frame'] = 'legacy'
anchors: list[AnchorRule] = Field(default_factory=list, max_length=4)
max_translate_x: float = Field(default=.03, ge=0, le=.15)
max_translate_y: float = Field(default=.06, ge=0, le=.20)
@model_validator(mode='after')
def validate_coordinate_model(self) -> 'CoordinateModel':
"""仅 anchor_frame 允许锚点配置;legacy 必须是空声明以保证路径隔离。"""
if self.type == 'legacy' and self.anchors:
raise ValueError('legacy coordinate model must not define frame anchors')
if self.type == 'anchor_frame':
AnchorFrameCoordinateModel(
type='anchor_frame', anchors=self.anchors,
max_translate_x=self.max_translate_x, max_translate_y=self.max_translate_y,
)
return self
class OrderCoordinateProfile(OrderProfileModel):
"""唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。"""
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
@@ -435,6 +475,7 @@ class OrderCoordinateProfile(OrderProfileModel):
table_regions: list[TableRegionProfile] = Field(min_length=1)
order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list)
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
coordinate_model: CoordinateModel = Field(default_factory=CoordinateModel)
@model_validator(mode='after')
def validate_profile_rules(self) -> 'OrderCoordinateProfile':
@@ -9,6 +9,7 @@ services/shipping_notice/document_layout/order_profile_matcher.py
from __future__ import annotations
from copy import deepcopy
import re
from typing import Any, Literal
@@ -17,8 +18,10 @@ from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.coordinate_region_text import (
positioned_token_spans,
read_coordinate_region_text,
visual_glyph_rows,
)
from app.services.shipping_notice.document_layout.order_profile import (
AnchorRule,
CRITICAL_STRUCTURE_DIMENSION_KEYS,
MatchDimensionResult,
MatchDimensionState,
@@ -31,6 +34,9 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
)
LAYOUT_MATCHING_FEATURES_VERSION = 'shipping-layout-matching-features.v2'
def _anchor_comparable_text(value: Any) -> str:
"""规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。"""
return ''.join(str(value or '').casefold().split())
@@ -66,6 +72,7 @@ class ProfileMatchCandidate(BaseModel):
dimension_scores: ProfileMatchDimensionScores | None = None
dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict)
margin_to_next: float | None = Field(default=None, ge=0, le=1)
coordinate_transform: dict[str, Any] | None = None
class ProfileMatchResult(BaseModel):
@@ -136,15 +143,23 @@ def match_frozen_coordinate_profiles(
document_match=definition.get('document_match'),
table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
coordinate_model=definition.get('coordinate_model') or {},
)
except (TypeError, ValueError):
continue
reason_codes: list[str] = []
signature_body, signature_meta = _extract_matching_signature(raw)
coordinate_transform, transform_reasons = _resolve_coordinate_transform(
profile=profile, pages=pages, page_glyphs=page_glyphs,
)
reason_codes.extend(transform_reasons)
observed_signature = _translate_signature(
signature=signature_body, coordinate_transform=coordinate_transform,
)
observed = _observe_layout_features(
layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables,
page_glyphs=page_glyphs, signature=signature_body,
page_glyphs=page_glyphs, signature=observed_signature,
)
if signature_body is None:
reason_codes.append('profile_signature_missing')
@@ -190,7 +205,7 @@ def match_frozen_coordinate_profiles(
dimension_results, hard_conflict_codes = _compute_dimension_results(
profile=profile,
signature=signature_body,
signature=observed_signature,
observed=observed,
tables=tables,
pages=pages,
@@ -200,6 +215,11 @@ def match_frozen_coordinate_profiles(
customer_hint_id=customer_hint_id,
)
reason_codes.extend(hard_conflict_codes)
if _profile_requires_unavailable_structure_evidence(
signature=observed_signature,
dimension_results=dimension_results,
):
reason_codes.append('profile_coordinate_evidence_unavailable')
weights = profile.document_match.scoring_weights
score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results)
@@ -223,6 +243,7 @@ def match_frozen_coordinate_profiles(
matched_anchor_count=sum(required_hits) + sum(optional_hits),
dimension_scores=dimension_scores,
dimension_states=dimension_states,
coordinate_transform=coordinate_transform,
)))
rendered = sorted(
@@ -251,6 +272,11 @@ 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):
return ProfileMatchResult(
status='evidence_insufficient', candidates=rendered,
top1_score=top1_score, top2_score=top2_score, margin=margin,
)
if not rendered:
return ProfileMatchResult(
status='no_match', candidates=rendered,
@@ -305,6 +331,138 @@ def match_frozen_coordinate_profiles(
)
def build_layout_matching_features(*, layout: dict[str, Any]) -> dict[str, Any]:
"""从完整坐标证据派生可持久化的候选表头特征,不保留逐字符正文。
特征生成不依赖任何 Profile;保存所有候选视觉行,运行时再由冻结签名选择,
避免“无 Profile 时猜一条表头”导致压缩后永久保存错误列拓扑。
"""
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
aspect_ratio = 0.0
if isinstance(first_page, dict):
try:
width, height = float(first_page.get('width') or 0), float(first_page.get('height') or 0)
aspect_ratio = round(width / height, 6) if width > 0 and height > 0 else 0.0
except (TypeError, ValueError):
pass
rendered_tables: list[dict[str, Any]] = []
for table in tables:
bbox = _normalized_table_bbox(table=table, pages=pages)
if bbox is None:
continue
candidates = _observe_header_candidates(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
primary_bbox=bbox,
)
first = candidates[0] if candidates else {}
rendered_tables.append({
'bbox': bbox,
'header_candidates': candidates,
'header_tokens': first.get('header_tokens', []),
'column_centers': first.get('column_centers', []),
'column_width_ratios': first.get('column_width_ratios', []),
})
result = {
'version': LAYOUT_MATCHING_FEATURES_VERSION,
'page_structure': {
'aspect_ratio': aspect_ratio,
'page_count': len(pages),
'table_count': len(tables),
},
'tables': rendered_tables,
'static_text_centers': _observe_static_text_centers(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
),
}
if not result['static_text_centers']:
result.pop('static_text_centers')
return result
def _observe_header_candidates(
*, glyph_tables: dict[str, Any], page_glyphs: dict[str, Any],
pages: dict[str, Any], primary_bbox: list[float],
) -> list[dict[str, Any]]:
"""提取主表顶部视觉行候选;不把数据行固化成唯一表头。"""
if not primary_bbox or len(primary_bbox) != 4:
return []
page = pages.get('1') or pages.get(1)
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
if not isinstance(glyphs, list):
glyphs = [g for values in glyph_tables.values() if isinstance(values, list) for g in values]
if not isinstance(page, dict) or not glyphs:
return []
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
if width <= 0 or height <= 0:
return []
table_height = max(0.001, primary_bbox[3] - primary_bbox[1])
rows = visual_glyph_rows(glyphs)
candidates: list[dict[str, Any]] = []
for row in rows:
centers_y = [
((float(g['bbox']['y0']) + float(g['bbox']['y1'])) / 2) / height
for g in row if isinstance(g.get('bbox'), dict)
]
if not centers_y:
continue
y = sum(centers_y) / len(centers_y)
if y < primary_bbox[1] or y > primary_bbox[1] + table_height * 0.30:
continue
spans = [
item for item in positioned_token_spans(row, respect_explicit_spaces=False)
if _usable_observed_header_token(str(item.get('text') or ''))
][:32]
if not spans:
continue
tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
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)
widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
bbox = [
round(min(float(g['bbox']['x0']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6),
round(min(float(g['bbox']['y0']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6),
round(max(float(g['bbox']['x1']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6),
round(max(float(g['bbox']['y1']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6),
]
candidates.append({'bbox': bbox, 'header_tokens': tokens, 'column_centers': centers, 'column_width_ratios': widths})
candidates.sort(key=lambda item: (item['bbox'][1], -len(item['header_tokens'])))
return candidates[:8]
def _normalized_table_bbox(*, table: dict[str, Any], pages: dict[str, Any]) -> list[float] | None:
"""将 Layout 表框转为页内归一化坐标;缺页尺寸时仅接受已经归一化的表框。"""
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
if bbox is None:
return None
try:
values = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
except (KeyError, TypeError, ValueError):
return None
if values[2] <= values[0] or values[3] <= values[1]:
return None
if max(values) <= 1:
return [round(value, 6) for value in values]
page_no = table.get('page_no') or 1
page = pages.get(str(page_no)) or pages.get(page_no)
if not isinstance(page, dict):
return None
try:
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
except (TypeError, ValueError):
return None
if width <= 0 or height <= 0:
return None
return [
round(values[0] / width, 6), round(values[1] / height, 6),
round(values[2] / width, 6), round(values[3] / height, 6),
]
def _selected_result(
*,
raw: dict[str, Any],
@@ -343,6 +501,212 @@ def _extract_matching_signature(raw: dict[str, Any]) -> tuple[dict[str, Any] | N
return signature, matching if isinstance(matching, dict) else {}
def _resolve_coordinate_transform(
*, profile: OrderCoordinateProfile, pages: dict[str, Any], page_glyphs: dict[str, Any],
) -> tuple[dict[str, Any] | None, list[str]]:
"""根据 Profile 声明的唯一静态锚点求受限平移,任何不确定性都返回硬失败原因。
Args:
profile: 当前冻结坐标 Profile;仅 ``anchor_frame`` 启用此能力。
pages: 当前 Layout 的页尺寸证据。
page_glyphs: 当前 Layout 的页级 PDF/OCR 字符坐标。
Returns:
``(transform, reason_codes)``。legacy 返回 ``(None, [])``;anchor_frame 仅在
所有锚点唯一且变换位于声明上限内时返回 ``status=applied``。
"""
model = profile.coordinate_model
if model.type != 'anchor_frame':
return None, []
deltas: list[tuple[float, float]] = []
anchor_ids: list[str] = []
for anchor in model.anchors:
found = _find_anchor_rule_matches(
anchor=anchor, pages=pages, page_glyphs=page_glyphs,
max_translate_x=min(.30, model.max_translate_x * 2),
max_translate_y=min(.30, model.max_translate_y * 2),
)
if not found:
return None, ['profile_anchor_frame_anchor_missing']
if len(found) != 1:
return None, ['profile_anchor_frame_anchor_ambiguous']
page_no, bbox = found[0]
page = pages.get(str(page_no)) or pages.get(page_no)
if not isinstance(page, dict) or anchor.region is None:
return None, ['profile_anchor_frame_coordinate_evidence_unavailable']
try:
width, height = float(page['width']), float(page['height'])
except (KeyError, TypeError, ValueError):
return None, ['profile_anchor_frame_coordinate_evidence_unavailable']
if width <= 0 or height <= 0:
return None, ['profile_anchor_frame_coordinate_evidence_unavailable']
observed_x = (bbox[0] + bbox[2]) / 2 / width
observed_y = (bbox[1] + bbox[3]) / 2 / height
expected_x = (anchor.region.x0 + anchor.region.x1) / 2
expected_y = (anchor.region.y0 + anchor.region.y1) / 2
deltas.append((observed_x - expected_x, observed_y - expected_y))
anchor_ids.append(anchor.anchor_id)
first_x, first_y = deltas[0]
if any(abs(x - first_x) > .01 or abs(y - first_y) > .01 for x, y in deltas[1:]):
return None, ['profile_anchor_frame_anchor_inconsistent']
if abs(first_x) > model.max_translate_x or abs(first_y) > model.max_translate_y:
return None, ['profile_anchor_frame_transform_out_of_range']
return {
'status': 'applied',
'translate_x': round(first_x, 6),
'translate_y': round(first_y, 6),
'anchor_ids': anchor_ids,
'reason_codes': [],
}, []
def _find_anchor_rule_matches(
*, anchor: AnchorRule, pages: dict[str, Any], page_glyphs: dict[str, Any],
max_translate_x: float, max_translate_y: float,
) -> list[tuple[int, list[float]]]:
"""在基线区加声明平移窗口内寻找唯一锚点,绝不退化为全文弱匹配。"""
if anchor.region is None:
return []
expected = [_anchor_comparable_text(value) for value in [anchor.text, *anchor.aliases]]
rendered: list[tuple[int, list[float]]] = []
for raw_page_no, page in pages.items():
try:
page_no, width, height = int(raw_page_no), float(page['width']), float(page['height'])
except (KeyError, TypeError, ValueError):
continue
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
if width <= 0 or height <= 0 or not isinstance(glyphs, list):
continue
for line in _group_glyph_lines(glyphs):
ordered = sorted(line, key=lambda item: float((item.get('bbox') or {}).get('x0') or 0))
comparable_parts: list[str] = []
glyph_spans: list[tuple[int, int, dict[str, Any]]] = []
for item in ordered:
part = _anchor_comparable_text(item.get('text') or '')
if not part:
continue
start = len(''.join(comparable_parts))
comparable_parts.append(part)
glyph_spans.append((start, start + len(part), item))
text = ''.join(comparable_parts)
if not text:
continue
matched_box_sets: list[list[dict[str, Any]]] = []
for value in expected:
if not value:
continue
starts: list[int] = []
offset = text.find(value)
while offset >= 0:
starts.append(offset)
offset = text.find(value, offset + 1)
if anchor.match_mode == 'exact' and not _anchor_rule_text_matches(value, text, mode='contains'):
starts = []
for start in starts:
end = start + len(value)
matched_box_sets.append([
item for span_start, span_end, item in glyph_spans
if span_start < end and span_end > start
])
if matched_box_sets:
break
if len(matched_box_sets) != 1 or not matched_box_sets[0]:
if len(matched_box_sets) > 1:
rendered.extend((page_no, [
min(float(item['bbox']['x0']) for item in boxes if isinstance(item.get('bbox'), dict)),
min(float(item['bbox']['y0']) for item in boxes if isinstance(item.get('bbox'), dict)),
max(float(item['bbox']['x1']) for item in boxes if isinstance(item.get('bbox'), dict)),
max(float(item['bbox']['y1']) for item in boxes if isinstance(item.get('bbox'), dict)),
]) for boxes in matched_box_sets if boxes)
continue
matched_boxes = matched_box_sets[0]
if not matched_boxes:
continue
boxes = [item.get('bbox') for item in matched_boxes if isinstance(item.get('bbox'), dict)]
if not boxes:
continue
bbox = [
min(float(item['x0']) for item in boxes), min(float(item['y0']) for item in boxes),
max(float(item['x1']) for item in boxes), max(float(item['y1']) for item in boxes),
]
center_x, center_y = (bbox[0] + bbox[2]) / 2 / width, (bbox[1] + bbox[3]) / 2 / height
if (
max(0, anchor.region.x0 - max_translate_x) <= center_x <= min(1, anchor.region.x1 + max_translate_x)
and max(0, anchor.region.y0 - max_translate_y) <= center_y <= min(1, anchor.region.y1 + max_translate_y)
):
rendered.append((page_no, bbox))
return rendered
def _group_glyph_lines(glyphs: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
"""按字符中心 Y 聚合视觉行,供框架锚点精确匹配,不改变既有字段提取逻辑。"""
lines: list[list[dict[str, Any]]] = []
for glyph in sorted((item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)), key=lambda item: (float(item['bbox'].get('y0') or 0), float(item['bbox'].get('x0') or 0))):
bbox = glyph['bbox']
try:
center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2
glyph_height = max(.01, float(bbox['y1']) - float(bbox['y0']))
except (KeyError, TypeError, ValueError):
continue
if lines:
previous = lines[-1][0]['bbox']
previous_y = (float(previous['y0']) + float(previous['y1'])) / 2
previous_height = max(.01, float(previous['y1']) - float(previous['y0']))
if abs(center_y - previous_y) <= max(glyph_height, previous_height) * .65:
lines[-1].append(glyph)
continue
lines.append([glyph])
return lines
def _anchor_rule_text_matches(expected: str, observed: str, *, mode: str) -> bool:
"""按 AnchorRule 的 exact/contains 合约比较已规范化文本。"""
return expected == observed if mode == 'exact' else expected in observed
def _translate_signature(
*, signature: dict[str, Any] | None, coordinate_transform: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""将当前 Profile 的签名副本映射到同一运行时框架,绝不回写冻结签名。"""
if not signature or not coordinate_transform or coordinate_transform.get('status') != 'applied':
return signature
try:
dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y'])
except (KeyError, TypeError, ValueError):
return signature
translated = deepcopy(signature)
for pattern in translated.get('table_patterns') or []:
if not isinstance(pattern, dict):
continue
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else {}
median = bbox.get('median') if isinstance(bbox.get('median'), list) else None
if median and len(median) == 4:
bbox['median'] = [median[0] + dx, median[1] + dy, median[2] + dx, median[3] + dy]
header = pattern.get('header_bbox')
if isinstance(header, list) and len(header) == 4:
pattern['header_bbox'] = [header[0] + dx, header[1] + dy, header[2] + dx, header[3] + dy]
for relation in translated.get('field_relation_graph') or []:
if isinstance(relation, dict):
# 同一平移不会改变两锚点的相对关系,特意不修改 dx/dy。
continue
return translated
def _profile_requires_unavailable_structure_evidence(
*, signature: dict[str, Any] | None,
dimension_results: dict[str, MatchDimensionResult],
) -> bool:
"""关键模板结构维度缺证据即禁止自动选中,不能靠缩小评分分母获得 hard match。"""
if not signature:
return False
return any(
dimension_results[key].state == 'unavailable'
for key in CRITICAL_STRUCTURE_DIMENSION_KEYS
)
def _aggregate_dimension_score(
*,
weights: Any,
@@ -664,6 +1028,17 @@ def _observe_layout_features(
signature: dict[str, Any] | None,
) -> dict[str, Any]:
"""从冻结 layout 聚合非敏感结构特征供维度比对。"""
persisted = layout.get('matching_features')
# 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v2 投影。
if isinstance(page_glyphs, dict) and any(isinstance(value, list) and value for value in page_glyphs.values()):
persisted = None
if isinstance(persisted, dict) and persisted.get('version') == LAYOUT_MATCHING_FEATURES_VERSION:
observed = _observed_features_from_persisted_projection(
features=persisted, signature=signature,
)
if observed is not None:
return observed
first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
aspect_ratio = 0.0
if isinstance(first_page, dict):
@@ -699,6 +1074,53 @@ def _observe_layout_features(
}
def _observed_features_from_persisted_projection(
*, features: dict[str, Any], signature: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""将压缩前持久化的轻量特征恢复为 matcher 输入,绝不读取逐字符正文。"""
page_structure = features.get('page_structure')
tables = features.get('tables')
if not isinstance(page_structure, dict) or not isinstance(tables, list):
return None
candidates = [item for item in tables if isinstance(item, dict) and isinstance(item.get('bbox'), list)]
if not candidates:
return None
expected = _signature_column_values(signature or {}, 'column_centers')
primary = candidates[0]
if expected:
def distance(item: dict[str, Any]) -> tuple[float, int]:
options = item.get('header_candidates') if isinstance(item.get('header_candidates'), list) else [item]
best = min((abs(len(option.get('column_centers') or []) - len(expected)) for option in options if isinstance(option, dict)), default=999)
return best, abs(len(item.get('column_centers') or []) - len(expected))
primary = min(candidates, key=distance)
options = primary.get('header_candidates') if isinstance(primary.get('header_candidates'), list) else []
if options:
primary = min(options, key=lambda item: abs(len(item.get('column_centers') or []) - len(expected))) | {'bbox': candidates[0].get('bbox')}
bbox = primary.get('bbox')
centers = primary.get('column_centers')
widths = primary.get('column_width_ratios')
tokens = primary.get('header_tokens')
if not (
isinstance(bbox, list) and len(bbox) == 4
and isinstance(centers, list) and isinstance(widths, list) and isinstance(tokens, list)
):
return None
return {
'aspect_ratio': float(page_structure.get('aspect_ratio') or 0),
'table_count': int(page_structure.get('table_count') or len(candidates)),
'page_count': int(page_structure.get('page_count') or 0),
'primary_table_bbox': bbox,
'header_tokens': tokens,
'column_count': len(centers),
'column_centers': centers,
'column_width_ratios': widths,
'static_text_centers': (
features.get('static_text_centers')
if isinstance(features.get('static_text_centers'), dict) else {}
),
}
def _select_signature_primary_table_bbox(
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
) -> list[float] | None:
@@ -881,11 +1303,13 @@ def _observe_static_text_centers(
result: dict[str, list[float]] = {}
for row in rows:
ordered = sorted(row, key=lambda item: item['bbox'].get('x0', 0))
text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered))
if not text:
text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered))[:80]
if not text or len(text) >= 80:
continue
xs = [(float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 / width for item in ordered]
ys = [(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 / height for item in ordered]
if len(result) >= 32:
break
result[text] = [round(sum(xs) / len(xs), 4), round(sum(ys) / len(ys), 4)]
return result
@@ -531,7 +531,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'字段已按 PDF 优先裁决,请核对辅助证据差异',
),
'evidence_missing': _meta('owner', 'open_order_review', '关键识别结果缺少有效证据'),
'customer_unresolved': _meta('owner', 'confirm_customer', '未能识别客户'),
'customer_unresolved': _meta('owner', 'confirm_customer', '客户尚未确认'),
'customer_ambiguous': _meta('owner', 'confirm_customer', '匹配到多个客户'),
'customer_out_of_scope': _meta('owner', 'confirm_customer', '客户不在当前业务范围内'),
'reservation_missing': _meta('owner', 'edit_reservation', '缺少有效 Reservation'),
@@ -1,7 +1,7 @@
"""
services/shipping_notice/lifecycle_projection.py
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份四阶段业务生命周期。
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
@@ -18,6 +18,7 @@ LIFECYCLE_STAGES: tuple[dict[str, str], ...] = (
{'code': 'intake_parse', 'label': '接收解析'},
{'code': 'order_review', 'label': '订单复核'},
{'code': 'fulfillment_prep', 'label': '通知准备'},
{'code': 'freight_upload', 'label': '货代上传'},
{'code': 'upload_complete', 'label': '通知完成'},
)
@@ -43,8 +44,8 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
'inventory_sufficiency': 'fulfillment_prep',
'excel_readiness': 'fulfillment_prep',
'artifact_generation': 'fulfillment_prep',
'freight_upload_rpa': 'upload_complete',
'manual_upload_handoff': 'upload_complete',
'freight_upload_rpa': 'freight_upload',
'manual_upload_handoff': 'freight_upload',
}
# 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。
@@ -60,7 +61,9 @@ LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = (
'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating',
'excel_generate', 'excel_generated',
}),
('upload_complete', {'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'completed'}),
('freight_upload', {
'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'upload_complete', 'completed',
}),
)
@@ -104,6 +107,7 @@ def project_lifecycle(
legacy_stage: str | None,
has_candidate_context: bool,
has_intake_parse_context: bool = False,
verified_upload_success: bool = False,
) -> dict[str, Any]:
"""按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。
@@ -111,7 +115,12 @@ def project_lifecycle(
"""
gate = current_gate if isinstance(current_gate, dict) else {}
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower()
if gate_code in LIFECYCLE_STAGE_BY_GATE:
# 成功事实高于当前 Gate/历史阶段:异步回调成功后旧 Gate 尚未清理时,用户仍应
# 看到已完成;反之任何技术完成、回执文本或旧 completed 都不能越过此条件。
if verified_upload_success:
lifecycle_stage = 'upload_complete'
authority = 'verified_upload_success'
elif gate_code in LIFECYCLE_STAGE_BY_GATE:
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
authority = 'process_gate'
else:
@@ -13,6 +13,24 @@ backend/app/services/shipping_notice/order_extraction.py
from __future__ import annotations
def reconcile_review_case_after_unit(*, run: Any, unit: Any) -> Any:
"""
Unit 结果已消费时,确保 Review Case 后仍执行统一校验/自动推进协调。
Args:
run: Unit 所属的订单抽取 Run。
unit: 已消费、需要回放的 PDF Unit。
Returns:
确保后的 Review Case;协调器副作用会刷新校验结果并按资格决定后续自动推进。
"""
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run
case = ensure_review_case_for_unit(run=run, unit=unit)
maybe_stp_auto_create_for_run(run=run)
return case
import hashlib
import json
from datetime import datetime
@@ -1271,8 +1289,7 @@ def submit_order_extraction_unit_result(
'idempotent_replay': True,
'unit_id': int(unit.id),
}
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
ensure_review_case_for_unit(run=run, unit=unit)
reconcile_review_case_after_unit(run=run, unit=unit)
return result
session = _runtime_session_for_run(run)
@@ -312,6 +312,7 @@ def _coordinate_profile_rows(
*, raw_profile: dict[str, Any], raw_table: dict[str, Any], layout: dict[str, Any],
contract: Any, schema_fields: dict[str, dict[str, Any]], document_id: int | None = None,
initial_carry: dict[str, Any] | None = None,
coordinate_transform: dict[str, Any] | None = None,
) -> list[dict[str, Any]] | None:
"""
用模板表区和整页字符生成带字段坐标的紧凑行候选。
@@ -324,6 +325,7 @@ def _coordinate_profile_rows(
schema_fields: field_id/code 对应的冻结 Schema 字段。
document_id: 当前 Unit 文档 ID;提供时生成稳定 token/evidence 引用。
initial_carry: 跨页固定子行的已解析字段。
coordinate_transform: 共同 matcher 对当前唯一 Profile 已确认的平移;不在本函数重算。
Returns:
规范化字段行;坐标前置条件缺失时返回 None。
@@ -364,11 +366,16 @@ def _coordinate_profile_rows(
relative_region = _coordinate_region_mapping(region.region)
if relative_region is None:
return None
evidence_relative_region = _translate_coordinate_region(
relative_region, coordinate_transform=coordinate_transform,
)
if evidence_relative_region is None:
return None
region_bbox = {
'x0': relative_region['x0'] * page_bbox['x1'],
'y0': relative_region['y0'] * page_bbox['y1'],
'x1': relative_region['x1'] * page_bbox['x1'],
'y1': relative_region['y1'] * page_bbox['y1'],
'x0': evidence_relative_region['x0'] * page_bbox['x1'],
'y0': evidence_relative_region['y0'] * page_bbox['y1'],
'x1': evidence_relative_region['x1'] * page_bbox['x1'],
'y1': evidence_relative_region['y1'] * page_bbox['y1'],
}
raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None
if not is_virtual_page and raw_bbox is not None and not _coordinate_regions_overlap(raw_bbox, region_bbox):
@@ -399,6 +406,7 @@ def _coordinate_profile_rows(
initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0),
line_start_field_code=region.line_start_field_code,
row_reconstruction_mode=region.row_reconstruction_mode,
coordinate_transform=coordinate_transform,
):
values: list[dict[str, Any]] = []
issues = list(reconstructed.issues)
@@ -442,6 +450,60 @@ def _coordinate_profile_rows(
return rows
def _selected_coordinate_transform(
*, profile_match: dict[str, Any], raw_profile: dict[str, Any],
) -> dict[str, Any] | None:
"""从共同 matcher 的唯一选中候选取得运行时变换,禁止为行解析二次匹配。"""
if str(profile_match.get('status') or '') not in {'unique_match', 'selected_by_score'}:
return None
identity = (
str(raw_profile.get('profile_code') or ''),
int(raw_profile.get('version') or 0),
str(raw_profile.get('checksum') or ''),
)
for candidate in profile_match.get('candidates') or []:
if not isinstance(candidate, dict):
continue
candidate_identity = (
str(candidate.get('profile_code') or ''),
int(candidate.get('version') or 0),
str(candidate.get('checksum') or profile_match.get('checksum') or ''),
)
if candidate_identity[:2] != identity[:2]:
continue
transform = candidate.get('coordinate_transform')
return transform if isinstance(transform, dict) else None
return None
def _translate_coordinate_region(
region: dict[str, float], *, coordinate_transform: dict[str, Any] | None,
) -> dict[str, float] | None:
"""在裁剪页级 glyph 前使用 matcher 已确认的受限平移;非法声明 fail-closed。"""
if coordinate_transform is None:
return region
if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied':
return None
try:
translate_x, translate_y = (
float(coordinate_transform['translate_x']),
float(coordinate_transform['translate_y']),
)
translated = {
'x0': float(region['x0']) + translate_x,
'y0': float(region['y0']) + translate_y,
'x1': float(region['x1']) + translate_x,
'y1': float(region['y1']) + translate_y,
}
except (KeyError, TypeError, ValueError):
return None
if not all(value == value and abs(value) != float('inf') for value in translated.values()):
return None
if not (0 <= translated['x0'] < translated['x1'] <= 1 and 0 <= translated['y0'] < translated['y1'] <= 1):
return None
return translated
def _coordinate_region_mapping(value: Any) -> dict[str, float] | None:
"""将模板相对区域统一为坐标字典,供绝对裁剪与行重建共同使用。
@@ -734,6 +796,9 @@ def _profile_table_candidates(
# MinerU HTML is intentionally neither required nor parsed on this path.
try:
profile = _frozen_coordinate_profile(raw_profile)
coordinate_transform = _selected_coordinate_transform(
profile_match=profile_match, raw_profile=raw_profile,
)
carry = None
parent_table_id = str(raw_table.get('continuation_of') or '')
if parent_table_id:
@@ -749,6 +814,7 @@ def _profile_table_candidates(
raw_profile=raw_profile, raw_table=raw_table, layout=layout,
contract=contract, schema_fields=schema_fields,
document_id=int(unit.document_id), initial_carry=carry,
coordinate_transform=coordinate_transform,
)
except (TypeError, ValueError):
issues.append('order_profile_snapshot_invalid')
@@ -1806,6 +1872,10 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An
candidates = extract_order_fields(
profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields,
coordinate_evidence=layout.get('coordinate_evidence') or {},
coordinate_transform=_selected_coordinate_transform(
profile_match=match.model_dump(mode='json') if hasattr(match, 'model_dump') else match,
raw_profile=raw,
),
)
return [item.model_dump(mode='json') for item in candidates if item.status == 'confirmed']
@@ -138,6 +138,8 @@ def _customer_step_for_case(
site_id=None,
actor_id=None,
reason=confirm_reason,
# 保存校验入口需将客户确认、Draft 校验与后续 Gate/STP 写入作为同一事务提交。
commit=False,
)
except Exception as exc: # noqa: BLE001
_LOGGER.warning(
@@ -179,6 +181,33 @@ def _customer_step_for_case(
}
def auto_confirm_unique_customer_for_review_case(
*,
case: ShippingOrderReviewCase,
trigger: str,
) -> dict[str, Any]:
"""
将当前 Case 的唯一 Shadow 客户候选落为 Bill-to 已确认事实。
用途与触发时机:保存订单并校验、恢复协调等入口在读取建单资格前调用;
仅 ``unique_candidate`` 能自动确认,其他匹配状态保持人工处置。
Args:
case: 当前文件 Stream 的可编辑订单复核 Case。
trigger: 调用来源,写入客户确认审计。
Returns:
客户步骤摘要;``auto_confirmed`` 时附带标准客户主键,其他状态不伪造确认事实。
"""
status, metadata = _customer_step_for_case(case=case, trigger=trigger)
if status == 'auto_confirmed':
db.session.flush()
return {
'status': status,
**(dict(metadata) if isinstance(metadata, dict) else {}),
}
def reconcile_single_case_for_auto_progress(
*,
case_no: Any = None,
@@ -6,7 +6,8 @@ backend/app/services/shipping_notice/order_review_disposition_service.py
workflow_ledger_service、order_task_service.resolve_order_task_for_candidate。
逻辑:处置只改变当前 PDF 的 Case 生命周期;锁定时分别 FOR UPDATE Case 与 Draft,
禁止 joinedload+FOR UPDATE。单文件重识别通过新的 Run 保留原始 PDF 与机器结果,
成功后才由 Run 终态钩子替代旧 Case;创建后继 Run 时显式传入 Case 对应 OT(非 Run 根号)。
成功后才由 Run 终态钩子替代旧 Case,并在 Stream 原子切换成功后补触发新版 Case 的统一自动推进;
创建后继 Run 时显式传入 Case 对应 OT(非 Run 根号)。
每次关键处置同时写 CaseEvent + 统一 ShippingAuditEvent;
质量异常原因码 `other` 时备注必填。被拒绝操作(无效原因、终态冲突、替代状态不满足、
WorkflowItem 已关闭等)在抛错前独立 commit 拒绝审计,避免 API 回滚吞掉留痕。由 workspace shipping_notice API 调用。
@@ -1015,7 +1016,17 @@ def reparse_case_document(
def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: bool) -> None:
"""在新版 Run 终态收口旧 Case:成功替代,失败恢复原草稿的原生命周期。"""
"""
在新版 Run 终态收口旧 Case,并在成功切换当前版本后恢复自动推进。
核心逻辑:重解析结果落库时新版 Case 尚不是 Stream 当前版本,协调器会安全跳过;
因此只在 ``activate_review_case`` 已确认切换成功后调用单 Case 协调器。这样复用
客户确认、Draft 校验、Gate 与 STP 幂等链路,且不会让晚到分支覆盖已确认版本。
Args:
run: 已到终态的重解析后继 Run。
succeeded: 新版 Run 是否成功到达可复核终态。
"""
marker = (run.input_snapshot_json or {}).get('review_reparse')
if not isinstance(marker, dict) or not run.reparse_of_run_id:
return
@@ -1042,10 +1053,21 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
# Run 已到终态但没有可复核新版本时,不可废弃旧草稿。
return
from app.services.shipping_notice.review_stream_service import activate_review_case
activate_review_case(
stream = activate_review_case(
case=replacement_case,
trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded',
)
# [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进。激活被并发确认或
# 晚到分支拒绝时,保持该草稿只读,不得错误建单或进入库存准备。
if int(stream.current_case_id or 0) == int(replacement_case.id):
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
)
reconcile_single_case_for_auto_progress(
case=replacement_case,
trigger='document_reparse_succeeded',
refresh_validation=True,
)
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={
'successor_run_no': run.run_no,
'replacement_case_no': replacement_case.case_no,
@@ -134,12 +134,31 @@ def _sanitize_candidates(raw: list[Any], *, display_map: dict[tuple[str, int], s
'missing_required_anchor_ids': [
str(c) for c in (item.get('missing_required_anchor_ids') or []) if c
][:12],
'coordinate_transform': _sanitize_coordinate_transform(item.get('coordinate_transform')),
})
if len(out) >= 5:
break
return out
def _sanitize_coordinate_transform(value: Any) -> dict[str, Any] | None:
"""投影受限坐标变换审计摘要;禁止泄露原始正文和完整坐标。"""
if not isinstance(value, dict):
return None
status = str(value.get('status') or '').strip()
if not status:
return None
result: dict[str, Any] = {'status': status}
for key in ('translate_x', 'translate_y'):
raw = value.get(key)
try:
result[key] = round(float(raw), 6) if raw is not None else None
except (TypeError, ValueError):
result[key] = None
result['reason_codes'] = [str(code) for code in (value.get('reason_codes') or []) if str(code).strip()][:12]
return result
def project_review_case_profile_match(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""
投影建单前文档模板匹配摘要。
@@ -47,6 +47,7 @@ from app.models import (
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
ShippingOrderReviewStream,
ShippingOrderIntake,
)
@@ -535,6 +536,40 @@ def _document_filename(run: ShippingOrderProcessingRun, document_id: int) -> str
return None
def _document_intake_for_retry(
run: ShippingOrderProcessingRun,
document_id: int,
) -> ShippingOrderIntake | None:
"""按冻结文档归属定位当前 Intake,避免工作台按文件名或会话猜测 SNI。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
for intake_snapshot in snapshot.get('intakes') or []:
if not isinstance(intake_snapshot, dict):
continue
for document in intake_snapshot.get('documents') or []:
if not isinstance(document, dict) or int(document.get('document_id') or 0) != int(document_id):
continue
intake_no = str(intake_snapshot.get('intake_no') or '').strip().upper()
if intake_no:
return ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none()
return None
def _intake_retry_projection(
case: ShippingOrderReviewCase,
run: ShippingOrderProcessingRun,
candidate: ShippingOrderCandidate | None,
) -> tuple[str | None, bool]:
"""返回当前 Case 唯一的 Intake 重试目标与服务端授权结果。"""
intake = _document_intake_for_retry(run, int(case.document_id))
retry_authorized = bool(
intake is not None
and str(intake.parse_status or '').strip().lower() == 'parse_failed'
and candidate is None
and not case.confirmed_task_id
)
return (intake.intake_no if retry_authorized else None, retry_authorized)
def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
"""由后端 Case 状态与 WorkflowItem 生命周期决定可用动作,前端不可自行推导确认资格。"""
from app.services.shipping_notice.tool_common import llm_review_enabled
@@ -651,6 +686,7 @@ def serialize_review_case(
run = case.run
draft = case.current_draft
candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None
intake_no, intake_retry_authorized = _intake_retry_projection(case, run, candidate)
schema_fields = _schema_fields(run)
header_fields = [item for item in schema_fields if item.get('scope') == 'header']
line_fields = [item for item in schema_fields if item.get('scope') == 'line']
@@ -678,7 +714,13 @@ def serialize_review_case(
'issues': list(draft.issue_summary_json or []),
'validation': dict(draft.validation_result_json or {}),
'build_eligibility': {
'can_build': bool((draft.validation_result_json or {}).get('can_build')),
# 未校验不是业务阻断;保留 None 让前端展示“尚未校验”,避免
# 把缺失的布尔值投影成 can_build=false。
'can_build': (
bool((draft.validation_result_json or {}).get('can_build'))
if str((draft.validation_result_json or {}).get('status') or '').strip() != 'not_validated'
else None
),
'can_auto_create': bool((draft.validation_result_json or {}).get('can_auto_create')),
'status': str((draft.validation_result_json or {}).get('status') or 'needs_review'),
'gates': dict((draft.validation_result_json or {}).get('gates') or {}),
@@ -912,6 +954,16 @@ def serialize_review_case(
# task_missing:无恢复 API 时明确 view + contact_admin;防御性剥离残留 confirm。
available_actions = list(bundle['available_actions']) if bundle else [a for a in _allowed_actions(case) if a != 'confirm']
if intake_retry_authorized:
available_actions = ['retry_parse']
elif (
candidate is None
and not case.confirmed_task_id
and (intake := _document_intake_for_retry(run, int(case.document_id))) is not None
and str(intake.parse_status or '').strip().lower() in {'parsing', 'queued', 'cancelled'}
):
# parsing / cancelled 等状态只可等待或查看;不得把草稿动作误投影为解析恢复。
available_actions = []
# 兼容兜底:task_missing 仍然优先固定视图动作。
if formal_ot.get('task_missing'):
available_actions = ['view', 'contact_admin']
@@ -976,6 +1028,7 @@ def serialize_review_case(
'draft': projected_draft,
'llm_suggestions': llm_suggestions,
'available_actions': available_actions,
'intake_no': intake_no,
'formal_editable_field_ids': (
list_editable_formal_field_ids(
schema_fields,
@@ -1002,6 +1055,8 @@ def _serialize_review_case_summary(
) -> dict[str, Any]:
"""为工作台文件队列投影单 Case 的只读识别与生命周期摘要。"""
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None
intake = _document_intake_for_retry(run, int(case.document_id))
intake_no, intake_retry_authorized = _intake_retry_projection(case, run, candidate)
# 空 Review Case 只是解析异常/人工处置容器,不能显示为已进入订单复核。
# 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。
lifecycle_stage = 'intake_parse'
@@ -1044,7 +1099,21 @@ def _serialize_review_case_summary(
'status': case.status,
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0,
'available_actions': _allowed_actions(case),
# Intake 解析失败没有 Candidate,恢复必须从当前阶段卡调用原 SNI retry API。
# 其它 Intake 状态(尤其 parsing/cancelled)不得由前端显示或猜测重试。
'available_actions': (
['retry_parse']
if intake_retry_authorized
else (
[]
if intake is not None
and str(intake.parse_status or '').strip().lower() in {'parsing', 'queued', 'cancelled'}
and candidate is None
and not case.confirmed_task_id
else _allowed_actions(case)
)
),
'intake_no': intake_no,
# 后端按 Case/正式任务裁决,禁止工作台仅为当前项从草稿拼接 PO 或阶段。
'po_number': str(candidate.po_number or '').strip() or None if candidate is not None else None,
'lifecycle_stage': lifecycle_stage,
@@ -129,6 +129,7 @@ def resume_after_review_change(
change_type: str | None = None,
skip_validate: bool = False,
allow_auto_create: bool = True,
expected_draft_version: int | None = None,
) -> dict[str, Any]:
"""
建单前统一恢复:重校验 → Gate 同步 → 资格重算 → 可选 auto_gate 建单。
@@ -141,6 +142,7 @@ def resume_after_review_change(
change_type: 可选失效规则键(process_gate_dependency)。
skip_validate: True 时跳过 validate_draft(调用方刚校验过)。
allow_auto_create: False 时只重算资格,不自动建单(例如仅预览)。
expected_draft_version: 可选乐观锁版本;显式保存校验时必须传入。
Returns:
resume_outcome 字典(含 gate_recalculated / auto_gate_allowed / task_created 等)。
@@ -177,12 +179,27 @@ def resume_after_review_change(
'case': serialize_review_case(case),
}
# [STEP 1.5] 唯一 Shadow 候选必须先写成 Bill-to confirmed,再读取建单资格。
# 否则保存校验会把“唯一候选待确认”误判为“客户未识别”。不在此处 commit,
# 保证客户确认、Draft 校验与后续 Gate/STP 决策属于同一事务。
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
auto_confirm_unique_customer_for_review_case,
)
customer_auto_confirmation = auto_confirm_unique_customer_for_review_case(
case=case,
trigger=trigger_code,
)
# [STEP 2] 显式全量校验(同步建单前 Gate)。
if not skip_validate:
validate_draft(
user_id=int(user_id),
case_no=str(case.case_no),
expected_draft_version=int(case.current_draft.draft_version),
expected_draft_version=(
int(expected_draft_version)
if expected_draft_version is not None
else int(case.current_draft.draft_version)
),
)
db.session.flush()
case = _reload_case(user_id=user_id, case_no=case_no)
@@ -216,6 +233,7 @@ def resume_after_review_change(
'auto_gate_allowed': snap['auto_gate_allowed'],
'qualification_status': snap['qualification_status'],
'failed_gates': snap['failed_gates'],
'customer_auto_confirmation': customer_auto_confirmation,
},
source='order_review_resume',
strict=True,
@@ -238,6 +256,7 @@ def resume_after_review_change(
),
'case': serialize_review_case(case),
'invalidated_gates': invalidated,
'customer_auto_confirmation': customer_auto_confirmation,
}
# [STEP 5] 可建单但不允许 auto_gate:等待人工确认建单。
@@ -276,6 +295,7 @@ def resume_after_review_change(
),
'case': serialize_review_case(case),
'invalidated_gates': invalidated,
'customer_auto_confirmation': customer_auto_confirmation,
}
# [STEP 6] auto_gate:入队 STP 幂等 Job(queued);Worker 再执行 confirm。
@@ -441,9 +441,12 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
}
task_no = str(getattr(task, 'task_no', None) or '').strip().upper() or None
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
verified_upload_success = has_verified_upload_success(task)
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
progress_state = (
'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'}
'uploaded' if verified_upload_success
else 'export_ready' if getattr(task, 'export_file_path', None)
else 'matched' if getattr(task, 'match_status', None)
else 'inventory_ready' if getattr(task, 'inventory_lines_json', None)
@@ -633,9 +636,14 @@ def project_stage_for_task(
map_notice_to_processing_status_stage,
)
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
# 业务完成不能仅信任 Notice 的历史聚合字段。复核工作台必须与批次投影
# 复用同一成功谓词,否则同一任务会在不同入口出现“已完成/待上传”分叉。
verified_upload_success = has_verified_upload_success(task)
raw_upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
progress_state = (
'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'}
'uploaded' if verified_upload_success
else 'export_ready' if getattr(task, 'export_file_path', None)
else 'matched' if getattr(task, 'match_status', None)
else 'inventory_ready' if getattr(task, 'inventory_lines_json', None)
@@ -656,10 +664,12 @@ def project_stage_for_task(
'stage_node': None,
}
# 上传登记/回调会先更新 ShippingNotice 聚合事实;旧 OT.stage 可能仍停在
# freight_uploading,不能用过期阶段覆盖已经完成的履约状态。
if progress_state in {'uploaded', 'closed', 'completed'}:
# 成功回调会先更新 Notice 聚合事实;旧 OT.stage 可能仍停在
# freight_uploading,只有三层成功事实齐备时才能覆盖为 completed。
if progress_state == 'uploaded':
return _with_label('completed', source='notice_terminal')
if raw_upload_status in {'uploaded', 'succeeded', 'success'}:
return _with_label('freight_uploading', source='upload_success_unverified')
# [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。
order_task = None
@@ -678,6 +688,8 @@ def project_stage_for_task(
order_task = None
ot_stage = str(getattr(order_task, 'stage', None) or '').strip().lower() if order_task else ''
if ot_stage and ot_stage in SHIPPING_PROCESSING_STAGES:
if ot_stage == 'completed' and not verified_upload_success:
return _with_label('freight_uploading', source='upload_success_unverified')
# [STEP 1b] 正式 OT 已创建但 stage 仍停在 order_creating:业务上已进入获取库存。
# Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。
if ot_stage == 'order_creating':
@@ -316,7 +316,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'gate_code': 'freight_upload_rpa',
'sequence_no': 19,
'label': '货代上传 RPA',
'ui_placement': {'target_surface': 'upload_complete', 'target_anchor': 'freight_upload'},
'ui_placement': {'target_surface': 'freight_upload', 'target_anchor': 'freight_upload'},
'responsible_party': 'worker',
'implementation_status': 'implemented',
'recoverable': True,
@@ -330,7 +330,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'gate_code': 'manual_upload_handoff',
'sequence_no': 20,
'label': '人工上传交接',
'ui_placement': {'target_surface': 'upload_complete', 'target_anchor': 'manual_upload'},
'ui_placement': {'target_surface': 'freight_upload', 'target_anchor': 'manual_upload'},
'responsible_party': 'owner',
'implementation_status': 'implemented',
'recoverable': True,
@@ -706,7 +706,7 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
'upload_rpa_failed': 'freight_upload_rpa',
'upload_rpa_login_failed': 'freight_upload_rpa',
'upload_platform_rejected': 'freight_upload_rpa',
'upload_result_unknown': 'manual_upload_handoff',
'upload_result_unknown': 'freight_upload_rpa',
}
# Candidate Qualification / 旧自动建单门禁键 → 唯一 owning_gate(禁止平行用户投影)。
@@ -167,7 +167,8 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
【触发时机】写状态机回写 OT、投影组装 order_task 工作项。
核心逻辑:上传完成 → completed;上传中/待上传 → freight_uploading;
核心逻辑:仅可审计的上传成功 → completed;上传中、待登记及历史无证据上传
→ freight_uploading;
导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching;
matching/inventory_ready/matched → inventory_matching;建单中 → order_creating。
领域映射唯一来源,禁止写状态机反向依赖投影私有函数。
@@ -185,8 +186,16 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
review = str(getattr(notice, 'review_status', None) or '').strip().lower()
match = str(getattr(notice, 'match_status', None) or '').strip().lower()
lifecycle = str(getattr(notice, 'lifecycle_status', None) or '').strip().lower()
if upload_st in {'uploaded', 'succeeded', 'success'} or lifecycle in {'archived', 'deleted'}:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
verified_upload_success = has_verified_upload_success(notice)
if lifecycle in {'voided', 'archived', 'deleted'}:
return ('cancelled', 'cancelled')
if verified_upload_success:
ps = 'uploaded'
elif upload_st in {'uploaded', 'succeeded', 'success'}:
# 历史聚合字段或单一回执不构成业务完成。保留在上传工作面,等待核对。
ps = 'waiting_upload'
elif upload_st in {'uploading', 'pending', 'failed'} or pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}:
ps = 'waiting_upload' if upload_st != 'failed' else 'upload_failed'
elif export_path:
@@ -444,6 +453,7 @@ def reconcile_processing_projection_facts(
legacy_actions: list[str] | None = None,
invalidated_from_stage: str | None = None,
excel_ready: bool = False,
verified_upload_success: bool | None = None,
) -> dict[str, Any]:
"""
在投影输出前强制 status/stage/gate/action 不变量,并写入 stage_nodes。
@@ -518,6 +528,17 @@ def reconcile_processing_projection_facts(
status = 'automating'
stage_idx = shipping_processing_stage_index(stage)
# 完成由上传成功谓词单独裁决。正式 OT 的历史 completed/uploaded 不能因为
# 旧字段、归档或技术流程结束而越过人工核对;取消态不在此规则内改写。
if verified_upload_success is True:
status = 'completed'
stage = 'completed'
gate = None
gate_action = None
elif verified_upload_success is False and status == 'completed':
status = 'waiting_human'
stage = 'freight_uploading'
# [BE-03] Extraction Run 完成误标为全流程 completed:早期 stage 时回退 status。
if status == 'completed' and stage and stage != 'completed':
if stage_idx is not None and stage_idx <= waiting_idx:
@@ -732,7 +753,21 @@ def apply_user_projection_fields(
# ===== [STEP 4] 按冻结映射规则计算 user_status(F3 优先级) =====
notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else ''
_rd_has_completed_process = notice_upload_status in {'uploaded', 'succeeded', 'success'}
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
# 读取路径也必须遵守三层上传成功事实;否则 retry 决策或旧 status=completed
# 会在这一步将前序 reconcile 的货代上传态重新提升为完成。
verified_upload_success = bool(notice is not None and has_verified_upload_success(notice))
unverified_upload_terminal = bool(
notice is not None
and not verified_upload_success
and (
old_status == 'completed'
or old_stage == 'completed'
or notice_upload_status in {'uploaded', 'succeeded', 'success'}
)
)
_rd_has_completed_process = verified_upload_success
def _compute_user_status() -> str:
# [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision
@@ -742,6 +777,8 @@ def apply_user_projection_fields(
return 'retryable'
if gate_status == 'blocked_manual':
return 'waiting_human'
if unverified_upload_terminal:
return 'waiting_human'
# 1) 终态短路:old_status completed/cancelled/failed
if old_status == 'completed':
return 'completed'
@@ -752,7 +789,7 @@ def apply_user_projection_fields(
# Retry Decision 可得时:优先用决策器
if retry_decision is not None:
# 4) rd_status=completed 或 action=noop 且 notice 完成态 → completed
if rd_status == _RD_STATUS_COMPLETED:
if rd_status == _RD_STATUS_COMPLETED and verified_upload_success:
return 'completed'
if rd_action == _RD_NOOP and _rd_has_completed_process:
return 'completed'
@@ -781,6 +818,12 @@ def apply_user_projection_fields(
user_status = _compute_user_status()
if unverified_upload_terminal:
payload['status'] = 'waiting_human'
payload['stage'] = 'freight_uploading'
old_status = 'waiting_human'
old_stage = 'freight_uploading'
# ===== [不变] user_stage 计算(保持不动) =====
user_stage = _USER_STAGE_TO_CODE.get(old_stage)
if user_stage is None:
@@ -49,7 +49,7 @@ from app.services.shipping_notice.processing_ownership import (
record_projection_inconsistency_audit,
)
from app.services.shipping_notice.lifecycle_projection import (
LIFECYCLE_STAGE_RANGES,
LIFECYCLE_STAGE_CODES,
project_lifecycle,
)
from app.services.shipping_notice.query_service import resolve_task_export_download
@@ -1280,19 +1280,34 @@ def _project_order_task_work_item(
str(run.status or ''),
stage=stage,
)
# 人工上传登记/RPA 回调先更新 ShippingNotice 聚合事实;旧 OT.status 可能仍为
# automating。终态 Notice 必须覆盖旧 OT 状态,保证统一投影、右侧状态和进度节点同源。
# 完成只接受三层可审计成功事实。旧 OT/process_status/upload_status 可能遗留
# completed/uploaded;缺少成功 Attempt 时必须停在货代上传,不能进入完成统计。
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
verified_upload_success = bool(
notice_for_stage is not None and has_verified_upload_success(notice_for_stage)
)
notice_process_status = str(getattr(notice_for_stage, 'process_status', None) or '').strip().lower() if notice_for_stage is not None else ''
notice_upload_status = str(getattr(notice_for_stage, 'upload_status', None) or '').strip().lower() if notice_for_stage is not None else ''
notice_lifecycle = str(getattr(notice_for_stage, 'lifecycle_status', None) or '').strip().lower() if notice_for_stage is not None else ''
if (
notice_process_status in {'uploaded', 'closed', 'completed'}
or notice_upload_status in {'uploaded', 'succeeded', 'success'}
or notice_lifecycle in {'voided', 'archived', 'deleted'}
):
if verified_upload_success:
status = 'completed'
stage = 'completed'
stage_label_key = 'completed'
elif notice_for_stage is not None and (
status == 'completed'
or stage == 'completed'
or notice_process_status in {'uploaded', 'closed', 'completed'}
or notice_upload_status in {'uploaded', 'succeeded', 'success'}
):
status = 'waiting_human'
stage = 'freight_uploading'
stage_label_key = 'freight_uploading'
elif notice_lifecycle in {'voided', 'archived', 'deleted'}:
status = 'cancelled'
# 取消/归档是终态而非完成态;保留最后业务工作面便于解释和审计回看。
stage = 'freight_uploading'
stage_label_key = 'freight_uploading'
# [BE-03] OT 上残留的 completed + 早期 stage 组合在输出前再折叠。
if status == 'completed' and stage != 'completed':
status = derivation_status_for_extraction_run('completed', stage=stage)
@@ -1382,6 +1397,7 @@ def _project_order_task_work_item(
'intake_no': _first_intake_no_for_run(run),
'status': status,
'stage': stage,
'verified_upload_success': verified_upload_success if notice_for_stage is not None else None,
# 与 Case.current_stage.label_key 同源;前端禁止用 stage 码直接当用户文案。
'stage_label_key': stage_label_key or (
'waiting_system_start' if stage == 'order_creating' else stage
@@ -1413,6 +1429,7 @@ def _project_order_task_work_item(
legacy_actions=legacy_actions,
invalidated_from_stage=invalidated_from_stage,
excel_ready=excel_ready,
verified_upload_success=verified_upload_success if notice_for_stage is not None else None,
)
# [STEP] 投影不一致:写审计后剥离内部诊断字段,避免泄漏给前端契约。
record_projection_inconsistency_audit(payload)
@@ -1677,8 +1694,14 @@ def _conversation_processing_group_for_work_item(item: dict[str, Any]) -> str:
item: order_task 工作项 dict。
Returns:
needs_action | processing | completed 之一。
needs_action | processing | completed | history 之一。
"""
is_unverified_upload_terminal = (
item.get('verified_upload_success') is False
and str(item.get('user_status') or item.get('status') or '').strip().lower() == 'completed'
)
if is_unverified_upload_terminal:
return 'needs_action'
user_group = str(item.get('user_group') or '').strip().lower()
if user_group in {'failed', 'waiting_human'}:
return 'needs_action'
@@ -1693,12 +1716,18 @@ def _conversation_processing_group_for_work_item(item: dict[str, Any]) -> str:
stage = str(item.get('stage') or '').strip().lower()
if user_status in {'waiting_human', 'retryable', 'failed'}:
return 'needs_action'
if user_status in {'completed', 'cancelled'}:
if user_status in {'cancelled', 'archived', 'voided', 'deleted'}:
return 'history'
if user_status == 'completed':
return 'completed'
if user_status == 'running':
return 'processing'
if status in {'failed', 'blocked'} or stage == 'waiting_review' or status == 'waiting_review':
return 'needs_action'
if status in {'cancelled', 'archived', 'voided', 'deleted'} or stage in {
'cancelled', 'archived', 'voided', 'deleted',
}:
return 'history'
if status == 'completed' or stage == 'completed':
return 'completed'
return 'processing'
@@ -1717,6 +1746,8 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) ->
user_status = str(item.get('user_status') or '').strip().lower()
status = str(item.get('status') or '').strip().lower()
stage = str(item.get('stage') or '').strip().lower()
if item.get('verified_upload_success') is False and user_status == 'completed':
return 'pending_review'
if user_status == 'waiting_human':
return 'pending_review'
if user_status == 'retryable':
@@ -2334,16 +2365,10 @@ def _conversation_task_row_from_work_item(
'document_id': source_document_id,
'filename': filename,
})
user_group = str(item.get('user_group') or '').strip().lower()
if not user_group:
user_status = str(item.get('user_status') or item.get('status') or '').strip().lower()
user_group = (
'failed' if user_status in {'failed', 'retryable'}
else 'waiting_human' if user_status in {'waiting_human', 'waiting_review'}
else 'completed' if user_status == 'completed'
else 'cancelled' if user_status == 'cancelled'
else 'processing'
)
# status_groups 与文件统计必须消费同一用户态裁决。尤其是旧载荷的
# completed + verified_upload_success=False,顶层已降级为待处理,不能在
# status_groups 又显示为 completed。
user_group = _batch_user_group(item)
return {
'user_task_no': user_task_no,
'submission_ordinal': None,
@@ -2415,6 +2440,7 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
),
# 空 Candidate 的接收解析只认后端持久化 Case 显式授予的上下文。
has_intake_parse_context=bool(item.get('intake_parse_authorized')),
verified_upload_success=bool(item.get('verified_upload_success')),
)
lifecycle_stage = lifecycle['lifecycle_stage']
if primary is not None:
@@ -2491,7 +2517,7 @@ def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) -
'download_excel', 'open_manual_upload', 'wait_manual_upload', 'mark_manual_uploaded',
'retry_freight_upload_rpa', 'retry_upload',
}:
return 'upload_complete'
return 'freight_upload'
# 历史 Review 投影的 view 与 view_result 同为只读查看入口;必须由后端附带
# 当前已裁决的工作台目标,前端不得因缺失目标误判为“前置阶段未完成”。
return lifecycle_stage if code in {'view', 'view_result', 'view_record'} else None
@@ -2509,6 +2535,7 @@ def _lifecycle_stage_from_item(item: dict[str, Any]) -> str | None:
legacy_stage=str(item.get('user_stage') or item.get('stage') or ''),
has_candidate_context=bool(item.get('has_formal_ot') or item.get('shipping_notice_no')),
has_intake_parse_context=bool(item.get('intake_parse_authorized')),
verified_upload_success=bool(item.get('verified_upload_success')),
)['lifecycle_stage']
@@ -2516,7 +2543,7 @@ def _current_file_representatives(work_items: list[dict[str, Any]]) -> list[dict
"""为批次投影选择每个业务文件唯一的当前代表项。
核心逻辑:EML 聚合根不参与文件口径;同一文件的旧 Run、旧 OT 或历史失败
投影只保留最新活动项。四阶段、文件统计、未分类统计必须共用本函数,避免一个
投影只保留最新活动项。五阶段、文件统计、未分类统计必须共用本函数,避免一个
PDF 同时被计入多个阶段或多个状态组。
Args:
@@ -2705,11 +2732,11 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) ->
return displayed
def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""从最终用户态工作项构建批次四阶段主进度。
def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""从最终用户态工作项构建批次五阶段主进度。
业务阶段映射和状态优先级只在后端维护;15 个技术节点仍附着在单项诊断字段,
绝不要求前端通过 stage 索引再计算四阶段。
绝不要求前端通过 stage 索引再计算业务阶段。
"""
ranked_items = sorted(
_current_file_representatives(work_items),
@@ -2733,17 +2760,21 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str,
'failed': 0,
'blocking_reason': None,
}
for code, _ in LIFECYCLE_STAGE_RANGES
for code in LIFECYCLE_STAGE_CODES
}
for item in ranked_items:
lifecycle_stage = _lifecycle_stage_from_item(item)
if lifecycle_stage is None:
continue
# 历史取消/归档只能保留在 history/status_groups,既不推动任一工作面,
# 也不得作为「通知完成」的分子或分母。
item_group = _batch_user_group(item)
if item_group in {'cancelled', 'archived'}:
continue
summary = stage_summaries[lifecycle_stage]
summary['total'] += 1
# 四阶段与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run
# 生命周期与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run
# 兼容投影中残留为 running,不能把后端已裁决为“待处理”的文件再显示为处理中。
item_group = _batch_user_group(item)
if item_group == 'completed':
summary['completed'] += 1
continue
@@ -2763,7 +2794,7 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str,
} or None
nodes: list[dict[str, Any]] = []
for code, _ in LIFECYCLE_STAGE_RANGES:
for code in LIFECYCLE_STAGE_CODES:
summary = stage_summaries[code]
# 卡片状态只由本阶段聚合事实计算,禁止由其他阶段的优先文件反向影响。
status = (
@@ -2781,8 +2812,13 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str,
return nodes
def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""兼容别名:已升级为五阶段输出,调用方应迁移至 ``_batch_lifecycle_nodes``。"""
return _batch_lifecycle_nodes(work_items)
def _unclassified_summary(work_items: list[dict[str, Any]]) -> dict[str, int]:
"""统计无法归入四阶段的业务文件,避免批次摘要与文件清单口径不一致。"""
"""统计无法归入业务生命周期的文件,避免批次摘要与文件清单口径不一致。"""
return {
'count': sum(
1 for item in _current_file_representatives(work_items)
@@ -2823,7 +2859,7 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An
优先级与 EML 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造
人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。
"""
# 批次主状态与文件计数、四阶段必须消费同一份“每文件唯一当前代表项”。
# 批次主状态与文件计数、五阶段必须消费同一份“每文件唯一当前代表项”。
# 否则历史 Run 的失败/待办虽然不再计数,仍可能抢走批次 CTA,形成
# “数字是当前、按钮却指向历史”的第二裁决源。
ranked = sorted(
@@ -2862,26 +2898,37 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An
def _batch_user_group(item: dict[str, Any]) -> str:
"""归一批次统计使用的互斥用户分组,优先消费领域投影已裁决的 user_group。"""
# 兼容载荷中可能残留 technical completed。只要正式 Notice/OT 已明确给出
# 未验证成功,就绝不能把它带入批次 completed 分子。
if item.get('verified_upload_success') is False and str(
item.get('user_status') or item.get('status') or ''
).strip().lower() == 'completed':
return 'waiting_human'
group = str(item.get('user_group') or '').strip().lower()
if group in {'failed', 'waiting_human', 'processing', 'completed'}:
if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived'}:
return group
status = str(item.get('user_status') or item.get('status') or '').strip().lower()
if status in {'failed', 'retryable'}:
return 'failed'
if status in {'waiting_human', 'waiting_review', 'idle'}:
return 'waiting_human'
if status in {'completed', 'cancelled'}:
if status == 'completed':
return 'completed'
if status in {'cancelled', 'archived', 'voided', 'deleted'}:
return 'cancelled'
return 'processing'
def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]:
"""按唯一当前业务文件统计互斥状态组,EML 容器永不计数。"""
# 已取消/归档文件保留在历史列表,但不构成当前任务完成率的分母或分子。
groups = {'failed': 0, 'waiting_human': 0, 'processing': 0, 'completed': 0}
for item in _current_file_representatives(work_items):
group = _batch_user_group(item)
summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
filename = str(summary.get('filename') or '').strip().lower()
if group not in groups:
continue
if not filename.endswith('.eml') and (filename or int(summary.get('document_id') or 0)):
groups[group] += 1
return {
@@ -2914,12 +2961,13 @@ def _conversation_processing_from_work_items(
Returns:
与 project_conversation_processing 同形的 dict。
"""
# 文件清单必须与批次统计、四阶段和 CTA 使用相同的当前文件代表项,同时
# 文件清单必须与批次统计、五阶段和 CTA 使用相同的当前文件代表项,同时
# 保留 EML 父卡,避免附件失去邮件归属或在多个状态组重复出现。
display_work_items = _display_work_items_from_current_files(work_items)
needs_action: list[dict[str, Any]] = []
processing: list[dict[str, Any]] = []
completed: list[dict[str, Any]] = []
history: list[dict[str, Any]] = []
all_rows: list[dict[str, Any]] = []
focused = str(focused_task_no or '').strip() or None
recent = str(recent_task_no or '').strip() or None
@@ -2938,6 +2986,8 @@ def _conversation_processing_from_work_items(
needs_action.append(row)
elif bucket == 'completed':
completed.append(row)
elif bucket == 'history':
history.append(row)
else:
processing.append(row)
@@ -2947,11 +2997,18 @@ def _conversation_processing_from_work_items(
needs_action.sort(key=_sort_key, reverse=True)
processing.sort(key=_sort_key, reverse=True)
completed.sort(key=_sort_key, reverse=True)
history.sort(key=_sort_key, reverse=True)
total = len(needs_action) + len(processing) + len(completed)
# [STEP 2] 会话文件数是业务 PDF 去重数,不是各任务 Run 文档数的简单求和。
# 仅以当前且仍活跃的业务文件兜底;取消/归档的历史文档不能因
# source_summary 仍保留 document_id 而重新进入完成率分母。
active_file_items = [
item for item in _current_file_representatives(work_items)
if _batch_user_group(item) in {'failed', 'waiting_human', 'processing', 'completed'}
]
document_ids = {
int(summary.get('document_id'))
for item in work_items
for item in active_file_items
if isinstance(item, dict) and str(item.get('work_item_type') or '') == 'order_task'
for child in (item.get('aggregate_children') or [item])
if isinstance(child, dict)
@@ -2964,6 +3021,7 @@ def _conversation_processing_from_work_items(
if document_ids
else sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed)
)
lifecycle_nodes = _batch_lifecycle_nodes(work_items)
return {
'projection_version': 1,
'summary': {
@@ -2972,7 +3030,7 @@ def _conversation_processing_from_work_items(
'processing': len(processing),
'needs_action': len(needs_action),
'completed': len(completed),
'history': 0,
'history': len(history),
**file_counts,
},
'focused_task_no': focused,
@@ -2980,7 +3038,7 @@ def _conversation_processing_from_work_items(
'needs_action': needs_action,
'processing': processing,
'completed': completed,
'history': [],
'history': history,
'status_groups': {
'failed': [row for row in all_rows if row.get('user_group') == 'failed'],
'waiting_human': [row for row in all_rows if row.get('user_group') == 'waiting_human'],
@@ -2989,7 +3047,10 @@ def _conversation_processing_from_work_items(
'cancelled': [row for row in all_rows if row.get('user_group') == 'cancelled'],
'archived': [row for row in all_rows if row.get('user_group') == 'archived'],
},
'four_stage_nodes': _batch_four_stage_nodes(work_items),
# 新客户端只消费 lifecycle_nodes;旧字段在一个发布周期内原样兼容,避免
# 会话卡、批次中心和嵌入式消费者在灰度期间看到不同阶段数。
'lifecycle_nodes': lifecycle_nodes,
'four_stage_nodes': lifecycle_nodes,
'unclassified_summary': _unclassified_summary(work_items),
'ui_state': _batch_ui_state_from_items(work_items),
'output_artifacts': _batch_output_artifacts(work_items),
@@ -6,7 +6,7 @@ services/shipping_notice/ui_state.py
process_gate_projection(统一 Gate 用户摘要)、
order_review_workbench_projection.apply_post_ot_gate_rules。
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind,再统一投影 actions,
再补充四阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
再补充五阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
stp_facts、progress_nodes);
若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影;
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办);
@@ -71,7 +71,8 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
{"id": "shipping-stage-1", "code": "intake_parse", "label": "接收解析"},
{"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"},
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "通知准备"},
{"id": "shipping-stage-4", "code": "upload_complete", "label": "通知完成"},
{"id": "shipping-stage-4", "code": "freight_upload", "label": "货代上传"},
{"id": "shipping-stage-5", "code": "upload_complete", "label": "通知完成"},
)
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
@@ -135,7 +136,7 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
}
# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
# 业务人员可见的五阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
_STAGE_CHECKPOINT_CODES: dict[str, str] = {
CP_PARSE_REVIEW: "order_review",
CP_RSV_REQ: "order_review",
@@ -148,12 +149,12 @@ _STAGE_CHECKPOINT_CODES: dict[str, str] = {
CP_READY_EXPORT: "fulfillment_prep",
CP_EXPORT_READY: "fulfillment_prep",
CP_EXPORT_GENERATED: "fulfillment_prep",
CP_WAITING_UPLOAD: "upload_complete",
CP_WAITING_UPLOAD: "freight_upload",
CP_UPLOAD_REQ: "fulfillment_prep",
CP_UPLOAD_FAILED: "upload_complete",
CP_UPLOAD_RESULT_UNKNOWN: "upload_complete",
CP_UPLOADED: "upload_complete",
CP_COMPLETED: "upload_complete",
CP_UPLOAD_FAILED: "freight_upload",
CP_UPLOAD_RESULT_UNKNOWN: "freight_upload",
CP_UPLOADED: "freight_upload",
CP_COMPLETED: "freight_upload",
CP_REJECTED: "order_review",
}
@@ -165,11 +166,13 @@ def _task_lifecycle(
gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate')
legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ''))
if legacy_stage is None:
legacy_stage = 'upload_complete' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None
legacy_stage = 'freight_upload' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None
if legacy_stage is None:
# 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。
legacy_index = _derive_current_step_index(task)
legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete')[legacy_index]
legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload')[legacy_index]
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
return project_lifecycle(
current_gate=gate if isinstance(gate, dict) else None,
blocking_reason=(
@@ -180,6 +183,7 @@ def _task_lifecycle(
legacy_stage=legacy_stage,
# ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。
has_candidate_context=True,
verified_upload_success=has_verified_upload_success(task),
)
@@ -249,7 +253,7 @@ def _unified_actions(*, process_gate: dict[str, Any] | None) -> dict[str, Any]:
def _derive_current_step_index(task: ShippingNotice) -> int:
"""
根据任务领域事实推导四阶段流程当前索引。
根据任务领域事实推导五阶段流程当前索引。
核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。
"""
@@ -295,7 +299,7 @@ def build_shipping_workflow_steps(
lifecycle_stage: str | None = None,
) -> list[dict[str, str]]:
"""
构造四阶段流程状态。
构造五阶段流程状态。
Returns:
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
@@ -304,13 +308,15 @@ def build_shipping_workflow_steps(
(index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage),
None,
)
# 正式 Gate 已存在时,四阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。
# 正式 Gate 已存在时,五阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。
current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task)
pending_reason = str(task.pending_human_reason or "").strip()
checkpoint_value = str(checkpoint or "").strip()
steps: list[dict[str, str]] = []
for index, step in enumerate(WORKFLOW_STEPS):
if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}:
# ``upload_complete`` 已由唯一成功谓词裁决。历史 Task.upload_status 不能让
# 流程条伪装为完成,否则会与 lifecycle_entries 和批次完成率分叉。
if lifecycle_stage == "upload_complete":
status = "completed"
elif index < current_index:
status = "completed"
@@ -664,7 +670,7 @@ def _build_stage_context(
stp_facts: dict[str, Any] | None,
process_gate: dict[str, Any] | None,
) -> dict[str, Any]:
"""构造四阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。
"""构造五阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。
通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成
只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。
@@ -834,13 +840,17 @@ def _build_stage_context(
ShippingExportArtifact.task_id == task.id,
).order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()).all()
latest_attempt = attempts[0] if attempts else None
succeeded_attempt = next(
(item for item in attempts if str(getattr(item, 'status', '') or '').lower() == 'succeeded'),
None,
)
latest_status = str(getattr(latest_attempt, 'status', '') or '').lower()
upload_outcome = (
'succeeded' if latest_status == 'succeeded' else
'failed' if latest_status in {'failed', 'timed_out'} else
'unknown' if latest_status == 'unknown' else
'running' if latest_status in {'pending', 'running'} else
'awaiting_manual' if lifecycle_stage == 'upload_complete' else
'awaiting_manual' if lifecycle_stage == 'freight_upload' else
'not_started'
)
return {
@@ -869,6 +879,15 @@ def _build_stage_context(
},
'upload': {
'outcome': upload_outcome,
# 成功工作面只能消费该不可变成功事实,而非“最近一条 Attempt”。后者可能
# 是迟到失败或人工核对记录,不能反向定义完成证据。
'succeeded_attempt': ({
'id': succeeded_attempt.id,
'status': succeeded_attempt.status,
'mode': succeeded_attempt.mode,
'freight_ref_no': succeeded_attempt.freight_ref_no,
'finished_at': succeeded_attempt.finished_at.isoformat() if succeeded_attempt.finished_at else None,
} if succeeded_attempt is not None else None),
'latest_attempt': ({
'id': latest_attempt.id,
'status': latest_attempt.status,
@@ -930,7 +949,7 @@ def build_task_ui_state(
'enabled': True,
# Artifact 已验证是下载授权的唯一来源;它直接声明展示位置,
# 不依赖旧 checkpoint 或 action code 位置映射。
'target_surface': 'upload_complete',
'target_surface': 'freight_upload',
'target_anchor': 'excel_artifact',
}, default_kind='view')
action_codes = {
@@ -80,6 +80,39 @@ def _aggregate_task_upload_status(task: ShippingNotice) -> None:
task.upload_status = 'pending'
def has_verified_upload_success(task: ShippingNotice) -> bool:
"""判断任务是否具备可审计的货代上传成功事实。
业务完成必须同时满足 Task 聚合、全部预约单和成功 Attempt 三层事实;历史字段、
单独回执号或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次
已完成分组与停止轮询共用的唯一成功谓词。
"""
try:
from flask import has_app_context
if not has_app_context():
return False
except Exception: # pragma: no cover - standalone/domain tests without Flask
return False
# 完成率只统计当前有效任务。已作废/归档的历史成功事实必须保留审计,
# 但不能再投影为「通知完成」或进入完成分母/分子。
if str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in {
'voided', 'archived', 'deleted', 'cancelled',
}:
return False
if getattr(task, 'id', None) is None or str(task.upload_status or '').strip().lower() != 'uploaded':
return False
reservations = ShippingReservation.query.filter_by(task_id=task.id).all()
if not reservations or any(row.status != 'uploaded' for row in reservations):
return False
return db.session.query(ShippingUploadAttempt.id).join(
ShippingExportArtifact,
ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id,
).filter(
ShippingExportArtifact.task_id == task.id,
ShippingUploadAttempt.status == 'succeeded',
).first() is not None
def complete_attempt(
attempt: ShippingUploadAttempt, *, success: bool, callback_id: str,
freight_ref_no: str | None = None, error_message: str | None = None,