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): def workspace_validate_shipping_order_review_draft(case_no: str):
"""显式重跑当前草稿校验,并触发统一恢复协调器(可 auto_gate)。""" """显式重跑当前草稿校验,并触发统一恢复协调器(可 auto_gate)。"""
user = _require_user() 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 ( from app.services.shipping_notice.order_review_resume_service import (
attach_resume_outcome, attach_resume_outcome,
resume_after_review_change, resume_after_review_change,
) )
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='draft_validated') payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='draft_validated')
result = validate_draft( # 保存校验必须由统一恢复协调器编排:唯一客户候选自动确认 → Draft 校验 →
user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'), # Gate/资格/STP。若先独立校验,会在同一次点击中把 unique_candidate 误判为未确认。
)
db.session.commit()
resume = resume_after_review_change( resume = resume_after_review_change(
user_id=user.id, user_id=user.id,
case_no=case_no, case_no=case_no,
trigger='draft_validated', trigger='draft_validated',
change_type=None, change_type=None,
skip_validate=True, skip_validate=False,
allow_auto_create=True, 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( @workspace_shipping_notice_bp.route(
@@ -8,6 +8,8 @@
from __future__ import annotations from __future__ import annotations
from copy import deepcopy
import math
import re import re
from statistics import median from statistics import median
from typing import Any, Literal from typing import Any, Literal
@@ -269,6 +271,7 @@ def reconstruct_coordinate_profile_rows(
line_start_field_code: str | None = None, line_start_field_code: str | None = None,
include_unanchored_rows: bool = False, include_unanchored_rows: bool = False,
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows', row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows',
coordinate_transform: dict[str, Any] | None = None,
) -> list[CoordinateProfileLogicalRow]: ) -> list[CoordinateProfileLogicalRow]:
""" """
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。 按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
@@ -279,7 +282,22 @@ def reconstruct_coordinate_profile_rows(
才是已授权的删除证据;未授权删除文字会被忽略。``include_deleted`` 仅供标注预览 才是已授权的删除证据;未授权删除文字会被忽略。``include_deleted`` 仅供标注预览
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启 返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启
``include_unanchored_rows``,在没有任何有效起行值时返回待复核的主行字段,不能用于正式解析。 ``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) 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) 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)) 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'] 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( def _reconstruct_adaptive_record_columns_profile_rows(
*, *,
glyphs: list[tuple[int, PositionedCharacter]], glyphs: list[tuple[int, PositionedCharacter]],
@@ -188,6 +188,13 @@ def _fit_layout_payload_to_budget(
coordinate_evidence = candidate.get('coordinate_evidence') coordinate_evidence = candidate.get('coordinate_evidence')
if isinstance(coordinate_evidence, dict): 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: if coordinate_evidence.pop('page_glyphs', None) is not None:
issues.append('shipping_document_layout_page_glyphs_compacted') issues.append('shipping_document_layout_page_glyphs_compacted')
if coordinate_evidence.pop('tables', None) is not None: 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')) sources = _coordinate_mapping(evidence.get('sources'))
source_pages = _coordinate_mapping(sources.get('pages')) source_pages = _coordinate_mapping(sources.get('pages'))
tables = _coordinate_mapping(evidence.get('tables')) 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()}): available_page_nos = {
return layout 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]]] = {} tables_by_page: dict[int, list[dict[str, Any]]] = {}
for raw_table in layout.get('tables') or []: for raw_table in layout.get('tables') or []:
if not isinstance(raw_table, dict): if not isinstance(raw_table, dict):
@@ -108,8 +124,12 @@ def ensure_on_demand_coordinate_evidence(
if table_id and chars: if table_id and chars:
tables[table_id] = chars tables[table_id] = chars
next_layout = dict(layout) next_layout = dict(layout)
next_layout['coordinate_evidence'] = { merged_evidence = {**evidence, 'pages': pages}
**evidence, 'pages': pages, 'page_glyphs': page_glyphs, if page_glyphs:
'tables': tables, 'sources': {**sources, 'pages': source_pages}, 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 return next_layout
@@ -49,6 +49,7 @@ class OrderFieldExtraction(BaseModel):
def extract_order_fields( def extract_order_fields(
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]], *, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False, coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False,
coordinate_transform: dict[str, Any] | None = None,
) -> list[OrderFieldExtraction]: ) -> list[OrderFieldExtraction]:
""" """
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。 用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
@@ -63,6 +64,12 @@ def extract_order_fields(
Returns: 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 [ return [
_extract_layout( _extract_layout(
layout=layout, layout=layout,
@@ -70,10 +77,49 @@ def extract_order_fields(
coordinate_evidence=coordinate_evidence, coordinate_evidence=coordinate_evidence,
allow_ocr_preview_fallback=allow_ocr_preview_fallback, 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( def _extract_layout(
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any], *, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
allow_ocr_preview_fallback: bool = False, allow_ocr_preview_fallback: bool = False,
@@ -427,6 +427,46 @@ class DocumentMatchProfile(OrderProfileModel):
return self 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): class OrderCoordinateProfile(OrderProfileModel):
"""唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。""" """唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。"""
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$') 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) table_regions: list[TableRegionProfile] = Field(min_length=1)
order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list) order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list)
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = 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') @model_validator(mode='after')
def validate_profile_rules(self) -> 'OrderCoordinateProfile': def validate_profile_rules(self) -> 'OrderCoordinateProfile':
@@ -9,6 +9,7 @@ services/shipping_notice/document_layout/order_profile_matcher.py
from __future__ import annotations from __future__ import annotations
from copy import deepcopy
import re import re
from typing import Any, Literal 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 ( from app.services.shipping_notice.document_layout.coordinate_region_text import (
positioned_token_spans, positioned_token_spans,
read_coordinate_region_text, read_coordinate_region_text,
visual_glyph_rows,
) )
from app.services.shipping_notice.document_layout.order_profile import ( from app.services.shipping_notice.document_layout.order_profile import (
AnchorRule,
CRITICAL_STRUCTURE_DIMENSION_KEYS, CRITICAL_STRUCTURE_DIMENSION_KEYS,
MatchDimensionResult, MatchDimensionResult,
MatchDimensionState, 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: def _anchor_comparable_text(value: Any) -> str:
"""规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。""" """规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。"""
return ''.join(str(value or '').casefold().split()) return ''.join(str(value or '').casefold().split())
@@ -66,6 +72,7 @@ class ProfileMatchCandidate(BaseModel):
dimension_scores: ProfileMatchDimensionScores | None = None dimension_scores: ProfileMatchDimensionScores | None = None
dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict) dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict)
margin_to_next: float | None = Field(default=None, ge=0, le=1) margin_to_next: float | None = Field(default=None, ge=0, le=1)
coordinate_transform: dict[str, Any] | None = None
class ProfileMatchResult(BaseModel): class ProfileMatchResult(BaseModel):
@@ -136,15 +143,23 @@ def match_frozen_coordinate_profiles(
document_match=definition.get('document_match'), document_match=definition.get('document_match'),
table_regions=definition.get('table_regions'), table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [], order_field_layouts=definition.get('order_field_layouts') or [],
coordinate_model=definition.get('coordinate_model') or {},
) )
except (TypeError, ValueError): except (TypeError, ValueError):
continue continue
reason_codes: list[str] = [] reason_codes: list[str] = []
signature_body, signature_meta = _extract_matching_signature(raw) 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( observed = _observe_layout_features(
layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables, 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: if signature_body is None:
reason_codes.append('profile_signature_missing') reason_codes.append('profile_signature_missing')
@@ -190,7 +205,7 @@ def match_frozen_coordinate_profiles(
dimension_results, hard_conflict_codes = _compute_dimension_results( dimension_results, hard_conflict_codes = _compute_dimension_results(
profile=profile, profile=profile,
signature=signature_body, signature=observed_signature,
observed=observed, observed=observed,
tables=tables, tables=tables,
pages=pages, pages=pages,
@@ -200,6 +215,11 @@ def match_frozen_coordinate_profiles(
customer_hint_id=customer_hint_id, customer_hint_id=customer_hint_id,
) )
reason_codes.extend(hard_conflict_codes) 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 weights = profile.document_match.scoring_weights
score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results) 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), matched_anchor_count=sum(required_hits) + sum(optional_hits),
dimension_scores=dimension_scores, dimension_scores=dimension_scores,
dimension_states=dimension_states, dimension_states=dimension_states,
coordinate_transform=coordinate_transform,
))) )))
rendered = sorted( rendered = sorted(
@@ -251,6 +272,11 @@ def match_frozen_coordinate_profiles(
candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6) candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6)
if not hard_valid: 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: if not rendered:
return ProfileMatchResult( return ProfileMatchResult(
status='no_match', candidates=rendered, 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( def _selected_result(
*, *,
raw: dict[str, Any], 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 {} 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( def _aggregate_dimension_score(
*, *,
weights: Any, weights: Any,
@@ -664,6 +1028,17 @@ def _observe_layout_features(
signature: dict[str, Any] | None, signature: dict[str, Any] | None,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""从冻结 layout 聚合非敏感结构特征供维度比对。""" """从冻结 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) first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
aspect_ratio = 0.0 aspect_ratio = 0.0
if isinstance(first_page, dict): 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( def _select_signature_primary_table_bbox(
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None, *, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
) -> list[float] | None: ) -> list[float] | None:
@@ -881,11 +1303,13 @@ def _observe_static_text_centers(
result: dict[str, list[float]] = {} result: dict[str, list[float]] = {}
for row in rows: for row in rows:
ordered = sorted(row, key=lambda item: item['bbox'].get('x0', 0)) 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)) text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered))[:80]
if not text: if not text or len(text) >= 80:
continue continue
xs = [(float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 / width for item in ordered] 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] 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)] result[text] = [round(sum(xs) / len(xs), 4), round(sum(ys) / len(ys), 4)]
return result return result
@@ -531,7 +531,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'字段已按 PDF 优先裁决,请核对辅助证据差异', '字段已按 PDF 优先裁决,请核对辅助证据差异',
), ),
'evidence_missing': _meta('owner', 'open_order_review', '关键识别结果缺少有效证据'), '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_ambiguous': _meta('owner', 'confirm_customer', '匹配到多个客户'),
'customer_out_of_scope': _meta('owner', 'confirm_customer', '客户不在当前业务范围内'), 'customer_out_of_scope': _meta('owner', 'confirm_customer', '客户不在当前业务范围内'),
'reservation_missing': _meta('owner', 'edit_reservation', '缺少有效 Reservation'), 'reservation_missing': _meta('owner', 'edit_reservation', '缺少有效 Reservation'),
@@ -1,7 +1,7 @@
""" """
services/shipping_notice/lifecycle_projection.py services/shipping_notice/lifecycle_projection.py
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份四阶段业务生命周期。 用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。 依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。 逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。 本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
@@ -18,6 +18,7 @@ LIFECYCLE_STAGES: tuple[dict[str, str], ...] = (
{'code': 'intake_parse', 'label': '接收解析'}, {'code': 'intake_parse', 'label': '接收解析'},
{'code': 'order_review', 'label': '订单复核'}, {'code': 'order_review', 'label': '订单复核'},
{'code': 'fulfillment_prep', 'label': '通知准备'}, {'code': 'fulfillment_prep', 'label': '通知准备'},
{'code': 'freight_upload', 'label': '货代上传'},
{'code': 'upload_complete', 'label': '通知完成'}, {'code': 'upload_complete', 'label': '通知完成'},
) )
@@ -43,8 +44,8 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
'inventory_sufficiency': 'fulfillment_prep', 'inventory_sufficiency': 'fulfillment_prep',
'excel_readiness': 'fulfillment_prep', 'excel_readiness': 'fulfillment_prep',
'artifact_generation': 'fulfillment_prep', 'artifact_generation': 'fulfillment_prep',
'freight_upload_rpa': 'upload_complete', 'freight_upload_rpa': 'freight_upload',
'manual_upload_handoff': 'upload_complete', 'manual_upload_handoff': 'freight_upload',
} }
# 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。 # 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。
@@ -60,7 +61,9 @@ LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = (
'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating', 'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating',
'excel_generate', 'excel_generated', '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, legacy_stage: str | None,
has_candidate_context: bool, has_candidate_context: bool,
has_intake_parse_context: bool = False, has_intake_parse_context: bool = False,
verified_upload_success: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。 """按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。
@@ -111,7 +115,12 @@ def project_lifecycle(
""" """
gate = current_gate if isinstance(current_gate, dict) else {} gate = current_gate if isinstance(current_gate, dict) else {}
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower() 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] lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
authority = 'process_gate' authority = 'process_gate'
else: else:
@@ -13,6 +13,24 @@ backend/app/services/shipping_notice/order_extraction.py
from __future__ import annotations 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 hashlib
import json import json
from datetime import datetime from datetime import datetime
@@ -1271,8 +1289,7 @@ def submit_order_extraction_unit_result(
'idempotent_replay': True, 'idempotent_replay': True,
'unit_id': int(unit.id), 'unit_id': int(unit.id),
} }
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit reconcile_review_case_after_unit(run=run, unit=unit)
ensure_review_case_for_unit(run=run, unit=unit)
return result return result
session = _runtime_session_for_run(run) 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], *, 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, contract: Any, schema_fields: dict[str, dict[str, Any]], document_id: int | None = None,
initial_carry: dict[str, Any] | None = None, initial_carry: dict[str, Any] | None = None,
coordinate_transform: dict[str, Any] | None = None,
) -> list[dict[str, Any]] | None: ) -> list[dict[str, Any]] | None:
""" """
用模板表区和整页字符生成带字段坐标的紧凑行候选。 用模板表区和整页字符生成带字段坐标的紧凑行候选。
@@ -324,6 +325,7 @@ def _coordinate_profile_rows(
schema_fields: field_id/code 对应的冻结 Schema 字段。 schema_fields: field_id/code 对应的冻结 Schema 字段。
document_id: 当前 Unit 文档 ID;提供时生成稳定 token/evidence 引用。 document_id: 当前 Unit 文档 ID;提供时生成稳定 token/evidence 引用。
initial_carry: 跨页固定子行的已解析字段。 initial_carry: 跨页固定子行的已解析字段。
coordinate_transform: 共同 matcher 对当前唯一 Profile 已确认的平移;不在本函数重算。
Returns: Returns:
规范化字段行;坐标前置条件缺失时返回 None。 规范化字段行;坐标前置条件缺失时返回 None。
@@ -364,11 +366,16 @@ def _coordinate_profile_rows(
relative_region = _coordinate_region_mapping(region.region) relative_region = _coordinate_region_mapping(region.region)
if relative_region is None: if relative_region is None:
return 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 = { region_bbox = {
'x0': relative_region['x0'] * page_bbox['x1'], 'x0': evidence_relative_region['x0'] * page_bbox['x1'],
'y0': relative_region['y0'] * page_bbox['y1'], 'y0': evidence_relative_region['y0'] * page_bbox['y1'],
'x1': relative_region['x1'] * page_bbox['x1'], 'x1': evidence_relative_region['x1'] * page_bbox['x1'],
'y1': relative_region['y1'] * page_bbox['y1'], 'y1': evidence_relative_region['y1'] * page_bbox['y1'],
} }
raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None 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): 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), initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0),
line_start_field_code=region.line_start_field_code, line_start_field_code=region.line_start_field_code,
row_reconstruction_mode=region.row_reconstruction_mode, row_reconstruction_mode=region.row_reconstruction_mode,
coordinate_transform=coordinate_transform,
): ):
values: list[dict[str, Any]] = [] values: list[dict[str, Any]] = []
issues = list(reconstructed.issues) issues = list(reconstructed.issues)
@@ -442,6 +450,60 @@ def _coordinate_profile_rows(
return 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: 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. # MinerU HTML is intentionally neither required nor parsed on this path.
try: try:
profile = _frozen_coordinate_profile(raw_profile) profile = _frozen_coordinate_profile(raw_profile)
coordinate_transform = _selected_coordinate_transform(
profile_match=profile_match, raw_profile=raw_profile,
)
carry = None carry = None
parent_table_id = str(raw_table.get('continuation_of') or '') parent_table_id = str(raw_table.get('continuation_of') or '')
if parent_table_id: if parent_table_id:
@@ -749,6 +814,7 @@ def _profile_table_candidates(
raw_profile=raw_profile, raw_table=raw_table, layout=layout, raw_profile=raw_profile, raw_table=raw_table, layout=layout,
contract=contract, schema_fields=schema_fields, contract=contract, schema_fields=schema_fields,
document_id=int(unit.document_id), initial_carry=carry, document_id=int(unit.document_id), initial_carry=carry,
coordinate_transform=coordinate_transform,
) )
except (TypeError, ValueError): except (TypeError, ValueError):
issues.append('order_profile_snapshot_invalid') 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( candidates = extract_order_fields(
profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields, profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields,
coordinate_evidence=layout.get('coordinate_evidence') or {}, 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'] 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, site_id=None,
actor_id=None, actor_id=None,
reason=confirm_reason, reason=confirm_reason,
# 保存校验入口需将客户确认、Draft 校验与后续 Gate/STP 写入作为同一事务提交。
commit=False,
) )
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
_LOGGER.warning( _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( def reconcile_single_case_for_auto_progress(
*, *,
case_no: Any = None, 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。 workflow_ledger_service、order_task_service.resolve_order_task_for_candidate。
逻辑:处置只改变当前 PDF 的 Case 生命周期;锁定时分别 FOR UPDATE Case 与 Draft, 逻辑:处置只改变当前 PDF 的 Case 生命周期;锁定时分别 FOR UPDATE Case 与 Draft,
禁止 joinedload+FOR UPDATE。单文件重识别通过新的 Run 保留原始 PDF 与机器结果, 禁止 joinedload+FOR UPDATE。单文件重识别通过新的 Run 保留原始 PDF 与机器结果,
成功后才由 Run 终态钩子替代旧 Case;创建后继 Run 时显式传入 Case 对应 OT(非 Run 根号)。 成功后才由 Run 终态钩子替代旧 Case,并在 Stream 原子切换成功后补触发新版 Case 的统一自动推进;
创建后继 Run 时显式传入 Case 对应 OT(非 Run 根号)。
每次关键处置同时写 CaseEvent + 统一 ShippingAuditEvent; 每次关键处置同时写 CaseEvent + 统一 ShippingAuditEvent;
质量异常原因码 `other` 时备注必填。被拒绝操作(无效原因、终态冲突、替代状态不满足、 质量异常原因码 `other` 时备注必填。被拒绝操作(无效原因、终态冲突、替代状态不满足、
WorkflowItem 已关闭等)在抛错前独立 commit 拒绝审计,避免 API 回滚吞掉留痕。由 workspace shipping_notice API 调用。 WorkflowItem 已关闭等)在抛错前独立 commit 拒绝审计,避免 API 回滚吞掉留痕。由 workspace shipping_notice API 调用。
@@ -1015,7 +1016,17 @@ def reparse_case_document(
def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: bool) -> None: 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') marker = (run.input_snapshot_json or {}).get('review_reparse')
if not isinstance(marker, dict) or not run.reparse_of_run_id: if not isinstance(marker, dict) or not run.reparse_of_run_id:
return return
@@ -1042,10 +1053,21 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
# Run 已到终态但没有可复核新版本时,不可废弃旧草稿。 # Run 已到终态但没有可复核新版本时,不可废弃旧草稿。
return return
from app.services.shipping_notice.review_stream_service import activate_review_case from app.services.shipping_notice.review_stream_service import activate_review_case
activate_review_case( stream = activate_review_case(
case=replacement_case, case=replacement_case,
trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded', 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={ _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={
'successor_run_no': run.run_no, 'successor_run_no': run.run_no,
'replacement_case_no': replacement_case.case_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': [ 'missing_required_anchor_ids': [
str(c) for c in (item.get('missing_required_anchor_ids') or []) if c str(c) for c in (item.get('missing_required_anchor_ids') or []) if c
][:12], ][:12],
'coordinate_transform': _sanitize_coordinate_transform(item.get('coordinate_transform')),
}) })
if len(out) >= 5: if len(out) >= 5:
break break
return out 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]: def project_review_case_profile_match(case: ShippingOrderReviewCase) -> dict[str, Any]:
""" """
投影建单前文档模板匹配摘要。 投影建单前文档模板匹配摘要。
@@ -47,6 +47,7 @@ from app.models import (
ShippingOrderProcessingRun, ShippingOrderProcessingRun,
ShippingOrderReviewCase, ShippingOrderReviewCase,
ShippingOrderReviewStream, ShippingOrderReviewStream,
ShippingOrderIntake,
) )
@@ -535,6 +536,40 @@ def _document_filename(run: ShippingOrderProcessingRun, document_id: int) -> str
return None 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]: def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
"""由后端 Case 状态与 WorkflowItem 生命周期决定可用动作,前端不可自行推导确认资格。""" """由后端 Case 状态与 WorkflowItem 生命周期决定可用动作,前端不可自行推导确认资格。"""
from app.services.shipping_notice.tool_common import llm_review_enabled from app.services.shipping_notice.tool_common import llm_review_enabled
@@ -651,6 +686,7 @@ def serialize_review_case(
run = case.run run = case.run
draft = case.current_draft draft = case.current_draft
candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None 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) schema_fields = _schema_fields(run)
header_fields = [item for item in schema_fields if item.get('scope') == 'header'] 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'] 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 []), 'issues': list(draft.issue_summary_json or []),
'validation': dict(draft.validation_result_json or {}), 'validation': dict(draft.validation_result_json or {}),
'build_eligibility': { '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')), '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'), 'status': str((draft.validation_result_json or {}).get('status') or 'needs_review'),
'gates': dict((draft.validation_result_json or {}).get('gates') or {}), '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。 # 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'] 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 仍然优先固定视图动作。 # 兼容兜底:task_missing 仍然优先固定视图动作。
if formal_ot.get('task_missing'): if formal_ot.get('task_missing'):
available_actions = ['view', 'contact_admin'] available_actions = ['view', 'contact_admin']
@@ -976,6 +1028,7 @@ def serialize_review_case(
'draft': projected_draft, 'draft': projected_draft,
'llm_suggestions': llm_suggestions, 'llm_suggestions': llm_suggestions,
'available_actions': available_actions, 'available_actions': available_actions,
'intake_no': intake_no,
'formal_editable_field_ids': ( 'formal_editable_field_ids': (
list_editable_formal_field_ids( list_editable_formal_field_ids(
schema_fields, schema_fields,
@@ -1002,6 +1055,8 @@ def _serialize_review_case_summary(
) -> dict[str, Any]: ) -> dict[str, Any]:
"""为工作台文件队列投影单 Case 的只读识别与生命周期摘要。""" """为工作台文件队列投影单 Case 的只读识别与生命周期摘要。"""
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None 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 只是解析异常/人工处置容器,不能显示为已进入订单复核。 # 空 Review Case 只是解析异常/人工处置容器,不能显示为已进入订单复核。
# 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。 # 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。
lifecycle_stage = 'intake_parse' lifecycle_stage = 'intake_parse'
@@ -1044,7 +1099,21 @@ def _serialize_review_case_summary(
'status': case.status, 'status': case.status,
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None, '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, '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 或阶段。 # 后端按 Case/正式任务裁决,禁止工作台仅为当前项从草稿拼接 PO 或阶段。
'po_number': str(candidate.po_number or '').strip() or None if candidate is not None else None, 'po_number': str(candidate.po_number or '').strip() or None if candidate is not None else None,
'lifecycle_stage': lifecycle_stage, 'lifecycle_stage': lifecycle_stage,
@@ -129,6 +129,7 @@ def resume_after_review_change(
change_type: str | None = None, change_type: str | None = None,
skip_validate: bool = False, skip_validate: bool = False,
allow_auto_create: bool = True, allow_auto_create: bool = True,
expected_draft_version: int | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
建单前统一恢复:重校验 → Gate 同步 → 资格重算 → 可选 auto_gate 建单。 建单前统一恢复:重校验 → Gate 同步 → 资格重算 → 可选 auto_gate 建单。
@@ -141,6 +142,7 @@ def resume_after_review_change(
change_type: 可选失效规则键(process_gate_dependency)。 change_type: 可选失效规则键(process_gate_dependency)。
skip_validate: True 时跳过 validate_draft(调用方刚校验过)。 skip_validate: True 时跳过 validate_draft(调用方刚校验过)。
allow_auto_create: False 时只重算资格,不自动建单(例如仅预览)。 allow_auto_create: False 时只重算资格,不自动建单(例如仅预览)。
expected_draft_version: 可选乐观锁版本;显式保存校验时必须传入。
Returns: Returns:
resume_outcome 字典(含 gate_recalculated / auto_gate_allowed / task_created 等)。 resume_outcome 字典(含 gate_recalculated / auto_gate_allowed / task_created 等)。
@@ -177,12 +179,27 @@ def resume_after_review_change(
'case': serialize_review_case(case), '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)。 # [STEP 2] 显式全量校验(同步建单前 Gate)。
if not skip_validate: if not skip_validate:
validate_draft( validate_draft(
user_id=int(user_id), user_id=int(user_id),
case_no=str(case.case_no), 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() db.session.flush()
case = _reload_case(user_id=user_id, case_no=case_no) 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'], 'auto_gate_allowed': snap['auto_gate_allowed'],
'qualification_status': snap['qualification_status'], 'qualification_status': snap['qualification_status'],
'failed_gates': snap['failed_gates'], 'failed_gates': snap['failed_gates'],
'customer_auto_confirmation': customer_auto_confirmation,
}, },
source='order_review_resume', source='order_review_resume',
strict=True, strict=True,
@@ -238,6 +256,7 @@ def resume_after_review_change(
), ),
'case': serialize_review_case(case), 'case': serialize_review_case(case),
'invalidated_gates': invalidated, 'invalidated_gates': invalidated,
'customer_auto_confirmation': customer_auto_confirmation,
} }
# [STEP 5] 可建单但不允许 auto_gate:等待人工确认建单。 # [STEP 5] 可建单但不允许 auto_gate:等待人工确认建单。
@@ -276,6 +295,7 @@ def resume_after_review_change(
), ),
'case': serialize_review_case(case), 'case': serialize_review_case(case),
'invalidated_gates': invalidated, 'invalidated_gates': invalidated,
'customer_auto_confirmation': customer_auto_confirmation,
} }
# [STEP 6] auto_gate:入队 STP 幂等 Job(queued);Worker 再执行 confirm。 # [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 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() upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
progress_state = ( 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 'export_ready' if getattr(task, 'export_file_path', None)
else 'matched' if getattr(task, 'match_status', None) else 'matched' if getattr(task, 'match_status', None)
else 'inventory_ready' if getattr(task, 'inventory_lines_json', 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, 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 = ( 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 'export_ready' if getattr(task, 'export_file_path', None)
else 'matched' if getattr(task, 'match_status', None) else 'matched' if getattr(task, 'match_status', None)
else 'inventory_ready' if getattr(task, 'inventory_lines_json', None) else 'inventory_ready' if getattr(task, 'inventory_lines_json', None)
@@ -656,10 +664,12 @@ def project_stage_for_task(
'stage_node': None, 'stage_node': None,
} }
# 上传登记/回调会先更新 ShippingNotice 聚合事实;旧 OT.stage 可能仍停在 # 成功回调会先更新 Notice 聚合事实;旧 OT.stage 可能仍停在
# freight_uploading,不能用过期阶段覆盖已经完成的履约状态。 # freight_uploading,只有三层成功事实齐备时才能覆盖为 completed。
if progress_state in {'uploaded', 'closed', 'completed'}: if progress_state == 'uploaded':
return _with_label('completed', source='notice_terminal') 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 同源)。 # [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。
order_task = None order_task = None
@@ -678,6 +688,8 @@ def project_stage_for_task(
order_task = None order_task = None
ot_stage = str(getattr(order_task, 'stage', None) or '').strip().lower() if order_task else '' 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 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:业务上已进入获取库存。 # [STEP 1b] 正式 OT 已创建但 stage 仍停在 order_creating:业务上已进入获取库存。
# Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。 # Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。
if ot_stage == 'order_creating': if ot_stage == 'order_creating':
@@ -316,7 +316,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'gate_code': 'freight_upload_rpa', 'gate_code': 'freight_upload_rpa',
'sequence_no': 19, 'sequence_no': 19,
'label': '货代上传 RPA', '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', 'responsible_party': 'worker',
'implementation_status': 'implemented', 'implementation_status': 'implemented',
'recoverable': True, 'recoverable': True,
@@ -330,7 +330,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = (
'gate_code': 'manual_upload_handoff', 'gate_code': 'manual_upload_handoff',
'sequence_no': 20, 'sequence_no': 20,
'label': '人工上传交接', 'label': '人工上传交接',
'ui_placement': {'target_surface': 'upload_complete', 'target_anchor': 'manual_upload'}, 'ui_placement': {'target_surface': 'freight_upload', 'target_anchor': 'manual_upload'},
'responsible_party': 'owner', 'responsible_party': 'owner',
'implementation_status': 'implemented', 'implementation_status': 'implemented',
'recoverable': True, 'recoverable': True,
@@ -706,7 +706,7 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
'upload_rpa_failed': 'freight_upload_rpa', 'upload_rpa_failed': 'freight_upload_rpa',
'upload_rpa_login_failed': 'freight_upload_rpa', 'upload_rpa_login_failed': 'freight_upload_rpa',
'upload_platform_rejected': '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(禁止平行用户投影)。 # Candidate Qualification / 旧自动建单门禁键 → 唯一 owning_gate(禁止平行用户投影)。
@@ -167,7 +167,8 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]:
【触发时机】写状态机回写 OT、投影组装 order_task 工作项。 【触发时机】写状态机回写 OT、投影组装 order_task 工作项。
核心逻辑:上传完成 → completed;上传中/待上传 → freight_uploading; 核心逻辑:仅可审计的上传成功 → completed;上传中、待登记及历史无证据上传
→ freight_uploading;
导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching; 导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching;
matching/inventory_ready/matched → inventory_matching;建单中 → order_creating。 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() review = str(getattr(notice, 'review_status', None) or '').strip().lower()
match = str(getattr(notice, 'match_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() 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' 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'}: 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' ps = 'waiting_upload' if upload_st != 'failed' else 'upload_failed'
elif export_path: elif export_path:
@@ -444,6 +453,7 @@ def reconcile_processing_projection_facts(
legacy_actions: list[str] | None = None, legacy_actions: list[str] | None = None,
invalidated_from_stage: str | None = None, invalidated_from_stage: str | None = None,
excel_ready: bool = False, excel_ready: bool = False,
verified_upload_success: bool | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
在投影输出前强制 status/stage/gate/action 不变量,并写入 stage_nodes。 在投影输出前强制 status/stage/gate/action 不变量,并写入 stage_nodes。
@@ -518,6 +528,17 @@ def reconcile_processing_projection_facts(
status = 'automating' status = 'automating'
stage_idx = shipping_processing_stage_index(stage) 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。 # [BE-03] Extraction Run 完成误标为全流程 completed:早期 stage 时回退 status。
if status == 'completed' and stage and stage != 'completed': if status == 'completed' and stage and stage != 'completed':
if stage_idx is not None and stage_idx <= waiting_idx: 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 优先级) ===== # ===== [STEP 4] 按冻结映射规则计算 user_status(F3 优先级) =====
notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else '' 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: def _compute_user_status() -> str:
# [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision # [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision
@@ -742,6 +777,8 @@ def apply_user_projection_fields(
return 'retryable' return 'retryable'
if gate_status == 'blocked_manual': if gate_status == 'blocked_manual':
return 'waiting_human' return 'waiting_human'
if unverified_upload_terminal:
return 'waiting_human'
# 1) 终态短路:old_status completed/cancelled/failed # 1) 终态短路:old_status completed/cancelled/failed
if old_status == 'completed': if old_status == 'completed':
return 'completed' return 'completed'
@@ -752,7 +789,7 @@ def apply_user_projection_fields(
# Retry Decision 可得时:优先用决策器 # Retry Decision 可得时:优先用决策器
if retry_decision is not None: if retry_decision is not None:
# 4) rd_status=completed 或 action=noop 且 notice 完成态 → completed # 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' return 'completed'
if rd_action == _RD_NOOP and _rd_has_completed_process: if rd_action == _RD_NOOP and _rd_has_completed_process:
return 'completed' return 'completed'
@@ -781,6 +818,12 @@ def apply_user_projection_fields(
user_status = _compute_user_status() 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 = _USER_STAGE_TO_CODE.get(old_stage) user_stage = _USER_STAGE_TO_CODE.get(old_stage)
if user_stage is None: if user_stage is None:
@@ -49,7 +49,7 @@ from app.services.shipping_notice.processing_ownership import (
record_projection_inconsistency_audit, record_projection_inconsistency_audit,
) )
from app.services.shipping_notice.lifecycle_projection import ( from app.services.shipping_notice.lifecycle_projection import (
LIFECYCLE_STAGE_RANGES, LIFECYCLE_STAGE_CODES,
project_lifecycle, project_lifecycle,
) )
from app.services.shipping_notice.query_service import resolve_task_export_download 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 ''), str(run.status or ''),
stage=stage, stage=stage,
) )
# 人工上传登记/RPA 回调先更新 ShippingNotice 聚合事实;旧 OT.status 可能仍为 # 完成只接受三层可审计成功事实。旧 OT/process_status/upload_status 可能遗留
# automating。终态 Notice 必须覆盖旧 OT 状态,保证统一投影、右侧状态和进度节点同源。 # 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_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_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 '' notice_lifecycle = str(getattr(notice_for_stage, 'lifecycle_status', None) or '').strip().lower() if notice_for_stage is not None else ''
if ( if verified_upload_success:
notice_process_status in {'uploaded', 'closed', 'completed'}
or notice_upload_status in {'uploaded', 'succeeded', 'success'}
or notice_lifecycle in {'voided', 'archived', 'deleted'}
):
status = 'completed' status = 'completed'
stage = 'completed' stage = 'completed'
stage_label_key = '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 组合在输出前再折叠。 # [BE-03] OT 上残留的 completed + 早期 stage 组合在输出前再折叠。
if status == 'completed' and stage != 'completed': if status == 'completed' and stage != 'completed':
status = derivation_status_for_extraction_run('completed', stage=stage) 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), 'intake_no': _first_intake_no_for_run(run),
'status': status, 'status': status,
'stage': stage, 'stage': stage,
'verified_upload_success': verified_upload_success if notice_for_stage is not None else None,
# 与 Case.current_stage.label_key 同源;前端禁止用 stage 码直接当用户文案。 # 与 Case.current_stage.label_key 同源;前端禁止用 stage 码直接当用户文案。
'stage_label_key': stage_label_key or ( 'stage_label_key': stage_label_key or (
'waiting_system_start' if stage == 'order_creating' else stage 'waiting_system_start' if stage == 'order_creating' else stage
@@ -1413,6 +1429,7 @@ def _project_order_task_work_item(
legacy_actions=legacy_actions, legacy_actions=legacy_actions,
invalidated_from_stage=invalidated_from_stage, invalidated_from_stage=invalidated_from_stage,
excel_ready=excel_ready, excel_ready=excel_ready,
verified_upload_success=verified_upload_success if notice_for_stage is not None else None,
) )
# [STEP] 投影不一致:写审计后剥离内部诊断字段,避免泄漏给前端契约。 # [STEP] 投影不一致:写审计后剥离内部诊断字段,避免泄漏给前端契约。
record_projection_inconsistency_audit(payload) 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。 item: order_task 工作项 dict。
Returns: 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() user_group = str(item.get('user_group') or '').strip().lower()
if user_group in {'failed', 'waiting_human'}: if user_group in {'failed', 'waiting_human'}:
return 'needs_action' 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() stage = str(item.get('stage') or '').strip().lower()
if user_status in {'waiting_human', 'retryable', 'failed'}: if user_status in {'waiting_human', 'retryable', 'failed'}:
return 'needs_action' 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' return 'completed'
if user_status == 'running': if user_status == 'running':
return 'processing' return 'processing'
if status in {'failed', 'blocked'} or stage == 'waiting_review' or status == 'waiting_review': if status in {'failed', 'blocked'} or stage == 'waiting_review' or status == 'waiting_review':
return 'needs_action' 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': if status == 'completed' or stage == 'completed':
return 'completed' return 'completed'
return 'processing' 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() user_status = str(item.get('user_status') or '').strip().lower()
status = str(item.get('status') or '').strip().lower() status = str(item.get('status') or '').strip().lower()
stage = str(item.get('stage') 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': if user_status == 'waiting_human':
return 'pending_review' return 'pending_review'
if user_status == 'retryable': if user_status == 'retryable':
@@ -2334,16 +2365,10 @@ def _conversation_task_row_from_work_item(
'document_id': source_document_id, 'document_id': source_document_id,
'filename': filename, 'filename': filename,
}) })
user_group = str(item.get('user_group') or '').strip().lower() # status_groups 与文件统计必须消费同一用户态裁决。尤其是旧载荷的
if not user_group: # completed + verified_upload_success=False,顶层已降级为待处理,不能在
user_status = str(item.get('user_status') or item.get('status') or '').strip().lower() # status_groups 又显示为 completed。
user_group = ( user_group = _batch_user_group(item)
'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'
)
return { return {
'user_task_no': user_task_no, 'user_task_no': user_task_no,
'submission_ordinal': None, 'submission_ordinal': None,
@@ -2415,6 +2440,7 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
), ),
# 空 Candidate 的接收解析只认后端持久化 Case 显式授予的上下文。 # 空 Candidate 的接收解析只认后端持久化 Case 显式授予的上下文。
has_intake_parse_context=bool(item.get('intake_parse_authorized')), has_intake_parse_context=bool(item.get('intake_parse_authorized')),
verified_upload_success=bool(item.get('verified_upload_success')),
) )
lifecycle_stage = lifecycle['lifecycle_stage'] lifecycle_stage = lifecycle['lifecycle_stage']
if primary is not None: 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', 'download_excel', 'open_manual_upload', 'wait_manual_upload', 'mark_manual_uploaded',
'retry_freight_upload_rpa', 'retry_upload', 'retry_freight_upload_rpa', 'retry_upload',
}: }:
return 'upload_complete' return 'freight_upload'
# 历史 Review 投影的 view 与 view_result 同为只读查看入口;必须由后端附带 # 历史 Review 投影的 view 与 view_result 同为只读查看入口;必须由后端附带
# 当前已裁决的工作台目标,前端不得因缺失目标误判为“前置阶段未完成”。 # 当前已裁决的工作台目标,前端不得因缺失目标误判为“前置阶段未完成”。
return lifecycle_stage if code in {'view', 'view_result', 'view_record'} else None 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 ''), 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_candidate_context=bool(item.get('has_formal_ot') or item.get('shipping_notice_no')),
has_intake_parse_context=bool(item.get('intake_parse_authorized')), has_intake_parse_context=bool(item.get('intake_parse_authorized')),
verified_upload_success=bool(item.get('verified_upload_success')),
)['lifecycle_stage'] )['lifecycle_stage']
@@ -2516,7 +2543,7 @@ def _current_file_representatives(work_items: list[dict[str, Any]]) -> list[dict
"""为批次投影选择每个业务文件唯一的当前代表项。 """为批次投影选择每个业务文件唯一的当前代表项。
核心逻辑:EML 聚合根不参与文件口径;同一文件的旧 Run、旧 OT 或历史失败 核心逻辑:EML 聚合根不参与文件口径;同一文件的旧 Run、旧 OT 或历史失败
投影只保留最新活动项。四阶段、文件统计、未分类统计必须共用本函数,避免一个 投影只保留最新活动项。五阶段、文件统计、未分类统计必须共用本函数,避免一个
PDF 同时被计入多个阶段或多个状态组。 PDF 同时被计入多个阶段或多个状态组。
Args: Args:
@@ -2705,11 +2732,11 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) ->
return displayed 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 个技术节点仍附着在单项诊断字段, 业务阶段映射和状态优先级只在后端维护;15 个技术节点仍附着在单项诊断字段,
绝不要求前端通过 stage 索引再计算四阶段。 绝不要求前端通过 stage 索引再计算业务阶段。
""" """
ranked_items = sorted( ranked_items = sorted(
_current_file_representatives(work_items), _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, 'failed': 0,
'blocking_reason': None, 'blocking_reason': None,
} }
for code, _ in LIFECYCLE_STAGE_RANGES for code in LIFECYCLE_STAGE_CODES
} }
for item in ranked_items: for item in ranked_items:
lifecycle_stage = _lifecycle_stage_from_item(item) lifecycle_stage = _lifecycle_stage_from_item(item)
if lifecycle_stage is None: if lifecycle_stage is None:
continue continue
# 历史取消/归档只能保留在 history/status_groups,既不推动任一工作面,
# 也不得作为「通知完成」的分子或分母。
item_group = _batch_user_group(item)
if item_group in {'cancelled', 'archived'}:
continue
summary = stage_summaries[lifecycle_stage] summary = stage_summaries[lifecycle_stage]
summary['total'] += 1 summary['total'] += 1
# 四阶段与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run # 生命周期与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run
# 兼容投影中残留为 running,不能把后端已裁决为“待处理”的文件再显示为处理中。 # 兼容投影中残留为 running,不能把后端已裁决为“待处理”的文件再显示为处理中。
item_group = _batch_user_group(item)
if item_group == 'completed': if item_group == 'completed':
summary['completed'] += 1 summary['completed'] += 1
continue continue
@@ -2763,7 +2794,7 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str,
} or None } or None
nodes: list[dict[str, Any]] = [] nodes: list[dict[str, Any]] = []
for code, _ in LIFECYCLE_STAGE_RANGES: for code in LIFECYCLE_STAGE_CODES:
summary = stage_summaries[code] summary = stage_summaries[code]
# 卡片状态只由本阶段聚合事实计算,禁止由其他阶段的优先文件反向影响。 # 卡片状态只由本阶段聚合事实计算,禁止由其他阶段的优先文件反向影响。
status = ( status = (
@@ -2781,8 +2812,13 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str,
return nodes 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]: def _unclassified_summary(work_items: list[dict[str, Any]]) -> dict[str, int]:
"""统计无法归入四阶段的业务文件,避免批次摘要与文件清单口径不一致。""" """统计无法归入业务生命周期的文件,避免批次摘要与文件清单口径不一致。"""
return { return {
'count': sum( 'count': sum(
1 for item in _current_file_representatives(work_items) 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 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造
人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。 人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。
""" """
# 批次主状态与文件计数、四阶段必须消费同一份“每文件唯一当前代表项”。 # 批次主状态与文件计数、五阶段必须消费同一份“每文件唯一当前代表项”。
# 否则历史 Run 的失败/待办虽然不再计数,仍可能抢走批次 CTA,形成 # 否则历史 Run 的失败/待办虽然不再计数,仍可能抢走批次 CTA,形成
# “数字是当前、按钮却指向历史”的第二裁决源。 # “数字是当前、按钮却指向历史”的第二裁决源。
ranked = sorted( 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: def _batch_user_group(item: dict[str, Any]) -> str:
"""归一批次统计使用的互斥用户分组,优先消费领域投影已裁决的 user_group。""" """归一批次统计使用的互斥用户分组,优先消费领域投影已裁决的 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() 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 return group
status = str(item.get('user_status') or item.get('status') or '').strip().lower() status = str(item.get('user_status') or item.get('status') or '').strip().lower()
if status in {'failed', 'retryable'}: if status in {'failed', 'retryable'}:
return 'failed' return 'failed'
if status in {'waiting_human', 'waiting_review', 'idle'}: if status in {'waiting_human', 'waiting_review', 'idle'}:
return 'waiting_human' return 'waiting_human'
if status in {'completed', 'cancelled'}: if status == 'completed':
return 'completed' return 'completed'
if status in {'cancelled', 'archived', 'voided', 'deleted'}:
return 'cancelled'
return 'processing' return 'processing'
def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]: def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]:
"""按唯一当前业务文件统计互斥状态组,EML 容器永不计数。""" """按唯一当前业务文件统计互斥状态组,EML 容器永不计数。"""
# 已取消/归档文件保留在历史列表,但不构成当前任务完成率的分母或分子。
groups = {'failed': 0, 'waiting_human': 0, 'processing': 0, 'completed': 0} groups = {'failed': 0, 'waiting_human': 0, 'processing': 0, 'completed': 0}
for item in _current_file_representatives(work_items): for item in _current_file_representatives(work_items):
group = _batch_user_group(item) group = _batch_user_group(item)
summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {} summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
filename = str(summary.get('filename') or '').strip().lower() 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)): if not filename.endswith('.eml') and (filename or int(summary.get('document_id') or 0)):
groups[group] += 1 groups[group] += 1
return { return {
@@ -2914,12 +2961,13 @@ def _conversation_processing_from_work_items(
Returns: Returns:
与 project_conversation_processing 同形的 dict。 与 project_conversation_processing 同形的 dict。
""" """
# 文件清单必须与批次统计、四阶段和 CTA 使用相同的当前文件代表项,同时 # 文件清单必须与批次统计、五阶段和 CTA 使用相同的当前文件代表项,同时
# 保留 EML 父卡,避免附件失去邮件归属或在多个状态组重复出现。 # 保留 EML 父卡,避免附件失去邮件归属或在多个状态组重复出现。
display_work_items = _display_work_items_from_current_files(work_items) display_work_items = _display_work_items_from_current_files(work_items)
needs_action: list[dict[str, Any]] = [] needs_action: list[dict[str, Any]] = []
processing: list[dict[str, Any]] = [] processing: list[dict[str, Any]] = []
completed: list[dict[str, Any]] = [] completed: list[dict[str, Any]] = []
history: list[dict[str, Any]] = []
all_rows: list[dict[str, Any]] = [] all_rows: list[dict[str, Any]] = []
focused = str(focused_task_no or '').strip() or None focused = str(focused_task_no or '').strip() or None
recent = str(recent_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) needs_action.append(row)
elif bucket == 'completed': elif bucket == 'completed':
completed.append(row) completed.append(row)
elif bucket == 'history':
history.append(row)
else: else:
processing.append(row) processing.append(row)
@@ -2947,11 +2997,18 @@ def _conversation_processing_from_work_items(
needs_action.sort(key=_sort_key, reverse=True) needs_action.sort(key=_sort_key, reverse=True)
processing.sort(key=_sort_key, reverse=True) processing.sort(key=_sort_key, reverse=True)
completed.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) total = len(needs_action) + len(processing) + len(completed)
# [STEP 2] 会话文件数是业务 PDF 去重数,不是各任务 Run 文档数的简单求和。 # [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 = { document_ids = {
int(summary.get('document_id')) 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' if isinstance(item, dict) and str(item.get('work_item_type') or '') == 'order_task'
for child in (item.get('aggregate_children') or [item]) for child in (item.get('aggregate_children') or [item])
if isinstance(child, dict) if isinstance(child, dict)
@@ -2964,6 +3021,7 @@ def _conversation_processing_from_work_items(
if document_ids if document_ids
else sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed) else sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed)
) )
lifecycle_nodes = _batch_lifecycle_nodes(work_items)
return { return {
'projection_version': 1, 'projection_version': 1,
'summary': { 'summary': {
@@ -2972,7 +3030,7 @@ def _conversation_processing_from_work_items(
'processing': len(processing), 'processing': len(processing),
'needs_action': len(needs_action), 'needs_action': len(needs_action),
'completed': len(completed), 'completed': len(completed),
'history': 0, 'history': len(history),
**file_counts, **file_counts,
}, },
'focused_task_no': focused, 'focused_task_no': focused,
@@ -2980,7 +3038,7 @@ def _conversation_processing_from_work_items(
'needs_action': needs_action, 'needs_action': needs_action,
'processing': processing, 'processing': processing,
'completed': completed, 'completed': completed,
'history': [], 'history': history,
'status_groups': { 'status_groups': {
'failed': [row for row in all_rows if row.get('user_group') == 'failed'], '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'], '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'], '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'], '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), 'unclassified_summary': _unclassified_summary(work_items),
'ui_state': _batch_ui_state_from_items(work_items), 'ui_state': _batch_ui_state_from_items(work_items),
'output_artifacts': _batch_output_artifacts(work_items), 'output_artifacts': _batch_output_artifacts(work_items),
@@ -6,7 +6,7 @@ services/shipping_notice/ui_state.py
process_gate_projection(统一 Gate 用户摘要)、 process_gate_projection(统一 Gate 用户摘要)、
order_review_workbench_projection.apply_post_ot_gate_rules。 order_review_workbench_projection.apply_post_ot_gate_rules。
逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind,再统一投影 actions, 逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind,再统一投影 actions,
再补充四阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、 再补充五阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、
stp_facts、progress_nodes); stp_facts、progress_nodes);
若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影; 若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影;
Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办); 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-1", "code": "intake_parse", "label": "接收解析"},
{"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"}, {"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"},
{"id": "shipping-stage-3", "code": "fulfillment_prep", "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] = { _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 已生成,请下载后在货代平台上传,并在本系统登记凭据"), CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
} }
# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。 # 业务人员可见的五阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
_STAGE_CHECKPOINT_CODES: dict[str, str] = { _STAGE_CHECKPOINT_CODES: dict[str, str] = {
CP_PARSE_REVIEW: "order_review", CP_PARSE_REVIEW: "order_review",
CP_RSV_REQ: "order_review", CP_RSV_REQ: "order_review",
@@ -148,12 +149,12 @@ _STAGE_CHECKPOINT_CODES: dict[str, str] = {
CP_READY_EXPORT: "fulfillment_prep", CP_READY_EXPORT: "fulfillment_prep",
CP_EXPORT_READY: "fulfillment_prep", CP_EXPORT_READY: "fulfillment_prep",
CP_EXPORT_GENERATED: "fulfillment_prep", CP_EXPORT_GENERATED: "fulfillment_prep",
CP_WAITING_UPLOAD: "upload_complete", CP_WAITING_UPLOAD: "freight_upload",
CP_UPLOAD_REQ: "fulfillment_prep", CP_UPLOAD_REQ: "fulfillment_prep",
CP_UPLOAD_FAILED: "upload_complete", CP_UPLOAD_FAILED: "freight_upload",
CP_UPLOAD_RESULT_UNKNOWN: "upload_complete", CP_UPLOAD_RESULT_UNKNOWN: "freight_upload",
CP_UPLOADED: "upload_complete", CP_UPLOADED: "freight_upload",
CP_COMPLETED: "upload_complete", CP_COMPLETED: "freight_upload",
CP_REJECTED: "order_review", 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') gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate')
legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or '')) legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ''))
if legacy_stage is None: 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: if legacy_stage is None:
# 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。 # 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。
legacy_index = _derive_current_step_index(task) 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( return project_lifecycle(
current_gate=gate if isinstance(gate, dict) else None, current_gate=gate if isinstance(gate, dict) else None,
blocking_reason=( blocking_reason=(
@@ -180,6 +183,7 @@ def _task_lifecycle(
legacy_stage=legacy_stage, legacy_stage=legacy_stage,
# ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。 # ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。
has_candidate_context=True, 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: def _derive_current_step_index(task: ShippingNotice) -> int:
""" """
根据任务领域事实推导四阶段流程当前索引。 根据任务领域事实推导五阶段流程当前索引。
核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。 核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。
""" """
@@ -295,7 +299,7 @@ def build_shipping_workflow_steps(
lifecycle_stage: str | None = None, lifecycle_stage: str | None = None,
) -> list[dict[str, str]]: ) -> list[dict[str, str]]:
""" """
构造四阶段流程状态。 构造五阶段流程状态。
Returns: Returns:
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。 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), (index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage),
None, None,
) )
# 正式 Gate 已存在时,四阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。 # 正式 Gate 已存在时,五阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。
current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task) 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() pending_reason = str(task.pending_human_reason or "").strip()
checkpoint_value = str(checkpoint or "").strip() checkpoint_value = str(checkpoint or "").strip()
steps: list[dict[str, str]] = [] steps: list[dict[str, str]] = []
for index, step in enumerate(WORKFLOW_STEPS): 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" status = "completed"
elif index < current_index: elif index < current_index:
status = "completed" status = "completed"
@@ -664,7 +670,7 @@ def _build_stage_context(
stp_facts: dict[str, Any] | None, stp_facts: dict[str, Any] | None,
process_gate: dict[str, Any] | None, process_gate: dict[str, Any] | None,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""构造四阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。 """构造五阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。
通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成 通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成
只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。 只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。
@@ -834,13 +840,17 @@ def _build_stage_context(
ShippingExportArtifact.task_id == task.id, ShippingExportArtifact.task_id == task.id,
).order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()).all() ).order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()).all()
latest_attempt = attempts[0] if attempts else None 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() latest_status = str(getattr(latest_attempt, 'status', '') or '').lower()
upload_outcome = ( upload_outcome = (
'succeeded' if latest_status == 'succeeded' else 'succeeded' if latest_status == 'succeeded' else
'failed' if latest_status in {'failed', 'timed_out'} else 'failed' if latest_status in {'failed', 'timed_out'} else
'unknown' if latest_status == 'unknown' else 'unknown' if latest_status == 'unknown' else
'running' if latest_status in {'pending', 'running'} 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' 'not_started'
) )
return { return {
@@ -869,6 +879,15 @@ def _build_stage_context(
}, },
'upload': { 'upload': {
'outcome': upload_outcome, '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': ({ 'latest_attempt': ({
'id': latest_attempt.id, 'id': latest_attempt.id,
'status': latest_attempt.status, 'status': latest_attempt.status,
@@ -930,7 +949,7 @@ def build_task_ui_state(
'enabled': True, 'enabled': True,
# Artifact 已验证是下载授权的唯一来源;它直接声明展示位置, # Artifact 已验证是下载授权的唯一来源;它直接声明展示位置,
# 不依赖旧 checkpoint 或 action code 位置映射。 # 不依赖旧 checkpoint 或 action code 位置映射。
'target_surface': 'upload_complete', 'target_surface': 'freight_upload',
'target_anchor': 'excel_artifact', 'target_anchor': 'excel_artifact',
}, default_kind='view') }, default_kind='view')
action_codes = { action_codes = {
@@ -80,6 +80,39 @@ def _aggregate_task_upload_status(task: ShippingNotice) -> None:
task.upload_status = 'pending' 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( def complete_attempt(
attempt: ShippingUploadAttempt, *, success: bool, callback_id: str, attempt: ShippingUploadAttempt, *, success: bool, callback_id: str,
freight_ref_no: str | None = None, error_message: str | None = None, freight_ref_no: str | None = None, error_message: str | None = None,
@@ -206,6 +206,62 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
ensure_mock.assert_called_once() ensure_mock.assert_called_once()
def test_unique_customer_candidate_can_be_confirmed_before_draft_validation(app):
"""保存校验前,唯一 Shadow 候选必须先落为 Bill-to 已确认事实。"""
from app.services.shipping_notice import order_review_auto_progress_coordinator as coord
case = SimpleNamespace(case_no='SORC-UNIQUE-CUSTOMER', candidate_id=31)
with patch.object(
coord,
'_customer_step_for_case',
return_value=('auto_confirmed', {'customer_id': 5555}),
) as step_mock:
result = coord.auto_confirm_unique_customer_for_review_case(
case=case,
trigger='draft_validated',
)
step_mock.assert_called_once_with(case=case, trigger='draft_validated')
assert result == {'status': 'auto_confirmed', 'customer_id': 5555}
def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(app):
"""唯一客户自动确认只 flush,不能在 Draft 校验前单独提交事务。"""
from app.services.shipping_notice import order_review_auto_progress_coordinator as coord
case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31)
candidate = SimpleNamespace(id=31)
shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555)
extraction = SimpleNamespace(id=101)
shadow_model = SimpleNamespace(
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)),
)
match_model = SimpleNamespace(
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))),
)
with patch.object(coord.db.session, 'get', return_value=candidate), patch.object(
coord,
'ShippingCustomerShadowResolution',
shadow_model,
), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object(
coord,
'_resolve_extraction_for_case',
return_value=extraction,
), patch.object(
coord,
'ShippingOrderCustomerMatch',
match_model,
), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object(
coord,
'record_fulfillment_audit',
):
status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated')
assert status == 'auto_confirmed'
assert metadata == {'customer_id': 5555, 'extraction_id': 101}
assert confirm_mock.call_args.kwargs['commit'] is False
def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app): def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app):
"""合同 4:恢复扫描只收敛超时事实,不能在失败后自动补建 STP Job。""" """合同 4:恢复扫描只收敛超时事实,不能在失败后自动补建 STP Job。"""
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
@@ -277,6 +277,53 @@ def test_coordinate_profile_row_layout_repeats_across_the_table():
] ]
def test_coordinate_profile_rows_apply_selected_anchor_frame_translation_to_all_regions():
"""锚点框架选中的平移必须同时投影主表、物理行和每个字段区。"""
baseline_layout = {
'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40},
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0,
'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .35},
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .25, 'x1': .25, 'y1': .35}},
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .25, 'x1': .55, 'y1': .35}},
{'field_code': 'qty', 'region': {'x0': .55, 'y0': .25, 'x1': .75, 'y1': .35}},
{'field_code': 'unit_price', 'region': {'x0': .75, 'y0': .25, 'x1': 1, 'y1': .35}},
],
}],
}
shifted = reconstruct_coordinate_profile_rows(
characters=_glyphs([('00010', 10), ('PART-A', 65), ('2', 135), ('10.50', 175)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .20},
**baseline_layout,
)
# Without the selected transform these glyphs sit outside all baseline Y regions.
assert shifted[0].fields == {
'customer_po_line_no': '00010', 'customer_part_number': 'PART-A',
'qty': '2', 'unit_price': '10.50',
}
def test_coordinate_profile_rows_reject_invalid_selected_anchor_frame_transform():
"""非 matcher 认可的变换不得悄悄回退为绝对坐标取值。"""
kwargs = {
'characters': _glyphs([('00010', 10), ('PART-A', 65)]),
'table_bbox': {'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40},
'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40}, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .20, 'x1': .25, 'y1': .40}},
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .20, 'x1': 1, 'y1': .40}},
]}],
}
assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={'status': 'pending'}) == []
assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={
'status': 'applied', 'translate_x': 0, 'translate_y': .9,
}) == []
def test_coordinate_profile_preview_can_expose_unanchored_main_row_for_review(): def test_coordinate_profile_preview_can_expose_unanchored_main_row_for_review():
"""仅预览模式在缺少有效起行值时保留字段证据,正式重建仍严格过滤。""" """仅预览模式在缺少有效起行值时保留字段证据,正式重建仍严格过滤。"""
kwargs = { kwargs = {
@@ -504,6 +504,8 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab
assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate'] assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate']
assert 'tables' not in pending.payload_json['coordinate_evidence'] assert 'tables' not in pending.payload_json['coordinate_evidence']
assert 'page_glyphs' not in pending.payload_json['coordinate_evidence'] assert 'page_glyphs' not in pending.payload_json['coordinate_evidence']
assert pending.payload_json['matching_features']['version'] == 'v1'
assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2]
assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json
assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json
assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json
@@ -569,6 +571,36 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map
assert 'tables' not in restored['coordinate_evidence'] assert 'tables' not in restored['coordinate_evidence']
def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app):
"""冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。"""
with app.app_context():
document = _document()
current = record_inline_layout_snapshot(document, {
**_snapshot(),
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'tables': {'table-1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
db.session.flush()
document.current_layout_version = current
frozen_layout = {
**_snapshot(),
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
}
restored = ensure_on_demand_coordinate_evidence(
document=document, layout=frozen_layout, page_nos={1},
)
# 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H'
assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H'
def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypatch): def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypatch):
"""同一页存在多张物理表时,每个 table_id 都必须获得独立坐标字符证据。""" """同一页存在多张物理表时,每个 table_id 都必须获得独立坐标字符证据。"""
with app.app_context(): with app.app_context():
@@ -442,6 +442,42 @@ def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
assert seen['characters'][0]['text'] == 'Terms' assert seen['characters'][0]['text'] == 'Terms'
def test_coordinate_profile_rows_forward_selected_match_transform_without_recomputing(monkeypatch):
"""工作流只能转交共同 matcher 的已选变换,不能由表格或订单值重新推断。"""
region = SimpleNamespace(
page_scope='all_pages', page_no=None, line_layouts=[SimpleNamespace(model_dump=lambda: {})],
region=SimpleNamespace(model_dump=lambda: {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.5}),
termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False),
line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines',
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]),
)
seen = {}
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.reconstruct_coordinate_profile_rows',
lambda **kwargs: (seen.update(coordinate_transform=kwargs.get('coordinate_transform')) or []),
)
transform = {
'status': 'applied', 'translate_x': 0.0, 'translate_y': .03,
'anchor_ids': ['title'], 'reason_codes': [],
}
rows = _coordinate_profile_rows(
raw_profile={}, raw_table={'table_id': 'order-table', 'page_no': 1},
layout={'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': [{'text': 'x', 'bbox': {'x0': 30, 'y0': 30, 'x1': 31, 'y1': 31}}]},
'tables': {},
}},
contract=SimpleNamespace(fields_by_code={}), schema_fields={}, coordinate_transform=transform,
)
assert rows == []
assert seen['coordinate_transform'] == transform
def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkeypatch): def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkeypatch):
"""固定子行以模板表区为权威,须读取 MinerU 框外续行并跳过同页无关表。""" """固定子行以模板表区为权威,须读取 MinerU 框外续行并跳过同页无关表。"""
region = SimpleNamespace( region = SimpleNamespace(
+14 -13
View File
@@ -77,18 +77,18 @@ def test_unified_actions_preserve_backend_surface_without_action_code_fallback()
"primary_action": { "primary_action": {
"code": "mark_manual_uploaded", "code": "mark_manual_uploaded",
"label": "登记人工上传", "label": "登记人工上传",
"target_surface": "upload_complete", "target_surface": "freight_upload",
}, },
"action_presentation": [{ "action_presentation": [{
"code": "download_excel", "code": "download_excel",
"label": "下载发货 Excel", "label": "下载发货 Excel",
"target_surface": "upload_complete", "target_surface": "freight_upload",
"target_anchor": "excel_artifact", "target_anchor": "excel_artifact",
}], }],
}, },
) )
assert state["primary"]["target_surface"] == "upload_complete" assert state["primary"]["target_surface"] == "freight_upload"
assert state["secondary"][0]["target_surface"] == "upload_complete" assert state["secondary"][0]["target_surface"] == "freight_upload"
assert state["secondary"][0]["target_anchor"] == "excel_artifact" assert state["secondary"][0]["target_anchor"] == "excel_artifact"
@@ -121,7 +121,7 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None:
assert "stage_context" in detailed_state assert "stage_context" in detailed_state
def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None: def test_build_task_ui_state_exposes_five_business_stages_and_unified_actions(app) -> None:
"""没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。""" """没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingNotice(
@@ -133,13 +133,13 @@ def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(ap
state = build_task_ui_state(task) state = build_task_ui_state(task)
assert state["stage"]["code"] == "order_review" assert state["stage"]["code"] == "order_review"
assert state["stage"]["index"] == 2 assert state["stage"]["index"] == 2
assert state["stage"]["total"] == 4 assert state["stage"]["total"] == 5
assert state["actions"]["primary"] is None assert state["actions"]["primary"] is None
assert state["actions"]["secondary"] == [] assert state["actions"]["secondary"] == []
def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None: def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None:
"""正式工作台的四个入口必须由后端下发,页面不能按阶段顺序自行生成。""" """正式工作台的五个入口必须由后端下发,页面不能按阶段顺序自行生成。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingNotice(
task_no="SN-UI-LIFECYCLE-ENTRIES", task_no="SN-UI-LIFECYCLE-ENTRIES",
@@ -153,6 +153,7 @@ def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> Non
{"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"}, {"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"},
{"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"}, {"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"},
{"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, {"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
{"code": "freight_upload", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
{"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, {"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
] ]
@@ -213,7 +214,7 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None: def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None:
"""正式人工上传 Gate 必须裁决为通知完成,不受旧复核字段影响。""" """正式人工上传 Gate 必须停留货代上传,不受旧复核字段影响。"""
with app.app_context(): with app.app_context():
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
@@ -235,16 +236,16 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No
state = build_task_ui_state(task) state = build_task_ui_state(task)
assert state['lifecycle_stage'] == 'upload_complete' assert state['lifecycle_stage'] == 'freight_upload'
assert state['lifecycle_authority'] == 'process_gate' assert state['lifecycle_authority'] == 'process_gate'
assert state['stage']['code'] == 'upload_complete' assert state['stage']['code'] == 'freight_upload'
assert [entry['state'] for entry in state['lifecycle_entries']] == [ assert [entry['state'] for entry in state['lifecycle_entries']] == [
'available', 'available', 'available', 'current', 'available', 'available', 'available', 'current', 'unavailable',
] ]
def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None: def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None:
"""库存匹配/上传结果只映射四个业务阶段。""" """库存匹配与无证据历史上传分别映射通知准备和货代上传。"""
with app.app_context(): with app.app_context():
fulfillment = ShippingNotice( fulfillment = ShippingNotice(
task_no="SN-UI-FULFILLMENT", task_no="SN-UI-FULFILLMENT",
@@ -259,7 +260,7 @@ def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(
) )
assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep" assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep"
upload_state = build_task_ui_state(upload, include_stage_context=True) upload_state = build_task_ui_state(upload, include_stage_context=True)
assert upload_state["stage"]["code"] == "upload_complete" assert upload_state["stage"]["code"] == "freight_upload"
# 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。 # 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。
assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual" assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual"
@@ -64,6 +64,7 @@ from app.jobs.queue import fail_job
from app.services.shipping_notice.order_extraction import ( from app.services.shipping_notice.order_extraction import (
submit_order_extraction_run_result, submit_order_extraction_run_result,
submit_order_extraction_unit_result, submit_order_extraction_unit_result,
reconcile_review_case_after_unit,
) )
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
from app.services.shipping_notice.order_extraction_plan import ( from app.services.shipping_notice.order_extraction_plan import (
@@ -2925,6 +2926,23 @@ def test_reparse_unit_submission_accepts_orphaned_consumed_intake(app):
assert ShippingOrderCandidate.query.filter_by(order_extraction_run_id=replacement.id).count() == 0 assert ShippingOrderCandidate.query.filter_by(order_extraction_run_id=replacement.id).count() == 0
def test_unit_replay_reconciles_review_case_after_ensure(monkeypatch):
"""Unit 幂等回放创建/恢复 Case 后必须进入统一自动校验协调器。"""
calls = []
monkeypatch.setattr(
'app.services.shipping_notice.order_review_service.ensure_review_case_for_unit',
lambda **kwargs: calls.append(('ensure', kwargs)) or object(),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_stp_auto_create_service.maybe_stp_auto_create_for_run',
lambda **kwargs: calls.append(('reconcile', kwargs)) or [{'validate_status': 'validated'}],
)
reconcile_review_case_after_unit(run='run', unit='unit')
assert [item[0] for item in calls] == ['ensure', 'reconcile']
def test_unit_submission_survives_deleted_chat_session(app): def test_unit_submission_survives_deleted_chat_session(app):
"""后台 Run 不得因 UI 会话历史已清理而回滚 Candidate/Review Case 持久化。""" """后台 Run 不得因 UI 会话历史已清理而回滚 Candidate/Review Case 持久化。"""
with app.app_context(): with app.app_context():
@@ -140,6 +140,27 @@ def test_anchor_relative_value_is_confirmed_with_native_page_coordinates():
assert result.source == 'pdf_coordinate' assert result.source == 'pdf_coordinate'
def test_anchor_frame_transform_moves_order_number_anchor_and_value_together():
"""共同 matcher 的纵向平移必须同时投影订单号标签和值框。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'po', 'text': 'PO NO',
'region': {'x0': .05, 'y0': .1, 'x1': .25, 'y1': .14},
'position_locked': True,
},
'absolute_value_region': {'x0': .2, 'y0': .1, 'x1': .9, 'y1': .14},
'value_mode': 'right_of_anchor',
})
result = extract_order_fields(
profile=profile,
schema_fields=_schema(),
coordinate_evidence=_evidence(pages={'1': _glyphs(('PO NO 45001', 20, 40))}),
coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .1},
)[0]
assert result.status == 'confirmed'
assert result.value == '45001'
def test_right_of_anchor_keeps_saved_value_width_when_actual_anchor_text_is_narrower(): def test_right_of_anchor_keeps_saved_value_width_when_actual_anchor_text_is_narrower():
"""值框只命中 USD 首字符时,应补齐同一连续词而非误报未读取到值。""" """值框只命中 USD 首字符时,应补齐同一连续词而非误报未读取到值。"""
profile = _profile(layout={ profile = _profile(layout={
@@ -86,6 +86,124 @@ def _with_signature(profile: dict, layout: dict) -> dict:
return enriched return enriched
def _anchor_frame_profile(code: str = 'PO_ANCHOR_FRAME') -> dict:
"""构造声明锚点坐标框架的最小 Profile,供平移门禁回归使用。"""
profile = _profile(code)
profile['definition']['coordinate_model'] = {
'type': 'anchor_frame',
'anchors': [{
'anchor_id': 'title', 'text': 'PURCHASE ORDER', 'match_mode': 'exact',
'minimum_evidence_level': 'coordinate',
'region': {'x0': .185, 'y0': .05, 'x1': .26, 'y1': .0857142857},
}],
'max_translate_x': .02,
'max_translate_y': .05,
}
return profile
def _layout_with_frame_anchor(*, anchor_y: float = .05, table_y: float = .25) -> dict:
"""构造标题与主表同步平移的坐标 Layout,模拟正文高度改变而非结构变更。"""
layout = _layout(bbox={'x0': .05, 'y0': table_y, 'x1': .95, 'y1': .95})
text = 'PURCHASE ORDER'
anchor_glyphs = [
{
'text': char,
'bbox': {'x0': 10 + index * 5, 'y0': anchor_y * 280, 'x1': 14 + index * 5, 'y1': anchor_y * 280 + 10},
'boundary_before': 'space' if index and text[index - 1] == ' ' else 'none',
}
for index, char in enumerate(text)
if char != ' '
]
header = layout['coordinate_evidence']['tables']['table-1']
for glyph in header:
glyph['bbox']['y0'] += (table_y - .25) * 280
glyph['bbox']['y1'] += (table_y - .25) * 280
plant_text = 'PLANT NAME: FACTORY A'
plant_glyphs = [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate(plant_text)
]
layout['coordinate_evidence']['page_glyphs']['1'] = [
*plant_glyphs,
*anchor_glyphs,
*header,
]
return layout
def test_anchor_frame_matches_bounded_vertical_translation_without_changing_legacy_profiles():
"""同一结构整体下移时仅启用锚点框架的 Profile 可命中,legacy 仍按原规则失败关闭。"""
baseline = _layout_with_frame_anchor()
shifted = _layout_with_frame_anchor(anchor_y=.095, table_y=.295)
framed = _with_signature(_anchor_frame_profile(), baseline)
legacy = _with_signature(_profile('PO_LEGACY'), baseline)
framed_result = match_frozen_coordinate_profiles(profiles=[framed], layout=shifted)
legacy_result = match_frozen_coordinate_profiles(profiles=[legacy], layout=shifted)
# 关键断言:变换来自唯一静态锚点,并且 legacy Profile 未因新能力改变行为。
assert framed_result.status == 'unique_match'
assert framed_result.candidates[0].coordinate_transform == {
'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.045,
'anchor_ids': ['title'], 'reason_codes': [],
}
assert legacy_result.candidates[0].coordinate_transform is None
def test_anchor_frame_fails_closed_when_anchor_is_missing_ambiguous_or_out_of_range():
"""锚点框架不得因缺锚、重锚或超界平移降级猜测,均须成为模板硬失败。"""
baseline = _layout_with_frame_anchor()
profile = _with_signature(_anchor_frame_profile(), baseline)
missing = _layout()
ambiguous = _layout_with_frame_anchor(anchor_y=.08, table_y=.28)
ambiguous['coordinate_evidence']['page_glyphs']['1'].extend(
_layout_with_frame_anchor(anchor_y=.115)['coordinate_evidence']['page_glyphs']['1'][21:34],
)
out_of_range = _layout_with_frame_anchor(anchor_y=.14, table_y=.34)
for layout, reason in (
(missing, 'profile_anchor_frame_anchor_missing'),
(ambiguous, 'profile_anchor_frame_anchor_ambiguous'),
(out_of_range, 'profile_anchor_frame_transform_out_of_range'),
):
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.candidates[0].hard_match is False
assert reason in result.candidates[0].reason_codes
def test_anchor_frame_matches_static_anchor_embedded_in_a_pdf_line():
"""PDF 原生字符常把多个标签拼成一行;锚点应返回自身字符框而非整行框。"""
baseline = _layout_with_frame_anchor()
title = baseline['coordinate_evidence']['page_glyphs']['1'][21:34]
prefix = [{'text': 'X', 'bbox': {'x0': 0, 'y0': 14, 'x1': 5, 'y1': 24}}]
suffix = [{'text': 'X', 'bbox': {'x0': 80, 'y0': 14, 'x1': 85, 'y1': 24}}]
for glyph in title:
glyph['bbox']['y0'] += 10
glyph['bbox']['y1'] += 10
prefix[0]['bbox']['y0'] += 10
prefix[0]['bbox']['y1'] += 10
suffix[0]['bbox']['y0'] += 10
suffix[0]['bbox']['y1'] += 10
baseline['coordinate_evidence']['page_glyphs']['1'] = [
*baseline['coordinate_evidence']['page_glyphs']['1'][:21],
*prefix,
*title,
*suffix,
*baseline['coordinate_evidence']['page_glyphs']['1'][34:],
]
profile = _with_signature(_anchor_frame_profile(), baseline)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=baseline)
# 关键断言:行内静态锚点仍唯一命中,且自身 bbox 不受前后文本扩大影响。
assert result.status == 'unique_match'
assert result.candidates[0].coordinate_transform == {
'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.035714,
'anchor_ids': ['title'], 'reason_codes': [],
}
def test_profile_matcher_uniquely_matches_label_value_anchor_not_dynamic_order_values(): def test_profile_matcher_uniquely_matches_label_value_anchor_not_dynamic_order_values():
"""工厂标签和值关系不受订单号、料号、数量变化影响。""" """工厂标签和值关系不受订单号、料号、数量变化影响。"""
layout = _layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X') layout = _layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X')
@@ -120,6 +238,37 @@ def test_profile_matcher_enforces_required_anchor_and_evidence_availability():
assert match_frozen_coordinate_profiles(profiles=[profile], layout={'tables': []}).status == 'evidence_insufficient' assert match_frozen_coordinate_profiles(profiles=[profile], layout={'tables': []}).status == 'evidence_insufficient'
def test_profile_matcher_uses_persisted_lightweight_features_when_glyphs_are_compacted():
"""字符坐标被压缩后,模板匹配仍须使用压缩前持久化的结构特征。"""
complete_layout = _layout()
profile = _profile('PO_A')
profile['definition']['document_match']['required_anchors'] = []
profile = _with_signature(profile, complete_layout)
compacted_layout = {
'tables': complete_layout['tables'],
'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']},
'matching_features': {
'version': 'shipping-layout-matching-features.v1',
'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1},
'tables': [{
'table_id': 'table-1', 'page_no': 1,
'bbox': [0.05, 0.25, 0.95, 0.95],
'header_tokens': ['item', 'no', 'qty'],
'column_centers': [0.1225, 0.2825, 0.4225],
'column_width_ratios': [0.1611, 0.0722, 0.1167],
}],
'static_text_centers': {},
},
}
result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout)
assert result.status == 'unique_match'
candidate = result.candidates[0]
assert candidate.dimension_states['header_semantic_position'] == 'matched'
assert candidate.dimension_states['column_topology'] == 'matched'
def test_profile_matcher_reports_only_missing_anchor_identifiers(): def test_profile_matcher_reports_only_missing_anchor_identifiers():
"""缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。""" """缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。"""
profile = _profile('PO_A') profile = _profile('PO_A')
@@ -101,3 +101,78 @@ def test_resume_waiting_manual_confirm_when_auto_gate_false(monkeypatch):
assert result['auto_gate_allowed'] is False assert result['auto_gate_allowed'] is False
assert result['task_created'] is False assert result['task_created'] is False
assert case.status == 'ready' assert case.status == 'ready'
def test_resume_auto_confirms_unique_customer_before_validating(monkeypatch):
"""保存校验时必须先确认唯一客户候选,再执行 Draft 校验。"""
case = _case(can_build=True, can_auto_create=False, validation_status='ready')
calls = []
monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case)
monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None)
monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: [])
monkeypatch.setattr(
'app.services.shipping_notice.order_review_auto_progress_coordinator.auto_confirm_unique_customer_for_review_case',
lambda **_kw: calls.append('customer') or {'status': 'auto_confirmed', 'customer_id': 5555},
)
monkeypatch.setattr(
svc,
'validate_draft',
lambda **_kw: calls.append('validate') or {'status': 'ready'},
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
lambda **_kw: None,
)
monkeypatch.setattr(svc.db.session, 'flush', lambda: None)
monkeypatch.setattr(svc.db.session, 'commit', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_projection.serialize_review_case',
lambda _c: {'case_no': case.case_no},
)
svc.resume_after_review_change(
user_id=7,
case_no=case.case_no,
trigger='draft_validated',
skip_validate=False,
)
assert calls == ['customer', 'validate']
def test_validate_draft_api_delegates_versioned_validation_to_resume_coordinator(app, monkeypatch):
"""保存校验 API 不可绕过协调器,必须传递乐观锁版本。"""
from app.api.workspace import shipping_notice as api
from app.services.shipping_notice import order_review_resume_service
user = SimpleNamespace(id=7)
calls = []
def fake_resume(**kwargs):
calls.append(kwargs)
return {
'case': {'case_no': kwargs['case_no']},
'outcome': 'blocked',
'gate_recalculated': True,
}
monkeypatch.setattr(api, '_require_user', lambda: user)
monkeypatch.setattr(order_review_resume_service, 'resume_after_review_change', fake_resume)
with app.test_request_context(
'/shipping-notice/order-review-cases/CASE-API/draft/validate',
method='POST',
json={'expected_draft_version': 12},
):
response, status = api.workspace_validate_shipping_order_review_draft('CASE-API')
assert status == 200
assert response.get_json()['data']['case'] == {'case_no': 'CASE-API'}
assert calls == [{
'user_id': 7,
'case_no': 'CASE-API',
'trigger': 'draft_validated',
'change_type': None,
'skip_validate': False,
'allow_auto_create': True,
'expected_draft_version': 12,
}]
@@ -401,6 +401,32 @@ def _materialized_run(*, user, agent, session, intake):
return run return run
def test_review_case_summary_exposes_only_failed_intake_retry_authorization(app):
"""当前阶段卡只消费服务端 parse_failed 的 SNI 编号与 retry_parse 授权。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-INTAKE-RETRY')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
case = ensure_run_review_cases(run=run)[0]
intake.parse_status = 'parse_failed'
db.session.commit()
failed = serialize_review_run(run)['items'][0]
# 关键断言:失败节点提供原 SNI 和 retry_parse;不需要重新上传或前端猜测。
assert failed['intake_no'] == intake.intake_no
assert failed['available_actions'] == ['retry_parse']
intake.parse_status = 'parsing'
db.session.commit()
parsing = serialize_review_run(run)['items'][0]
# 关键断言:运行中只能等待 Worker 超时回收,不能显示冲突重试动作。
assert parsing['available_actions'] == []
intake.parse_status = 'cancelled'
db.session.commit()
cancelled = serialize_review_run(run)['items'][0]
assert cancelled['available_actions'] == []
def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'reservation-id') -> None: def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'reservation-id') -> None:
""" """
为 Review 就绪路径测试注入行级 catch-all 库存源规则。 为 Review 就绪路径测试注入行级 catch-all 库存源规则。
@@ -1768,6 +1794,63 @@ def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(a
raise AssertionError('superseded case must not be reparsed') raise AssertionError('superseded case must not be reparsed')
def test_successful_document_reparse_reconciles_only_activated_replacement_case(app, monkeypatch):
"""PDF 重识别成功切换当前版本后,必须补触发新版 Case 的统一自动推进。"""
with app.app_context():
from app.services.shipping_notice import order_review_disposition_service as disposition
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-PROGRESS')
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
source_case = ensure_run_review_cases(run=source)[0]
transition_order_extraction_run(source, target_status='processing')
transition_order_extraction_run(source, target_status='review_required', result={})
replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other')
ensure_order_extraction_plan(replacement)
for unit in replacement.extraction_plan.units:
unit.status = 'candidate_ready'
replacement_case = ensure_run_review_cases(run=replacement)[0]
reconciled = []
monkeypatch.setattr(
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
'reconcile_single_case_for_auto_progress',
lambda **kwargs: reconciled.append(kwargs) or {'enqueue_status': 'queued'},
)
finalize_document_reparse(run=replacement, succeeded=True)
assert reconciled == [{
'case': replacement_case,
'trigger': 'document_reparse_succeeded',
'refresh_validation': True,
}]
def test_document_reparse_does_not_reconcile_when_stream_activation_is_rejected(app, monkeypatch):
"""Stream 冲突或已确认旧版本拒绝切换时,不得推进晚到的新版草稿。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-CONFLICT')
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
source_case = ensure_run_review_cases(run=source)[0]
mark_review_stream_confirmed(case=source_case)
transition_order_extraction_run(source, target_status='processing')
transition_order_extraction_run(source, target_status='review_required', result={})
replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other')
ensure_order_extraction_plan(replacement)
for unit in replacement.extraction_plan.units:
unit.status = 'candidate_ready'
ensure_run_review_cases(run=replacement)
reconciled = []
monkeypatch.setattr(
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
'reconcile_single_case_for_auto_progress',
lambda **kwargs: reconciled.append(kwargs),
)
finalize_document_reparse(run=replacement, succeeded=True)
assert reconciled == []
def test_run_auto_progress_ignores_legacy_open_case_that_is_not_stream_current(app): def test_run_auto_progress_ignores_legacy_open_case_that_is_not_stream_current(app):
"""Run 级协调只能处理文件 Stream 当前 Case,不能重启残留旧版本。""" """Run 级协调只能处理文件 Stream 当前 Case,不能重启残留旧版本。"""
with app.app_context(): with app.app_context():
@@ -2456,3 +2539,17 @@ def test_assert_exact_duplicate_excludes_same_case_wave_tasks(app):
) )
assert exc.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE' assert exc.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
del agent, session, intake del agent, session, intake
def test_unvalidated_draft_is_not_projected_as_build_blocked(app):
"""未执行校验的 Draft 必须保持 not_validated,不能伪造成 can_build=false。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='UNVALIDATED-PROJECTION')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
case = ensure_review_case_for_unit(run=run, unit=unit)
db.session.flush()
detail = serialize_review_case(case)
eligibility = detail['draft']['build_eligibility']
assert eligibility['status'] == 'not_validated'
assert eligibility['can_build'] is None
@@ -106,13 +106,13 @@ def test_fulfillment_action_presentation_declares_lifecycle_surface():
)['target_surface'] == 'fulfillment_prep' )['target_surface'] == 'fulfillment_prep'
assert action_presentation( assert action_presentation(
'retry_freight_upload_rpa', gate_code='freight_upload_rpa', 'retry_freight_upload_rpa', gate_code='freight_upload_rpa',
)['target_surface'] == 'upload_complete' )['target_surface'] == 'freight_upload'
assert action_presentation( assert action_presentation(
'regenerate_manual_upload_todo', gate_code='manual_upload_handoff', 'regenerate_manual_upload_todo', gate_code='manual_upload_handoff',
)['target_surface'] == 'upload_complete' )['target_surface'] == 'freight_upload'
assert action_presentation( assert action_presentation(
'mark_manual_uploaded', gate_code='manual_upload_handoff', 'mark_manual_uploaded', gate_code='manual_upload_handoff',
)['target_surface'] == 'upload_complete' )['target_surface'] == 'freight_upload'
def test_manual_upload_handoff_authorizes_excel_regeneration_at_artifact_anchor(): def test_manual_upload_handoff_authorizes_excel_regeneration_at_artifact_anchor():
@@ -558,7 +558,7 @@ def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action(
'mark_manual_uploaded', 'mark_manual_uploaded',
'retry_freight_upload_rpa', 'retry_freight_upload_rpa',
] ]
assert summary['primary_action']['target_surface'] == 'upload_complete' assert summary['primary_action']['target_surface'] == 'freight_upload'
assert summary['primary_action']['target_anchor'] == 'manual_upload' assert summary['primary_action']['target_anchor'] == 'manual_upload'
@@ -223,9 +223,11 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
) )
uploaded = SimpleNamespace( uploaded = SimpleNamespace(
id=None,
current_step='', upload_status='uploaded', export_file_path=None, current_step='', upload_status='uploaded', export_file_path=None,
) )
assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed') # 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。
assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading')
waiting = SimpleNamespace( waiting = SimpleNamespace(
current_step='', upload_status='pending', export_file_path='/x.xlsx', current_step='', upload_status='pending', export_file_path='/x.xlsx',
@@ -103,14 +103,14 @@ def test_map_run_status_to_processing_status() -> None:
('inventory_snapshots_ready', 'fulfillment_prep'), ('inventory_snapshots_ready', 'fulfillment_prep'),
('inventory_matched', 'fulfillment_prep'), ('inventory_matched', 'fulfillment_prep'),
('excel_generated', 'fulfillment_prep'), ('excel_generated', 'fulfillment_prep'),
('upload_receipt_recorded', 'upload_complete'), ('upload_receipt_recorded', 'freight_upload'),
], ],
) )
def test_batch_four_stage_nodes_maps_auto_progress_gate_stages( def test_batch_lifecycle_nodes_maps_auto_progress_gate_stages(
stage: str, stage: str,
expected_lifecycle_stage: str, expected_lifecycle_stage: str,
) -> None: ) -> None:
"""自动推进 Gate 的真实阶段码必须归入对应四阶段,不能回退到接收解析。""" """自动推进 Gate 的真实阶段码必须归入对应五阶段,不能回退到接收解析。"""
nodes = _batch_four_stage_nodes([{ nodes = _batch_four_stage_nodes([{
'stage': stage, 'stage': stage,
'user_stage': stage, 'user_stage': stage,
@@ -127,7 +127,7 @@ def test_batch_four_stage_nodes_maps_auto_progress_gate_stages(
('item', 'expected_lifecycle_stage'), ('item', 'expected_lifecycle_stage'),
[ [
({'user_stage': 'inventory_match'}, 'fulfillment_prep'), ({'user_stage': 'inventory_match'}, 'fulfillment_prep'),
({'user_stage': 'freight_upload'}, 'upload_complete'), ({'user_stage': 'freight_upload'}, 'freight_upload'),
({'user_stage': 'customer_resolving'}, 'order_review'), ({'user_stage': 'customer_resolving'}, 'order_review'),
({'user_stage': 'duplicate_checking'}, 'order_review'), ({'user_stage': 'duplicate_checking'}, 'order_review'),
({'user_stage': 'waiting_human_review'}, 'order_review'), ({'user_stage': 'waiting_human_review'}, 'order_review'),
@@ -142,11 +142,11 @@ def test_batch_four_stage_nodes_maps_auto_progress_gate_stages(
({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'), ({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'),
], ],
) )
def test_batch_four_stage_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases( def test_batch_lifecycle_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases(
item: dict[str, object], item: dict[str, object],
expected_lifecycle_stage: str, expected_lifecycle_stage: str,
) -> None: ) -> None:
"""批次四阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。""" """批次五阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。"""
nodes = _batch_four_stage_nodes([{ nodes = _batch_four_stage_nodes([{
**item, **item,
'status': 'waiting_human', 'status': 'waiting_human',
@@ -177,6 +177,7 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'order_review', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'order_review', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'fulfillment_prep', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'fulfillment_prep', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
] ]
assert fulfillment_state['primary_action']['execution_mode'] == 'navigate' assert fulfillment_state['primary_action']['execution_mode'] == 'navigate'
@@ -232,6 +233,7 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'order_review', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'order_review', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
] ]
@@ -478,7 +480,7 @@ def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(ap
def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_summary() -> None: def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_summary() -> None:
"""四阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。""" """五阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。"""
projection = _conversation_processing_from_work_items([ projection = _conversation_processing_from_work_items([
{ {
'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW', 'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW',
@@ -503,8 +505,36 @@ def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_s
assert projection['unclassified_summary'] == {'count': 1} assert projection['unclassified_summary'] == {'count': 1}
def test_batch_payload_exposes_five_nodes_and_unverified_legacy_completion_stays_freight_upload(app) -> None:
"""新字段固定五节点,兼容字段同值,旧 technical completed 不得计作通知完成。"""
with app.app_context():
projection = _conversation_processing_from_work_items([{
'work_item_type': 'order_task', 'work_item_no': 'OT-LEGACY-UPLOADED',
'root_order_task_no': 'OT-LEGACY-UPLOADED', 'source_type': 'direct_pdf',
'shipping_notice_no': 'SN-LEGACY-UPLOADED', 'has_formal_ot': True,
'source_summary': {'document_id': 601, 'filename': 'legacy.pdf'},
'status': 'completed', 'stage': 'completed',
'user_status': 'completed', 'user_stage': 'completed',
'verified_upload_success': False,
'available_actions': [], 'facts': {'upload_state': 'succeeded'},
}])
assert [node['code'] for node in projection['lifecycle_nodes']] == [
'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete',
]
assert projection['four_stage_nodes'] == projection['lifecycle_nodes']
freight = next(node for node in projection['lifecycle_nodes'] if node['code'] == 'freight_upload')
assert freight['summary']['needs_action'] == 1
assert freight['summary']['completed'] == 0
assert projection['summary']['completed'] == 0
assert projection['status_groups']['completed'] == []
assert [row['user_task_no'] for row in projection['status_groups']['waiting_human']] == [
'OT-LEGACY-UPLOADED',
]
def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None: def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None:
"""同一 EML 的两份订单 PDF 应在四阶段摘要中计为两项,而非一张父卡。""" """同一 EML 的两份订单 PDF 应在五阶段摘要中计为两项,而非一张父卡。"""
nodes = _batch_four_stage_nodes([{ nodes = _batch_four_stage_nodes([{
'work_item_type': 'order_task', 'work_item_type': 'order_task',
'work_item_no': 'INTAKE:SNI-DOUBLE', 'work_item_no': 'INTAKE:SNI-DOUBLE',
@@ -632,6 +662,38 @@ def test_conversation_status_groups_use_the_same_current_file_representative() -
] ]
@pytest.mark.parametrize('terminal_status', ['cancelled', 'archived'])
def test_cancelled_or_archived_file_stays_in_history_and_out_of_completion_metrics(
app,
terminal_status: str,
) -> None:
"""取消或归档仅保留历史,不得进入会话完成、文件完成或第五阶段统计。"""
with app.app_context():
work_items = [{
'work_item_type': 'order_task',
'work_item_no': f'OT-{terminal_status.upper()}',
'user_status': terminal_status,
'user_stage': 'freight_uploading',
# 覆盖历史兼容载荷尚未写入 user_group 的回退路径。
'status': terminal_status,
'stage': terminal_status,
'source_summary': {'document_id': 570, 'filename': 'history.pdf'},
}]
projection = _conversation_processing_from_work_items(work_items)
assert projection['summary']['completed'] == 0
assert projection['summary']['history'] == 1
assert projection['summary']['total_files'] == 0
assert projection['summary']['completed_files'] == 0
assert projection['completed'] == []
assert [row['user_task_no'] for row in projection['history']] == [
f'OT-{terminal_status.upper()}',
]
assert [row['user_task_no'] for row in projection['status_groups'][terminal_status]] == [
f'OT-{terminal_status.upper()}',
]
assert all(node['summary']['total'] == 0 for node in projection['lifecycle_nodes'])
def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> None: def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> None:
"""历史失败项不得在互斥统计后仍抢走批次当前按钮。""" """历史失败项不得在互斥统计后仍抢走批次当前按钮。"""
work_items = [ work_items = [
@@ -1031,6 +1093,7 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -
{'code': 'intake_parse', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'intake_parse', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'order_review', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'order_review', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
] ]
assert leaf['intake_parse_authorized'] is True assert leaf['intake_parse_authorized'] is True
@@ -1172,7 +1235,7 @@ def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document
def test_conversation_projection_is_the_complete_batch_display_source(app) -> None: def test_conversation_projection_is_the_complete_batch_display_source(app) -> None:
"""会话投影一次下发分组、EML 子文件、四阶段及 UI 动作,前端无需二次裁决。""" """会话投影一次下发分组、EML 子文件、五阶段及 UI 动作,前端无需二次裁决。"""
with app.app_context(): with app.app_context():
items = _aggregate_eml_order_task_work_items([ items = _aggregate_eml_order_task_work_items([
{ {
@@ -1868,16 +1931,16 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
assert synced['status'] == 'automating' assert synced['status'] == 'automating'
assert synced['stage'] == 'freight_uploading' assert synced['stage'] == 'freight_uploading'
# 人工上传回执已落库时,Notice 终态必须覆盖尚未来得及同步的 OT 旧状态。 # 历史 Notice.upload_status 不构成成功证据;未补齐 Attempt/预约单时仍须停在货代上传。
notice.upload_status = 'uploaded' notice.upload_status = 'uploaded'
order_task.status = 'automating' order_task.status = 'automating'
order_task.stage = 'freight_uploading' order_task.stage = 'freight_uploading'
db.session.commit() db.session.commit()
completed = _project_order_task_work_item(run) unverified = _project_order_task_work_item(run)
assert completed['status'] == 'completed' assert unverified['status'] == 'waiting_human'
assert completed['stage'] == 'completed' assert unverified['stage'] == 'freight_uploading'
assert completed['user_status'] == 'completed' assert unverified['user_status'] == 'waiting_human'
assert all(node['status'] == 'passed' for node in completed['stage_nodes']) assert unverified['verified_upload_success'] is False
def test_conversation_processing_rebuild_prefers_work_item_user_status(app): def test_conversation_processing_rebuild_prefers_work_item_user_status(app):
@@ -242,8 +242,8 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating():
assert stage['source'] == 'domain_facts' assert stage['source'] == 'domain_facts'
def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage(): def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload():
"""人工上传已完成时,旧 OT freight_uploading 阶段不能覆盖 Notice 终态。""" """历史 Notice.upload_status 无成功 Attempt 时不得绕过货代上传核对。"""
task = SimpleNamespace( task = SimpleNamespace(
id=1, id=1,
order_task_id=9, order_task_id=9,
@@ -253,8 +253,8 @@ def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
step_payload_json=None, step_payload_json=None,
) )
stage = project_stage_for_task(task) stage = project_stage_for_task(task)
assert stage['code'] == 'completed' assert stage['code'] == 'freight_uploading'
assert stage['source'] == 'notice_terminal' assert stage['source'] == 'upload_success_unverified'
def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch): def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch):
+28 -1
View File
@@ -18,7 +18,10 @@ from app.models import (
ShippingUploadAttempt, ShippingUploadAttempt,
) )
from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success
from app.services.shipping_notice.upload_attempt_service import complete_attempt, mark_attempt_result_unknown, start_rpa_attempt, void_rejected_artifact from app.services.shipping_notice.upload_attempt_service import (
complete_attempt, has_verified_upload_success, mark_attempt_result_unknown,
start_rpa_attempt, void_rejected_artifact,
)
from app.services.shipping_notice.state_machine import resolve_task_ui_state from app.services.shipping_notice.state_machine import resolve_task_ui_state
@@ -64,10 +67,34 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app):
assert ShippingUploadAttempt.query.count() == 1 assert ShippingUploadAttempt.query.count() == 1
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
# 三层成功事实齐全后,才允许任务进入业务「通知完成」。
assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True
with pytest.raises(ConflictError): with pytest.raises(ConflictError):
start_rpa_attempt(task, artifact_id=artifact.id) start_rpa_attempt(task, artifact_id=artifact.id)
def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app):
"""历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。"""
with app.app_context():
task, _artifact, _reservation = _ready_artifact()
task.upload_status = 'uploaded'
db.session.flush()
assert has_verified_upload_success(task) is False
def test_archived_upload_success_is_not_counted_as_completed(app):
"""归档任务保留上传审计,但不能再计入当前通知完成统计。"""
with app.app_context():
task, artifact, _reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
complete_attempt(attempt, success=True, callback_id='callback-archived', freight_ref_no='REF-ARCHIVED')
task.lifecycle_status = 'archived'
db.session.flush()
assert has_verified_upload_success(task) is False
def test_failed_attempt_does_not_complete_reservation(app): def test_failed_attempt_does_not_complete_reservation(app):
"""RPA 失败仅释放 Artifact 重试状态,不能把预约单错误标记为上传完成。""" """RPA 失败仅释放 Artifact 重试状态,不能把预约单错误标记为上传完成。"""
with app.app_context(): with app.app_context():
+4 -1
View File
@@ -13,7 +13,10 @@
### 当前业务阶段基线(2026-08) ### 当前业务阶段基线(2026-08)
业务人员只看到四个阶段:`接收解析 → 订单复核 → 通知准备 → 通知完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于通知准备;上传或登记回执后进入通知完成。`ui_state` 是唯一前端读模型,按钮由后端统一返回。阶段四的进入不等于上传成功:必须有服务端确认的上传 Attempt 和回执事实;同一 Gate 的全局处理按钮只在右侧“当前处理”出现一次。 业务人员只看到五个阶段:`接收解析 → 订单复核 → 通知准备 → 货代上传 → 通知完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`freight_upload`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于通知准备;下载 Excel、RPA 上传、人工回执登记、失败重试和未知结果核对属于货代上传。`ui_state` 是唯一前端读模型,按钮由后端统一返回。
- **完成口径**:只有 `upload_status=uploaded`、全部预约单均为 `uploaded`、且存在关联 Artifact 的 `ShippingUploadAttempt.status=succeeded` 三项事实同时成立,才进入「通知完成」并计入任务/批次完成率。PDF 候选成功、技术 `completed`、回执文本、取消或归档均不得替代成功事实。
- **恢复口径**:上传失败、RPA 运行中、人工待登记和历史无成功 Attempt 的 `uploaded` 都停在「货代上传」。未知结果必须先查询货代侧或登记核对证据,禁止自动重试;取消/归档是终态但不计为通知完成。同一 Gate 的全局处理按钮只在右侧“当前处理”出现一次。
- **模式**:直通处理(STP)+ 例外工作台。可信 PDF 自动建 Task 并推进至「Excel 已生成,待人工上传」;解析不确定进入人工复核;建单后异常优先在对话侧 Process Gate 轻量处理,复杂数据进复核工作台。 - **模式**:直通处理(STP)+ 例外工作台。可信 PDF 自动建 Task 并推进至「Excel 已生成,待人工上传」;解析不确定进入人工复核;建单后异常优先在对话侧 Process Gate 轻量处理,复杂数据进复核工作台。
- **双工作台架构(2026-08-02 冻结)**:对话工作台 = 主入口/主状态/主进度/轻量操作;复核工作台 = 深度编辑与证据处理;Task 工作台 = 仅备用深链(非主导航)。后端工作流始终后台运行,前端只消费状态投影。权威线框见 [review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md) §0。 - **双工作台架构(2026-08-02 冻结)**:对话工作台 = 主入口/主状态/主进度/轻量操作;复核工作台 = 深度编辑与证据处理;Task 工作台 = 仅备用深链(非主导航)。后端工作流始终后台运行,前端只消费状态投影。权威线框见 [review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md) §0。
+3 -2
View File
@@ -76,12 +76,13 @@
- 匹配结果有缺口时,缺货预约单继续等待补货;本轮已满足预约单仍可进入滚动制单 - 匹配结果有缺口时,缺货预约单继续等待补货;本轮已满足预约单仍可进入滚动制单
- 至少一个预约单满足时,生成包含全部当前可用预约单的**本轮发货 Excel**,并完成该文件的货代上传 - 至少一个预约单满足时,生成包含全部当前可用预约单的**本轮发货 Excel**,并完成该文件的货代上传
### 四阶段工作台速查(2026-08) ### 五阶段工作台速查(2026-08)
- **接收解析**:核对邮件正文、当前附件和解析异常;模板匹配只在这里查看。需要替换文件或重新识别时,按“当前处理”提示操作。 - **接收解析**:核对邮件正文、当前附件和解析异常;模板匹配只在这里查看。需要替换文件或重新识别时,按“当前处理”提示操作。
- **订单复核**:核对订单字段、客户、冲突、重复和 Reservation;此阶段不处理库存数量或上传。 - **订单复核**:核对订单字段、客户、冲突、重复和 Reservation;此阶段不处理库存数量或上传。
- **通知准备**:查看已经冻结的订单、每行库存来源/需求/可用/缺口和通知 Excel 状态;尚未生成匹配结果时,以右侧“当前处理”的提示为准。 - **通知准备**:查看已经冻结的订单、每行库存来源/需求/可用/缺口和通知 Excel 状态;尚未生成匹配结果时,以右侧“当前处理”的提示为准。
- **通知完成**:下载 Excel、按右侧“当前处理”登记人工上传或重试,并查看最近上传尝试与货代回执。进入本阶段不表示已经上传成功;只有系统显示已确认的上传结果才可视为完成。 - **货代上传**:下载 Excel、按右侧“当前处理”执行 RPA、登记人工上传、处理失败或核对未知结果,并查看最近上传尝试与货代回执。未知结果不得自动重试。
- **通知完成**:只读查看已核验的上传时间、货代回执、成功 Attempt 和预约单汇总。仅 Task 状态、全部预约单和成功 Attempt 三项事实同时满足时,才可视为完成并计入完成率;取消/归档不计完成。
同一问题只在右侧 **“当前处理”** 提供一个主操作按钮;页面中其他区域用于查看明细或填写被该按钮打开的表单,避免重复点击不同入口。 同一问题只在右侧 **“当前处理”** 提供一个主操作按钮;页面中其他区域用于查看明细或填写被该按钮打开的表单,避免重复点击不同入口。
+10 -9
View File
@@ -5,22 +5,23 @@
> **同步维护**:流程、字段规则、人工确认节点等变更时,**须同时更新本文件与** **`business.md`**。\ > **同步维护**:流程、字段规则、人工确认节点等变更时,**须同时更新本文件与** **`business.md`**。\
> **Dify 文档维护原则**:Dify 编排仅在本文件维护,且以**节点级配置**为准;重点维护各节点的职责、输入、输出、条件、Tool 绑定与连线关系,不再额外维护独立 DSL 解读文档。\ > **Dify 文档维护原则**:Dify 编排仅在本文件维护,且以**节点级配置**为准;重点维护各节点的职责、输入、输出、条件、Tool 绑定与连线关系,不再额外维护独立 DSL 解读文档。\
## 四阶段 UI 状态契约(2026-08) ## 五阶段 UI 状态契约(2026-08)
业务人员只看到四个阶段:`intake_parse`(接收解析)→ `order_review`(订单复核)→ `fulfillment_prep`(通知准备)→ `upload_complete`(通知完成)。`ui_state` 是唯一前端读模型;Gate/Execution 是业务门禁真相。正式 Task 的操作使用 `ui_state.actions.primary/secondary`,批次 / 生命周期投影的操作使用 `ui_state.primary_action/secondary_actions`;两者均由后端下发,前端不得根据领域字段自行推导阶段或按钮;`process_status` 已删除。 业务人员只看到五个阶段:`intake_parse`(接收解析)→ `order_review`(订单复核)→ `fulfillment_prep`(通知准备)→ `freight_upload`(货代上传)→ `upload_complete`(通知完成)。`ui_state` 是唯一前端读模型;Gate/Execution 是业务门禁真相。正式 Task 的操作使用 `ui_state.actions.primary/secondary`,批次 / 生命周期投影的操作使用 `ui_state.primary_action/secondary_actions`;两者均由后端下发,前端不得根据领域字段自行推导阶段或按钮;`process_status` 已删除。
### 四阶段工作面与动作宿主(2026-08) ### 五阶段工作面与动作宿主(2026-08)
- 接收解析只展示邮件/附件、解析证据与原 PDF 的单文件重识别;模板匹配只在该阶段展示,不支持上传替代 PDF。 - 接收解析只展示邮件/附件、解析证据与原 PDF 的单文件重识别;模板匹配只在该阶段展示,不支持上传替代 PDF。
- 订单复核只展示字段、客户、冲突、重复和 Reservation 人工裁决;不得展示库存数量、缺口或上传操作。 - 订单复核只展示字段、客户、冲突、重复和 Reservation 人工裁决;不得展示库存数量、缺口或上传操作。
- 通知准备只展示冻结订单、库存匹配行和 Excel 产物状态。任务详情的 `ui_state.stage_context.preparation` 是只读摘要;未生成匹配结果时必须明确显示当前 Gate,不能显示“处理结果已完成”。 - 通知准备只展示冻结订单、库存匹配行和 Excel 产物状态。任务详情的 `ui_state.stage_context.preparation` 是只读摘要;未生成匹配结果时必须明确显示当前 Gate,不能显示“处理结果已完成”。
- 通知完成只展示 Excel、最新上传 Attempt 和回执。`upload_complete` 只是第四阶段工作面;只有可追溯 `ShippingUploadAttempt.status=succeeded` 才是上传成功。人工登记必须同时提交回执号和证据资产。 - 货代上传展示 Excel、RPA 状态、人工上传登记、失败恢复、未知结果核对和最新上传 Attempt;`freight_upload_rpa` / `manual_upload_handoff` 的动作只落在此工作面。人工登记必须同时提交回执号和证据资产;未知结果禁止自动重试。
- 通知完成只读展示上传时间、货代回执、成功 Attempt 和预约单汇总。只有 `has_verified_upload_success(task)`(Task `uploaded`、全部预约单 `uploaded`、关联 Artifact 存在 `ShippingUploadAttempt.status=succeeded`)才进入;历史 `uploaded/completed`、候选/PDF 成功、单独回执、取消或归档均不得进入完成统计。
- 桌面右栏 `ReviewCurrentProcessingCard` 是每个 Gate 唯一全局写入口;主区仅显示事实、行级局部操作或被右栏定位的裁决表单。`TaskTodoPanel` 在生命周期工作台仅作无界面动作执行宿主,禁止重复渲染 Gate 或主按钮。 - 桌面右栏 `ReviewCurrentProcessingCard` 是每个 Gate 唯一全局写入口;主区仅显示事实、行级局部操作或被右栏定位的裁决表单。`TaskTodoPanel` 在生命周期工作台仅作无界面动作执行宿主,禁止重复渲染 Gate 或主按钮。
- `stage_context` 不落库、不驱动状态、不授权动作,仅由正式任务详情与单票 `/ui-state` 按需返回;任务列表、聊天轻量投影不加载它,以避免 N+1 查询。 - `stage_context` 不落库、不驱动状态、不授权动作,仅由正式任务详情与单票 `/ui-state` 按需返回;任务列表、聊天轻量投影不加载它,以避免 N+1 查询。
### Dify 配置边界(2026-08) ### Dify 配置边界(2026-08)
本次四阶段工作面调整**无需修改 Dify**。Dify 不能创建/推进 Gate,不能确认客户、裁决订单、匹配库存、生成 Excel、上传货代或登记回执;这些写入只由 HXOPS 服务端 Gate 校验后的工作台动作执行。若管理员维护现有 `shipping_notice` Chatflow,仍只能保留只读 `get_task_status` Tool,并原样传递 HXOPS 注入的短效能力令牌;发现任何写 Tool 或由 Dify 推断“已完成”时,应停止发布并移除。 本次五阶段工作面调整**无需修改 Dify**。Dify 不能创建/推进 Gate,不能确认客户、裁决订单、匹配库存、生成 Excel、上传货代或登记回执;这些写入只由 HXOPS 服务端 Gate 校验后的工作台动作执行。若管理员维护现有 `shipping_notice` Chatflow,仍只能保留只读 `get_task_status` Tool,并原样传递 HXOPS 注入的短效能力令牌;发现任何写 Tool 或由 Dify 推断“已完成”时,应停止发布并移除。
## 2026-07-31 订单解析增强最终实施方案(待实施) ## 2026-07-31 订单解析增强最终实施方案(待实施)
@@ -363,7 +364,7 @@ L1 字段级:目标单元格 + 表头 + 相邻单元格
| `standard` | 默认 | 订单字段 + 明细;右侧阻断/库存异常摘要 | 常驻 PDF 列、常驻 AI、常驻完整检查、对话上下文 | | `standard` | 默认 | 订单字段 + 明细;右侧阻断/库存异常摘要 | 常驻 PDF 列、常驻 AI、常驻完整检查、对话上下文 |
| `evidence` | 字段「定位证据」 | PDF 证据抽屉(可固定)+ 当前字段/行编辑 | 强制整页跳变;重跑识别 | | `evidence` | 字段「定位证据」 | PDF 证据抽屉(可固定)+ 当前字段/行编辑 | 强制整页跳变;重跑识别 |
| `inventory` | 「查看库存问题」 | 异常行优先的明细 + 库存处理卡 | 重新识别 PDF;已通过行常驻展开 | | `inventory` | 「查看库存问题」 | 异常行优先的明细 + 库存处理卡 | 重新识别 PDF;已通过行常驻展开 |
| `reparse` | 重新识别进行中 | 四阶段真实进度 | 展示/编辑旧 Draft 完整编辑区 | | `reparse` | 重新识别进行中 | 五阶段真实进度 | 展示/编辑旧 Draft 完整编辑区 |
| `confirm_progress` | 确认建单成功 | 真实 Task / auto_progress | 继续编辑已确认 Draft | | `confirm_progress` | 确认建单成功 | 真实 Task / auto_progress | 继续编辑已确认 Draft |
模式切换规则:除证据定位打开抽屉外,系统只提示模式、不强制跳变;文件切换保留当前模式与字段滚动位置;关闭证据抽屉后恢复滚动。业务写操作仍走既有 Case/Draft API 与乐观锁,布局层不得改后端状态机。 模式切换规则:除证据定位打开抽屉外,系统只提示模式、不强制跳变;文件切换保留当前模式与字段滚动位置;关闭证据抽屉后恢复滚动。业务写操作仍走既有 Case/Draft API 与乐观锁,布局层不得改后端状态机。
@@ -1726,7 +1727,7 @@ GET /api/admin/shipping-order-schema/published-contract
### 发货任务处置生命周期 ### 发货任务处置生命周期
- 业务人员只看到四阶段:`接收解析 → 订单复核 → 通知准备 → 通知完成`;Gate/Execution 是业务判断真相,`ui_state` 是唯一前端读模型,任务处置使用独立的 `lifecycle_status=active|voided|archived`。 - 业务人员只看到五阶段:`接收解析 → 订单复核 → 通知准备 → 货代上传 → 通知完成`;Gate/Execution 是业务判断真相,`ui_state` 是唯一前端读模型,任务处置使用独立的 `lifecycle_status=active|voided|archived`。
- 用户点击删除时,服务端以任务行锁重算资格并写入 `ShippingTaskEvent` 审计(操作者、请求 ID、原因和处置前后事实)。纯误建任务仅进入回收站;已有业务单、Candidate 消费、库存链接或导出 Artifact 的任务同时设为 `voided` 后进入回收站。存在修订后继的任务禁止 delete/void,只允许 archive,避免破坏版本链。 - 用户点击删除时,服务端以任务行锁重算资格并写入 `ShippingTaskEvent` 审计(操作者、请求 ID、原因和处置前后事实)。纯误建任务仅进入回收站;已有业务单、Candidate 消费、库存链接或导出 Artifact 的任务同时设为 `voided` 后进入回收站。存在修订后继的任务禁止 delete/void,只允许 archive,避免破坏版本链。
- `upload_status` 为 queued/pending/running/uploading/uploaded/succeeded/success、存在货代参考号/回执时,平台禁止 delete/void,只允许 archive。异步编排、队列、RPA 回调和上传入口必须统一检查 `task_is_active`。 - `upload_status` 为 queued/pending/running/uploading/uploaded/succeeded/success、存在货代参考号/回执时,平台禁止 delete/void,只允许 archive。异步编排、队列、RPA 回调和上传入口必须统一检查 `task_is_active`。
- 回收站只允许恢复仍为 `active` 的纯误建任务;已作废或已归档任务不得恢复,必须走受控新建/修订业务流程。永久删除仅在第五阶段实现,并重新检查全部引用。 - 回收站只允许恢复仍为 `active` 的纯误建任务;已作废或已归档任务不得恢复,必须走受控新建/修订业务流程。永久删除仅在第五阶段实现,并重新检查全部引用。
@@ -2481,9 +2482,9 @@ ui_state.actions -> 前端唯一可渲染的履约动作投影
- `checkpoint` 不再产生履约 UI 可写动作;它继续作为后端流程、自动推进和诊断状态使用。建任务前 Case 的复核动作不属于正式履约 Gate,仍由其独立的 Case 权限/状态契约管理。 - `checkpoint` 不再产生履约 UI 可写动作;它继续作为后端流程、自动推进和诊断状态使用。建任务前 Case 的复核动作不属于正式履约 Gate,仍由其独立的 Case 权限/状态契约管理。
- 每个 `PROCESS_GATE_DEFINITIONS` 项必须声明 `ui_placement.target_surface` 与 `ui_placement.target_anchor`。后端在投影当前 Gate 动作时将该位置一并写入 `ui_state.actions`;未知位置前端不得猜测或兜底渲染。 - 每个 `PROCESS_GATE_DEFINITIONS` 项必须声明 `ui_placement.target_surface` 与 `ui_placement.target_anchor`。后端在投影当前 Gate 动作时将该位置一并写入 `ui_state.actions`;未知位置前端不得猜测或兜底渲染。
- 页面仅提供稳定锚点(例如 `fulfillment_prep/excel_artifact`、`upload_complete/freight_upload`、`upload_complete/manual_upload`)。是否显示“重新生成 Excel”、RPA 重试或人工上传登记,完全由当前 Gate 的已授权动作决定;前端不得以生命周期、按钮码、前缀或任务状态自行放行。 - 页面仅提供稳定锚点(例如 `fulfillment_prep/excel_artifact`、`freight_upload/freight_upload`、`freight_upload/manual_upload`)。是否显示“重新生成 Excel”、RPA 重试或人工上传登记,完全由当前 Gate 的已授权动作决定;前端不得以生命周期、按钮码、前缀或任务状态自行放行。
- `freight_upload_rpa` / `manual_upload_handoff` 可经 RecoveryPlan 授权 `regenerate_excel_artifact`:当前上传 Gate 负责权限、并发和版本校验,目标为 `artifact_generation`;RecoveryPlan 自己声明 `fulfillment_prep/excel_artifact`,优先于当前 Gate 的上传位置。只在当前 Artifact 为未上传 `ready`、无成功/未知回执、无 RPA 进行中且无活动 RecoveryPlan 时下发。执行时仅将旧 Artifact 标为 `superseded`、终止未完成上传并释放其 Reservation 占用,再生成新 Artifact;库存快照、行级匹配、人工短缺放行和人工补录不失效。 - `freight_upload_rpa` / `manual_upload_handoff` 可经 RecoveryPlan 授权 `regenerate_excel_artifact`:当前上传 Gate 负责权限、并发和版本校验,目标为 `artifact_generation`;RecoveryPlan 自己声明 `fulfillment_prep/excel_artifact`,优先于当前 Gate 的上传位置。只在当前 Artifact 为未上传 `ready`、无成功/未知回执、无 RPA 进行中且无活动 RecoveryPlan 时下发。执行时仅将旧 Artifact 标为 `superseded`、终止未完成上传并释放其 Reservation 占用,再生成新 Artifact;库存快照、行级匹配、人工短缺放行和人工补录不失效。
- 已通过 `resolve_task_export_download` 校验的 Excel Artifact 可额外下发只读下载动作,并明确挂在 `upload_complete/excel_artifact`;这不是前端独立的操作栏,也不覆盖 Gate 对写动作的授权。 - 已通过 `resolve_task_export_download` 校验的 Excel Artifact 可额外下发只读下载动作,并明确挂在 `freight_upload/excel_artifact`;这不是前端独立的操作栏,也不覆盖 Gate 对写动作的授权。
- Gate 写操作沿用既有版本校验与 `chat_process_gate_*` 审计;Artifact 下载沿用既有访问审计。二者均须保留操作者、时间、动作/访问内容及可追溯的对象快照/版本信息。 - Gate 写操作沿用既有版本校验与 `chat_process_gate_*` 审计;Artifact 下载沿用既有访问审计。二者均须保留操作者、时间、动作/访问内容及可追溯的对象快照/版本信息。
本次只调整 HXOPS 后端投影与前端展示契约,**无需修改 Dify 配置**。Dify 不裁决 Process Gate、不生成履约按钮、不调用 Excel/RPA/上传写路径;Dify 侧继续遵守本章 §2 的只读解释和受控复核边界。 本次只调整 HXOPS 后端投影与前端展示契约,**无需修改 Dify 配置**。Dify 不裁决 Process Gate、不生成履约按钮、不调用 Excel/RPA/上传写路径;Dify 侧继续遵守本章 §2 的只读解释和受控复核边界。
+3 -2
View File
@@ -2,12 +2,13 @@
## 知识库同步状态校验 ## 知识库同步状态校验
## 货代发货通知四阶段 ## 货代发货通知五阶段
- 接收解析:接收、解析和抽取订单字段。 - 接收解析:接收、解析和抽取订单字段。
- 订单复核:核对订单并确认正式建单。 - 订单复核:核对订单并确认正式建单。
- 通知准备:库存处理、匹配和生成发货通知 Excel;展示冻结订单、行级库存/缺口和 Excel 状态。 - 通知准备:库存处理、匹配和生成发货通知 Excel;展示冻结订单、行级库存/缺口和 Excel 状态。
- 通知完成:上传通知或登记上传回执;仅服务端确认的上传 Attempt 成功后显示完成结果。 - 货代上传:下载 Excel、RPA 上传、人工上传回执登记、失败恢复和未知结果核对;未知结果禁止自动重试。
- 通知完成:只读展示已核验的上传成功证据;仅 Task 聚合、全部预约单与成功 Upload Attempt 同时满足时显示并计入完成。
- 平台把文本提交给 Dify 后,会继续确认 Dify 的 `indexing_status`;只有 `completed` 才展示“同步:已完成”。 - 平台把文本提交给 Dify 后,会继续确认 Dify 的 `indexing_status`;只有 `completed` 才展示“同步:已完成”。
- Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。 - Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。
+3 -1
View File
@@ -4,7 +4,9 @@
### 阶段与状态职责基线(2026-08) ### 阶段与状态职责基线(2026-08)
业务阶段固定为 `intake_parse`、`order_review`、`fulfillment_prep`、`upload_complete` 四项(接收解析、订单复核、通知准备、通知完成);Gate/Execution 负责业务判断,`ui_state` 负责前端投影,`lifecycle_status` 独立表示 active/voided/archived,`process_status` 已删除。`ui_state.stage_context` 是正式任务详情按需返回的只读阶段事实,不是新的 State、数据库字段或动作权限来源;上传成功必须以 `ShippingUploadAttempt.status=succeeded` 为准。 业务阶段固定为 `intake_parse`、`order_review`、`fulfillment_prep`、`freight_upload`、`upload_complete` 五项(接收解析、订单复核、通知准备、货代上传、通知完成);这是唯一用户可见生命周期投影,不是第二套状态机。Gate/Execution、Intake、Run/Unit、checkpoint、RPA 状态和 UploadAttempt 仍是执行事实;`ui_state` 负责前端投影,`lifecycle_status` 独立表示 active/voided/archived,`process_status` 已删除。`ui_state.stage_context` 是正式任务详情按需返回的只读阶段事实,不是新的 State、数据库字段或动作权限来源。
`has_verified_upload_success(task)` 是唯一完成谓词:Task 聚合 `upload_status=uploaded`、全部 `ShippingReservation.status=uploaded`、关联 `ShippingExportArtifact` 存在 `ShippingUploadAttempt.status=succeeded`。只有该谓词为真时技术投影为 `completed`、生命周期投影为 `upload_complete`;旧 `uploaded/completed`、候选/PDF 成功、单独回执、取消或归档不能进入完成。批次接口首选 `lifecycle_nodes`;`four_stage_nodes` 在一个发布周期内作为同值的五阶段兼容别名。
### STP 阶段 0:字段契约与状态语义冻结(2026-07-30,项次派生 Phase 0 纠偏) ### STP 阶段 0:字段契约与状态语义冻结(2026-07-30,项次派生 Phase 0 纠偏)
@@ -47,6 +47,8 @@ import type {
OrderFieldValuePreview, OrderFieldValuePreview,
OrderProfileCanvasRegion, OrderProfileCanvasRegion,
OrderProfileDocumentMatchAnchor, OrderProfileDocumentMatchAnchor,
OrderProfileAnchorRule,
OrderCoordinateProfileDefinition,
OrderProfileFieldRegion, OrderProfileFieldRegion,
OrderProfileRelativeRegion, OrderProfileRelativeRegion,
OrderProfileBoundSample, OrderProfileBoundSample,
@@ -384,6 +386,44 @@ const documentMatch = reactive({
minimumMargin: 0.15, minimumMargin: 0.15,
}); });
const documentMatchDirty = ref(false); const documentMatchDirty = ref(false);
/** 坐标框架默认关闭;仅管理员显式启用后才写入 anchor_frame 声明。 */
const coordinateModel = reactive({
type: 'legacy' as 'legacy' | 'anchor_frame',
anchors: [] as OrderProfileAnchorRule[],
maxTranslateX: 0.03,
maxTranslateY: 0.06,
});
const coordinateModelDirty = ref(false);
const coordinateModelValid = computed(() => (
coordinateModel.type === 'legacy'
|| (coordinateModel.anchors.length > 0
&& coordinateModel.anchors.length <= 4
&& coordinateModel.anchors.every((anchor) => Boolean(anchor.text?.trim() && anchor.region))
&& Number.isFinite(coordinateModel.maxTranslateX)
&& Number.isFinite(coordinateModel.maxTranslateY)
&& coordinateModel.maxTranslateX >= 0 && coordinateModel.maxTranslateX <= 0.15
&& coordinateModel.maxTranslateY >= 0 && coordinateModel.maxTranslateY <= 0.2)
));
const enableAnchorFrameFromDocumentAnchor = () => {
const source = documentMatch.requiredAnchors[0];
if (!source?.label_region) return;
coordinateModel.type = 'anchor_frame';
coordinateModel.anchors = [{
anchor_id: `frame_${source.anchor_id}`.replace(/[^a-zA-Z0-9_]/g, '_').toLowerCase(),
text: source.label,
aliases: [],
match_mode: 'exact',
region: source.label_region,
position_locked: true,
minimum_evidence_level: 'coordinate',
}];
coordinateModelDirty.value = true;
};
const setCoordinateModelType = (type: 'legacy' | 'anchor_frame') => {
coordinateModel.type = type;
if (type === 'legacy') coordinateModel.anchors = [];
coordinateModelDirty.value = true;
};
/** /**
* 共同画布的字段选项只决定视觉定位;coordinate 末端值源仍必须由 Schema 显式授权 * 共同画布的字段选项只决定视觉定位;coordinate 末端值源仍必须由 Schema 显式授权
* pdf_coordinate。XFA 的正式取值来自 datasets,不能因未授权 PDF 文本而在画布中消失。 * pdf_coordinate。XFA 的正式取值来自 datasets,不能因未授权 PDF 文本而在画布中消失。
@@ -521,7 +561,7 @@ const draftSaveAdapter = computed<OrderProfileDraftSaveAdapter>(() => (
adapterKey: valueAdapterKey.value, adapterKey: valueAdapterKey.value,
adapters: { adapters: {
xfa_dataset: { xfa_dataset: {
hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value || xfaDirty.value, hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value || coordinateModelDirty.value || xfaDirty.value,
skipUnchangedManualSave: true, skipUnchangedManualSave: true,
canSave: !xfaValidateBlocked.value, canSave: !xfaValidateBlocked.value,
canValidate: !xfaDirty.value && !xfaValidateBlocked.value, canValidate: !xfaDirty.value && !xfaValidateBlocked.value,
@@ -538,7 +578,7 @@ const draftSaveAdapter = computed<OrderProfileDraftSaveAdapter>(() => (
applySavedDraft: async (saved) => valueAdapterDesk.applySavedDraft(saved as ShippingOrderDocumentProfile), applySavedDraft: async (saved) => valueAdapterDesk.applySavedDraft(saved as ShippingOrderDocumentProfile),
}, },
coordinate_ocr: { coordinate_ocr: {
hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value, hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value || coordinateModelDirty.value,
skipUnchangedManualSave: false, skipUnchangedManualSave: false,
canSave: issues.value.length === 0, canSave: issues.value.length === 0,
canValidate: issues.value.length === 0, canValidate: issues.value.length === 0,
@@ -770,6 +810,7 @@ const issues = computed(() => {
if (regions.value.some( if (regions.value.some(
(item) => item.kind === "order_field" && item.valueMode === "multi_line" && !item.stopAnchorText?.trim(), (item) => item.kind === "order_field" && item.valueMode === "multi_line" && !item.stopAnchorText?.trim(),
)) result.push("多行订单字段必须填写结束标签。"); )) result.push("多行订单字段必须填写结束标签。");
if (!coordinateModelValid.value) result.push(t('admin.shippingOrderProfiles.workbench.coordinateModelInvalid'));
if (regions.value.some((item) => !normalizedCanvasRegion(item.region))) { if (regions.value.some((item) => !normalizedCanvasRegion(item.region))) {
result.push("存在无效的页面坐标框,请重新绘制该标注。"); result.push("存在无效的页面坐标框,请重新绘制该标注。");
} }
@@ -1377,7 +1418,7 @@ const definition = () => {
})), })),
}; };
}); });
return { const visualDefinition: OrderCoordinateProfileDefinition = {
document_match: { document_match: {
document_type: "purchase_order" as const, document_type: "purchase_order" as const,
page_pattern: "one_or_more" as const, page_pattern: "one_or_more" as const,
@@ -1481,6 +1522,15 @@ const definition = () => {
}; };
}), }),
}; };
if (coordinateModel.type === 'anchor_frame') {
visualDefinition.coordinate_model = {
type: 'anchor_frame',
anchors: coordinateModel.anchors.map((anchor) => ({ ...anchor })),
max_translate_x: coordinateModel.maxTranslateX,
max_translate_y: coordinateModel.maxTranslateY,
};
}
return visualDefinition;
}; };
/** /**
* 保存当前草稿定义并附带当前标签租约。 * 保存当前草稿定义并附带当前标签租约。
@@ -2344,6 +2394,19 @@ const edit = async (profile: ShippingOrderDocumentProfile) => {
documentMatch.minimumScore = definition.document_match.minimum_score; documentMatch.minimumScore = definition.document_match.minimum_score;
documentMatch.minimumMargin = definition.document_match.minimum_margin; documentMatch.minimumMargin = definition.document_match.minimum_margin;
documentMatchDirty.value = false; documentMatchDirty.value = false;
const configuredModel = definition.coordinate_model;
if (configuredModel?.type === 'anchor_frame') {
coordinateModel.type = 'anchor_frame';
coordinateModel.anchors = (configuredModel.anchors || []).map((anchor) => ({ ...anchor }));
coordinateModel.maxTranslateX = Number(configuredModel.max_translate_x ?? 0.03);
coordinateModel.maxTranslateY = Number(configuredModel.max_translate_y ?? 0.06);
} else {
coordinateModel.type = 'legacy';
coordinateModel.anchors = [];
coordinateModel.maxTranslateX = 0.03;
coordinateModel.maxTranslateY = 0.06;
}
coordinateModelDirty.value = false;
regions.value = restoreRegions(profile); regions.value = restoreRegions(profile);
history.value = []; history.value = [];
future.value = []; future.value = [];
@@ -2781,6 +2844,37 @@ onBeforeUnmount(() => {
<p v-if="documentAnchorNotice" class="document-match-editor__warning">{{ documentAnchorNotice }}</p> <p v-if="documentAnchorNotice" class="document-match-editor__warning">{{ documentAnchorNotice }}</p>
</section> </section>
<section class="coordinate-model-editor">
<strong>{{ t('admin.shippingOrderProfiles.workbench.coordinateModelTitle') }}</strong>
<p>{{ t('admin.shippingOrderProfiles.workbench.coordinateModelHint') }}</p>
<label>
{{ t('admin.shippingOrderProfiles.workbench.coordinateModelType') }}
<select
:value="coordinateModel.type"
class="select-field"
:disabled="deskTableConfigReadonly"
@change="(event) => setCoordinateModelType((event.target as HTMLSelectElement).value as 'legacy' | 'anchor_frame')"
>
<option value="legacy">{{ t('admin.shippingOrderProfiles.workbench.coordinateModelLegacy') }}</option>
<option value="anchor_frame">{{ t('admin.shippingOrderProfiles.workbench.coordinateModelAnchorFrame') }}</option>
</select>
</label>
<template v-if="coordinateModel.type === 'anchor_frame'">
<button type="button" class="btn-secondary" :disabled="deskTableConfigReadonly || !documentMatch.requiredAnchors.length" @click="enableAnchorFrameFromDocumentAnchor">
{{ t('admin.shippingOrderProfiles.workbench.coordinateModelUseDocumentAnchor') }}
</button>
<label>
{{ t('admin.shippingOrderProfiles.workbench.coordinateModelMaxX') }}
<input v-model.number="coordinateModel.maxTranslateX" type="number" min="0" max="0.15" step="0.001" class="input-field" :disabled="deskTableConfigReadonly" @change="coordinateModelDirty = true" />
</label>
<label>
{{ t('admin.shippingOrderProfiles.workbench.coordinateModelMaxY') }}
<input v-model.number="coordinateModel.maxTranslateY" type="number" min="0" max="0.2" step="0.001" class="input-field" :disabled="deskTableConfigReadonly" @change="coordinateModelDirty = true" />
</label>
<p v-if="!coordinateModelValid" class="document-match-editor__warning">{{ t('admin.shippingOrderProfiles.workbench.coordinateModelInvalid') }}</p>
</template>
</section>
<section v-if="deskActivePageHasLines" class="table-region-editor"> <section v-if="deskActivePageHasLines" class="table-region-editor">
<strong>{{ t('admin.shippingOrderProfiles.workbench.tableRegionSettings') }}</strong> <strong>{{ t('admin.shippingOrderProfiles.workbench.tableRegionSettings') }}</strong>
<label>{{ t('admin.shippingOrderProfiles.workbench.rowReconstructionMode') }} <label>{{ t('admin.shippingOrderProfiles.workbench.rowReconstructionMode') }}
@@ -60,6 +60,13 @@ export type XfaTotalAmountPolicy = 'must_equal_line_sum' | 'disabled';
export interface OrderProfileRelativeRegion { x0: number; y0: number; x1: number; y1: number; } export interface OrderProfileRelativeRegion { x0: number; y0: number; x1: number; y1: number; }
export interface OrderProfileDocumentMatchAnchor { anchor_id: string; label: string; value: string; value_position: 'right' | 'below'; page_no?: number | null; label_region?: OrderProfileRelativeRegion | null; value_region?: OrderProfileRelativeRegion | null; minimum_evidence_level: OrderProfileEvidenceLevel; } export interface OrderProfileDocumentMatchAnchor { anchor_id: string; label: string; value: string; value_position: 'right' | 'below'; page_no?: number | null; label_region?: OrderProfileRelativeRegion | null; value_region?: OrderProfileRelativeRegion | null; minimum_evidence_level: OrderProfileEvidenceLevel; }
export interface OrderProfileAnchorRule { anchor_id: string; text: string; aliases?: string[]; match_mode: 'exact' | 'contains'; region?: OrderProfileRelativeRegion | null; position_locked?: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; } export interface OrderProfileAnchorRule { anchor_id: string; text: string; aliases?: string[]; match_mode: 'exact' | 'contains'; region?: OrderProfileRelativeRegion | null; position_locked?: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
export type OrderProfileCoordinateModelType = 'legacy' | 'anchor_frame';
export interface OrderProfileCoordinateModel {
type?: OrderProfileCoordinateModelType;
anchors?: OrderProfileAnchorRule[];
max_translate_x?: number;
max_translate_y?: number;
}
export interface OrderProfileFieldRegion { field_id: string; field_code: string; scope: 'header' | 'line'; region: OrderProfileRelativeRegion; extractor_key: OrderProfileExtractorKey; allowed_sources: OrderProfileAllowedSource[]; minimum_evidence_level: OrderProfileEvidenceLevel; target_fields?: Array<{ field_id: string; field_code: string; scope: 'header' | 'line' }>; } export interface OrderProfileFieldRegion { field_id: string; field_code: string; scope: 'header' | 'line'; region: OrderProfileRelativeRegion; extractor_key: OrderProfileExtractorKey; allowed_sources: OrderProfileAllowedSource[]; minimum_evidence_level: OrderProfileEvidenceLevel; target_fields?: Array<{ field_id: string; field_code: string; scope: 'header' | 'line' }>; }
export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: string; field_code: string; scope: 'header'; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; normalizer_key?: string | null; required: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; } export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: string; field_code: string; scope: 'header'; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; normalizer_key?: string | null; required: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; } export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
@@ -80,6 +87,8 @@ export interface OrderProfileVisualDefinition {
table_regions: OrderProfileTableRegion[]; table_regions: OrderProfileTableRegion[];
order_field_layouts?: OrderProfileOrderFieldLayout[]; order_field_layouts?: OrderProfileOrderFieldLayout[];
draft_unbound_order_field_layouts?: OrderProfileDraftUnboundOrderFieldLayout[]; draft_unbound_order_field_layouts?: OrderProfileDraftUnboundOrderFieldLayout[];
/** 扁平坐标框架契约;legacy 不提交该配置,anchor_frame 由管理员显式启用。 */
coordinate_model?: OrderProfileCoordinateModel;
} }
/** coordinate/OCR adapter 仅复用共同视觉定义,不增加独立生命周期字段。 */ /** coordinate/OCR adapter 仅复用共同视觉定义,不增加独立生命周期字段。 */
@@ -238,7 +238,7 @@ export const getWorkspaceShippingProcessing = async (
.then((raw): WorkspaceShippingProcessingResponse => ({ .then((raw): WorkspaceShippingProcessingResponse => ({
conversation_id: String(raw?.conversation_id || normalized), conversation_id: String(raw?.conversation_id || normalized),
work_items: normalizeShippingProcessingWorkItems(raw?.work_items), work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
// 会话级 status_groups / 四阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段, // 会话级 status_groups / 五阶段 / 产物均已由后端裁决;在 API 边界一次规范任务字段,
// 保证对话卡与批次中心消费同一份 DTO,后续组件不得再做 snake/camel 兼容分支。 // 保证对话卡与批次中心消费同一份 DTO,后续组件不得再做 snake/camel 兼容分支。
conversation_processing: raw?.conversation_processing conversation_processing: raw?.conversation_processing
? normalizeConversationProcessingProjection(raw.conversation_processing) ? normalizeConversationProcessingProjection(raw.conversation_processing)
@@ -1,6 +1,6 @@
/** /**
* features/chat/components/ShippingWorkflowStepper.vue * features/chat/components/ShippingWorkflowStepper.vue
* 用途:货代发货四阶段 Stepper 展示组件。 * 用途:货代发货五阶段 Stepper 展示组件。
* 依赖:shipping/shippingStepper、vue-i18n。 * 依赖:shipping/shippingStepper、vue-i18n。
* 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。 * 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。
*/ */
@@ -33,7 +33,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
<template> <template>
<div class="space-y-2"> <div class="space-y-2">
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div> <div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div>
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4' : 'md:grid-cols-4'"> <div class="grid gap-2" :class="compact ? 'sm:grid-cols-5' : 'md:grid-cols-5'">
<div <div
v-for="(step, index) in steps" v-for="(step, index) in steps"
:key="step.id" :key="step.id"
@@ -167,7 +167,9 @@ const hasDiagnosticDetails = computed(() => Boolean(
<div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4"> <div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
<section <section
class="rounded-lg border px-3 py-2 text-xs" class="rounded-lg border px-3 py-2 text-xs"
:class="eligibility.can_build :class="eligibility.can_build === null
? 'border-slate-200 bg-slate-50 text-slate-800 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100'
: eligibility.can_build
? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-100' ? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-100'
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'" : 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
data-testid="review-eligibility-details-overall" data-testid="review-eligibility-details-overall"
@@ -175,8 +177,10 @@ const hasDiagnosticDetails = computed(() => Boolean(
<div class="flex flex-wrap items-center justify-between gap-2"> <div class="flex flex-wrap items-center justify-between gap-2">
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span> <span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
<span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span> <span class="text-slate-600 dark:text-slate-300">{{ t('chat.shippingOrderReview.buildEligibility.manualBuildLabel') }}</span>
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'"> <span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build === null ? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-100' : eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
<span data-testid="review-eligibility-manual-status">{{ eligibility.can_build <span data-testid="review-eligibility-manual-status">{{ eligibility.can_build === null
? t('chat.shippingOrderReview.buildEligibility.notValidated')
: eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.canBuildYes') ? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}</span> : t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}</span>
</span> </span>
@@ -153,6 +153,7 @@ const lowConfidenceFields = computed(() => props.eligibility?.issues?.flatMap((i
) || []); ) || []);
const unexplainedBlocked = computed(() => Boolean( const unexplainedBlocked = computed(() => Boolean(
props.eligibility props.eligibility
&& props.eligibility.status !== 'not_validated'
&& props.eligibility.can_build === false && props.eligibility.can_build === false
&& !props.eligibility.issues?.length && !props.eligibility.issues?.length
&& !props.eligibility.failed_gates?.length && !props.eligibility.failed_gates?.length
@@ -212,13 +213,17 @@ const gateChecklist = computed(() => {
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2> <h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
<span <span
class="rounded-full px-2.5 py-1 text-xs font-medium" class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="eligibility.can_build :class="eligibility.can_build === null
? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'
: eligibility.can_build
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100' ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'" : 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
data-testid="review-build-eligibility-badge" data-testid="review-build-eligibility-badge"
> >
{{ {{
eligibility.can_build eligibility.status === 'not_validated'
? t('chat.shippingOrderReview.buildEligibility.notValidated')
: eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.canBuildYes') ? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') : t('chat.shippingOrderReview.buildEligibility.canBuildNo')
}} }}
@@ -0,0 +1,63 @@
/**
* features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts
* 用途:锁定唯一标准客户候选的工作台提示,避免将可自动确认状态误报为未识别。
* 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel。
* 逻辑:unique_candidate 显示自动确认说明和明确按钮;其他未确认状态维持人工选择入口。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewCustomerResolutionPanel from './ReviewCustomerResolutionPanel.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingCustomer: { loadFailed: '加载失败', confirmFailed: '确认失败' },
shippingOrderReview: {
customerResolution: {
title: '客户确认', subtitle: '请选择标准客户', uniqueCandidateHint: '已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。',
confirmUniqueCandidate: '确认唯一候选', selectCustomer: '选择标准客户', retrying: '识别中…', retryCustomer: '重新识别客户',
retryDone: '已重新识别客户', retryFailed: '重新识别客户失败', confirmed: '客户已确认', confirmReason: '人工确认',
standardCustomer: '标准客户', customerCode: '客户编码', matchedInputs: '匹配输入', candidates: '候选客户', pdfReparseHint: '请重新识别 PDF',
inputLabels: { customerCode: '客户编码', customerName: '客户名称', address: '地址', email: '邮箱', domain: '域名', other: '其他' },
status: { unique_candidate: '唯一候选', unmatched: '未匹配', confirmed: '已确认' },
},
resume: { autoCreated: '已自动建单', waitingManualConfirm: '等待人工确认' },
},
},
},
},
});
function mountPanel(status: string) {
return mount(ReviewCustomerResolutionPanel, {
props: {
caseNo: 'CASE-CUSTOMER-1',
editable: true,
resolution: { resolved: false, status, raw_name: 'ACME' },
},
global: {
plugins: [i18n],
stubs: { ShippingCustomerConfirmDialog: true },
},
});
}
describe('ReviewCustomerResolutionPanel', () => {
it('唯一候选展示自动确认说明和明确确认入口', () => {
const wrapper = mountPanel('unique_candidate');
expect(wrapper.text()).toContain('保存校验时系统会自动确认');
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('确认唯一候选');
});
it('非唯一未确认状态维持人工选择客户入口', () => {
const wrapper = mountPanel('unmatched');
expect(wrapper.text()).not.toContain('保存校验时系统会自动确认');
expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('选择标准客户');
});
});
@@ -41,6 +41,10 @@ const options = ref<ShippingCustomerOption[]>([]);
const loadingOptions = ref(false); const loadingOptions = ref(false);
const resolved = computed(() => Boolean(props.resolution?.resolved)); const resolved = computed(() => Boolean(props.resolution?.resolved));
const hasUniqueCandidate = computed(() => (
!resolved.value
&& String(props.resolution?.status || '').trim() === 'unique_candidate'
));
const statusLabel = computed(() => { const statusLabel = computed(() => {
const status = String(props.resolution?.status || '').trim(); const status = String(props.resolution?.status || '').trim();
if (!status) { if (!status) {
@@ -198,7 +202,11 @@ async function onRetry() {
<header class="flex flex-wrap items-start justify-between gap-2"> <header class="flex flex-wrap items-start justify-between gap-2">
<div> <div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2> <h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.customerResolution.subtitle') }}</p> <p class="mt-0.5 text-xs text-muted">
{{ hasUniqueCandidate
? t('chat.shippingOrderReview.customerResolution.uniqueCandidateHint')
: t('chat.shippingOrderReview.customerResolution.subtitle') }}
</p>
</div> </div>
<span <span
class="rounded-full px-2.5 py-1 text-xs font-medium" class="rounded-full px-2.5 py-1 text-xs font-medium"
@@ -244,7 +252,9 @@ async function onRetry() {
:disabled="busy" :disabled="busy"
@click="openSelectDialog" @click="openSelectDialog"
> >
{{ t('chat.shippingOrderReview.customerResolution.selectCustomer') }} {{ hasUniqueCandidate
? t('chat.shippingOrderReview.customerResolution.confirmUniqueCandidate')
: t('chat.shippingOrderReview.customerResolution.selectCustomer') }}
</button> </button>
<button <button
type="button" type="button"
@@ -30,7 +30,7 @@ export type ReviewDocumentNavItem = {
lifecycle_stage?: ReviewLifecycleStageCode | null; lifecycle_stage?: ReviewLifecycleStageCode | null;
}; };
type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'; type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow'; export type ReviewDocumentNavMode = 'hidden' | 'tabs' | 'sidebar' | 'sidebar_search' | 'narrow';
@@ -112,7 +112,7 @@ function caseStatusLabel(status: string): string {
/** 后端阶段码只做 i18n 投影;缺失时保留空白,禁止按 Case 状态补造阶段。 */ /** 后端阶段码只做 i18n 投影;缺失时保留空白,禁止按 Case 状态补造阶段。 */
function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null { function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
const code = String(item.lifecycle_stage || '').trim() as ReviewLifecycleStageCode; const code = String(item.lifecycle_stage || '').trim() as ReviewLifecycleStageCode;
if (!['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes(code)) return null; if (!['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(code)) return null;
const key = `chat.shippingOrderReview.lifecycle.stages.${code}`; const key = `chat.shippingOrderReview.lifecycle.stages.${code}`;
return te(key) ? t(key) : null; return te(key) ? t(key) : null;
} }
@@ -17,6 +17,7 @@ const i18n = createI18n({
messages: { messages: {
'zh-CN': { 'zh-CN': {
chat: { chat: {
shippingNoticeRetryParse: '重试解析',
shippingOrderReview: { shippingOrderReview: {
lifecycle: { lifecycle: {
navigation: '订单生命周期阶段', navigation: '订单生命周期阶段',
@@ -33,6 +34,7 @@ const i18n = createI18n({
const stages: ReviewLifecycleStageItem[] = [ const stages: ReviewLifecycleStageItem[] = [
{ code: 'order_review', label: '订单复核', state: 'completed' }, { code: 'order_review', label: '订单复核', state: 'completed' },
{ code: 'fulfillment_prep', label: '通知准备', state: 'current' }, { code: 'fulfillment_prep', label: '通知准备', state: 'current' },
{ code: 'freight_upload', label: '货代上传', state: 'blocked', reason: '请先完成通知准备' },
{ code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' }, { code: 'upload_complete', label: '通知完成', state: 'blocked', reason: '请先完成通知准备' },
]; ];
@@ -45,6 +47,30 @@ function mountNavigation() {
} }
describe('ReviewLifecycleStageNavigation', () => { describe('ReviewLifecycleStageNavigation', () => {
it('only exposes retry_parse on the current intake stage when the server authorizes it', async () => {
const wrapper = mount(ReviewLifecycleStageNavigation, {
props: {
stages: [
{ code: 'intake_parse', label: '接收解析', state: 'current' },
...stages,
],
activeCode: 'intake_parse',
availableActions: ['retry_parse'],
retrying: false,
},
global: { plugins: [i18n] },
});
// 关键断言:重试入口必须位于已发送文件的当前阶段卡,且完全由后端动作授权。
const retry = wrapper.get('[data-testid="review-lifecycle-stage-retry-parse"]');
expect(retry.text()).toContain('重试解析');
await retry.trigger('click');
expect(wrapper.emitted('retry-parse')).toEqual([[]]);
await wrapper.setProps({ availableActions: [] });
expect(wrapper.find('[data-testid="review-lifecycle-stage-retry-parse"]').exists()).toBe(false);
});
it('renders intake_parse as the first lifecycle stage', () => { it('renders intake_parse as the first lifecycle stage', () => {
const wrapper = mount(ReviewLifecycleStageNavigation, { const wrapper = mount(ReviewLifecycleStageNavigation, {
props: { props: {
@@ -63,9 +89,10 @@ describe('ReviewLifecycleStageNavigation', () => {
'review-lifecycle-stage-intake_parse', 'review-lifecycle-stage-intake_parse',
'review-lifecycle-stage-order_review', 'review-lifecycle-stage-order_review',
'review-lifecycle-stage-fulfillment_prep', 'review-lifecycle-stage-fulfillment_prep',
'review-lifecycle-stage-freight_upload',
'review-lifecycle-stage-upload_complete', 'review-lifecycle-stage-upload_complete',
]); ]);
expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-4'); expect(wrapper.find('[data-testid="review-lifecycle-stage-navigation"] > div').classes()).toContain('sm:grid-cols-5');
}); });
it('allows opening a completed stage for inspection', async () => { it('allows opening a completed stage for inspection', async () => {
@@ -1,13 +1,13 @@
<!-- <!--
features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue
用途:订单生命周期工作台的四阶段导航,只呈现父级已裁决的阶段状态。 用途:订单生命周期工作台的五阶段导航,只呈现父级已裁决的阶段状态。
依赖:父级 ShippingOrderReviewView 提供阶段、状态和阻断原因;lucide-vue-next 图标。 依赖:父级 ShippingOrderReviewView 提供阶段、状态和阻断原因;lucide-vue-next 图标。
逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。 逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { Check, LockKeyhole } from 'lucide-vue-next'; import { Check, LockKeyhole } from 'lucide-vue-next';
export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'; export type ReviewLifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked'; export type ReviewLifecycleStageState = 'current' | 'completed' | 'blocked';
export interface ReviewLifecycleStageItem { export interface ReviewLifecycleStageItem {
@@ -21,13 +21,25 @@ const props = defineProps<{
stages: ReviewLifecycleStageItem[]; stages: ReviewLifecycleStageItem[];
/** 后端尚未下发入口时为空;导航只能展示加载/未授权态,不能自行指定订单复核。 */ /** 后端尚未下发入口时为空;导航只能展示加载/未授权态,不能自行指定订单复核。 */
activeCode: ReviewLifecycleStageCode | null; activeCode: ReviewLifecycleStageCode | null;
/** 仅消费当前对象后端下发的恢复动作,禁止按阶段或状态由前端猜测。 */
availableActions?: string[];
/** retry_parse 请求中的互斥状态,避免用户重复提交。 */
retrying?: boolean;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
select: [code: ReviewLifecycleStageCode]; select: [code: ReviewLifecycleStageCode];
'open-detail': [code: ReviewLifecycleStageCode]; 'open-detail': [code: ReviewLifecycleStageCode];
'retry-parse': [];
}>(); }>();
/** 接收解析的恢复只在后端明确授权且该阶段为当前阶段时展示。 */
function canRetryParse(stage: ReviewLifecycleStageItem): boolean {
return stage.code === 'intake_parse'
&& stage.state === 'current'
&& (props.availableActions || []).includes('retry_parse');
}
/** /**
* 阶段导航只允许进入当前或已完成阶段;blocked 仅说明前置条件,不替代后端 Gate 判定。 * 阶段导航只允许进入当前或已完成阶段;blocked 仅说明前置条件,不替代后端 Gate 判定。
*/ */
@@ -43,7 +55,7 @@ function selectStage(stage: ReviewLifecycleStageItem) {
:aria-label="$t('chat.shippingOrderReview.lifecycle.navigation')" :aria-label="$t('chat.shippingOrderReview.lifecycle.navigation')"
data-testid="review-lifecycle-stage-navigation" data-testid="review-lifecycle-stage-navigation"
> >
<div class="grid gap-2 sm:grid-cols-4"> <div class="grid gap-2 sm:grid-cols-5">
<div <div
v-for="stage in props.stages" v-for="stage in props.stages"
:key="stage.code" :key="stage.code"
@@ -81,6 +93,16 @@ function selectStage(stage: ReviewLifecycleStageItem) {
? $t('chat.shippingOrderReview.lifecycle.completed') ? $t('chat.shippingOrderReview.lifecycle.completed')
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }} : (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
</button> </button>
<button
v-if="canRetryParse(stage)"
type="button"
class="mt-2 rounded border border-brand-300 px-2 py-1 text-xs font-medium text-brand-700 hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 dark:border-brand-700 dark:text-brand-200 dark:hover:bg-brand-950/40"
data-testid="review-lifecycle-stage-retry-parse"
:disabled="props.retrying === true"
@click="emit('retry-parse')"
>
{{ $t('chat.shippingNoticeRetryParse') }}
</button>
</div> </div>
</div> </div>
</nav> </nav>
@@ -18,6 +18,10 @@ const i18n = createI18n({
title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板', title: '文档模板匹配', subtitle: '摘要', selected: '命中模板', noSelected: '未选定模板',
expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板', expandCandidates: '查看候选模板({count})', collapseCandidates: '收起候选模板',
routeType: '路由类型', executionMode: '执行模式', routeType: '路由类型', executionMode: '执行模式',
coordinateModel: {
anchorFrame: '锚点坐标框架', status: '变换状态', translateX: '横向平移',
translateY: '纵向平移', reasonCodes: '原因码',
},
status: { matched: '已匹配', ambiguous: '多个候选' }, status: { matched: '已匹配', ambiguous: '多个候选' },
} } }, } } },
}, },
@@ -44,6 +48,34 @@ function mountPanel(needsReview = false) {
}); });
} }
function mountAnchorFramePanel(visibility: 'admin' | 'admin_only' = 'admin') {
return mount(ReviewProfileMatchPanel, {
props: {
profileMatch: {
available: true,
visibility,
status: 'unique_match',
needs_review: false,
selected_profile: { profile_code: 'ODP-A', display_name: '客户订单模板', version: 1 },
candidates: [{
profile_code: 'ODP-A',
version: 1,
display_name: '客户订单模板',
score: 0.99,
coordinate_transform: {
status: 'applied',
translate_x: 0.001,
translate_y: 0.03,
reason_codes: [],
},
}],
fallback_reason_codes: [],
},
},
global: { plugins: [i18n] },
});
}
describe('ReviewProfileMatchPanel', () => { describe('ReviewProfileMatchPanel', () => {
it('默认收起无需关注的候选列表', () => { it('默认收起无需关注的候选列表', () => {
const wrapper = mountPanel(false); const wrapper = mountPanel(false);
@@ -69,4 +101,23 @@ describe('ReviewProfileMatchPanel', () => {
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).toContain('客户订单模板'); expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).toContain('客户订单模板');
expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).not.toContain('ODP-A'); expect(wrapper.get('[data-testid="review-profile-match-candidates"]').text()).not.toContain('ODP-A');
}); });
it('管理员技术详情展示锚点框架平移和稳定原因码,不展示原始正文或完整坐标', async () => {
const wrapper = mountAnchorFramePanel();
await wrapper.get('[data-testid="review-profile-match-candidates-toggle"]').trigger('click');
const details = wrapper.get('[data-testid="review-profile-match-details"]');
expect(details.text()).toContain('锚点坐标框架');
expect(details.text()).toContain('纵向平移');
expect(details.text()).toContain('0.03');
expect(details.text()).not.toContain('ORDER NO.');
expect(details.text()).not.toContain('x0');
});
it('非管理员不可见锚点框架技术详情', async () => {
const wrapper = mountAnchorFramePanel('admin_only');
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-profile-match-coordinate-transform"]').exists()).toBe(false);
});
}); });
@@ -30,6 +30,19 @@ const candidateCount = computed(() => (props.profileMatch?.candidates || []).len
const defaultCandidatesExpanded = computed(() => false); const defaultCandidatesExpanded = computed(() => false);
const candidatesOpenOverride = ref<boolean | null>(null); const candidatesOpenOverride = ref<boolean | null>(null);
const candidatesExpanded = computed(() => candidatesOpenOverride.value ?? defaultCandidatesExpanded.value); const candidatesExpanded = computed(() => candidatesOpenOverride.value ?? defaultCandidatesExpanded.value);
const selectedCoordinateTransform = computed(() => {
if (!isAdminView.value) return null;
const selectedCode = String(props.profileMatch?.selected_profile?.profile_code || '');
const selectedVersion = props.profileMatch?.selected_profile?.version;
const candidate = (props.profileMatch?.candidates || []).find((item) => (
item.profile_code === selectedCode
&& (selectedVersion == null || item.version === selectedVersion)
));
return candidate?.coordinate_transform || null;
});
const coordinateTransformReasonCodes = computed(() => (
selectedCoordinateTransform.value?.reason_codes || []
));
watch( watch(
() => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`, () => `${props.profileMatch?.status || ''}:${props.profileMatch?.selected_profile?.profile_code || ''}:${candidateCount.value}`,
@@ -118,6 +131,17 @@ const selectedLabel = computed(() => {
<dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt> <dt class="text-muted">{{ t('chat.shippingOrderReview.profileMatch.executionMode') }}</dt>
<dd class="font-mono">{{ profileMatch.execution_mode }}</dd> <dd class="font-mono">{{ profileMatch.execution_mode }}</dd>
</div> </div>
<div v-if="selectedCoordinateTransform" data-testid="review-profile-match-coordinate-transform" class="mt-2 rounded-lg border border-sky-200 bg-sky-50 px-2.5 py-2 text-[11px] text-sky-950 dark:border-sky-900 dark:bg-sky-950/30 dark:text-sky-100">
<div class="font-medium">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.anchorFrame') }}</div>
<div class="mt-1 flex flex-wrap gap-x-3 gap-y-1">
<span>{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.status') }}: {{ selectedCoordinateTransform.status }}</span>
<span v-if="selectedCoordinateTransform.translate_x != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateX') }}: {{ selectedCoordinateTransform.translate_x }}</span>
<span v-if="selectedCoordinateTransform.translate_y != null">{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.translateY') }}: {{ selectedCoordinateTransform.translate_y }}</span>
</div>
<div v-if="coordinateTransformReasonCodes.length" class="mt-1">
{{ t('chat.shippingOrderReview.profileMatch.coordinateModel.reasonCodes') }}: {{ coordinateTransformReasonCodes.join(', ') }}
</div>
</div>
</dl> </dl>
<ul <ul
class="mt-2 max-h-48 space-y-1.5 overflow-y-auto pr-1" class="mt-2 max-h-48 space-y-1.5 overflow-y-auto pr-1"
@@ -801,6 +801,7 @@ describe('ShippingConversationProcessingCard', () => {
lifecycleEntries: [ lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
blocking_reason: null, blocking_reason: null,
@@ -820,6 +821,7 @@ describe('ShippingConversationProcessingCard', () => {
expect(row.text()).toContain('通知准备'); expect(row.text()).toContain('通知准备');
expect(row.text()).toContain('订单复核 · 可进入'); expect(row.text()).toContain('订单复核 · 可进入');
expect(row.text()).toContain('通知准备 · 当前可处理'); expect(row.text()).toContain('通知准备 · 当前可处理');
expect(row.text()).toContain('货代上传 · 前置未完成');
expect(row.text()).toContain('通知完成 · 前置未完成'); expect(row.text()).toContain('通知完成 · 前置未完成');
}); });
@@ -50,8 +50,8 @@ const props = defineProps<{
hasMoreHistory?: boolean; hasMoreHistory?: boolean;
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */ /** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
workbenchMode?: boolean; workbenchMode?: boolean;
/** 批次四阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */ /** 批次五阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'; lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
/** 批次中心本地搜索:只筛叶子文件,父 EML 卡仍保留。 */ /** 批次中心本地搜索:只筛叶子文件,父 EML 卡仍保留。 */
fileSearchQuery?: string; fileSearchQuery?: string;
/** 后端已授权下载的正式 Excel 对应 OT。 */ /** 后端已授权下载的正式 Excel 对应 OT。 */
@@ -94,12 +94,13 @@ type WorkbenchFileRow = {
po_number?: string | null; po_number?: string | null;
projection?: ShippingProcessingProjection; projection?: ShippingProcessingProjection;
}; };
const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const; const LIFECYCLE_STAGE_CODES = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'] as const;
type LifecycleStageCode = typeof LIFECYCLE_STAGE_CODES[number]; type LifecycleStageCode = typeof LIFECYCLE_STAGE_CODES[number];
const LIFECYCLE_STAGE_LABEL_KEYS: Record<string, string> = { const LIFECYCLE_STAGE_LABEL_KEYS: Record<string, string> = {
intake_parse: 'intakeParse', intake_parse: 'intakeParse',
order_review: 'orderReview', order_review: 'orderReview',
fulfillment_prep: 'fulfillmentPrep', fulfillment_prep: 'fulfillmentPrep',
freight_upload: 'freightUpload',
upload_complete: 'uploadComplete', upload_complete: 'uploadComplete',
}; };
@@ -454,7 +455,7 @@ function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessin
return taskReasonLabel(task); return taskReasonLabel(task);
} }
/** 文件工作面显示四阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */ /** 文件工作面显示五阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
function workbenchFileLifecycleStage(file: WorkbenchFileRow): string { function workbenchFileLifecycleStage(file: WorkbenchFileRow): string {
const code = String(file.projection?.uiState?.lifecycleStage || '').trim(); const code = String(file.projection?.uiState?.lifecycleStage || '').trim();
const key = LIFECYCLE_STAGE_LABEL_KEYS[code]; const key = LIFECYCLE_STAGE_LABEL_KEYS[code];
@@ -2,7 +2,7 @@
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts * features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
* 用途:验收批次进度中心只投影后端实时状态,不再保留文件详情抽屉。 * 用途:验收批次进度中心只投影后端实时状态,不再保留文件详情抽屉。
* 依赖:Vitest、Vue Test Utils、Timeline、ShippingConversationProcessingCard、shipping API。 * 依赖:Vitest、Vue Test Utils、Timeline、ShippingConversationProcessingCard、shipping API。
* 逻辑:四阶段、生命周期入口与单文件取消均由后端 Projection/availableActions 决定。 * 逻辑:五阶段、生命周期入口与单文件取消均由后端 Projection/availableActions 决定。
*/ */
import { flushPromises, mount } from '@vue/test-utils'; import { flushPromises, mount } from '@vue/test-utils';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -116,23 +116,29 @@ describe('ShippingWorkflowTimeline', () => {
api.reparseBatch.mockClear(); api.reparseBatch.mockClear();
}); });
it('renders backend-owned four-stage summaries and the authorized download toolbar', async () => { it('prefers backend five-stage lifecycle nodes and shows the authorized download toolbar in freight upload', async () => {
const processing = processingProjection({ const processing = processingProjection({
four_stage_nodes: [ lifecycle_nodes: [
{ code: 'intake_parse', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } }, { code: 'intake_parse', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
{ code: 'order_review', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } }, { code: 'order_review', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
{ code: 'fulfillment_prep', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } }, { code: 'fulfillment_prep', status: 'passed', summary: { total: 1, completed: 1, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
{ code: 'upload_complete', status: 'running', summary: { total: 1, completed: 0, needs_action: 1, processing: 0, failed: 0, blocking_reason: { code: 'manual_upload_pending' } } }, { code: 'freight_upload', status: 'running', summary: { total: 1, completed: 0, needs_action: 1, processing: 0, failed: 0, blocking_reason: { code: 'manual_upload_pending' } } },
{ code: 'upload_complete', status: 'pending', summary: { total: 1, completed: 0, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } },
], ],
// 新字段存在时必须优先使用,不能显示兼容字段的旧/冲突结果。
four_stage_nodes: [{ code: 'upload_complete', status: 'passed', summary: { total: 9, completed: 9, needs_action: 0, processing: 0, failed: 0, blocking_reason: null } }],
output_artifacts: [{ order_task_no: 'OT-1', filename: 'notice.xlsx', type: 'xlsx', status: 'ready', action: { code: 'download_excel', enabled: true } }], output_artifacts: [{ order_task_no: 'OT-1', filename: 'notice.xlsx', type: 'xlsx', status: 'ready', action: { code: 'download_excel', enabled: true } }],
} as Partial<ConversationProcessingProjection>); } as Partial<ConversationProcessingProjection>);
const wrapper = mountTimeline(processing, [fileProjection()]); const wrapper = mountTimeline(processing, [fileProjection()]);
await flushPromises(); await flushPromises();
expect(wrapper.get('[data-testid="shipping-workflow-four-stage-progress"]').text()).toContain('接收解析'); const progress = wrapper.get('[data-testid="shipping-workflow-lifecycle-progress"]');
const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-upload_complete"]'); expect(progress.text()).toContain('接收解析');
// 四阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。 expect(progress.text()).toContain('货代上传');
expect(upload.text()).toBe('通知完成1'); expect(progress.findAll('button')).toHaveLength(5);
const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-freight_upload"]');
// 五阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。
expect(upload.text()).toBe('货代上传1');
await upload.trigger('click'); await upload.trigger('click');
expect(wrapper.find('[data-testid="shipping-workflow-download-toolbar"]').exists()).toBe(true); expect(wrapper.find('[data-testid="shipping-workflow-download-toolbar"]').exists()).toBe(true);
}); });
@@ -463,7 +469,7 @@ describe('ShippingWorkflowTimeline', () => {
})); }));
}); });
it('shows only title and total on four-stage cards', async () => { it('falls back to the compatibility lifecycle field and shows only title and total', async () => {
const processing = processingProjection({ const processing = processingProjection({
four_stage_nodes: [{ four_stage_nodes: [{
code: 'order_review', status: 'blocked', code: 'order_review', status: 'blocked',
@@ -1,6 +1,6 @@
/** /**
* features/chat/components/shipping/ShippingWorkflowTimeline.vue * features/chat/components/shipping/ShippingWorkflowTimeline.vue
* 用途:聊天页右侧「批次进度中心」——后端批次投影、四阶段进度和文件行操作。 * 用途:聊天页右侧「批次进度中心」——后端批次投影、五阶段进度和文件行操作。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、 * 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
* ReasonDialog、ProcessGateRecoveryCard。 * ReasonDialog、ProcessGateRecoveryCard。
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示, * 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
@@ -115,25 +115,28 @@ const processing = computed(() => ctl.value.processing?.value ?? null);
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */ /** 展示投影:统一 ShippingProcessing / conversation_processing。 */
const displayProcessing = computed(() => processing.value); const displayProcessing = computed(() => processing.value);
const batchArtifacts = computed(() => displayProcessing.value?.output_artifacts || []); const batchArtifacts = computed(() => displayProcessing.value?.output_artifacts || []);
const batchFourStageNodes = computed(() => displayProcessing.value?.four_stage_nodes || []); const batchLifecycleNodes = computed(() => (
const lifecycleFilter = ref<'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'>('all'); displayProcessing.value?.lifecycle_nodes || displayProcessing.value?.four_stage_nodes || []
));
const lifecycleFilter = ref<'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete'>('all');
const fileSearchQuery = ref(''); const fileSearchQuery = ref('');
const selectedDownloadTaskNos = ref<string[]>([]); const selectedDownloadTaskNos = ref<string[]>([]);
/** 四阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */ /** 五阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = { const BATCH_LIFECYCLE_I18N_KEYS: Record<string, string> = {
intake_parse: 'intakeParse', intake_parse: 'intakeParse',
order_review: 'orderReview', order_review: 'orderReview',
fulfillment_prep: 'fulfillmentPrep', fulfillment_prep: 'fulfillmentPrep',
freight_upload: 'freightUpload',
upload_complete: 'uploadComplete', upload_complete: 'uploadComplete',
}; };
function batchFourStageLabelKey(code: string): string { function batchLifecycleLabelKey(code: string): string {
return BATCH_FOUR_STAGE_I18N_KEYS[code] || code; return BATCH_LIFECYCLE_I18N_KEYS[code] || code;
} }
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete') { function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete') {
lifecycleFilter.value = lifecycleFilter.value === code ? 'all' : code; lifecycleFilter.value = lifecycleFilter.value === code ? 'all' : code;
} }
/** 阶段卡仅展示后端统计总数;状态、阻塞和推进语义由颜色与边框表达。 */ /** 阶段卡仅展示后端统计总数;状态、阻塞和推进语义由颜色与边框表达。 */
function stageTotalText(node: NonNullable<typeof batchFourStageNodes.value>[number]): string { function stageTotalText(node: NonNullable<typeof batchLifecycleNodes.value>[number]): string {
return String(Number(node.summary?.total || 0)); return String(Number(node.summary?.total || 0));
} }
/** 下载资格仅来自后端 output_artifacts 的授权动作;筛选仅影响展示,不缩减授权集合。 */ /** 下载资格仅来自后端 output_artifacts 的授权动作;筛选仅影响展示,不缩减授权集合。 */
@@ -1024,15 +1027,15 @@ watch(
/> />
</div> </div>
</div> </div>
<section v-if="batchFourStageNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-four-stage-progress"> <section v-if="batchLifecycleNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-lifecycle-progress">
<div class="grid grid-cols-4 gap-2"> <div class="grid grid-cols-2 gap-2 sm:grid-cols-5">
<button v-for="node in batchFourStageNodes" :key="node.code" type="button" class="rounded-lg border px-2 py-2 text-left text-xs transition-colors" :class="[node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary', lifecycleFilter === node.code ? 'ring-2 ring-brand-400 ring-offset-1' : 'hover:brightness-95']" :data-testid="`shipping-workflow-stage-filter-${node.code}`" @click="selectLifecycleFilter(node.code)"> <button v-for="node in batchLifecycleNodes" :key="node.code" type="button" class="rounded-lg border px-2 py-2 text-left text-xs transition-colors" :class="[node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary', lifecycleFilter === node.code ? 'ring-2 ring-brand-400 ring-offset-1' : 'hover:brightness-95']" :data-testid="`shipping-workflow-stage-filter-${node.code}`" @click="selectLifecycleFilter(node.code)">
<span class="block font-semibold">{{ t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(node.code)}`) }}</span> <span class="block font-semibold">{{ t(`chat.shippingNoticeUi.stage.${batchLifecycleLabelKey(node.code)}`) }}</span>
<span class="mt-0.5 block text-[11px] opacity-80">{{ stageTotalText(node) }}</span> <span class="mt-0.5 block text-[11px] opacity-80">{{ stageTotalText(node) }}</span>
</button> </button>
</div> </div>
<div v-if="lifecycleFilter !== 'all'" class="mt-2 flex items-center justify-between gap-2 text-xs text-secondary"> <div v-if="lifecycleFilter !== 'all'" class="mt-2 flex items-center justify-between gap-2 text-xs text-secondary">
<span>{{ t('chat.shippingProcessing.batchWorkbench.filteringByStage', { stage: t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(lifecycleFilter)}`) }) }}</span> <span>{{ t('chat.shippingProcessing.batchWorkbench.filteringByStage', { stage: t(`chat.shippingNoticeUi.stage.${batchLifecycleLabelKey(lifecycleFilter)}`) }) }}</span>
<button type="button" class="text-brand-700 hover:underline" data-testid="shipping-workflow-clear-stage-filter" @click="lifecycleFilter = 'all'">{{ t('chat.shippingProcessing.batchWorkbench.clearStageFilter') }}</button> <button type="button" class="text-brand-700 hover:underline" data-testid="shipping-workflow-clear-stage-filter" @click="lifecycleFilter = 'all'">{{ t('chat.shippingProcessing.batchWorkbench.clearStageFilter') }}</button>
</div> </div>
<p v-if="Number(displayProcessing?.unclassified_summary?.count || 0) > 0" class="mt-2 text-xs text-amber-700" data-testid="shipping-workflow-unclassified-summary"> <p v-if="Number(displayProcessing?.unclassified_summary?.count || 0) > 0" class="mt-2 text-xs text-amber-700" data-testid="shipping-workflow-unclassified-summary">
@@ -1048,7 +1051,7 @@ watch(
<span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.search.label') }}</span> <span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.search.label') }}</span>
<input v-model="fileSearchQuery" type="search" class="w-full rounded-md border border-default bg-surface px-2.5 py-1.5 text-xs" :placeholder="t('chat.shippingProcessing.batchWorkbench.search.placeholder')" data-testid="shipping-workflow-file-search"> <input v-model="fileSearchQuery" type="search" class="w-full rounded-md border border-default bg-surface px-2.5 py-1.5 text-xs" :placeholder="t('chat.shippingProcessing.batchWorkbench.search.placeholder')" data-testid="shipping-workflow-file-search">
</label> </label>
<div v-if="lifecycleFilter === 'upload_complete' && downloadableTaskNos.length" class="flex flex-wrap items-center gap-2" data-testid="shipping-workflow-download-toolbar"> <div v-if="lifecycleFilter === 'freight_upload' && downloadableTaskNos.length" class="flex flex-wrap items-center gap-2" data-testid="shipping-workflow-download-toolbar">
<label class="inline-flex items-center gap-1 text-xs text-secondary"><input type="checkbox" :checked="allDownloadableSelected" data-testid="shipping-workflow-download-select-all" @change="toggleAllDownloadSelections"><span>{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selectAll') }}</span></label> <label class="inline-flex items-center gap-1 text-xs text-secondary"><input type="checkbox" :checked="allDownloadableSelected" data-testid="shipping-workflow-download-select-all" @change="toggleAllDownloadSelections"><span>{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selectAll') }}</span></label>
<span class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selected', { count: selectedDownloadTaskNos.length }) }}</span> <span class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selected', { count: selectedDownloadTaskNos.length }) }}</span>
<button type="button" class="rounded-md border border-brand-300 px-2.5 py-1 text-xs font-medium text-brand-700 disabled:opacity-50" :disabled="!selectedDownloadTaskNos.length" data-testid="shipping-workflow-download-selected" @click="downloadSelectedBatchArtifacts">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadSelected') }}</button> <button type="button" class="rounded-md border border-brand-300 px-2.5 py-1 text-xs font-medium text-brand-700 disabled:opacity-50" :disabled="!selectedDownloadTaskNos.length" data-testid="shipping-workflow-download-selected" @click="downloadSelectedBatchArtifacts">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadSelected') }}</button>
@@ -65,12 +65,12 @@ describe('shipping order review workbench viewport layout contract', () => {
expect(share1440).toBeGreaterThanOrEqual(0.62); expect(share1440).toBeGreaterThanOrEqual(0.62);
}); });
it('keeps four lifecycle columns while reserving 16rem only for the desktop sidebar', () => { it('keeps five lifecycle columns while reserving 16rem only for the desktop sidebar', () => {
const lifecycleNavigation = readFileSync(lifecycleNavigationPath, 'utf8'); const lifecycleNavigation = readFileSync(lifecycleNavigationPath, 'utf8');
const reviewWorkbench = readFileSync(reviewWorkbenchPath, 'utf8'); const reviewWorkbench = readFileSync(reviewWorkbenchPath, 'utf8');
// 关键断言:接收解析为第四阶段;必须断言真实导航组件,不能只验证 spec 内常量。 // 关键断言:导航真实渲染五个业务阶段,不能只验证 spec 内常量。
expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-4"'); expect(lifecycleNavigation).toContain('class="grid gap-2 sm:grid-cols-5"');
// sidebar/sidebar_search 是唯一允许预留 16rem 的模式;tabs/hidden/narrow 均落入 contents。 // sidebar/sidebar_search 是唯一允许预留 16rem 的模式;tabs/hidden/narrow 均落入 contents。
expect(reviewWorkbench).toMatch(/reviewDocumentNavigationMode\.value === 'sidebar'\s*\|\|\s*reviewDocumentNavigationMode\.value === 'sidebar_search'/); expect(reviewWorkbench).toMatch(/reviewDocumentNavigationMode\.value === 'sidebar'\s*\|\|\s*reviewDocumentNavigationMode\.value === 'sidebar_search'/);
expect(reviewWorkbench).toMatch(/:class="reviewDocumentNavigationUsesSidebar\s*\? 'grid gap-2 lg:grid-cols-\[16rem_minmax\(0,1fr\)\] lg:items-start lg:gap-3'\s*:\s*'contents'"/); expect(reviewWorkbench).toMatch(/:class="reviewDocumentNavigationUsesSidebar\s*\? 'grid gap-2 lg:grid-cols-\[16rem_minmax\(0,1fr\)\] lg:items-start lg:gap-3'\s*:\s*'contents'"/);
@@ -669,6 +669,51 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.activeCase.value?.case_no).toBe('CASE-B'); expect(review.activeCase.value?.case_no).toBe('CASE-B');
}); });
it('keeps the latest Run and Case when an older load response arrives last', async () => {
// 关键断言:重识别跳转新版本后,旧 Run 的迟到响应不得覆盖新版工作面。
let resolveOldRun: ((value: Record<string, unknown>) => void) | null = null;
api.getRun.mockImplementation((runNo: string) => (runNo === 'RUN-OLD'
? new Promise<Record<string, unknown>>((resolve) => { resolveOldRun = resolve; })
: Promise.resolve({
run_no: runNo,
summary: {},
items: [{ case_no: 'CASE-NEW', document_id: 2, status: 'draft', issue_count: 0 }],
})));
api.getQueue.mockImplementation((runNo: string) => Promise.resolve({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{
case_no: runNo === 'RUN-OLD' ? 'CASE-OLD' : 'CASE-NEW',
document_id: runNo === 'RUN-OLD' ? 1 : 2,
source_run_no: runNo,
status: 'draft', issue_count: 0, available_actions: [],
}],
}));
api.getCase.mockImplementation((caseNo: string) => Promise.resolve(buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-OLD' ? 'RUN-OLD' : 'RUN-NEW',
document: {
id: caseNo === 'CASE-OLD' ? 1 : 2,
file_name: caseNo === 'CASE-OLD' ? 'old.pdf' : 'new.pdf',
},
})));
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
const olderLoad = review.load('RUN-OLD', 'CASE-OLD');
await Promise.resolve();
await review.load('RUN-NEW', 'CASE-NEW');
resolveOldRun?.({
run_no: 'RUN-OLD',
summary: {},
items: [{ case_no: 'CASE-OLD', document_id: 1, status: 'superseded', issue_count: 0 }],
});
await olderLoad;
expect(review.reviewRun.value?.run_no).toBe('RUN-NEW');
expect(review.activeCase.value?.case_no).toBe('CASE-NEW');
});
it('blocks confirm when build eligibility cannot build', async () => { it('blocks confirm when build eligibility cannot build', async () => {
const review = useShippingOrderReview(); const review = useShippingOrderReview();
@@ -654,21 +654,34 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
/** /**
* ???? WorkItem ??????????????????? * ???? WorkItem ???????????????????
*/ */
const refreshWorkItemContext = async (conversationId?: string, itemNo?: string) => { const refreshWorkItemContext = async (
conversationId?: string,
itemNo?: string,
options?: { expectedLoadGeneration?: number },
) => {
const isExpectedLoad = () => (
options?.expectedLoadGeneration == null
|| options.expectedLoadGeneration === caseLoadGeneration
);
const conversation = String(conversationId || contextConversationId || '').trim(); const conversation = String(conversationId || contextConversationId || '').trim();
if (conversation) contextConversationId = conversation; if (conversation) contextConversationId = conversation;
if (itemNo) contextItemNo = itemNo; if (itemNo) contextItemNo = itemNo;
if (!isExpectedLoad()) return;
versionsLoading.value = true; versionsLoading.value = true;
try { try {
reviewProgressContext.value = await resolveWorkItem(conversation, { const context = await resolveWorkItem(conversation, {
itemNo: contextItemNo || undefined, itemNo: contextItemNo || undefined,
caseNo: activeCase.value?.case_no, caseNo: activeCase.value?.case_no,
}); });
if (!isExpectedLoad()) return;
reviewProgressContext.value = context;
versions.value = []; versions.value = [];
} catch { } catch {
if (!isExpectedLoad()) return;
reviewProgressContext.value = null; reviewProgressContext.value = null;
versions.value = []; versions.value = [];
} finally { } finally {
if (!isExpectedLoad()) return;
versionsLoading.value = false; versionsLoading.value = false;
refreshStatusMessage(); refreshStatusMessage();
} }
@@ -848,8 +861,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
preferredCaseNo?: string, preferredCaseNo?: string,
options?: { conversationId?: string; itemNo?: string; restoreProgress?: boolean }, options?: { conversationId?: string; itemNo?: string; restoreProgress?: boolean },
) => { ) => {
++caseLoadGeneration; const generation = ++caseLoadGeneration;
++intakeParseRequestGeneration; ++intakeParseRequestGeneration;
requestedCaseNo.value = String(preferredCaseNo || '').trim() || null;
loading.value = true; loading.value = true;
loadFailed.value = false; loadFailed.value = false;
draftConflict.value = null; draftConflict.value = null;
@@ -874,18 +888,25 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
getWorkspaceShippingOrderReviewRun(runNo), getWorkspaceShippingOrderReviewRun(runNo),
getWorkspaceShippingOrderReviewQueue(runNo), getWorkspaceShippingOrderReviewQueue(runNo),
]); ]);
if (generation !== caseLoadGeneration) return;
reviewRun.value = run; reviewRun.value = run;
reviewQueue.value = queue; reviewQueue.value = queue;
// [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。 // [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。
const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no; const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no;
const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null; const caseSnapshot = caseNo ? await getWorkspaceShippingOrderReviewCase(caseNo) : null;
if (generation !== caseLoadGeneration) return;
applyCaseSnapshot(caseSnapshot); applyCaseSnapshot(caseSnapshot);
evidence.value = caseNo ? (await getWorkspaceShippingOrderReviewEvidence(caseNo)).items : []; const caseEvidence = caseNo ? await getWorkspaceShippingOrderReviewEvidence(caseNo) : null;
if (generation !== caseLoadGeneration) return;
evidence.value = caseEvidence?.items || [];
// [STEP] ??????? PDF?????????????????????? // [STEP] ??????? PDF??????????????????????
clearPreview(); clearPreview();
await refreshWorkItemContext(contextConversationId, contextItemNo); await refreshWorkItemContext(contextConversationId, contextItemNo, {
expectedLoadGeneration: generation,
});
// refreshWorkItemContext ????? ref???????? ref????? load ??????????? // refreshWorkItemContext ????? ref???????? ref????? load ???????????
} catch { } catch {
if (generation !== caseLoadGeneration) return;
loadFailed.value = true; loadFailed.value = true;
reviewRun.value = null; reviewRun.value = null;
activeCase.value = null; activeCase.value = null;
@@ -894,6 +915,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
versions.value = []; versions.value = [];
statusMessage.value = null; statusMessage.value = null;
} finally { } finally {
if (generation !== caseLoadGeneration) return;
loading.value = false; loading.value = false;
} }
}; };
@@ -1235,7 +1235,9 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
}], }],
waiting_human: [], processing: [], completed: [], cancelled: [], archived: [], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
}, },
four_stage_nodes: [{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }], lifecycle_nodes: [{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }],
// 兼容字段故意给出不同值,验证适配层优先消费 lifecycle_nodes。
four_stage_nodes: [{ code: 'upload_complete', label_key: 'shipping.stage.complete', status: 'passed' }],
output_artifacts: [{ order_task_no: 'OT-API-1', filename: 'shipping.xlsx', type: 'excel', status: 'ready', action: { code: 'download_excel', enabled: true } }], output_artifacts: [{ order_task_no: 'OT-API-1', filename: 'shipping.xlsx', type: 'excel', status: 'ready', action: { code: 'download_excel', enabled: true } }],
} as unknown as ConversationProcessingProjection; } as unknown as ConversationProcessingProjection;
@@ -1247,9 +1249,10 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
expect(eml.uiState?.primary_action?.i18nKey).toBe('shipping.retry'); expect(eml.uiState?.primary_action?.i18nKey).toBe('shipping.retry');
expect(eml.aggregateChildren?.[0]?.uiState?.primary_action?.code).toBe('retry'); expect(eml.aggregateChildren?.[0]?.uiState?.primary_action?.code).toBe('retry');
expect(eml.aggregateChildren?.[0]?.sourceSummary.filename).toBe('a.pdf'); expect(eml.aggregateChildren?.[0]?.sourceSummary.filename).toBe('a.pdf');
// 批次统计、四阶段与产物均是后端事实,适配时不得从附件重算或丢失。 // 批次统计、五阶段与产物均是后端事实,适配时不得从附件重算或丢失。
expect(normalized.summary.total_files).toBe(7); expect(normalized.summary.total_files).toBe(7);
expect(normalized.four_stage_nodes).toEqual([{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }]); expect(normalized.lifecycle_nodes).toEqual([{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }]);
expect(normalized.four_stage_nodes).toEqual([{ code: 'upload_complete', label_key: 'shipping.stage.complete', status: 'passed' }]);
expect(normalized.output_artifacts?.[0]?.action.enabled).toBe(true); expect(normalized.output_artifacts?.[0]?.action.enabled).toBe(true);
}); });
@@ -946,7 +946,7 @@ export function resolveConversationProcessingFromUnified(
stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null }, stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
): ConversationProcessingProjection | null { ): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : []; const items = Array.isArray(workItems) ? workItems : [];
// [AUTHORITY] conversation_processing.status_groups 与 four_stage_nodes / ui_state // [AUTHORITY] conversation_processing.status_groups 与 lifecycle_nodes / ui_state
// 同属后端一次裁决。即使顶层 work_items 非空,也不得前端二次聚合或用旧快照覆盖。 // 同属后端一次裁决。即使顶层 work_items 非空,也不得前端二次聚合或用旧快照覆盖。
if (embedded && typeof embedded === 'object' && embedded.status_groups) { if (embedded && typeof embedded === 'object' && embedded.status_groups) {
return normalizeConversationProcessingProjection(embedded); return normalizeConversationProcessingProjection(embedded);
@@ -1035,11 +1035,11 @@ export function normalizeConversationProcessingProjection(
: null) : null)
), ),
targetLifecycleStage: ( targetLifecycleStage: (
['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes( ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
String(rawAction.targetLifecycleStage), String(rawAction.targetLifecycleStage),
) )
? rawAction.targetLifecycleStage ? rawAction.targetLifecycleStage
: (['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'].includes( : (['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
String(rawAction.target_lifecycle_stage), String(rawAction.target_lifecycle_stage),
) )
? rawAction.target_lifecycle_stage ? rawAction.target_lifecycle_stage
@@ -1192,7 +1192,8 @@ export function normalizeConversationProcessingProjection(
completed, completed,
history, history,
status_groups: normalizedGroups || projection.status_groups, status_groups: normalizedGroups || projection.status_groups,
four_stage_nodes: projection.four_stage_nodes || [], lifecycle_nodes: projection.lifecycle_nodes || projection.four_stage_nodes || [],
four_stage_nodes: projection.four_stage_nodes || projection.lifecycle_nodes || [],
unclassified_summary: projection.unclassified_summary || { count: 0 }, unclassified_summary: projection.unclassified_summary || { count: 0 },
ui_state: projection.ui_state || undefined, ui_state: projection.ui_state || undefined,
output_artifacts: projection.output_artifacts || [], output_artifacts: projection.output_artifacts || [],
@@ -1,6 +1,6 @@
/** /**
* features/chat/shipping/shippingStepper.spec.ts * features/chat/shipping/shippingStepper.spec.ts
* 用途:验证发货通知四阶段 Stepper 只消费后端 UI State 投影。 * 用途:验证发货通知五阶段 Stepper 只消费后端 UI State 投影。
* 依赖:shippingStepper 纯函数、vitest。 * 依赖:shippingStepper 纯函数、vitest。
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。 * 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
*/ */
@@ -12,19 +12,20 @@ import {
} from './shippingStepper'; } from './shippingStepper';
describe('shippingStepper', () => { describe('shippingStepper', () => {
it('renders exactly four stages from backend ui_state', () => { it('renders exactly five stages from backend ui_state', () => {
const steps = resolveShippingWorkflowSteps({ const steps = resolveShippingWorkflowSteps({
ui_state: { ui_state: {
steps: [ steps: [
{ id: 'shipping-stage-1', code: 'intake_parse', label: '接收解析', status: 'completed' }, { id: 'shipping-stage-1', code: 'intake_parse', label: '接收解析', status: 'completed' },
{ id: 'shipping-stage-2', code: 'order_review', label: '订单复核', status: 'completed' }, { id: 'shipping-stage-2', code: 'order_review', label: '订单复核', status: 'completed' },
{ id: 'shipping-stage-3', code: 'fulfillment_prep', label: '通知准备', status: 'blocked' }, { id: 'shipping-stage-3', code: 'fulfillment_prep', label: '通知准备', status: 'blocked' },
{ id: 'shipping-stage-4', code: 'upload_complete', label: '通知完成', status: 'pending' }, { id: 'shipping-stage-4', code: 'freight_upload', label: '货代上传', status: 'pending' },
{ id: 'shipping-stage-5', code: 'upload_complete', label: '通知完成', status: 'pending' },
], ],
}, },
}); });
expect(steps).toHaveLength(4); expect(steps).toHaveLength(5);
expect(steps[2]?.status).toBe('blocked'); expect(steps[2]?.status).toBe('blocked');
}); });
@@ -33,17 +34,18 @@ describe('shippingStepper', () => {
expect(normalizeShippingWorkflowSteps(null)).toEqual([]); expect(normalizeShippingWorkflowSteps(null)).toEqual([]);
}); });
it('maps technical processing stages into the four business stages', () => { it('maps technical processing stages into the five business stages', () => {
const base = normalizeShippingWorkflowSteps([ const base = normalizeShippingWorkflowSteps([
{ code: 'intake_parse', status: 'pending' }, { code: 'intake_parse', status: 'pending' },
{ code: 'order_review', status: 'pending' }, { code: 'order_review', status: 'pending' },
{ code: 'fulfillment_prep', status: 'pending' }, { code: 'fulfillment_prep', status: 'pending' },
{ code: 'freight_upload', status: 'pending' },
{ code: 'upload_complete', status: 'pending' }, { code: 'upload_complete', status: 'pending' },
]); ]);
const steps = applyShippingProcessingStageToSteps(base, { const steps = applyShippingProcessingStageToSteps(base, {
stage: 'inventory_matching', stage: 'inventory_matching',
status: 'running', status: 'running',
}); });
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending']); expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending', 'pending']);
}); });
}); });
@@ -1,8 +1,8 @@
/** /**
* features/chat/shipping/shippingStepper.ts * features/chat/shipping/shippingStepper.ts
* 用途:基于后端 ui_state 投影渲染四阶段业务 Stepper。 * 用途:基于后端 ui_state 投影渲染五阶段业务 Stepper。
* 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。 * 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。
* 逻辑:只消费后端 ui_state.steps 四阶段投影;缺失投影时 fail-closed。 * 逻辑:只消费后端 ui_state.steps 五阶段投影;缺失投影时 fail-closed。
*/ */
import { import {
FULFILLMENT_PROGRESS_NODES, FULFILLMENT_PROGRESS_NODES,
@@ -32,6 +32,7 @@ export const SHIPPING_WORKFLOW_STEP_LABELS = [
'chat.shippingNoticeUi.stage.intakeParse', 'chat.shippingNoticeUi.stage.intakeParse',
'chat.shippingNoticeUi.stage.orderReview', 'chat.shippingNoticeUi.stage.orderReview',
'chat.shippingNoticeUi.stage.fulfillmentPrep', 'chat.shippingNoticeUi.stage.fulfillmentPrep',
'chat.shippingNoticeUi.stage.freightUpload',
'chat.shippingNoticeUi.stage.uploadComplete', 'chat.shippingNoticeUi.stage.uploadComplete',
] as const; ] as const;
@@ -90,7 +91,7 @@ const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
inventory_matching: 2, inventory_matching: 2,
excel_generating: 2, excel_generating: 2,
freight_uploading: 3, freight_uploading: 3,
completed: 3, completed: 4,
}; };
/** /**
@@ -163,7 +163,7 @@ export interface ShippingProcessingPrimaryAction {
} }
/** 订单生命周期工作台的后端目标阶段。 */ /** 订单生命周期工作台的后端目标阶段。 */
export type LifecycleWorkbenchStage = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'; export type LifecycleWorkbenchStage = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
/** 文件级生命周期入口;状态、目标均由后端裁决。 */ /** 文件级生命周期入口;状态、目标均由后端裁决。 */
export interface ShippingProcessingLifecycleEntry { export interface ShippingProcessingLifecycleEntry {
@@ -678,9 +678,23 @@ export interface ConversationProcessingProjection {
cancelled: ConversationProcessingUserTask[]; cancelled: ConversationProcessingUserTask[];
archived: ConversationProcessingUserTask[]; archived: ConversationProcessingUserTask[];
}; };
/** 会话批次主进度;后端已将技术阶段折叠为四个业务节点。 */ /** 会话批次主进度;后端已将技术阶段折叠为五个业务节点。 */
lifecycle_nodes?: Array<{
code: LifecycleWorkbenchStage;
label_key: string;
status: 'passed' | 'running' | 'blocked' | 'pending';
summary?: {
total: number;
completed: number;
needs_action: number;
processing: number;
failed: number;
blocking_reason?: ShippingProcessingBlockingReason | null;
};
}>;
/** @deprecated 兼容旧客户端;当前值同 lifecycle_nodes,已包含五阶段。 */
four_stage_nodes?: Array<{ four_stage_nodes?: Array<{
code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'; code: LifecycleWorkbenchStage;
label_key: string; label_key: string;
status: 'passed' | 'running' | 'blocked' | 'pending'; status: 'passed' | 'running' | 'blocked' | 'pending';
/** 批次阶段摘要由后端按完整叶子工作项裁决,禁止页面从筛选结果反算。 */ /** 批次阶段摘要由后端按完整叶子工作项裁决,禁止页面从筛选结果反算。 */
@@ -693,7 +707,7 @@ export interface ConversationProcessingProjection {
blocking_reason?: ShippingProcessingBlockingReason | null; blocking_reason?: ShippingProcessingBlockingReason | null;
}; };
}>; }>;
/** 后端无法归类到四阶段的业务文件数量;页面只提示,不擅自归类。 */ /** 后端无法归类到五阶段的业务文件数量;页面只提示,不擅自归类。 */
unclassified_summary?: { count: number }; unclassified_summary?: { count: number };
/** 批次级用户态:状态、问题与可操作动作必须来自同一次后端裁决。 */ /** 批次级用户态:状态、问题与可操作动作必须来自同一次后端裁决。 */
ui_state?: ConversationProcessingUiState; ui_state?: ConversationProcessingUiState;
@@ -711,8 +725,8 @@ export interface ConversationProcessingProjection {
export interface ConversationProcessingUiState { export interface ConversationProcessingUiState {
status: ShippingUserProcessingStatus; status: ShippingUserProcessingStatus;
stage: string; stage: string;
/** 后端从技术节点裁决的四阶段业务编码,批次中心与工作台共同消费。 */ /** 后端从技术节点裁决的五阶段业务编码,批次中心与工作台共同消费。 */
lifecycleStage?: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'; lifecycleStage?: LifecycleWorkbenchStage;
lifecycleEntries?: ShippingProcessingLifecycleEntry[]; lifecycleEntries?: ShippingProcessingLifecycleEntry[];
blocking_reason: ShippingProcessingBlockingReason | null; blocking_reason: ShippingProcessingBlockingReason | null;
primary_action: ShippingProcessingPrimaryAction | null; primary_action: ShippingProcessingPrimaryAction | null;
@@ -1445,7 +1459,7 @@ export interface ShippingTaskUiState {
primary?: ShippingUnifiedAction | null; primary?: ShippingUnifiedAction | null;
secondary?: ShippingUnifiedAction[]; secondary?: ShippingUnifiedAction[];
}; };
/** 四阶段工作台只读事实;由后端 ui_state 投影,不参与状态或权限裁决。 */ /** 五阶段工作台只读事实;由后端 ui_state 投影,不参与状态或权限裁决。 */
stage_context?: { stage_context?: {
preparation?: { preparation?: {
status?: 'processing' | 'blocked' | 'ready' | string; status?: 'processing' | 'blocked' | 'ready' | string;
@@ -1483,6 +1497,14 @@ export interface ShippingTaskUiState {
} | null; } | null;
upload?: { upload?: {
outcome?: 'not_started' | 'running' | 'awaiting_manual' | 'succeeded' | 'failed' | 'unknown' | string; outcome?: 'not_started' | 'running' | 'awaiting_manual' | 'succeeded' | 'failed' | 'unknown' | string;
/** 仅 upload_complete 工作面读取的、后端验证过的成功上传事实。 */
succeeded_attempt?: {
id?: number | null;
status?: string | null;
mode?: string | null;
freight_ref_no?: string | null;
finished_at?: string | null;
} | null;
latest_attempt?: { latest_attempt?: {
id?: number | null; id?: number | null;
status?: string | null; status?: string | null;
@@ -2255,6 +2277,8 @@ export interface ShippingOrderReviewCaseSummary {
draft_version?: number | null; draft_version?: number | null;
issue_count: number; issue_count: number;
available_actions: string[]; available_actions: string[];
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
intake_no?: string | null;
source_run_no?: string | null; source_run_no?: string | null;
} }
@@ -2435,7 +2459,8 @@ export interface ShippingOrderReviewBuildEligibilityIssue {
} }
export interface ShippingOrderReviewBuildEligibility { export interface ShippingOrderReviewBuildEligibility {
can_build: boolean; /** 未执行校验时为 null;只有 validated/needs_review 才返回布尔结论。 */
can_build: boolean | null;
can_auto_create?: boolean; can_auto_create?: boolean;
status: string; status: string;
gates?: Record<string, boolean>; gates?: Record<string, boolean>;
@@ -2632,6 +2657,8 @@ export interface ShippingOrderReviewCase {
build_eligibility?: ShippingOrderReviewBuildEligibility; build_eligibility?: ShippingOrderReviewBuildEligibility;
} | null; } | null;
available_actions: string[]; available_actions: string[];
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
intake_no?: string | null;
/** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */ /** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */
formal_editable_field_ids?: string[]; formal_editable_field_ids?: string[];
/** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */ /** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */
@@ -2936,6 +2963,14 @@ export interface ShippingOrderReviewProfileMatchCandidate {
hard_match?: boolean | null; hard_match?: boolean | null;
reason_codes?: string[]; reason_codes?: string[];
missing_required_anchor_ids?: string[]; missing_required_anchor_ids?: string[];
/** 管理员技术详情:共同 matcher 已确认的受限平移,不含正文或完整坐标。 */
coordinate_transform?: {
status: 'applied' | 'unavailable' | 'rejected' | string;
translate_x?: number | null;
translate_y?: number | null;
anchor_ids?: string[];
reason_codes?: string[];
} | null;
} }
/** 建单前文档模板匹配只读投影。 */ /** 建单前文档模板匹配只读投影。 */
@@ -21,6 +21,7 @@ import {
retryWorkspaceShippingOrderStpAutoCreate, retryWorkspaceShippingOrderStpAutoCreate,
retryWorkspaceShippingTask, retryWorkspaceShippingTask,
retryWorkspaceShippingTaskLine, retryWorkspaceShippingTaskLine,
retryShippingNoticeIntake,
} from '@/features/chat/api/shipping.api'; } from '@/features/chat/api/shipping.api';
const { downloadWorkspaceShippingLineInventoryFileMock } = vi.hoisted(() => ({ const { downloadWorkspaceShippingLineInventoryFileMock } = vi.hoisted(() => ({
@@ -111,6 +112,7 @@ const shippingProcessingProjection = ref<Record<string, any> | null>(null);
/** 正式任务投影的请求中状态;用于覆盖 Case 先到、Projection 后到的过渡窗口。 */ /** 正式任务投影的请求中状态;用于覆盖 Case 先到、Projection 后到的过渡窗口。 */
const shippingProcessingLoading = ref(false); const shippingProcessingLoading = ref(false);
const intakeParseContext = ref<Record<string, any> | null>(null); const intakeParseContext = ref<Record<string, any> | null>(null);
const requestedCaseNo = ref<string | null>(null);
/** 每个用例必须从独立的 Case 图快照开始,避免嵌套 schema/draft 被浅拷贝污染。 */ /** 每个用例必须从独立的 Case 图快照开始,避免嵌套 schema/draft 被浅拷贝污染。 */
function createActiveCaseFixture() { function createActiveCaseFixture() {
@@ -177,6 +179,7 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
job_id: 901, job_id: 901,
case: null, case: null,
}), }),
retryShippingNoticeIntake: vi.fn().mockResolvedValue({ intake_no: 'SNI-RETRY-1', parse_status: 'queued' }),
getWorkspaceShippingTask: vi.fn().mockResolvedValue({ getWorkspaceShippingTask: vi.fn().mockResolvedValue({
task_no: 'SN-MOCK', task_no: 'SN-MOCK',
status: 'created', status: 'created',
@@ -229,7 +232,7 @@ function createReviewComposableMock() {
loadFailed: ref(false), loadFailed: ref(false),
caseSwitchLoading: ref(false), caseSwitchLoading: ref(false),
caseSwitchFailed: ref(false), caseSwitchFailed: ref(false),
requestedCaseNo: ref(null), requestedCaseNo,
saving: ref(false), saving: ref(false),
validationInProgress: ref(false), validationInProgress: ref(false),
saveFailed: ref(false), saveFailed: ref(false),
@@ -587,6 +590,7 @@ async function mountView(query: Record<string, string> = {}) {
intake_parse: '接收解析', intake_parse: '接收解析',
order_review: '订单复核', order_review: '订单复核',
fulfillment_prep: '通知准备', fulfillment_prep: '通知准备',
freight_upload: '货代上传',
upload_complete: '通知完成', upload_complete: '通知完成',
}, },
prepare: { prepare: {
@@ -665,6 +669,7 @@ async function mountView(query: Record<string, string> = {}) {
/** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */ /** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */
function resetActiveCaseFixture() { function resetActiveCaseFixture() {
activeCase.value = createActiveCaseFixture(); activeCase.value = createActiveCaseFixture();
requestedCaseNo.value = null;
shippingProcessingProjection.value = null; shippingProcessingProjection.value = null;
shippingProcessingLoading.value = false; shippingProcessingLoading.value = false;
intakeParseContext.value = null; intakeParseContext.value = null;
@@ -679,6 +684,20 @@ describe('ShippingOrderReviewView layout phase 1', () => {
reviewProgressContext.value = null; reviewProgressContext.value = null;
}); });
it('keeps the requested replacement Case when the loaded Run updates the URL', async () => {
// 关键断言:新版 Run 先到而旧 URL Case 仍在时,不能拼出 RUN-NEW + CASE-OLD。
const wrapper = await mountView({ case_no: 'CASE-OLD' });
requestedCaseNo.value = 'CASE-NEW';
reviewRun.value = {
...reviewRun.value,
run_no: 'RUN-NEW',
};
await flushPromises();
expect((wrapper.vm as any).$route.query.run_no).toBe('RUN-NEW');
expect((wrapper.vm as any).$route.query.case_no).toBe('CASE-NEW');
});
it('uses the current-task card as the only Gate action entry for every formal-OT Gate', async () => { it('uses the current-task card as the only Gate action entry for every formal-OT Gate', async () => {
activeCase.value = { activeCase.value = {
...activeCase.value, ...activeCase.value,
@@ -1031,7 +1050,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
const shell = wrapper.get('[data-testid="review-workbench-ot-shell"]'); const shell = wrapper.get('[data-testid="review-workbench-ot-shell"]');
const navigation = wrapper.get('[data-testid="review-document-navigation"]'); const navigation = wrapper.get('[data-testid="review-document-navigation"]');
// 2–4 文件不浪费一列宽度,但必须在四阶段前完成文件选择。 // 2–4 文件不浪费一列宽度,但必须在五阶段前完成文件选择。
expect(navigation.attributes('data-nav-mode')).toBe('tabs'); expect(navigation.attributes('data-nav-mode')).toBe('tabs');
expect(shell.classes()).toContain('contents'); expect(shell.classes()).toContain('contents');
expect(wrapper.html().indexOf('review-document-navigation')) expect(wrapper.html().indexOf('review-document-navigation'))
@@ -1082,6 +1101,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
lifecycleEntries: [ lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
}, },
@@ -1115,7 +1135,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
const wrapper = await mountView({ lifecycle_stage: 'order_review' }); const wrapper = await mountView({ lifecycle_stage: 'order_review' });
await flushPromises(); await flushPromises();
for (const code of ['order_review', 'fulfillment_prep', 'upload_complete']) { for (const code of ['order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete']) {
const stage = wrapper.get(`[data-testid="review-lifecycle-stage-${code}"]`); const stage = wrapper.get(`[data-testid="review-lifecycle-stage-${code}"]`);
expect(stage.findAll('button')[1].attributes('disabled')).toBeDefined(); expect(stage.findAll('button')[1].attributes('disabled')).toBeDefined();
} }
@@ -1136,6 +1156,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
}], }],
@@ -1151,6 +1172,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
}], }],
@@ -1178,6 +1200,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
}], }],
@@ -1193,6 +1216,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
}], }],
@@ -1236,6 +1260,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
}], }],
@@ -1322,6 +1347,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
}, },
@@ -1506,6 +1532,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
lifecycleEntries: [ lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
blocking_reason: null, blocking_reason: null,
@@ -1587,7 +1614,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('3'); expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('3');
expect(wrapper.find('[data-testid="review-fulfillment-prep-workspace"]').exists()).toBe(true); expect(wrapper.find('[data-testid="review-fulfillment-prep-workspace"]').exists()).toBe(true);
expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成'); expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成');
// 通知准备工作区必须属于四阶段导航的下方主区,不能仍停留在导航之前的状态摘要区。 // 通知准备工作区必须属于五阶段导航的下方主区,不能仍停留在导航之前的状态摘要区。
expect(wrapper.html().indexOf('review-lifecycle-workbench-header')) expect(wrapper.html().indexOf('review-lifecycle-workbench-header'))
.toBeLessThan(wrapper.html().indexOf('review-fulfillment-prep-workspace')); .toBeLessThan(wrapper.html().indexOf('review-fulfillment-prep-workspace'));
}); });
@@ -1760,6 +1787,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
lifecycle_entries: [ lifecycle_entries: [
{ code: 'order_review', state: 'available', target_surface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'available', target_surface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', target_surface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'current', target_surface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', target_surface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', target_surface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', target_surface: 'order_lifecycle_workbench' },
], ],
}, },
@@ -1802,7 +1830,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.get('[data-testid="review-footer-actions"]').text()).toContain('保存订单并校验'); expect(wrapper.get('[data-testid="review-footer-actions"]').text()).toContain('保存订单并校验');
}); });
it('keeps backend-authorized manual upload registration out of the upload main area', async () => { it('keeps notification completion read-only even when an obsolete manual-upload action arrives', async () => {
const originalQueue = reviewQueue.value; const originalQueue = reviewQueue.value;
try { try {
activeCase.value = { activeCase.value = {
@@ -1817,6 +1845,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'current', targetSurface: 'order_lifecycle_workbench' },
], ],
}], }],
@@ -1836,7 +1865,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
actions: { actions: {
primary: { primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true, code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
target_surface: 'upload_complete', target_surface: 'freight_upload',
target_anchor: 'manual_upload', target_anchor: 'manual_upload',
requires_confirmation: false, requires_confirmation: false,
}, },
@@ -1847,8 +1876,9 @@ describe('ShippingOrderReviewView layout phase 1', () => {
} as any); } as any);
const withAuthorization = await mountView({ lifecycle_stage: 'upload_complete' }); const withAuthorization = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises(); await flushPromises();
// Gate 写操作只在右侧“当前任务”显示;主区只保留上传事实与审计摘要。 // 完成面必须屏蔽迟到的 Gate 写操作;主区只保留验证成功事实与审计摘要。
expect(withAuthorization.find('[data-testid="review-lifecycle-upload-manual"]').exists()).toBe(false); expect(withAuthorization.find('[data-testid="review-lifecycle-upload-manual"]').exists()).toBe(false);
expect(withAuthorization.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
// 正式动作直接提交当前 Gate,不允许无界面 TaskTodoPanel 作为隐藏执行器。 // 正式动作直接提交当前 Gate,不允许无界面 TaskTodoPanel 作为隐藏执行器。
expect((withAuthorization.vm as { formalTodoPanelRef?: unknown }).formalTodoPanelRef).toBeUndefined(); expect((withAuthorization.vm as { formalTodoPanelRef?: unknown }).formalTodoPanelRef).toBeUndefined();
} finally { } finally {
@@ -1856,7 +1886,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
} }
}); });
it('opens the page-level evidence dialog when the authorized current-task action is manual upload', async () => { it('opens the page-level evidence dialog from freight upload when the current-task action is manual upload', async () => {
activeCase.value = { activeCase.value = {
...activeCase.value, ...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-UPLOAD-DIALOG', confirmed_task_id: 19, has_formal_ot: true, status: 'confirmed', confirmed_task_no: 'SN-UPLOAD-DIALOG', confirmed_task_id: 19, has_formal_ot: true,
@@ -1869,7 +1899,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
primary: { primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true, code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
dispatch: 'dialog', ui_handler: 'manual_upload_evidence', dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
target_surface: 'upload_complete', target_anchor: 'manual_upload', target_surface: 'freight_upload', target_anchor: 'manual_upload',
requires_confirmation: false, requires_confirmation: false,
}, },
secondary: [], secondary: [],
@@ -1878,7 +1908,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
}, },
} as any); } as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' }); const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
await flushPromises(); await flushPromises();
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click'); await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
await flushPromises(); await flushPromises();
@@ -1886,7 +1916,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(true); expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(true);
}); });
it('renders the authorized Excel download in every upload-complete order line instead of the task rail', async () => { it('renders the authorized Excel download in every freight-upload order line instead of the task rail', async () => {
activeCase.value = { activeCase.value = {
...activeCase.value, ...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-DOWNLOAD-DISPATCH', confirmed_task_id: 20, has_formal_ot: true, status: 'confirmed', confirmed_task_no: 'SN-DOWNLOAD-DISPATCH', confirmed_task_id: 20, has_formal_ot: true,
@@ -1926,26 +1956,26 @@ describe('ShippingOrderReviewView layout phase 1', () => {
secondary: [{ secondary: [{
code: 'download_excel', label: '下载 Excel', kind: 'view', enabled: true, code: 'download_excel', label: '下载 Excel', kind: 'view', enabled: true,
dispatch: 'view', ui_handler: 'excel_download', dispatch: 'view', ui_handler: 'excel_download',
target_surface: 'upload_complete', target_anchor: 'excel_artifact', target_surface: 'freight_upload', target_anchor: 'excel_artifact',
requires_confirmation: false, requires_confirmation: false,
}], }],
}, },
lifecycle_stage: 'upload_complete', lifecycle_stage: 'freight_upload',
lifecycle_entries: [{ code: 'upload_complete', state: 'current' }], lifecycle_entries: [{ code: 'freight_upload', state: 'current' }],
process_gate: { execution_no: 'EXEC-DOWNLOAD-DISPATCH' }, summary: {}, steps: [], process_gate: { execution_no: 'EXEC-DOWNLOAD-DISPATCH' }, summary: {}, steps: [],
}, },
} as any); } as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' }); const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
await flushPromises(); await flushPromises();
const rows = wrapper.findAll('[data-testid="review-upload-complete-line"]'); const rows = wrapper.findAll('[data-testid="review-freight-upload-line"]');
expect(rows).toHaveLength(2); expect(rows).toHaveLength(2);
expect(rows[0].text()).toContain('PN-ONE'); expect(rows[0].text()).toContain('PN-ONE');
expect(rows[1].text()).toContain('PN-TWO'); expect(rows[1].text()).toContain('PN-TWO');
expect(wrapper.find('[data-testid="review-current-task-recovery-download_excel"]').exists()).toBe(false); expect(wrapper.find('[data-testid="review-current-task-recovery-download_excel"]').exists()).toBe(false);
await wrapper.get('[data-testid="review-upload-complete-download-LINE-1"]').trigger('click'); await wrapper.get('[data-testid="review-freight-upload-download-LINE-1"]').trigger('click');
await flushPromises(); await flushPromises();
// 下载是 Artifact 只读操作;订单行不按 PO 聚合,且不得伪装成 Gate mutation。 // 下载是 Artifact 只读操作;订单行不按 PO 聚合,且不得伪装成 Gate mutation。
@@ -1969,6 +1999,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' }, { code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }, { code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' }, { code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
], ],
}], }],
@@ -2103,6 +2134,104 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="review-lifecycle-upload-download"]').exists()).toBe(false); expect(wrapper.find('[data-testid="review-lifecycle-upload-download"]').exists()).toBe(false);
}); });
it('retries the server-authorized failed Intake from the current lifecycle card and refreshes projections', async () => {
const originalQueue = reviewQueue.value;
try {
activeCase.value = {
...activeCase.value,
available_actions: ['retry_parse'],
intake_no: 'SNI-RETRY-1',
};
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'intake_parse',
lifecycle_entries: [],
intake_parse_authorized: true,
available_actions: ['retry_parse'],
intake_no: 'SNI-RETRY-1',
}],
};
const wrapper = await mountView({ lifecycle_stage: 'intake_parse' });
// 关键断言:已发送 EML 的恢复从当前阶段卡执行,并且使用服务端下发的原 SNI。
await wrapper.get('[data-testid="review-lifecycle-stage-retry-parse"]').trigger('click');
await flushPromises();
expect(retryShippingNoticeIntake).toHaveBeenCalledWith('SNI-RETRY-1');
expect(reloadLatestDraftMock).toHaveBeenCalled();
expect(refreshShippingProcessingMock).toHaveBeenCalled();
} finally {
reviewQueue.value = originalQueue;
}
});
it('does not show intake retry while parsing or after cancellation', async () => {
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0], lifecycle_stage: 'intake_parse', lifecycle_entries: [], intake_parse_authorized: true,
}],
};
for (const status of ['parsing', 'cancelled']) {
activeCase.value = { ...activeCase.value, status, available_actions: [], intake_no: null };
const wrapper = await mountView({ lifecycle_stage: 'intake_parse' });
// 关键断言:运行中等待超时回收,取消态不可复活,均无 retry_parse 入口。
expect(wrapper.find('[data-testid="review-lifecycle-stage-retry-parse"]').exists()).toBe(false);
}
} finally {
reviewQueue.value = originalQueue;
}
});
it('renders completion evidence only from the verified succeeded attempt', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-VERIFIED-EVIDENCE', confirmed_task_id: 22, has_formal_ot: true,
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-VERIFIED-EVIDENCE', status: 'completed', upload_status: 'uploaded', lines: [], events: [],
ui_state: {
lifecycle_stage: 'upload_complete',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available' },
{ code: 'order_review', state: 'available' },
{ code: 'fulfillment_prep', state: 'available' },
{ code: 'freight_upload', state: 'available' },
{ code: 'upload_complete', state: 'current' },
],
actions: {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
},
secondary: [],
},
stage_context: {
upload: {
latest_attempt: { status: 'failed', mode: 'rpa', freight_ref_no: 'LATEST-FAILED' },
succeeded_attempt: { status: 'succeeded', mode: 'manual', freight_ref_no: 'VERIFIED-REF' },
},
},
summary: {}, steps: [],
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises();
const evidence = wrapper.get('[data-testid="review-lifecycle-upload-complete"]');
expect(evidence.text()).toContain('VERIFIED-REF');
expect(evidence.text()).toContain('succeeded');
expect(evidence.text()).not.toContain('LATEST-FAILED');
expect(evidence.text()).not.toContain('failed');
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
});
it('renders empty optional schema fields as editable line columns', async () => { it('renders empty optional schema fields as editable line columns', async () => {
const wrapper = await mountView(); const wrapper = await mountView();
const inputs = wrapper.findAll('[data-testid="review-line-field-input"]'); const inputs = wrapper.findAll('[data-testid="review-line-field-input"]');
@@ -1,6 +1,6 @@
<!-- <!--
features/chat/views/ShippingOrderReviewView.vue features/chat/views/ShippingOrderReviewView.vue
用途:建单前/正式任务「订单生命周期工作台」(主编辑区 + 四阶段导航 + 工作台侧栏 + workbenchMode)。 用途:建单前/正式任务「订单生命周期工作台」(主编辑区 + 五阶段导航 + 工作台侧栏 + workbenchMode)。
依赖:路由参数、useShippingOrderReview、ReviewWorkbenchHeader/Footer、ReviewDocumentNavigation、 依赖:路由参数、useShippingOrderReview、ReviewWorkbenchHeader/Footer、ReviewDocumentNavigation、
ReviewProcessDetailDrawer、ReviewUnsavedSwitchDialog、 ReviewProcessDetailDrawer、ReviewUnsavedSwitchDialog、
ReviewWorkbenchModeToggle、ReviewDocumentEvidenceDrawer、ReviewVersionHistoryDrawer、 ReviewWorkbenchModeToggle、ReviewDocumentEvidenceDrawer、ReviewVersionHistoryDrawer、
@@ -31,6 +31,7 @@ import {
retryWorkspaceShippingOrderStpAutoCreate, retryWorkspaceShippingOrderStpAutoCreate,
retryWorkspaceShippingTask, retryWorkspaceShippingTask,
retryWorkspaceShippingTaskLine, retryWorkspaceShippingTaskLine,
retryShippingNoticeIntake,
decideWorkspaceShippingOrderReviewLineFulfillment, decideWorkspaceShippingOrderReviewLineFulfillment,
viewWorkspaceShippingOrderReviewHighlightDiagnostic, viewWorkspaceShippingOrderReviewHighlightDiagnostic,
} from '../api/shipping.api'; } from '../api/shipping.api';
@@ -217,6 +218,7 @@ const LIFECYCLE_STAGE_CODES: ReviewLifecycleStageCode[] = [
'intake_parse', 'intake_parse',
'order_review', 'order_review',
'fulfillment_prep', 'fulfillment_prep',
'freight_upload',
'upload_complete', 'upload_complete',
]; ];
@@ -322,7 +324,40 @@ const isLifecycleIntakeParse = computed(() => (
lifecycleActiveStageCode.value === 'intake_parse' && intakeParseContextAuthorized.value lifecycleActiveStageCode.value === 'intake_parse' && intakeParseContextAuthorized.value
)); ));
const isLifecycleFulfillmentPrep = computed(() => lifecycleActiveStageCode.value === 'fulfillment_prep'); const isLifecycleFulfillmentPrep = computed(() => lifecycleActiveStageCode.value === 'fulfillment_prep');
const isLifecycleFreightUpload = computed(() => lifecycleActiveStageCode.value === 'freight_upload');
const isLifecycleUploadComplete = computed(() => lifecycleActiveStageCode.value === 'upload_complete'); const isLifecycleUploadComplete = computed(() => lifecycleActiveStageCode.value === 'upload_complete');
/** 当前阶段重试只取 Case 的服务端授权,不从输入框附件卡或本地状态推断。 */
const intakeParseRetryAvailable = computed(() => (
isLifecycleIntakeParse.value
&& (activeCase.value?.available_actions || []).includes('retry_parse')
&& Boolean(String(activeCase.value?.intake_no || '').trim())
));
const intakeParseRetrying = ref(false);
/**
* 对已发送文件重投原 Intake 的解析任务。
* 成功后同步 Case、统一处理投影并重新读取 Intake 上下文;后端状态会转为 queued,
* 原有 polling 会继续推进,运行中不再展示 retry_parse。
*/
async function retryCurrentIntakeParse(): Promise<void> {
const intakeNo = String(activeCase.value?.intake_no || '').trim();
if (!intakeParseRetryAvailable.value || !intakeNo || intakeParseRetrying.value) return;
intakeParseRetrying.value = true;
try {
await retryShippingNoticeIntake(intakeNo);
await Promise.all([
reloadLatestDraft(),
refreshShippingProcessing(),
activeCase.value?.case_no
? ensureIntakeParseContextLoaded(activeCase.value.case_no)
: Promise.resolve(false),
]);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingNoticeRetryParse'));
} finally {
intakeParseRetrying.value = false;
}
}
/** /**
* 只切换前端工作面并同步可分享深链;禁止在导航点击中修改任何订单生命周期字段。 * 只切换前端工作面并同步可分享深链;禁止在导航点击中修改任何订单生命周期字段。
@@ -508,10 +543,10 @@ const formalTaskActions = computed(() => {
}); });
/** /**
* 通知完成明细的只读 Excel 动作。 * 货代上传工作面的 Excel 下载动作。
* *
* Artifact 下载由后端 ui_state.actions 授权;它属于订单行结果表的行内操作, * Artifact 下载由后端 ui_state.actions 授权;它属于货代上传工作面,
* 不与右侧当前任务的 Gate 动作混排。每个行入口下载同一正式任务已校验的 Excel。 * 不与只读成功证据或右侧当前任务 Gate 动作混排。
*/ */
const uploadCompletionExcelDownloadAction = computed(() => formalTaskActions.value.find((action) => ( const uploadCompletionExcelDownloadAction = computed(() => formalTaskActions.value.find((action) => (
action.enabled action.enabled
@@ -573,6 +608,22 @@ const currentTaskRecoveryActions = computed(() => {
})).filter((action) => action.code) })).filter((action) => action.code)
}); });
/**
* 已验证的通知完成面只展示成功证据,不能因迟到或历史 Gate 动作再次提供写入口。
* 核心逻辑:货代上传工作面仍原样消费后端授权动作;完成面只把动作降为只读,
* 不修改服务端授权,也不根据客户端状态推导新的操作。
* @returns 当前工作面允许交给 ReviewCurrentProcessingCard 展示的动作。
*/
const visibleCurrentTaskPrimaryAction = computed(() => (
isLifecycleUploadComplete.value ? null : currentTaskPrimaryAction.value
));
const visibleCurrentTaskRecoveryActions = computed(() => (
isLifecycleUploadComplete.value ? [] : currentTaskRecoveryActions.value
));
const visibleCurrentTaskRetryable = computed(() => (
isLifecycleUploadComplete.value ? false : currentTaskRetryable.value
));
/** 管理员诊断:后端 technical_progress / automation.technical 仅 admin 投影。 */ /** 管理员诊断:后端 technical_progress / automation.technical 仅 admin 投影。 */
const showAdminTaskMissingDiagnosis = computed(() => ( const showAdminTaskMissingDiagnosis = computed(() => (
Boolean(displayCase.value?.task_missing) Boolean(displayCase.value?.task_missing)
@@ -1898,7 +1949,7 @@ const showWorkbenchGrid = computed(
const headerSchemaFields = computed(() => (displayCase.value?.schema.fields || []).filter((field) => field.scope === 'header')); const headerSchemaFields = computed(() => (displayCase.value?.schema.fields || []).filter((field) => field.scope === 'header'));
const lineSchemaFields = computed(() => (displayCase.value?.schema.fields || []).filter((field) => field.scope === 'line')); const lineSchemaFields = computed(() => (displayCase.value?.schema.fields || []).filter((field) => field.scope === 'line'));
/** 通知完成仅展示订单行的核心识别字段,字段值始终按当前行的 line_key 读取。 */ /** 货代上传仅展示订单行的核心识别字段,字段值始终按当前行的 line_key 读取。 */
const uploadCompletionLineFields = computed(() => { const uploadCompletionLineFields = computed(() => {
const codes = ['line_no', 'part_number', 'quantity']; const codes = ['line_no', 'part_number', 'quantity'];
return codes.map((code) => lineSchemaFields.value.find((field) => field.field_code === code)) return codes.map((code) => lineSchemaFields.value.find((field) => field.field_code === code))
@@ -2106,7 +2157,7 @@ async function retryFormalPreparationLine(lineKey: string) {
} }
/** /**
* 人工上传登记是后端 Gate 的受控写动作;仅进入「通知完成」工作面不构成授权。 * 人工上传登记是后端 Gate 的受控写动作;仅进入「货代上传」工作面不构成授权。
* 任务详情与批次中心共用 ui_state.actions,避免页面按上传状态或生命周期自行放行。 * 任务详情与批次中心共用 ui_state.actions,避免页面按上传状态或生命周期自行放行。
*/ */
const manualUploadRegistrationAuthorized = computed(() => { const manualUploadRegistrationAuthorized = computed(() => {
@@ -3308,6 +3359,7 @@ watch(
if (resolvedRunNo && resolvedRunNo !== runNo.value) { if (resolvedRunNo && resolvedRunNo !== runNo.value) {
const resolvedCaseNo = String( const resolvedCaseNo = String(
pendingCrossRunCaseNo.value pendingCrossRunCaseNo.value
|| requestedCaseNo.value
|| route.query.case_no || route.query.case_no
|| route.query.case || route.query.case
|| activeCase.value?.case_no || activeCase.value?.case_no
@@ -3464,8 +3516,11 @@ watch(
<ReviewLifecycleStageNavigation <ReviewLifecycleStageNavigation
:stages="lifecycleStageItems" :stages="lifecycleStageItems"
:active-code="lifecycleActiveStageCode" :active-code="lifecycleActiveStageCode"
:available-actions="activeCase?.available_actions || []"
:retrying="intakeParseRetrying"
@select="(code) => { void selectLifecycleStage(code); }" @select="(code) => { void selectLifecycleStage(code); }"
@open-detail="() => { processDetailOpen = true; }" @open-detail="() => { processDetailOpen = true; }"
@retry-parse="() => void retryCurrentIntakeParse()"
/> />
</div> </div>
</div> </div>
@@ -3543,11 +3598,11 @@ watch(
:automation="displayCase?.automation" :automation="displayCase?.automation"
:show-retry="showObjectRetryOnRail" :show-retry="showObjectRetryOnRail"
:user-status="currentTaskUserStatus" :user-status="currentTaskUserStatus"
:retryable="currentTaskRetryable" :retryable="visibleCurrentTaskRetryable"
:blocking-reason="currentTaskBlockingReason" :blocking-reason="currentTaskBlockingReason"
:gate-status="currentTaskGateStatus" :gate-status="currentTaskGateStatus"
:primary-action="currentTaskPrimaryAction" :primary-action="visibleCurrentTaskPrimaryAction"
:recovery-actions="currentTaskRecoveryActions" :recovery-actions="visibleCurrentTaskRecoveryActions"
:retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading" :retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading"
:loading="caseContentSkeleton || formalTaskProjectionPending" :loading="caseContentSkeleton || formalTaskProjectionPending"
@retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())" @retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"
@@ -3642,14 +3697,14 @@ watch(
</section> </section>
<section <section
v-if="hasCreatedShippingTask && formalTaskDetail && isLifecycleUploadComplete" v-if="hasCreatedShippingTask && formalTaskDetail && isLifecycleFreightUpload"
class="rounded-xl border border-default bg-surface p-3" class="rounded-xl border border-default bg-surface p-3"
data-testid="review-lifecycle-upload-complete" data-testid="review-lifecycle-freight-upload"
> >
<div class="flex flex-wrap items-start justify-between gap-3"> <div class="flex flex-wrap items-start justify-between gap-3">
<div> <div>
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.upload.title') }}</h2> <h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.upload.subtitle') }}</p> <p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.subtitle') }}</p>
</div> </div>
<span class="rounded-full bg-surface-muted px-2 py-1 text-xs text-secondary">{{ formalTaskDetail.upload_status || '-' }}</span> <span class="rounded-full bg-surface-muted px-2 py-1 text-xs text-secondary">{{ formalTaskDetail.upload_status || '-' }}</span>
</div> </div>
@@ -3658,7 +3713,7 @@ watch(
<p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt" class="mt-1">{{ t('chat.shippingOrderReview.lifecycle.upload.attempt', { status: formalTaskDetail.ui_state.stage_context.upload.latest_attempt.status || '-', mode: formalTaskDetail.ui_state.stage_context.upload.latest_attempt.mode || '-' }) }}</p> <p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt" class="mt-1">{{ t('chat.shippingOrderReview.lifecycle.upload.attempt', { status: formalTaskDetail.ui_state.stage_context.upload.latest_attempt.status || '-', mode: formalTaskDetail.ui_state.stage_context.upload.latest_attempt.mode || '-' }) }}</p>
<p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt?.error_code" class="mt-1 text-rose-700 dark:text-rose-300">{{ formalTaskDetail.ui_state.stage_context.upload.latest_attempt.error_code }}</p> <p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt?.error_code" class="mt-1 text-rose-700 dark:text-rose-300">{{ formalTaskDetail.ui_state.stage_context.upload.latest_attempt.error_code }}</p>
</div> </div>
<div v-if="displayDraftLines.length" class="mt-3 overflow-x-auto" data-testid="review-upload-complete-lines"> <div v-if="displayDraftLines.length" class="mt-3 overflow-x-auto" data-testid="review-freight-upload-lines">
<table class="min-w-full text-left text-xs"> <table class="min-w-full text-left text-xs">
<thead class="border-b border-default bg-surface-muted/50 text-secondary"> <thead class="border-b border-default bg-surface-muted/50 text-secondary">
<tr> <tr>
@@ -3673,7 +3728,7 @@ watch(
v-for="line in displayDraftLines" v-for="line in displayDraftLines"
:key="String(line.line_key)" :key="String(line.line_key)"
class="border-b border-default last:border-0" class="border-b border-default last:border-0"
data-testid="review-upload-complete-line" data-testid="review-freight-upload-line"
> >
<td class="px-3 py-2 font-medium text-primary">{{ processDetailPoNumber || '—' }}</td> <td class="px-3 py-2 font-medium text-primary">{{ processDetailPoNumber || '—' }}</td>
<td v-for="field in uploadCompletionLineFields" :key="field.field_id" class="px-3 py-2">{{ lineFieldDisplayValue(line, field) || '—' }}</td> <td v-for="field in uploadCompletionLineFields" :key="field.field_id" class="px-3 py-2">{{ lineFieldDisplayValue(line, field) || '—' }}</td>
@@ -3683,7 +3738,7 @@ watch(
v-if="uploadCompletionExcelDownloadAction" v-if="uploadCompletionExcelDownloadAction"
type="button" type="button"
class="rounded border border-brand-200 px-2 py-1 font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50 dark:border-brand-800 dark:text-brand-200 dark:hover:bg-brand-950/40" class="rounded border border-brand-200 px-2 py-1 font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50 dark:border-brand-800 dark:text-brand-200 dark:hover:bg-brand-950/40"
:data-testid="`review-upload-complete-download-${line.line_key}`" :data-testid="`review-freight-upload-download-${line.line_key}`"
:disabled="saving" :disabled="saving"
@click="void executeFormalTaskAction(uploadCompletionExcelDownloadAction, {})" @click="void executeFormalTaskAction(uploadCompletionExcelDownloadAction, {})"
> >
@@ -3696,6 +3751,19 @@ watch(
</div> </div>
</section> </section>
<section
v-if="hasCreatedShippingTask && formalTaskDetail && isLifecycleUploadComplete"
class="rounded-xl border border-emerald-200 bg-emerald-50/40 p-3 dark:border-emerald-900 dark:bg-emerald-950/20"
data-testid="review-lifecycle-upload-complete"
>
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.subtitle') }}</p>
<div class="mt-3 rounded-lg border border-emerald-200 bg-surface/70 p-3 text-xs text-secondary dark:border-emerald-900">
<p>{{ t('chat.shippingOrderReview.lifecycle.upload.receipt', { value: formalTaskDetail.ui_state?.stage_context?.upload?.succeeded_attempt?.freight_ref_no || '-' }) }}</p>
<p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.succeeded_attempt" class="mt-1">{{ t('chat.shippingOrderReview.lifecycle.upload.attempt', { status: formalTaskDetail.ui_state.stage_context.upload.succeeded_attempt.status || '-', mode: formalTaskDetail.ui_state.stage_context.upload.succeeded_attempt.mode || '-' }) }}</p>
</div>
</section>
<ReviewIntakeParsePanel <ReviewIntakeParsePanel
v-if="isLifecycleIntakeParse" v-if="isLifecycleIntakeParse"
:context="intakeParseContext" :context="intakeParseContext"
@@ -4138,11 +4206,11 @@ watch(
:has-formal-ot="shippingProcessingProjection?.hasFormalOt ?? hasFormalOt" :has-formal-ot="shippingProcessingProjection?.hasFormalOt ?? hasFormalOt"
:shipping-notice-no="shippingProcessingProjection?.shippingNoticeNo ?? confirmedNoticeTaskNo" :shipping-notice-no="shippingProcessingProjection?.shippingNoticeNo ?? confirmedNoticeTaskNo"
:user-status="currentTaskUserStatus" :user-status="currentTaskUserStatus"
:retryable="currentTaskRetryable" :retryable="visibleCurrentTaskRetryable"
:blocking-reason="currentTaskBlockingReason" :blocking-reason="currentTaskBlockingReason"
:gate-status="currentTaskGateStatus" :gate-status="currentTaskGateStatus"
:primary-action="currentTaskPrimaryAction" :primary-action="visibleCurrentTaskPrimaryAction"
:recovery-actions="currentTaskRecoveryActions" :recovery-actions="visibleCurrentTaskRecoveryActions"
:retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading" :retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading"
:loading="caseContentSkeleton || formalTaskProjectionPending" :loading="caseContentSkeleton || formalTaskProjectionPending"
@retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())" @retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"
@@ -162,10 +162,11 @@ function toItem(
actionCode: code, actionCode: code,
labelKey, labelKey,
targetLifecycleStage: ( targetLifecycleStage: (
targetLifecycleStage === 'intake_parse' targetLifecycleStage === 'intake_parse'
|| targetLifecycleStage === 'order_review' || targetLifecycleStage === 'order_review'
|| targetLifecycleStage === 'fulfillment_prep' || targetLifecycleStage === 'fulfillment_prep'
|| targetLifecycleStage === 'upload_complete' || targetLifecycleStage === 'freight_upload'
|| targetLifecycleStage === 'upload_complete'
) ? targetLifecycleStage : null, ) ? targetLifecycleStage : null,
}; };
} }
@@ -1,6 +1,6 @@
<!-- <!--
features/shipping-progress/components/WorkbenchProgressGrouped.vue features/shipping-progress/components/WorkbenchProgressGrouped.vue
用途:任务台四阶段进度——接收解析 / 订单复核 / 通知准备 / 通知完成;可选动作栏。 用途:任务台五阶段进度——接收解析 / 订单复核 / 通知准备 / 货代上传 / 通知完成;可选动作栏。
依赖:vue-i18n、ShippingProcessingProjection、UnifiedProgressTrack、UnifiedActionBar。 依赖:vue-i18n、ShippingProcessingProjection、UnifiedProgressTrack、UnifiedActionBar。
逻辑:由 ShippingTaskWorkbench 挂载;任务台履约动作归 TaskTodoPanel,默认关闭本组件动作栏(UI-05)。 逻辑:由 ShippingTaskWorkbench 挂载;任务台履约动作归 TaskTodoPanel,默认关闭本组件动作栏(UI-05)。
--> -->
@@ -14,8 +14,8 @@ import type { ActionPresentationItem } from '../types';
import UnifiedActionBar from './UnifiedActionBar.vue'; import UnifiedActionBar from './UnifiedActionBar.vue';
import UnifiedProgressTrack from './UnifiedProgressTrack.vue'; import UnifiedProgressTrack from './UnifiedProgressTrack.vue';
type FourStageNode = { type LifecycleNode = {
code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'; code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
status: 'passed' | 'running' | 'blocked' | 'pending'; status: 'passed' | 'running' | 'blocked' | 'pending';
}; };
@@ -23,10 +23,12 @@ const props = withDefaults(defineProps<{
projection: ShippingProcessingProjection; projection: ShippingProcessingProjection;
/** 是否渲染投影动作栏;任务台内嵌时应为 false,避免与 TaskTodoPanel 双入口。 */ /** 是否渲染投影动作栏;任务台内嵌时应为 false,避免与 TaskTodoPanel 双入口。 */
showActions?: boolean; showActions?: boolean;
/** 是否允许展开技术 15 节点;批次中心只展示业务四阶段。 */ /** 是否允许展开技术 15 节点;批次中心只展示业务五阶段。 */
showTechnicalDetail?: boolean; showTechnicalDetail?: boolean;
/** 后端已折叠的四阶段节点;缺失时 fail-closed,不从 15 阶重算。 */ /** 后端已折叠的五阶段节点;缺失时 fail-closed,不从 15 阶重算。 */
fourStageNodes?: FourStageNode[] | null; lifecycleNodes?: LifecycleNode[] | null;
/** @deprecated 一次发布兼容旧调用方;值与 lifecycleNodes 相同,后者存在时优先。 */
fourStageNodes?: LifecycleNode[] | null;
}>(), { }>(), {
showActions: true, showActions: true,
showTechnicalDetail: true, showTechnicalDetail: true,
@@ -41,15 +43,20 @@ const showDetailTrack = ref(false);
const projectionRef = computed(() => props.projection); const projectionRef = computed(() => props.projection);
const actionPresentation = useProcessingActionPresentation(projectionRef, { surface: 'workbench' }); const actionPresentation = useProcessingActionPresentation(projectionRef, { surface: 'workbench' });
const DOMAIN_LABELS: Record<FourStageNode['code'], string> = { const DOMAIN_LABELS: Record<LifecycleNode['code'], string> = {
intake_parse: '接收解析', intake_parse: '接收解析',
order_review: '订单复核', order_review: '订单复核',
fulfillment_prep: '通知准备', fulfillment_prep: '通知准备',
freight_upload: '货代上传',
upload_complete: '通知完成', upload_complete: '通知完成',
}; };
// 四阶段是后端从正式 Gate/work_items 裁决后的业务投影;这里不再由 15 阶技术节点聚合。 // 五阶段是后端从正式 Gate/work_items 裁决后的业务投影;这里不再由 15 阶技术节点聚合。
const domainSummaries = computed(() => Array.isArray(props.fourStageNodes) ? props.fourStageNodes : []); const domainSummaries = computed(() => (
Array.isArray(props.lifecycleNodes)
? props.lifecycleNodes
: (Array.isArray(props.fourStageNodes) ? props.fourStageNodes : [])
));
/** /**
* 判断某域是否为当前/已过/未到。 * 判断某域是否为当前/已过/未到。
@@ -57,7 +64,7 @@ const domainSummaries = computed(() => Array.isArray(props.fourStageNodes) ? pro
/** /**
* 域标签样式。 * 域标签样式。
*/ */
function domainClass(state: FourStageNode['status']): string { function domainClass(state: LifecycleNode['status']): string {
if (state === 'passed') return 'border-emerald-200 bg-emerald-50 text-emerald-800'; if (state === 'passed') return 'border-emerald-200 bg-emerald-50 text-emerald-800';
if (state === 'blocked') return 'border-amber-300 bg-amber-50 text-amber-900'; if (state === 'blocked') return 'border-amber-300 bg-amber-50 text-amber-900';
if (state === 'running') return 'border-brand-300 bg-brand-50 text-brand-800'; if (state === 'running') return 'border-brand-300 bg-brand-50 text-brand-800';
@@ -82,7 +89,7 @@ const currentStageLabel = computed(() => {
当前阶段:{{ currentStageLabel }} 当前阶段:{{ currentStageLabel }}
</div> </div>
<div class="grid gap-2 sm:grid-cols-4" data-testid="workbench-four-stage-track"> <div class="grid gap-2 sm:grid-cols-5" data-testid="workbench-lifecycle-track">
<div <div
v-for="domain in domainSummaries" v-for="domain in domainSummaries"
:key="domain.code" :key="domain.code"
@@ -180,32 +180,34 @@ describe('shipping progress presenters', () => {
const wrapper = mount(WorkbenchProgressGrouped, { const wrapper = mount(WorkbenchProgressGrouped, {
props: { props: {
projection, projection,
fourStageNodes: [ lifecycleNodes: [
{ code: 'intake_parse', status: 'passed' }, { code: 'intake_parse', status: 'passed' },
{ code: 'order_review', status: 'blocked' }, { code: 'order_review', status: 'blocked' },
{ code: 'fulfillment_prep', status: 'pending' }, { code: 'fulfillment_prep', status: 'pending' },
{ code: 'freight_upload', status: 'pending' },
{ code: 'upload_complete', status: 'pending' }, { code: 'upload_complete', status: 'pending' },
], ],
}, },
global: { plugins: [i18n] }, global: { plugins: [i18n] },
}); });
expect(wrapper.find('[data-testid="workbench-progress-grouped"]').exists()).toBe(true); expect(wrapper.find('[data-testid="workbench-progress-grouped"]').exists()).toBe(true);
expect(wrapper.findAll('[data-domain]').length).toBe(4); expect(wrapper.findAll('[data-domain]').length).toBe(5);
}); });
it('uses backend four-stage nodes instead of the current technical stage', () => { it('uses backend five-stage nodes instead of the current technical stage', () => {
const blockedProjection = { const blockedProjection = {
...projection, ...projection,
// stage 仍是早期解析节点;四阶段态必须以服务端折叠节点为准。 // stage 仍是早期解析节点;五阶段态必须以服务端折叠节点为准。
stage: 'document_parsing', stage: 'document_parsing',
}; };
const wrapper = mount(WorkbenchProgressGrouped, { const wrapper = mount(WorkbenchProgressGrouped, {
props: { props: {
projection: blockedProjection, projection: blockedProjection,
fourStageNodes: [ lifecycleNodes: [
{ code: 'intake_parse', status: 'passed' }, { code: 'intake_parse', status: 'passed' },
{ code: 'order_review', status: 'passed' }, { code: 'order_review', status: 'passed' },
{ code: 'fulfillment_prep', status: 'blocked' }, { code: 'fulfillment_prep', status: 'blocked' },
{ code: 'freight_upload', status: 'pending' },
{ code: 'upload_complete', status: 'pending' }, { code: 'upload_complete', status: 'pending' },
], ],
}, },
@@ -214,4 +216,26 @@ describe('shipping progress presenters', () => {
expect(wrapper.get('[data-domain="fulfillment_prep"]').attributes('data-state')).toBe('blocked'); expect(wrapper.get('[data-domain="fulfillment_prep"]').attributes('data-state')).toBe('blocked');
expect(wrapper.get('[data-domain="intake_parse"]').attributes('data-state')).toBe('passed'); expect(wrapper.get('[data-domain="intake_parse"]').attributes('data-state')).toBe('passed');
}); });
it('prefers lifecycle nodes and falls back to the one-release compatibility field', () => {
const preferred = mount(WorkbenchProgressGrouped, {
props: {
projection,
lifecycleNodes: [{ code: 'freight_upload', status: 'running' }],
fourStageNodes: [{ code: 'upload_complete', status: 'passed' }],
},
global: { plugins: [i18n] },
});
expect(preferred.find('[data-domain="freight_upload"]').exists()).toBe(true);
expect(preferred.find('[data-domain="upload_complete"]').exists()).toBe(false);
const fallback = mount(WorkbenchProgressGrouped, {
props: {
projection,
fourStageNodes: [{ code: 'freight_upload', status: 'running' }],
},
global: { plugins: [i18n] },
});
expect(fallback.find('[data-domain="freight_upload"]').exists()).toBe(true);
});
}); });
@@ -3,7 +3,7 @@
* 用途:发货「任务中心」壳——Pending|Processing|Done + 识别 Run 续办表;列表入口 + STP 重试。 * 用途:发货「任务中心」壳——Pending|Processing|Done + 识别 Run 续办表;列表入口 + STP 重试。
* 依赖:shipping-tasks.api(my-todos)、shipping.api(详情/STP retry)、ShippingRunProgressTable、 * 依赖:shipping-tasks.api(my-todos)、shipping.api(详情/STP retry)、ShippingRunProgressTable、
* useShippingTodoBadge、useMessage、shippingProcessingLabels。 * useShippingTodoBadge、useMessage、shippingProcessingLabels。
* 逻辑:选中项展示入口卡 + 四阶段筛选 + 统一进度紧凑摘要;主按钮深链「订单生命周期工作台」; * 逻辑:选中项展示入口卡 + 五阶段筛选 + 统一进度紧凑摘要;主按钮深链「订单生命周期工作台」;
* review_case 在 failed/manual_fallback 时提供「重试自动推进」(与底栏同一 API/幂等键); * review_case 在 failed/manual_fallback 时提供「重试自动推进」(与底栏同一 API/幂等键);
* 不内嵌 ShippingTaskWorkbench;生命周期筛选、禁用与深链只消费后端 * 不内嵌 ShippingTaskWorkbench;生命周期筛选、禁用与深链只消费后端
* ui_state.lifecycle_entries,Intake parse_status 仅用于解析任务轮询。 * ui_state.lifecycle_entries,Intake parse_status 仅用于解析任务轮询。
@@ -78,11 +78,12 @@ const { refreshShippingTodoBadge } = useShippingTodoBadge();
const surface = ref<'todos' | 'runs'>('todos'); const surface = ref<'todos' | 'runs'>('todos');
const bucket = ref<'pending' | 'processing' | 'done'>('pending'); const bucket = ref<'pending' | 'processing' | 'done'>('pending');
const filterTodoCategory = ref<'all' | 'review' | 'exception' | 'manual_upload' | 'intake_parse'>('all'); const filterTodoCategory = ref<'all' | 'review' | 'exception' | 'manual_upload' | 'intake_parse'>('all');
type LifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'; type LifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'freight_upload' | 'upload_complete';
const LIFECYCLE_STAGES: LifecycleStageCode[] = [ const LIFECYCLE_STAGES: LifecycleStageCode[] = [
'intake_parse', 'intake_parse',
'order_review', 'order_review',
'fulfillment_prep', 'fulfillment_prep',
'freight_upload',
'upload_complete', 'upload_complete',
]; ];
const lifecycleStageFilter = ref<'all' | LifecycleStageCode>('all'); const lifecycleStageFilter = ref<'all' | LifecycleStageCode>('all');
@@ -1,6 +1,6 @@
/** /**
* features/workspace/shipping-task-center/ShippingTaskWorkbench.vue * features/workspace/shipping-task-center/ShippingTaskWorkbench.vue
* 用途:发货任务处理主区——当前待办栏、四阶段进度、最后活动/终止原因、STP 事实、订单概览、时间线。 * 用途:发货任务处理主区——当前待办栏、五阶段进度、最后活动/终止原因、STP 事实、订单概览、时间线。
* 依赖:TaskTodoPanel、StpProgressFactsPanel、TaskProgressTimeline、ShippingTaskParsedResultCard、 * 依赖:TaskTodoPanel、StpProgressFactsPanel、TaskProgressTimeline、ShippingTaskParsedResultCard、
* useShippingProcessingWorkItem、ShippingWorkflowStepper、listWorkspaceShippingTaskAuditTimeline。 * useShippingProcessingWorkItem、ShippingWorkflowStepper、listWorkspaceShippingTaskAuditTimeline。
* 逻辑:由 ShippingTaskCenterPage 选中任务后挂载;OT 身份取 detail.order_task_no(禁止 WorkflowItem); * 逻辑:由 ShippingTaskCenterPage 选中任务后挂载;OT 身份取 detail.order_task_no(禁止 WorkflowItem);
+9
View File
@@ -3680,6 +3680,15 @@
"noIssues": "No blocking configuration issue.", "noIssues": "No blocking configuration issue.",
"currentConfiguration": "Current configuration", "currentConfiguration": "Current configuration",
"tableRegionSettings": "Line table settings", "tableRegionSettings": "Line table settings",
"coordinateModelTitle": "Coordinate value model",
"coordinateModelHint": "Legacy frozen absolute coordinates are used by default. Enable this only for bounded translation with stable static anchors.",
"coordinateModelType": "Coordinate model",
"coordinateModelLegacy": "Legacy (frozen absolute coordinates)",
"coordinateModelAnchorFrame": "Anchor frame (bounded translation)",
"coordinateModelUseDocumentAnchor": "Use the first document anchor",
"coordinateModelMaxX": "Maximum horizontal translation (page width)",
"coordinateModelMaxY": "Maximum vertical translation (page height)",
"coordinateModelInvalid": "An anchor frame requires at least one stable anchor with coordinates and valid translation limits.",
"rowReconstructionMode": "Line reconstruction mode", "rowReconstructionMode": "Line reconstruction mode",
"rowReconstructionModes": { "rowReconstructionModes": {
"fixedSubrows": "Fixed subrows (default)", "fixedSubrows": "Fixed subrows (default)",
+16 -3
View File
@@ -558,7 +558,7 @@
"resolveFailed": "Failed to resolve conflict. Refresh and try again." "resolveFailed": "Failed to resolve conflict. Refresh and try again."
}, },
"shippingNoticeUi": { "shippingNoticeUi": {
"stage": {"intakeParse": "Intake and parsing", "orderReview": "Order review", "fulfillmentPrep": "Notification preparation", "uploadComplete": "Notification completion"}, "stage": {"intakeParse": "Intake and parsing", "orderReview": "Order review", "fulfillmentPrep": "Notification preparation", "freightUpload": "Freight upload", "uploadComplete": "Notification completion"},
"rpaModeBrowser": "Real RPA", "rpaModeBrowser": "Real RPA",
"rpaModeMock": "Mock RPA", "rpaModeMock": "Mock RPA",
"rpaModeUnknown": "RPA mode unknown", "rpaModeUnknown": "RPA mode unknown",
@@ -1478,14 +1478,17 @@
"blocked": "Prerequisite incomplete", "blocked": "Prerequisite incomplete",
"prerequisite": "Complete the current stage first", "prerequisite": "Complete the current stage first",
"identity": {"po": "PO: {value}", "case": "Case: {value}", "version": "Order version: V{value}"}, "identity": {"po": "PO: {value}", "case": "Case: {value}", "version": "Order version: V{value}"},
"descriptions": {"intake_parse": "Review the email body and current attachment, then resolve intake parsing issues.", "order_review": "Verify fields and evidence, resolve conflicts, and freeze the order.", "fulfillment_prep": "Complete inventory matching and generate the notice Excel.", "upload_complete": "Download, upload or register the notice, and retain the receipt."}, "descriptions": {"intake_parse": "Review the email body and current attachment, then resolve intake parsing issues.", "order_review": "Verify fields and evidence, resolve conflicts, and freeze the order.", "fulfillment_prep": "Complete inventory matching and generate the notice Excel.", "freight_upload": "Download the notice, run RPA or register a manual upload, and reconcile unknown results.", "upload_complete": "Shown only after complete upload-success evidence is verified."},
"intakeParse": {"title": "Intake and parsing", "email": "Email body", "emailPreviewTitle": "Safe email body preview", "noEmail": "No email context", "attachment": "Current attachment", "fileName": "File name", "fileType": "File type", "preview": "Attachment preview", "previewLoading": "Loading attachment preview…", "loadPreview": "Load attachment preview", "previewUnsupported": "The current attachment is not a PDF and cannot be previewed here.", "loading": "Loading intake parsing context…", "loadFailed": "Failed to load intake parsing context.", "retry": "Retry"}, "intakeParse": {"title": "Intake and parsing", "email": "Email body", "emailPreviewTitle": "Safe email body preview", "noEmail": "No email context", "attachment": "Current attachment", "fileName": "File name", "fileType": "File type", "preview": "Attachment preview", "previewLoading": "Loading attachment preview…", "loadPreview": "Load attachment preview", "previewUnsupported": "The current attachment is not a PDF and cannot be previewed here.", "loading": "Loading intake parsing context…", "loadFailed": "Failed to load intake parsing context.", "retry": "Retry"},
"prepare": {"title": "Notice preparation", "subtitle": "Handle inventory candidates, matching issues, and notice generation here.", "frozenOrder": "Frozen order", "inventorySource": "Inventory source", "excel": "Shipping Excel", "downloadInventory": "Download inventory file", "retryInventory": "Re-fetch inventory", "releaseShortage": "Release shortage", "releaseShortageHint": "Release allows shipping Excel generation. State the reason for this shortage release.", "releaseReasonPlaceholder": "Enter release reason (required)", "releaseConfirm": "Confirm release", "requiredQty": "Required quantity", "matchWorkspace": "Inventory matching", "lineCount": "{count} inventory results", "lineStatus": "Match status", "matched": "Matched", "shortage": "Inventory shortage", "matchStatus": {"not_found": "Inventory not found", "preparing": "Preparing inventory", "mapping_failed": "Inventory mapping failed", "unavailable": "Inventory unavailable", "source_conflict": "Inventory source conflict", "invalid_key": "Invalid match key", "result_missing": "Awaiting match result", "unknown": "Unknown status"}, "pending": "Inventory matching or the shipping file is not ready yet. Use the current processing card to continue.", "loadFailed": "Failed to load notice preparation details; current data could not be confirmed.", "detailUnavailable": "Notice preparation details have not returned yet, so frozen order and inventory matching data cannot be shown.", "retry": "Reload"}, "prepare": {"title": "Notice preparation", "subtitle": "Handle inventory candidates, matching issues, and notice generation here.", "frozenOrder": "Frozen order", "inventorySource": "Inventory source", "excel": "Shipping Excel", "downloadInventory": "Download inventory file", "retryInventory": "Re-fetch inventory", "releaseShortage": "Release shortage", "releaseShortageHint": "Release allows shipping Excel generation. State the reason for this shortage release.", "releaseReasonPlaceholder": "Enter release reason (required)", "releaseConfirm": "Confirm release", "requiredQty": "Required quantity", "matchWorkspace": "Inventory matching", "lineCount": "{count} inventory results", "lineStatus": "Match status", "matched": "Matched", "shortage": "Inventory shortage", "matchStatus": {"not_found": "Inventory not found", "preparing": "Preparing inventory", "mapping_failed": "Inventory mapping failed", "unavailable": "Inventory unavailable", "source_conflict": "Inventory source conflict", "invalid_key": "Invalid match key", "result_missing": "Awaiting match result", "unknown": "Unknown status"}, "pending": "Inventory matching or the shipping file is not ready yet. Use the current processing card to continue.", "loadFailed": "Failed to load notice preparation details; current data could not be confirmed.", "detailUnavailable": "Notice preparation details have not returned yet, so frozen order and inventory matching data cannot be shown.", "retry": "Reload"},
"upload": {"title": "Notice completion", "subtitle": "Download the notice Excel, upload or register manual upload, and retain the receipt.", "manualUpload": "Register manual upload", "receipt": "Freight receipt: {value}", "attempt": "Latest upload attempt: {mode} · {status}"}, "freightUpload": {"title": "Freight upload", "subtitle": "Download the notice Excel, run RPA or register manual upload; reconcile an unknown result before retrying."},
"uploadComplete": {"title": "Notification completion", "subtitle": "Upload-success evidence is verified. This view is read only."},
"upload": {"title": "Freight upload", "subtitle": "Download the notice Excel, upload or register manual upload, and retain the receipt.", "manualUpload": "Register manual upload", "receipt": "Freight receipt: {value}", "attempt": "Latest upload attempt: {mode} · {status}"},
"stages": { "stages": {
"intake_parse": "Intake and parsing", "intake_parse": "Intake and parsing",
"order_review": "Order review", "order_review": "Order review",
"fulfillment_prep": "Notification preparation", "fulfillment_prep": "Notification preparation",
"freight_upload": "Freight upload",
"upload_complete": "Notification completion" "upload_complete": "Notification completion"
} }
}, },
@@ -1964,6 +1967,8 @@
"retrying": "Identifying…", "retrying": "Identifying…",
"retryDone": "Customer re-identified", "retryDone": "Customer re-identified",
"retryFailed": "Failed to re-identify customer", "retryFailed": "Failed to re-identify customer",
"uniqueCandidateHint": "One standard customer candidate was found. Saving and validating will confirm it automatically, or you can confirm it manually.",
"confirmUniqueCandidate": "Confirm unique candidate",
"confirmed": "Customer confirmed", "confirmed": "Customer confirmed",
"confirmReason": "Manual customer confirmation in the order lifecycle workbench", "confirmReason": "Manual customer confirmation in the order lifecycle workbench",
"pdfReparseHint": "For PDF layout issues, use “Reparse this PDF” at the top—not these buttons.", "pdfReparseHint": "For PDF layout issues, use “Reparse this PDF” at the top—not these buttons.",
@@ -2354,6 +2359,13 @@
"profile_ambiguous": "Multiple profile candidates with insufficient margin", "profile_ambiguous": "Multiple profile candidates with insufficient margin",
"profile_not_matched": "No usable profile matched", "profile_not_matched": "No usable profile matched",
"profile_drift": "Layout drifted from the profile" "profile_drift": "Layout drifted from the profile"
},
"coordinateModel": {
"anchorFrame": "Anchor-frame coordinates",
"status": "Transform status",
"translateX": "Horizontal translation",
"translateY": "Vertical translation",
"reasonCodes": "Reason codes"
} }
}, },
"buildEligibility": { "buildEligibility": {
@@ -2361,6 +2373,7 @@
"subtitle": "Checks whether the order information and inventory sources are ready for order creation.", "subtitle": "Checks whether the order information and inventory sources are ready for order creation.",
"canBuildYes": "Can build", "canBuildYes": "Can build",
"canBuildNo": "Cannot build yet", "canBuildNo": "Cannot build yet",
"notValidated": "Not validated",
"manualBuildLabel": "Manual build", "manualBuildLabel": "Manual build",
"autoBuildLabel": "Automatic build", "autoBuildLabel": "Automatic build",
"autoBuildYes": "Eligible for automatic creation", "autoBuildYes": "Eligible for automatic creation",
+1 -1
View File
@@ -320,7 +320,7 @@
"freeze_not_ready": "Order is not ready to build or freeze", "freeze_not_ready": "Order is not ready to build or freeze",
"profile_not_auto_freeze_approved": "Document profile is not approved for auto build", "profile_not_auto_freeze_approved": "Document profile is not approved for auto build",
"profile_manual_confirmation_required": "Document profile requires manual confirmation", "profile_manual_confirmation_required": "Document profile requires manual confirmation",
"customer_unresolved": "Customer is unresolved", "customer_unresolved": "Customer has not been confirmed",
"customer_ambiguous": "Customer resolution is ambiguous", "customer_ambiguous": "Customer resolution is ambiguous",
"field_conflict": "Field conflicts need manual resolution", "field_conflict": "Field conflicts need manual resolution",
"duplicate_unresolved": "Duplicate order is unresolved", "duplicate_unresolved": "Duplicate order is unresolved",
+9
View File
@@ -3549,6 +3549,15 @@
"noIssues": "ไม่มีปัญหาการตั้งค่าที่ขัดขวาง", "noIssues": "ไม่มีปัญหาการตั้งค่าที่ขัดขวาง",
"currentConfiguration": "การตั้งค่าปัจจุบัน", "currentConfiguration": "การตั้งค่าปัจจุบัน",
"tableRegionSettings": "การตั้งค่าตารางรายละเอียด", "tableRegionSettings": "การตั้งค่าตารางรายละเอียด",
"coordinateModelTitle": "โมเดลค่าพิกัด",
"coordinateModelHint": "ค่าเริ่มต้นใช้พิกัดสัมบูรณ์ที่แช่แข็ง เปิดใช้งานเฉพาะเมื่อมีการเลื่อนที่จำกัดและจุดยึดคงที่เท่านั้น",
"coordinateModelType": "โมเดลพิกัด",
"coordinateModelLegacy": "Legacy (พิกัดสัมบูรณ์ที่แช่แข็ง)",
"coordinateModelAnchorFrame": "กรอบจุดยึด (การเลื่อนที่จำกัด)",
"coordinateModelUseDocumentAnchor": "ใช้จุดยึดเอกสารแรก",
"coordinateModelMaxX": "การเลื่อนแนวนอนสูงสุด (ความกว้างหน้า)",
"coordinateModelMaxY": "การเลื่อนแนวตั้งสูงสุด (ความสูงหน้า)",
"coordinateModelInvalid": "กรอบจุดยึดต้องมีจุดยึดคงที่พร้อมพิกัดอย่างน้อยหนึ่งจุดและขีดจำกัดการเลื่อนที่ถูกต้อง",
"rowReconstructionMode": "โหมดสร้างแถวรายละเอียดใหม่", "rowReconstructionMode": "โหมดสร้างแถวรายละเอียดใหม่",
"rowReconstructionModes": { "rowReconstructionModes": {
"fixedSubrows": "แถวย่อยคงที่ (ค่าเริ่มต้น)", "fixedSubrows": "แถวย่อยคงที่ (ค่าเริ่มต้น)",
+16 -3
View File
@@ -558,7 +558,7 @@
"resolveFailed": "แก้ความขัดแย้งไม่สำเร็จ กรุณารีเฟรชแล้วลองใหม่" "resolveFailed": "แก้ความขัดแย้งไม่สำเร็จ กรุณารีเฟรชแล้วลองใหม่"
}, },
"shippingNoticeUi": { "shippingNoticeUi": {
"stage": {"intakeParse": "รับและแยกวิเคราะห์", "orderReview": "ตรวจสอบคำสั่งซื้อ", "fulfillmentPrep": "เตรียมการแจ้งการจัดส่ง", "uploadComplete": "การแจ้งการจัดส่งเสร็จสิ้น"}, "stage": {"intakeParse": "รับและแยกวิเคราะห์", "orderReview": "ตรวจสอบคำสั่งซื้อ", "fulfillmentPrep": "เตรียมการแจ้งการจัดส่ง", "freightUpload": "อัปโหลดให้ผู้ให้บริการขนส่ง", "uploadComplete": "การแจ้งการจัดส่งเสร็จสิ้น"},
"rpaModeBrowser": "RPA จริง", "rpaModeBrowser": "RPA จริง",
"rpaModeMock": "Mock RPA", "rpaModeMock": "Mock RPA",
"rpaModeUnknown": "ไม่ทราบโหมด RPA", "rpaModeUnknown": "ไม่ทราบโหมด RPA",
@@ -1478,14 +1478,17 @@
"blocked": "เงื่อนไขก่อนหน้ายังไม่เสร็จ", "blocked": "เงื่อนไขก่อนหน้ายังไม่เสร็จ",
"prerequisite": "กรุณาทำขั้นตอนปัจจุบันให้เสร็จก่อน", "prerequisite": "กรุณาทำขั้นตอนปัจจุบันให้เสร็จก่อน",
"identity": {"po": "PO: {value}", "case": "Case: {value}", "version": "เวอร์ชันคำสั่งซื้อ: V{value}"}, "identity": {"po": "PO: {value}", "case": "Case: {value}", "version": "เวอร์ชันคำสั่งซื้อ: V{value}"},
"descriptions": {"intake_parse": "ตรวจสอบเนื้อหาอีเมลและไฟล์แนบปัจจุบัน แล้วจัดการปัญหาการแยกวิเคราะห์ขาเข้า", "order_review": "ตรวจสอบข้อมูลและหลักฐาน แก้ข้อขัดแย้ง และตรึงคำสั่งซื้อ", "fulfillment_prep": "จับคู่สต็อกและสร้าง Excel แจ้งงาน", "upload_complete": "ดาวน์โหลด อัปโหลด หรือลงทะเบียนแจ้งงาน พร้อมเก็บใบตอบรับ"}, "descriptions": {"intake_parse": "ตรวจสอบเนื้อหาอีเมลและไฟล์แนบปัจจุบัน แล้วจัดการปัญหาการแยกวิเคราะห์ขาเข้า", "order_review": "ตรวจสอบข้อมูลและหลักฐาน แก้ข้อขัดแย้ง และตรึงคำสั่งซื้อ", "fulfillment_prep": "จับคู่สต็อกและสร้าง Excel แจ้งงาน", "freight_upload": "ดาวน์โหลดไฟล์แจ้งงาน รัน RPA หรือลงทะเบียนการอัปโหลดด้วยตนเอง และตรวจสอบผลลัพธ์ที่ไม่ทราบ", "upload_complete": "แสดงเมื่อยืนยันหลักฐานความสำเร็จของการอัปโหลดครบถ้วนแล้วเท่านั้น"},
"intakeParse": {"title": "รับและแยกวิเคราะห์", "email": "เนื้อหาอีเมล", "emailPreviewTitle": "ตัวอย่างเนื้อหาอีเมลแบบปลอดภัย", "noEmail": "ไม่มีบริบทอีเมล", "attachment": "ไฟล์แนบปัจจุบัน", "fileName": "ชื่อไฟล์", "fileType": "ประเภทไฟล์", "preview": "ตัวอย่างไฟล์แนบ", "previewLoading": "กำลังโหลดตัวอย่างไฟล์แนบ…", "loadPreview": "โหลดตัวอย่างไฟล์แนบ", "previewUnsupported": "ไฟล์แนบปัจจุบันไม่ใช่ PDF และไม่สามารถแสดงตัวอย่างที่นี่ได้", "loading": "กำลังโหลดบริบทการแยกวิเคราะห์ขาเข้า…", "loadFailed": "โหลดบริบทการแยกวิเคราะห์ขาเข้าไม่สำเร็จ", "retry": "ลองอีกครั้ง"}, "intakeParse": {"title": "รับและแยกวิเคราะห์", "email": "เนื้อหาอีเมล", "emailPreviewTitle": "ตัวอย่างเนื้อหาอีเมลแบบปลอดภัย", "noEmail": "ไม่มีบริบทอีเมล", "attachment": "ไฟล์แนบปัจจุบัน", "fileName": "ชื่อไฟล์", "fileType": "ประเภทไฟล์", "preview": "ตัวอย่างไฟล์แนบ", "previewLoading": "กำลังโหลดตัวอย่างไฟล์แนบ…", "loadPreview": "โหลดตัวอย่างไฟล์แนบ", "previewUnsupported": "ไฟล์แนบปัจจุบันไม่ใช่ PDF และไม่สามารถแสดงตัวอย่างที่นี่ได้", "loading": "กำลังโหลดบริบทการแยกวิเคราะห์ขาเข้า…", "loadFailed": "โหลดบริบทการแยกวิเคราะห์ขาเข้าไม่สำเร็จ", "retry": "ลองอีกครั้ง"},
"prepare": {"title": "เตรียมการแจ้ง", "subtitle": "จัดการตัวเลือกสต็อก ปัญหาการจับคู่ และการสร้างไฟล์แจ้งงานที่นี่", "frozenOrder": "คำสั่งซื้อที่ตรึงแล้ว", "inventorySource": "แหล่งสต็อก", "excel": "Excel การจัดส่ง", "downloadInventory": "ดาวน์โหลดไฟล์สินค้าคงคลัง", "retryInventory": "ดึงข้อมูลสต็อกอีกครั้ง", "releaseShortage": "อนุมัติส่วนขาดสต็อก", "releaseShortageHint": "การอนุมัติทำให้สร้าง Excel การจัดส่งได้ โปรดระบุเหตุผลสำหรับส่วนขาดนี้", "releaseReasonPlaceholder": "กรอกเหตุผลการอนุมัติ (จำเป็น)", "releaseConfirm": "ยืนยันการอนุมัติ", "requiredQty": "จำนวนที่ต้องการ", "matchWorkspace": "การจับคู่สต็อก", "lineCount": "ผลลัพธ์สต็อก {count} รายการ", "lineStatus": "สถานะการจับคู่", "matched": "จับคู่แล้ว", "shortage": "สต็อกไม่เพียงพอ", "matchStatus": {"not_found": "ไม่พบสต็อก", "preparing": "กำลังเตรียมสต็อก", "mapping_failed": "จับคู่ฟิลด์สต็อกไม่สำเร็จ", "unavailable": "สต็อกไม่พร้อมใช้", "source_conflict": "แหล่งสต็อกขัดแย้ง", "invalid_key": "คีย์จับคู่ไม่ถูกต้อง", "result_missing": "กำลังรอผลการจับคู่", "unknown": "ไม่ทราบสถานะ"}, "pending": "การจับคู่สต็อกหรือไฟล์แจ้งการจัดส่งยังไม่พร้อม โปรดดำเนินการจากบัตรงานปัจจุบัน", "loadFailed": "โหลดรายละเอียดการเตรียมการแจ้งไม่สำเร็จ จึงยังยืนยันข้อมูลปัจจุบันไม่ได้", "detailUnavailable": "ยังไม่ได้รับรายละเอียดการเตรียมการแจ้ง จึงยังแสดงคำสั่งซื้อที่ตรึงและข้อมูลการจับคู่สต็อกไม่ได้", "retry": "โหลดอีกครั้ง"}, "prepare": {"title": "เตรียมการแจ้ง", "subtitle": "จัดการตัวเลือกสต็อก ปัญหาการจับคู่ และการสร้างไฟล์แจ้งงานที่นี่", "frozenOrder": "คำสั่งซื้อที่ตรึงแล้ว", "inventorySource": "แหล่งสต็อก", "excel": "Excel การจัดส่ง", "downloadInventory": "ดาวน์โหลดไฟล์สินค้าคงคลัง", "retryInventory": "ดึงข้อมูลสต็อกอีกครั้ง", "releaseShortage": "อนุมัติส่วนขาดสต็อก", "releaseShortageHint": "การอนุมัติทำให้สร้าง Excel การจัดส่งได้ โปรดระบุเหตุผลสำหรับส่วนขาดนี้", "releaseReasonPlaceholder": "กรอกเหตุผลการอนุมัติ (จำเป็น)", "releaseConfirm": "ยืนยันการอนุมัติ", "requiredQty": "จำนวนที่ต้องการ", "matchWorkspace": "การจับคู่สต็อก", "lineCount": "ผลลัพธ์สต็อก {count} รายการ", "lineStatus": "สถานะการจับคู่", "matched": "จับคู่แล้ว", "shortage": "สต็อกไม่เพียงพอ", "matchStatus": {"not_found": "ไม่พบสต็อก", "preparing": "กำลังเตรียมสต็อก", "mapping_failed": "จับคู่ฟิลด์สต็อกไม่สำเร็จ", "unavailable": "สต็อกไม่พร้อมใช้", "source_conflict": "แหล่งสต็อกขัดแย้ง", "invalid_key": "คีย์จับคู่ไม่ถูกต้อง", "result_missing": "กำลังรอผลการจับคู่", "unknown": "ไม่ทราบสถานะ"}, "pending": "การจับคู่สต็อกหรือไฟล์แจ้งการจัดส่งยังไม่พร้อม โปรดดำเนินการจากบัตรงานปัจจุบัน", "loadFailed": "โหลดรายละเอียดการเตรียมการแจ้งไม่สำเร็จ จึงยังยืนยันข้อมูลปัจจุบันไม่ได้", "detailUnavailable": "ยังไม่ได้รับรายละเอียดการเตรียมการแจ้ง จึงยังแสดงคำสั่งซื้อที่ตรึงและข้อมูลการจับคู่สต็อกไม่ได้", "retry": "โหลดอีกครั้ง"},
"upload": {"title": "แจ้งเสร็จสิ้น", "subtitle": "ดาวน์โหลด Excel แจ้งงาน อัปโหลดหรือลงทะเบียนการอัปโหลดด้วยตนเอง และเก็บใบตอบรับ", "manualUpload": "ลงทะเบียนอัปโหลดด้วยตนเอง", "receipt": "ใบตอบรับจากผู้ขนส่ง: {value}", "attempt": "ความพยายามอัปโหลดล่าสุด: {mode} · {status}"}, "freightUpload": {"title": "อัปโหลดให้ผู้ให้บริการขนส่ง", "subtitle": "ดาวน์โหลด Excel แจ้งงาน รัน RPA หรือลงทะเบียนการอัปโหลดด้วยตนเอง; หากผลลัพธ์ไม่ทราบให้ตรวจสอบก่อนลองใหม่"},
"uploadComplete": {"title": "แจ้งเสร็จสิ้น", "subtitle": "ยืนยันหลักฐานความสำเร็จของการอัปโหลดแล้ว หน้านี้อ่านได้อย่างเดียว"},
"upload": {"title": "อัปโหลดให้ผู้ให้บริการขนส่ง", "subtitle": "ดาวน์โหลด Excel แจ้งงาน อัปโหลดหรือลงทะเบียนการอัปโหลดด้วยตนเอง และเก็บใบตอบรับ", "manualUpload": "ลงทะเบียนอัปโหลดด้วยตนเอง", "receipt": "ใบตอบรับจากผู้ขนส่ง: {value}", "attempt": "ความพยายามอัปโหลดล่าสุด: {mode} · {status}"},
"stages": { "stages": {
"intake_parse": "รับและแยกวิเคราะห์", "intake_parse": "รับและแยกวิเคราะห์",
"order_review": "ทบทวนคำสั่งซื้อ", "order_review": "ทบทวนคำสั่งซื้อ",
"fulfillment_prep": "เตรียมการแจ้ง", "fulfillment_prep": "เตรียมการแจ้ง",
"freight_upload": "อัปโหลดให้ผู้ให้บริการขนส่ง",
"upload_complete": "แจ้งเสร็จสิ้น" "upload_complete": "แจ้งเสร็จสิ้น"
} }
}, },
@@ -1964,6 +1967,8 @@
"retrying": "กำลังระบุ…", "retrying": "กำลังระบุ…",
"retryDone": "ระบุลูกค้าใหม่แล้ว", "retryDone": "ระบุลูกค้าใหม่แล้ว",
"retryFailed": "ระบุลูกค้าใหม่ไม่สำเร็จ", "retryFailed": "ระบุลูกค้าใหม่ไม่สำเร็จ",
"uniqueCandidateHint": "พบผู้สมัครลูกค้ามาตรฐานเพียงรายเดียว การบันทึกและตรวจสอบจะยืนยันโดยอัตโนมัติ หรือยืนยันด้วยตนเองได้",
"confirmUniqueCandidate": "ยืนยันผู้สมัครรายเดียว",
"confirmed": "ยืนยันลูกค้าแล้ว", "confirmed": "ยืนยันลูกค้าแล้ว",
"confirmReason": "ยืนยันลูกค้าด้วยตนเองจากโต๊ะทำงานวงจรชีวิตคำสั่งซื้อ", "confirmReason": "ยืนยันลูกค้าด้วยตนเองจากโต๊ะทำงานวงจรชีวิตคำสั่งซื้อ",
"pdfReparseHint": "หากเลย์เอาต์ PDF ผิด ใช้ “ระบุ PDF นี้อีกครั้ง” ด้านบน ไม่ใช่ปุ่มในส่วนนี้", "pdfReparseHint": "หากเลย์เอาต์ PDF ผิด ใช้ “ระบุ PDF นี้อีกครั้ง” ด้านบน ไม่ใช่ปุ่มในส่วนนี้",
@@ -2354,6 +2359,13 @@
"profile_ambiguous": "มีหลายเทมเพลตและคะแนนต่างกันไม่พอ", "profile_ambiguous": "มีหลายเทมเพลตและคะแนนต่างกันไม่พอ",
"profile_not_matched": "ไม่พบเทมเพลตที่ใช้ได้", "profile_not_matched": "ไม่พบเทมเพลตที่ใช้ได้",
"profile_drift": "เลย์เอาต์เพี้ยนจากเทมเพลต" "profile_drift": "เลย์เอาต์เพี้ยนจากเทมเพลต"
},
"coordinateModel": {
"anchorFrame": "พิกัดกรอบจุดยึด",
"status": "สถานะการแปลง",
"translateX": "การเลื่อนแนวนอน",
"translateY": "การเลื่อนแนวตั้ง",
"reasonCodes": "รหัสเหตุผล"
} }
}, },
"buildEligibility": { "buildEligibility": {
@@ -2361,6 +2373,7 @@
"subtitle": "ตรวจสอบว่าข้อมูลคำสั่งซื้อและแหล่งสต็อกพร้อมสำหรับสร้างคำสั่งซื้อหรือไม่", "subtitle": "ตรวจสอบว่าข้อมูลคำสั่งซื้อและแหล่งสต็อกพร้อมสำหรับสร้างคำสั่งซื้อหรือไม่",
"canBuildYes": "สร้างได้", "canBuildYes": "สร้างได้",
"canBuildNo": "ยังสร้างไม่ได้", "canBuildNo": "ยังสร้างไม่ได้",
"notValidated": "ยังไม่ได้ตรวจสอบ",
"manualBuildLabel": "สร้างด้วยตนเอง", "manualBuildLabel": "สร้างด้วยตนเอง",
"autoBuildLabel": "สร้างอัตโนมัติ", "autoBuildLabel": "สร้างอัตโนมัติ",
"autoBuildYes": "มีสิทธิ์สร้างอัตโนมัติ", "autoBuildYes": "มีสิทธิ์สร้างอัตโนมัติ",
+1 -1
View File
@@ -254,7 +254,7 @@
"freeze_not_ready": "คำสั่งซื้อยังไม่พร้อมสร้างหรือ freeze", "freeze_not_ready": "คำสั่งซื้อยังไม่พร้อมสร้างหรือ freeze",
"profile_not_auto_freeze_approved": "โปรไฟล์เอกสารยังไม่ได้รับอนุมัติ auto build", "profile_not_auto_freeze_approved": "โปรไฟล์เอกสารยังไม่ได้รับอนุมัติ auto build",
"profile_manual_confirmation_required": "โปรไฟล์เอกสารต้องยืนยันด้วยตนเอง", "profile_manual_confirmation_required": "โปรไฟล์เอกสารต้องยืนยันด้วยตนเอง",
"customer_unresolved": "ยังระบุลูกค้าไม่ได้", "customer_unresolved": "ยังไม่ได้ยืนยันลูกค้า",
"customer_ambiguous": "การระบุลูกค้ามีความคลุมเครือ", "customer_ambiguous": "การระบุลูกค้ามีความคลุมเครือ",
"field_conflict": "ฟิลด์ขัดแย้ง ต้องตัดสินด้วยตนเอง", "field_conflict": "ฟิลด์ขัดแย้ง ต้องตัดสินด้วยตนเอง",
"duplicate_unresolved": "คำสั่งซื้อซ้ำยังไม่ได้รับการแก้ไข", "duplicate_unresolved": "คำสั่งซื้อซ้ำยังไม่ได้รับการแก้ไข",
+9
View File
@@ -3791,6 +3791,15 @@
"noIssues": "没有阻断配置问题。", "noIssues": "没有阻断配置问题。",
"currentConfiguration": "当前配置", "currentConfiguration": "当前配置",
"tableRegionSettings": "明细表区设置", "tableRegionSettings": "明细表区设置",
"coordinateModelTitle": "坐标取值模型",
"coordinateModelHint": "默认使用冻结绝对坐标;仅在版式存在受限平移且有稳定静态锚点时启用。",
"coordinateModelType": "坐标模型",
"coordinateModelLegacy": "Legacy(冻结绝对坐标)",
"coordinateModelAnchorFrame": "锚点坐标框架(受限平移)",
"coordinateModelUseDocumentAnchor": "使用首个匹配锚点建立框架",
"coordinateModelMaxX": "最大横向平移(相对页宽)",
"coordinateModelMaxY": "最大纵向平移(相对页高)",
"coordinateModelInvalid": "锚点坐标框架必须至少有一个带坐标的稳定锚点,且平移上限在允许范围内。",
"rowReconstructionMode": "明细行重建方式", "rowReconstructionMode": "明细行重建方式",
"rowReconstructionModes": { "rowReconstructionModes": {
"fixedSubrows": "固定子行(默认)", "fixedSubrows": "固定子行(默认)",
+16 -3
View File
@@ -592,7 +592,7 @@
"resolveFailed": "解决冲突失败,请刷新后重试" "resolveFailed": "解决冲突失败,请刷新后重试"
}, },
"shippingNoticeUi": { "shippingNoticeUi": {
"stage": {"intakeParse": "接收解析", "orderReview": "订单复核", "fulfillmentPrep": "通知准备", "uploadComplete": "通知完成"}, "stage": {"intakeParse": "接收解析", "orderReview": "订单复核", "fulfillmentPrep": "通知准备", "freightUpload": "货代上传", "uploadComplete": "通知完成"},
"rpaModeBrowser": "真实 RPA", "rpaModeBrowser": "真实 RPA",
"rpaModeMock": "Mock RPA", "rpaModeMock": "Mock RPA",
"rpaModeUnknown": "RPA 模式未知", "rpaModeUnknown": "RPA 模式未知",
@@ -1585,14 +1585,17 @@
"blocked": "前置未完成", "blocked": "前置未完成",
"prerequisite": "请先完成当前阶段", "prerequisite": "请先完成当前阶段",
"identity": {"po": "PO:{value}", "case": "Case:{value}", "version": "订单版本:V{value}"}, "identity": {"po": "PO:{value}", "case": "Case:{value}", "version": "订单版本:V{value}"},
"descriptions": {"intake_parse": "核对邮件正文和当前附件,处置接收解析异常。", "order_review": "核实字段和证据,处理冲突并冻结订单。", "fulfillment_prep": "完成库存匹配并生成通知 Excel。", "upload_complete": "下载通知文件、上传或登记回执,完成闭环。"}, "descriptions": {"intake_parse": "核对邮件正文和当前附件,处置接收解析异常。", "order_review": "核实字段和证据,处理冲突并冻结订单。", "fulfillment_prep": "完成库存匹配并生成通知 Excel。", "freight_upload": "下载通知文件、执行 RPA 或登记人工上传,并核对未知结果。", "upload_complete": "仅在上传成功证据完整时展示通知完成。"},
"intakeParse": {"title": "接收解析", "email": "邮件正文", "emailPreviewTitle": "邮件正文安全预览", "noEmail": "无邮件上下文", "attachment": "当前附件", "fileName": "文件名", "fileType": "文件类型", "preview": "附件预览", "previewLoading": "正在加载附件预览…", "loadPreview": "加载附件预览", "previewUnsupported": "当前附件不是 PDF,不能在此预览。", "loading": "正在加载接收解析上下文…", "loadFailed": "接收解析上下文加载失败。", "retry": "重试"}, "intakeParse": {"title": "接收解析", "email": "邮件正文", "emailPreviewTitle": "邮件正文安全预览", "noEmail": "无邮件上下文", "attachment": "当前附件", "fileName": "文件名", "fileType": "文件类型", "preview": "附件预览", "previewLoading": "正在加载附件预览…", "loadPreview": "加载附件预览", "previewUnsupported": "当前附件不是 PDF,不能在此预览。", "loading": "正在加载接收解析上下文…", "loadFailed": "接收解析上下文加载失败。", "retry": "重试"},
"prepare": {"title": "通知准备", "subtitle": "库存候选、匹配异常和通知文件生成均在此阶段处理。", "frozenOrder": "冻结订单", "inventorySource": "库存源", "excel": "通知 Excel", "downloadInventory": "下载库存文件", "retryInventory": "重新获取库存", "releaseShortage": "库存缺口放行", "releaseShortageHint": "放行后可生成发货 Excel;请填写本次缺口放行原因。", "releaseReasonPlaceholder": "请输入放行原因(必填)", "releaseConfirm": "确认放行", "requiredQty": "需求数量", "matchWorkspace": "库存匹配", "lineCount": "{count} 行库存结果", "lineStatus": "匹配状态", "matched": "已匹配", "shortage": "库存不足", "matchStatus": {"not_found": "未匹配到库存", "preparing": "库存准备中", "mapping_failed": "库存映射失败", "unavailable": "库存不可用", "source_conflict": "库存源冲突", "invalid_key": "匹配键无效", "result_missing": "等待匹配结果", "unknown": "状态未知"}, "pending": "库存匹配或通知文件尚未生成。请查看右侧当前处理,按当前门禁继续。", "loadFailed": "通知准备任务详情加载失败,当前数据未能确认。", "detailUnavailable": "通知准备任务详情尚未返回,暂时无法展示冻结订单和库存匹配数据。", "retry": "重新加载"}, "prepare": {"title": "通知准备", "subtitle": "库存候选、匹配异常和通知文件生成均在此阶段处理。", "frozenOrder": "冻结订单", "inventorySource": "库存源", "excel": "通知 Excel", "downloadInventory": "下载库存文件", "retryInventory": "重新获取库存", "releaseShortage": "库存缺口放行", "releaseShortageHint": "放行后可生成发货 Excel;请填写本次缺口放行原因。", "releaseReasonPlaceholder": "请输入放行原因(必填)", "releaseConfirm": "确认放行", "requiredQty": "需求数量", "matchWorkspace": "库存匹配", "lineCount": "{count} 行库存结果", "lineStatus": "匹配状态", "matched": "已匹配", "shortage": "库存不足", "matchStatus": {"not_found": "未匹配到库存", "preparing": "库存准备中", "mapping_failed": "库存映射失败", "unavailable": "库存不可用", "source_conflict": "库存源冲突", "invalid_key": "匹配键无效", "result_missing": "等待匹配结果", "unknown": "状态未知"}, "pending": "库存匹配或通知文件尚未生成。请查看右侧当前处理,按当前门禁继续。", "loadFailed": "通知准备任务详情加载失败,当前数据未能确认。", "detailUnavailable": "通知准备任务详情尚未返回,暂时无法展示冻结订单和库存匹配数据。", "retry": "重新加载"},
"upload": {"title": "通知完成", "subtitle": "下载已生成的通知 Excel,上传货代或登记人工上传,并保留回执。", "manualUpload": "登记人工上传", "receipt": "货代回执:{value}", "attempt": "最近上传尝试:{mode} · {status}"}, "freightUpload": {"title": "货代上传", "subtitle": "下载已生成的通知 Excel,执行 RPA 或登记人工上传;结果未知时先核对后再处理。"},
"uploadComplete": {"title": "通知完成", "subtitle": "上传成功证据已核验,以下内容仅供查看。"},
"upload": {"title": "货代上传", "subtitle": "下载已生成的通知 Excel,上传货代或登记人工上传,并保留回执。", "manualUpload": "登记人工上传", "receipt": "货代回执:{value}", "attempt": "最近上传尝试:{mode} · {status}"},
"stages": { "stages": {
"intake_parse": "接收解析", "intake_parse": "接收解析",
"order_review": "订单复核", "order_review": "订单复核",
"fulfillment_prep": "通知准备", "fulfillment_prep": "通知准备",
"freight_upload": "货代上传",
"upload_complete": "通知完成" "upload_complete": "通知完成"
} }
}, },
@@ -2071,6 +2074,8 @@
"retrying": "识别中…", "retrying": "识别中…",
"retryDone": "已重新识别客户", "retryDone": "已重新识别客户",
"retryFailed": "重新识别客户失败", "retryFailed": "重新识别客户失败",
"uniqueCandidateHint": "已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。",
"confirmUniqueCandidate": "确认唯一候选",
"confirmed": "客户已确认", "confirmed": "客户已确认",
"confirmReason": "订单生命周期工作台人工确认标准客户", "confirmReason": "订单生命周期工作台人工确认标准客户",
"pdfReparseHint": "若 PDF 版面错误,请使用顶部「重新识别此 PDF」,不要用本区按钮。", "pdfReparseHint": "若 PDF 版面错误,请使用顶部「重新识别此 PDF」,不要用本区按钮。",
@@ -2473,6 +2478,13 @@
"profile_ambiguous": "多个模板候选分差不足", "profile_ambiguous": "多个模板候选分差不足",
"profile_not_matched": "未匹配到可用模板", "profile_not_matched": "未匹配到可用模板",
"profile_drift": "版面相对模板发生漂移" "profile_drift": "版面相对模板发生漂移"
},
"coordinateModel": {
"anchorFrame": "锚点坐标框架",
"status": "变换状态",
"translateX": "横向平移",
"translateY": "纵向平移",
"reasonCodes": "原因码"
} }
}, },
"buildEligibility": { "buildEligibility": {
@@ -2480,6 +2492,7 @@
"subtitle": "检查订单信息和库存来源是否满足创建条件。", "subtitle": "检查订单信息和库存来源是否满足创建条件。",
"canBuildYes": "可建单", "canBuildYes": "可建单",
"canBuildNo": "暂不可建单", "canBuildNo": "暂不可建单",
"notValidated": "尚未校验",
"manualBuildLabel": "人工建单", "manualBuildLabel": "人工建单",
"autoBuildLabel": "自动建单", "autoBuildLabel": "自动建单",
"autoBuildYes": "可自动建单", "autoBuildYes": "可自动建单",
+1 -1
View File
@@ -320,7 +320,7 @@
"freeze_not_ready": "订单尚未满足建单/冻结条件", "freeze_not_ready": "订单尚未满足建单/冻结条件",
"profile_not_auto_freeze_approved": "文档模板未通过自动建单审批", "profile_not_auto_freeze_approved": "文档模板未通过自动建单审批",
"profile_manual_confirmation_required": "文档模板需要人工确认", "profile_manual_confirmation_required": "文档模板需要人工确认",
"customer_unresolved": "客户尚未识别", "customer_unresolved": "客户尚未确认",
"customer_ambiguous": "客户识别存在歧义", "customer_ambiguous": "客户识别存在歧义",
"field_conflict": "字段存在冲突,需人工裁决", "field_conflict": "字段存在冲突,需人工裁决",
"duplicate_unresolved": "重复订单尚未处理", "duplicate_unresolved": "重复订单尚未处理",
+9
View File
@@ -3554,6 +3554,15 @@
"noIssues": "沒有阻斷設定問題。", "noIssues": "沒有阻斷設定問題。",
"currentConfiguration": "目前設定", "currentConfiguration": "目前設定",
"tableRegionSettings": "明細表區設定", "tableRegionSettings": "明細表區設定",
"coordinateModelTitle": "座標取值模型",
"coordinateModelHint": "預設使用凍結絕對座標;僅在版式存在受限平移且有穩定靜態錨點時啟用。",
"coordinateModelType": "座標模型",
"coordinateModelLegacy": "Legacy(凍結絕對座標)",
"coordinateModelAnchorFrame": "錨點座標框架(受限平移)",
"coordinateModelUseDocumentAnchor": "使用首個匹配錨點建立框架",
"coordinateModelMaxX": "最大橫向平移(相對頁寬)",
"coordinateModelMaxY": "最大縱向平移(相對頁高)",
"coordinateModelInvalid": "錨點座標框架必須至少有一個帶座標的穩定錨點,且平移上限在允許範圍內。",
"rowReconstructionMode": "明細行重建方式", "rowReconstructionMode": "明細行重建方式",
"rowReconstructionModes": { "rowReconstructionModes": {
"fixedSubrows": "固定子行(預設)", "fixedSubrows": "固定子行(預設)",
+16 -3
View File
@@ -558,7 +558,7 @@
"resolveFailed": "解決衝突失敗,請重新整理後再試" "resolveFailed": "解決衝突失敗,請重新整理後再試"
}, },
"shippingNoticeUi": { "shippingNoticeUi": {
"stage": {"intakeParse": "接收解析", "orderReview": "訂單複核", "fulfillmentPrep": "通知準備", "uploadComplete": "通知完成"}, "stage": {"intakeParse": "接收解析", "orderReview": "訂單複核", "fulfillmentPrep": "通知準備", "freightUpload": "貨代上傳", "uploadComplete": "通知完成"},
"rpaModeBrowser": "真實 RPA", "rpaModeBrowser": "真實 RPA",
"rpaModeMock": "Mock RPA", "rpaModeMock": "Mock RPA",
"rpaModeUnknown": "RPA 模式未知", "rpaModeUnknown": "RPA 模式未知",
@@ -1478,14 +1478,17 @@
"blocked": "前置未完成", "blocked": "前置未完成",
"prerequisite": "請先完成目前階段", "prerequisite": "請先完成目前階段",
"identity": {"po": "PO:{value}", "case": "Case:{value}", "version": "訂單版本:V{value}"}, "identity": {"po": "PO:{value}", "case": "Case:{value}", "version": "訂單版本:V{value}"},
"descriptions": {"intake_parse": "核對郵件正文和目前附件,處理接收解析異常。", "order_review": "核實欄位與證據、處理衝突並凍結訂單。", "fulfillment_prep": "完成庫存匹配並產生通知 Excel。", "upload_complete": "下載、上傳或登記通知,並保留回執。"}, "descriptions": {"intake_parse": "核對郵件正文和目前附件,處理接收解析異常。", "order_review": "核實欄位與證據、處理衝突並凍結訂單。", "fulfillment_prep": "完成庫存匹配並產生通知 Excel。", "freight_upload": "下載通知檔案、執行 RPA 或登記人工上傳,並核對未知結果。", "upload_complete": "僅在上傳成功證據完整時顯示通知完成。"},
"intakeParse": {"title": "接收解析", "email": "郵件正文", "emailPreviewTitle": "郵件正文安全預覽", "noEmail": "無郵件上下文", "attachment": "目前附件", "fileName": "檔案名稱", "fileType": "檔案類型", "preview": "附件預覽", "previewLoading": "正在載入附件預覽…", "loadPreview": "載入附件預覽", "previewUnsupported": "目前附件不是 PDF,無法在此預覽。", "loading": "正在載入接收解析上下文…", "loadFailed": "接收解析上下文載入失敗。", "retry": "重試"}, "intakeParse": {"title": "接收解析", "email": "郵件正文", "emailPreviewTitle": "郵件正文安全預覽", "noEmail": "無郵件上下文", "attachment": "目前附件", "fileName": "檔案名稱", "fileType": "檔案類型", "preview": "附件預覽", "previewLoading": "正在載入附件預覽…", "loadPreview": "載入附件預覽", "previewUnsupported": "目前附件不是 PDF,無法在此預覽。", "loading": "正在載入接收解析上下文…", "loadFailed": "接收解析上下文載入失敗。", "retry": "重試"},
"prepare": {"title": "通知準備", "subtitle": "在此處處理庫存候選、匹配異常與通知檔產生。", "frozenOrder": "凍結訂單", "inventorySource": "庫存來源", "excel": "發貨 Excel", "downloadInventory": "下載庫存檔案", "retryInventory": "重新取得庫存", "releaseShortage": "放行庫存缺口", "releaseShortageHint": "放行後可產生發貨 Excel;請填寫本次缺口放行原因。", "releaseReasonPlaceholder": "請輸入放行原因(必填)", "releaseConfirm": "確認放行", "requiredQty": "需求數量", "matchWorkspace": "庫存匹配", "lineCount": "{count} 行庫存結果", "lineStatus": "匹配狀態", "matched": "已匹配", "shortage": "庫存不足", "matchStatus": {"not_found": "未匹配到庫存", "preparing": "庫存準備中", "mapping_failed": "庫存對應失敗", "unavailable": "庫存不可用", "source_conflict": "庫存來源衝突", "invalid_key": "匹配鍵無效", "result_missing": "等待匹配結果", "unknown": "狀態未知"}, "pending": "庫存匹配或通知檔案尚未產生。請查看右側目前處理,依目前門禁繼續。", "loadFailed": "通知準備任務詳情載入失敗,目前資料無法確認。", "detailUnavailable": "通知準備任務詳情尚未返回,暫時無法展示凍結訂單和庫存匹配資料。", "retry": "重新載入"}, "prepare": {"title": "通知準備", "subtitle": "在此處處理庫存候選、匹配異常與通知檔產生。", "frozenOrder": "凍結訂單", "inventorySource": "庫存來源", "excel": "發貨 Excel", "downloadInventory": "下載庫存檔案", "retryInventory": "重新取得庫存", "releaseShortage": "放行庫存缺口", "releaseShortageHint": "放行後可產生發貨 Excel;請填寫本次缺口放行原因。", "releaseReasonPlaceholder": "請輸入放行原因(必填)", "releaseConfirm": "確認放行", "requiredQty": "需求數量", "matchWorkspace": "庫存匹配", "lineCount": "{count} 行庫存結果", "lineStatus": "匹配狀態", "matched": "已匹配", "shortage": "庫存不足", "matchStatus": {"not_found": "未匹配到庫存", "preparing": "庫存準備中", "mapping_failed": "庫存對應失敗", "unavailable": "庫存不可用", "source_conflict": "庫存來源衝突", "invalid_key": "匹配鍵無效", "result_missing": "等待匹配結果", "unknown": "狀態未知"}, "pending": "庫存匹配或通知檔案尚未產生。請查看右側目前處理,依目前門禁繼續。", "loadFailed": "通知準備任務詳情載入失敗,目前資料無法確認。", "detailUnavailable": "通知準備任務詳情尚未返回,暫時無法展示凍結訂單和庫存匹配資料。", "retry": "重新載入"},
"upload": {"title": "通知完成", "subtitle": "下載通知 Excel、上傳或登記人工上傳,並保留回執。", "manualUpload": "登記人工上傳", "receipt": "貨代回執:{value}", "attempt": "最近上傳嘗試:{mode} · {status}"}, "freightUpload": {"title": "貨代上傳", "subtitle": "下載通知 Excel、執行 RPA 或登記人工上傳;結果未知時請先核對。"},
"uploadComplete": {"title": "通知完成", "subtitle": "上傳成功證據已核驗,以下內容僅供查看。"},
"upload": {"title": "貨代上傳", "subtitle": "下載通知 Excel、上傳或登記人工上傳,並保留回執。", "manualUpload": "登記人工上傳", "receipt": "貨代回執:{value}", "attempt": "最近上傳嘗試:{mode} · {status}"},
"stages": { "stages": {
"intake_parse": "接收解析", "intake_parse": "接收解析",
"order_review": "訂單覆核", "order_review": "訂單覆核",
"fulfillment_prep": "通知準備", "fulfillment_prep": "通知準備",
"freight_upload": "貨代上傳",
"upload_complete": "通知完成" "upload_complete": "通知完成"
} }
}, },
@@ -1964,6 +1967,8 @@
"retrying": "識別中…", "retrying": "識別中…",
"retryDone": "已重新識別客戶", "retryDone": "已重新識別客戶",
"retryFailed": "重新識別客戶失敗", "retryFailed": "重新識別客戶失敗",
"uniqueCandidateHint": "已找到唯一標準客戶候選;儲存校驗時系統會自動確認,也可手動確認。",
"confirmUniqueCandidate": "確認唯一候選",
"confirmed": "客戶已確認", "confirmed": "客戶已確認",
"confirmReason": "訂單生命週期工作台人工確認標準客戶", "confirmReason": "訂單生命週期工作台人工確認標準客戶",
"pdfReparseHint": "若 PDF 版面錯誤,請使用頂部「重新識別此 PDF」,不要用本區按鈕。", "pdfReparseHint": "若 PDF 版面錯誤,請使用頂部「重新識別此 PDF」,不要用本區按鈕。",
@@ -2354,6 +2359,13 @@
"profile_ambiguous": "多個範本候選分差不足", "profile_ambiguous": "多個範本候選分差不足",
"profile_not_matched": "未匹配到可用範本", "profile_not_matched": "未匹配到可用範本",
"profile_drift": "版面相對範本發生漂移" "profile_drift": "版面相對範本發生漂移"
},
"coordinateModel": {
"anchorFrame": "錨點座標框架",
"status": "變換狀態",
"translateX": "橫向平移",
"translateY": "縱向平移",
"reasonCodes": "原因碼"
} }
}, },
"buildEligibility": { "buildEligibility": {
@@ -2361,6 +2373,7 @@
"subtitle": "檢查訂單資訊和庫存來源是否符合建立條件。", "subtitle": "檢查訂單資訊和庫存來源是否符合建立條件。",
"canBuildYes": "可建單", "canBuildYes": "可建單",
"canBuildNo": "暫不可建單", "canBuildNo": "暫不可建單",
"notValidated": "尚未校驗",
"manualBuildLabel": "人工建單", "manualBuildLabel": "人工建單",
"autoBuildLabel": "自動建單", "autoBuildLabel": "自動建單",
"autoBuildYes": "可自動建單", "autoBuildYes": "可自動建單",
+1 -1
View File
@@ -320,7 +320,7 @@
"freeze_not_ready": "訂單尚未滿足建單/凍結條件", "freeze_not_ready": "訂單尚未滿足建單/凍結條件",
"profile_not_auto_freeze_approved": "文件模板未通過自動建單審批", "profile_not_auto_freeze_approved": "文件模板未通過自動建單審批",
"profile_manual_confirmation_required": "文件模板需要人工確認", "profile_manual_confirmation_required": "文件模板需要人工確認",
"customer_unresolved": "客戶尚未識別", "customer_unresolved": "客戶尚未確認",
"customer_ambiguous": "客戶識別存在歧義", "customer_ambiguous": "客戶識別存在歧義",
"field_conflict": "欄位存在衝突,需人工裁決", "field_conflict": "欄位存在衝突,需人工裁決",
"duplicate_unresolved": "重複訂單尚未處理", "duplicate_unresolved": "重複訂單尚未處理",