Merge branch 'hugo-shipping-notice' into dev
# Conflicts: # frontend/src/features/chat/components/ChatViewContent.vue
This commit is contained in:
commit
80d78130f8
121 files changed
+9621
-1263
No files matched your search
@@ -0,0 +1,384 @@
|
||||
"""
|
||||
backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py
|
||||
|
||||
用途:验证客户识别三级命中(canonical 等值 > 完整包含 > 截断包含)与受控自动确认边界。
|
||||
依赖:内存数据库、customer_normalization、identity_resolution.resolver、
|
||||
customer_auto_resolution、customer_shadow_resolution。
|
||||
逻辑:以 QCH/Quanta 真实差异形态(标点变体、c/o 截断、折行块整段提取、家族前缀、
|
||||
跨行 vs 单行证据)构造分支,断言影子候选层级、状态语义,以及自动确认只放行
|
||||
「等值唯一」与「完整包含唯一且证据授权」,截断建议永不自动确认。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_auto_resolution import resolve_auto_customer_decision
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
IDENTITY_MATCH_CONTAINMENT_STRONG,
|
||||
IDENTITY_MATCH_CONTAINMENT_WEAK,
|
||||
IDENTITY_MATCH_EQUALITY,
|
||||
canonical_identity_key,
|
||||
classify_identity_containment,
|
||||
normalize_identity_evidence_value,
|
||||
)
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
from app.services.shipping_notice.identity_resolution import resolve_candidate_identity
|
||||
|
||||
FIELD_ID = 'fid-ship-to-customer'
|
||||
RULE_SET_DEF_ID = 'def-ship-to-customer'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestCanonicalIdentityKey:
|
||||
"""canonical 键:标点/空白/大小写不敏感,中文保留。"""
|
||||
|
||||
def test_punctuation_whitespace_case_insensitive(self):
|
||||
# 关键断言:QCH 注册值与 PDF 打印值的标点/空格差异不再分裂等值命中。
|
||||
assert canonical_identity_key('QCH, INC., A NEVADA CORPORATION') == canonical_identity_key(
|
||||
'qch inc a nevada corporation',
|
||||
)
|
||||
|
||||
def test_keeps_cjk_word_chars(self):
|
||||
# 关键断言:中文客户名不被剔除,仍可参与等值比较。
|
||||
assert canonical_identity_key('英業達股份有限公司桃科廠') == '英業達股份有限公司桃科廠'
|
||||
assert canonical_identity_key('Inventec 英業達') == 'inventec英業達'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestNormalizeIdentityEvidenceValue:
|
||||
"""识别证据统一归一化:三处调用点同源,兜底分支折叠内部空白。"""
|
||||
|
||||
def test_fallback_collapses_newlines(self):
|
||||
# 关键断言:多行提取值折叠换行后可与单行注册证据等值(修复换行不对称缺陷)。
|
||||
assert normalize_identity_evidence_value('QUANTA MFG,\n1 WALDENBOOKS DR.') == 'QUANTA MFG, 1 WALDENBOOKS DR.'
|
||||
|
||||
def test_name_normalizer_strips_punctuation(self):
|
||||
assert normalize_identity_evidence_value('Hyve, Solutions', normalizer_key='name') == 'HYVESOLUTIONS'
|
||||
|
||||
def test_email_branch_keeps_semantic_chars(self):
|
||||
assert normalize_identity_evidence_value('A@B.COM', option_key='from_email') == 'a@b.com'
|
||||
|
||||
def test_blank_returns_none(self):
|
||||
assert normalize_identity_evidence_value(' ') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestClassifyIdentityContainment:
|
||||
"""双向包含分级:强=指纹完整出现;弱=提取值疑似截断;邮箱/域名不参与。"""
|
||||
|
||||
EVIDENCE = 'QCH INC., A NEVADA CORPORATION C/O QUANTA'
|
||||
|
||||
def test_strong_when_fingerprint_fully_inside_runtime(self):
|
||||
# 关键断言:折行块整段进入字段值时,完整指纹命中判强包含(可受控自动确认)。
|
||||
assert classify_identity_containment(
|
||||
'QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC', self.EVIDENCE,
|
||||
) == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_weak_when_runtime_is_truncation(self):
|
||||
# 关键断言:截断方向只判弱命中——剩余部分未经验证,禁止自动确认。
|
||||
assert classify_identity_containment(
|
||||
'QCH, INC., A NEVADA CORPORATION c/o', self.EVIDENCE,
|
||||
) == IDENTITY_MATCH_CONTAINMENT_WEAK
|
||||
|
||||
def test_fragment_below_minimum_chars_rejected(self):
|
||||
# 关键断言:'c/o'→'CO' 这类短碎片不得产生包含噪声。
|
||||
assert classify_identity_containment('c/o', self.EVIDENCE) is None
|
||||
|
||||
def test_email_domain_never_contained(self):
|
||||
assert classify_identity_containment('ops@corp.com', 'ops@corp', option_key='from_email') is None
|
||||
|
||||
def test_unrelated_values_rejected(self):
|
||||
assert classify_identity_containment('HYVE SOLUTIONS CORPORATION', self.EVIDENCE) is None
|
||||
|
||||
|
||||
def _build_identity_world(*, runtime_value: str, evidences: list[dict]):
|
||||
"""
|
||||
构建最小识别世界:发布规则集 + 单 Header 字段抽取链 + 客户/证据主数据。
|
||||
|
||||
Args:
|
||||
runtime_value: 已裁决 Header 字段值(模拟 PDF 提取结果)。
|
||||
evidences: 注册证据列表,每项含 customer_name/short_code/normalized_value,
|
||||
可选 auto(默认 True,对应 auto_match_allowed)。
|
||||
Returns:
|
||||
(candidate, intake) 供 resolve_candidate_identity / 影子刷新使用。
|
||||
"""
|
||||
user = User(username='tier-user', email='tier@example.com', role='user')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', lock_version=1, checksum='1' * 64,
|
||||
definition_json={'fields': [{
|
||||
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'display_name': 'Ship To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'trim',
|
||||
}]},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
definition_json = {
|
||||
'order_schema': {'id': version.id, 'version': version.version, 'checksum': version.checksum},
|
||||
'definitions': [{
|
||||
'id': RULE_SET_DEF_ID, 'definition_code': 'ship_to_customer_rule',
|
||||
'display_name': 'Ship To Customer', 'evidence_label': 'Ship To',
|
||||
'target_type': 'customer', 'context_field_id': FIELD_ID,
|
||||
'default_weight': 100, 'max_automation': 'conditional', 'status': 'active',
|
||||
'field_config': {
|
||||
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'scope': 'header',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
'context_source': {'provider': 'order_field', 'option_key': None},
|
||||
'available_for_customer_identity': True,
|
||||
},
|
||||
}],
|
||||
}
|
||||
db.session.add(ShippingIdentityRuleSet(version=1, status='published', definition_json=definition_json, checksum='c' * 64))
|
||||
db.session.add(ShippingIdentityDefinition(
|
||||
id=RULE_SET_DEF_ID, definition_code='ship_to_customer_rule', target_type='customer',
|
||||
context_field_id=FIELD_ID, default_weight=100, max_automation='conditional', status='active',
|
||||
))
|
||||
intake = ShippingOrderIntake(intake_no='INT-TIER', asset_id=1, user_id=user.id, parser_version='test')
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
intake_id=intake.id, schema_version_id=version.id, input_snapshot_hash='h' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, field_id=FIELD_ID, decision_status='accepted', decided_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, field_id=FIELD_ID, decision_id=decision.id, value_text=runtime_value,
|
||||
))
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-TIER', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key='tier-test', candidate_status='accepted', order_extraction_id=extraction.id,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
for index, spec in enumerate(evidences, start=1):
|
||||
customer = ShippingCustomer(
|
||||
standard_name=spec['customer_name'], short_code=spec['short_code'], status='active',
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingIdentityEvidence(
|
||||
definition_id=RULE_SET_DEF_ID, customer_id=customer.id,
|
||||
raw_value=spec['normalized_value'], normalized_value=spec['normalized_value'],
|
||||
status='approved', auto_match_allowed=spec.get('auto', True),
|
||||
))
|
||||
db.session.commit()
|
||||
return candidate, intake
|
||||
|
||||
|
||||
class TestResolverTierMatching:
|
||||
"""影子识别三级命中与状态语义(resolve_candidate_identity)。"""
|
||||
|
||||
def test_punctuation_variant_hits_equality_tier(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:'QCH,' vs 'QCH' 标点差异经 canonical 等值命中,不再是 unmatched。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
|
||||
def test_truncated_runtime_becomes_weak_suggestion(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:c/o 截断形态产出唯一弱命中候选(unique_candidate 仅表示展示层唯一),
|
||||
# match_kind=containment_weak,交由人工确认。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_WEAK
|
||||
|
||||
def test_wrapped_block_hits_strong_containment(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:折行块整段提取时完整指纹出现,判强包含。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_family_prefix_stays_ambiguous(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:家族共享前缀同时包含命中 QCG/TW 两个站点客户 → ambiguous,不取首条。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='Quanta Computer Inc.',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'QUANTA QCG', 'short_code': 'QCG',
|
||||
'normalized_value': 'QUANTA COMPUTER INC. DE 2470.58.340',
|
||||
},
|
||||
{
|
||||
'customer_name': 'QUANTA TW', 'short_code': 'TWQ',
|
||||
'normalized_value': 'QUANTA COMPUTER INC. HQ PLANT',
|
||||
},
|
||||
],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'ambiguous'
|
||||
assert {item['match_kind'] for item in result['customer_matches']} == {IDENTITY_MATCH_CONTAINMENT_WEAK}
|
||||
|
||||
def test_equality_beats_containment_in_order(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:等值候选排在包含候选之前,且顶层唯一时状态为 unique_candidate。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
|
||||
'normalized_value': 'WISTRON CORPORATION',
|
||||
},
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
|
||||
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
},
|
||||
],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
names = {item['standard_name']: item for item in result['customer_matches']}
|
||||
# 关键断言:等值候选排第一,强包含候选次之;强层级唯一 → unique_candidate。
|
||||
assert result['customer_matches'][0]['standard_name'] == 'WIWYNN CZ BRNO'
|
||||
assert names['WIWYNN CZ BRNO']['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
assert names['WIWYNN CZ']['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_multiline_runtime_matches_single_line_evidence(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:运行侧换行折叠修复后,跨行提取值可与单行注册证据等值命中。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='Quanta Manufacturing Nashville, LLC,\n1 Waldenbooks Dr.',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QUANTA MANUFACTURING NASHVILLE, LLC, 1 WALDENBOOKS DR.',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
|
||||
|
||||
class TestAutoConfirmDecision:
|
||||
"""自动确认分级裁决(resolve_auto_customer_decision)。"""
|
||||
|
||||
def _shadow(self, candidate):
|
||||
return refresh_candidate_shadow_resolution(candidate)
|
||||
|
||||
def test_equality_unique_confirms_strong(self, app):
|
||||
with app.app_context():
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_strong_match'
|
||||
assert decision['customer_id'] is not None
|
||||
|
||||
def test_containment_strong_unique_confirms_with_match_kind(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:指纹完整出现的唯一包含命中且证据授权 → unique_containment_match,
|
||||
# 审计证据带 match_kind=containment_strong 溯源。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_containment_match'
|
||||
assert decision['customer_id'] is not None
|
||||
assert decision['evidence'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_truncation_only_never_confirms(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:截断形态(本单 7911678818.PDF)永不自动确认,保持 unmatched 交人工。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unmatched'
|
||||
assert decision['customer_id'] is None
|
||||
|
||||
def test_unauthorized_evidence_never_confirms(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:auto_match_allowed=False 的证据即使等值唯一也不自动确认。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION', 'auto': False,
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unmatched'
|
||||
assert decision['customer_id'] is None
|
||||
|
||||
def test_equality_precedes_containment(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:等值命中存在时包含命中不参与裁决,等值客户唯一即确认。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
|
||||
'normalized_value': 'WISTRON CORPORATION',
|
||||
},
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
|
||||
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
},
|
||||
],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_strong_match'
|
||||
customers = {c.id: c.standard_name for c in ShippingCustomer.query.all()}
|
||||
assert customers[decision['customer_id']] == 'WIWYNN CZ BRNO'
|
||||
@@ -235,6 +235,180 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
|
||||
assert bundle['user_status'] == 'waiting_human'
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [BR] blocking_reason 资格快照回退:
|
||||
# automation 无具体原因码时,回退到草稿校验快照(validation_result_json)
|
||||
# 中首要 blocking issue 的冻结 explainability 透传(code/message/next_action),
|
||||
# 让批次中心与工作台展示具体原因,而非「当前步骤需要人工处理」兜底。
|
||||
# ============================================================
|
||||
|
||||
def _validation_snapshot_with_issues(issues: list[dict]) -> dict:
|
||||
"""构造与 order_build_eligibility 持久化结构一致的 validation 快照。"""
|
||||
return {'can_build': False, 'can_auto_create': False, 'issues': issues}
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_falls_back_to_primary_validation_issue_when_automation_lacks_reason():
|
||||
"""[BR-1] automation 无具体原因码时,blocking_reason 必须回退到首要 blocking issue。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
'message': '客户尚未确认',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
# 断言意图:透传冻结契约的事实三元组,前端据此展示「客户尚未确认 / 确认客户」
|
||||
assert reason['code'] == 'customer_unresolved'
|
||||
assert reason['message'] == '客户尚未确认'
|
||||
assert reason['next_action'] == 'confirm_customer'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_validation_fallback_skips_degraded_and_non_blocking_issues():
|
||||
"""[BR-2] 降级码(unknown_business_failure)与非 blocking issue 不进入回退。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
# 仅阻断自动建单,不属用户阻断
|
||||
{
|
||||
'code': 'candidate_qualification_blocked',
|
||||
'severity': 'auto_create_blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'llm_path_cannot_auto_freeze',
|
||||
'message': '智能识别结果尚未通过自动建单资格检查',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
# 契约降级码:不透传给用户
|
||||
{
|
||||
'code': 'weird_new_issue',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'unknown_business_failure',
|
||||
'message': '业务处理失败,请凭请求编号联系管理员',
|
||||
'next_action': '',
|
||||
},
|
||||
},
|
||||
# 首个可用 blocking issue
|
||||
{
|
||||
'code': 'required_field_missing',
|
||||
'severity': 'blocking',
|
||||
'field_code': 'reservation_id',
|
||||
'explainability': {
|
||||
'reason_code': 'required_field_missing',
|
||||
'message': '缺少创建订单所需字段',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'required_field_missing'
|
||||
assert reason['next_action'] == 'open_order_review'
|
||||
assert reason['details'].get('field_code') == 'reservation_id'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_keeps_mapped_automation_reason_over_validation_fallback(monkeypatch):
|
||||
"""[BR-3] automation 已有映射的具体原因码时不回退,避免覆盖更精确的裁决。"""
|
||||
from app.services.shipping_notice import reconciliation_projector
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
monkeypatch.setattr(
|
||||
reconciliation_projector,
|
||||
'project_case_automation_status',
|
||||
lambda case, *, validation, post_confirm: {
|
||||
'status': 'manual_fallback',
|
||||
'retryable': False,
|
||||
'reason_code': 'duplicate_decision_required',
|
||||
},
|
||||
)
|
||||
bundle = reconciliation_projector.project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'duplicate_decision_required'
|
||||
assert reason.get('message') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_without_usable_issues_keeps_legacy_blocking_reason():
|
||||
"""[BR-4] 快照无可用 issue 时保持既有兜底行为(不得抛错、不得造原因)。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation={'can_build': True, 'can_auto_create': True, 'issues': []},
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert isinstance(reason, dict)
|
||||
assert reason.get('message') is None
|
||||
assert reason.get('next_action') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_unmapped_automation_reason_uses_existing_generic_i18n_key():
|
||||
"""[BR-5] 未映射原因码的 fail-closed 兜底必须指向前端真实存在的键。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_blocking_reason,
|
||||
)
|
||||
|
||||
reason = project_case_blocking_reason({
|
||||
'status': 'manual_fallback',
|
||||
'reason_code': 'totally_new_unmapped_code',
|
||||
})
|
||||
|
||||
assert reason['code'] == 'totally_new_unmapped_code'
|
||||
# 此前指向不存在的 shipping.review.blocked_generic,任何未映射码都会双重落空
|
||||
assert reason['i18n_key'] == 'chat.shippingProcessing.reasonCode.unknown'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task():
|
||||
"""字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。"""
|
||||
|
||||
@@ -91,7 +91,7 @@ def test_fetch_gate_positions_batched(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
ot_b = ShippingOrderTask(
|
||||
@@ -345,7 +345,7 @@ def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
|
||||
@@ -29,6 +29,14 @@ RESERVATION_DEFINITION = {
|
||||
],
|
||||
}
|
||||
|
||||
LN_RESERVATION_DEFINITION = {
|
||||
'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1},
|
||||
'fields': DEFINITION['fields'] + [
|
||||
{'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line', 'required': True},
|
||||
{'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line'},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _row(po: str, part: str) -> dict:
|
||||
return {'status': 'parsed', 'issues': [], 'fields': [
|
||||
@@ -38,6 +46,12 @@ def _row(po: str, part: str) -> dict:
|
||||
]}
|
||||
|
||||
|
||||
def _ln_row(po: str, part: str, ln: str) -> dict:
|
||||
row = _row(po, part)
|
||||
row['fields'].append({'field_id': 'ln', 'value': ln, 'quote': ln})
|
||||
return row
|
||||
|
||||
|
||||
def _page_glyphs(*lines: str) -> list[dict]:
|
||||
"""构造跨页 Reservation 路由回归所需的最小坐标文字。"""
|
||||
glyphs = []
|
||||
@@ -152,6 +166,63 @@ def test_approved_pdf_marks_conflicting_reservation_region_for_review():
|
||||
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
|
||||
|
||||
|
||||
def test_approved_pdf_maps_reservation_by_printed_ln_when_ln_non_contiguous():
|
||||
"""PO_6075309 回归:LN=1/2/4/5 非连续时 L#n 必须按 LN 值落行,整单不转复核。
|
||||
|
||||
关键断言:L#4/L#5 分别写入 LN=4/LN=5 行(旧位置序会把 L#4 错配到 LN=5 并把
|
||||
L#5 误报 line_out_of_range);行级 reservation 已全部归属后 source_missing_fields
|
||||
不得残留 line_index 0 的假缺失(``or -1`` falsy bug)。
|
||||
"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=LN_RESERVATION_DEFINITION,
|
||||
table={'rows': [
|
||||
_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2'),
|
||||
_ln_row('PO-1', 'P-4', '4'), _ln_row('PO-1', 'P-5', '5'),
|
||||
]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '1000159370', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation L#1: 1000159370'},
|
||||
{'value': '1000159366', 'scope': 'line', 'line_no': 2, 'raw_text': 'Reservation L#2: 1000159366'},
|
||||
{'value': '1000159379', 'scope': 'line', 'line_no': 4, 'raw_text': 'Reservation L#4: 1000159379'},
|
||||
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
order = (orders or [])[0]
|
||||
assert order.get('reservation_region_status') != 'needs_review'
|
||||
assert 'source_missing_fields' not in order
|
||||
expected_by_ln = {'1': '1000159370', '2': '1000159366', '4': '1000159379', '5': '1000159236'}
|
||||
for line in order['lines']:
|
||||
ln = next(item['observations'][0]['value'] for item in line['fields'] if item['field_id'] == 'ln')
|
||||
assert any(
|
||||
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == expected_by_ln[ln]
|
||||
for item in line['fields']
|
||||
)
|
||||
|
||||
|
||||
def test_approved_pdf_keeps_reservation_review_when_referenced_ln_row_is_missing():
|
||||
"""被引用的印刷行号在解析行中不存在时必须转复核,不得按位置静默写入。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=LN_RESERVATION_DEFINITION,
|
||||
table={'rows': [_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2')]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
order = (orders or [])[0]
|
||||
assert order['reservation_region_status'] == 'needs_review'
|
||||
assert order['reservation_region_review_reasons'] == ['line_out_of_range']
|
||||
# LN=1/LN=2 行无对应候选,reservation 保持缺失供人工补录。
|
||||
assert all(
|
||||
not any(item['field_id'] == 'line-reservation' for item in line['fields'])
|
||||
for line in order['lines']
|
||||
)
|
||||
|
||||
|
||||
def test_enabled_reservation_region_reads_vendor_comments_across_pages():
|
||||
"""已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。"""
|
||||
result = _reservation_region_candidates(
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
"""
|
||||
tests/test_order_profile_header_identity.py
|
||||
|
||||
用途:锁定 schema_canonical_header_atoms / schema_canonical_header_tokens 的表头
|
||||
别名语义归一行为,及其在表头原子硬互斥(_header_discriminator_atoms_conflict)
|
||||
与 signature_conflict 二次机会门禁中的防回归契约;含真实故障单 PO_6075316
|
||||
(日期换词 + 相邻列并格 + 空串 token)的形状回归。
|
||||
依赖:order_profile_matcher.schema_canonical_header_atoms /
|
||||
schema_canonical_header_tokens / _header_token_atoms /
|
||||
_header_discriminator_atoms_conflict。
|
||||
逻辑:pure_unit;别名命中产出 field::<field_code> 标记原子(atoms 为集合语义、
|
||||
tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤;
|
||||
None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date
|
||||
别名的契约下跨措辞对齐,异义词不归并。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_header_discriminator_atoms_conflict,
|
||||
_header_token_atoms,
|
||||
schema_canonical_header_atoms,
|
||||
schema_canonical_header_tokens,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_none_or_empty_mapping_degrades_to_word_atoms():
|
||||
"""未配置别名表时必须与既有词级原子化完全一致(零行为变化)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', 'Unit Price']
|
||||
# 关键断言:None 与空 dict 均退化为 _header_token_atoms,结果与直接调用逐项相等
|
||||
assert schema_canonical_header_atoms(tokens, None) == _header_token_atoms(tokens)
|
||||
assert schema_canonical_header_atoms(tokens, {}) == _header_token_atoms(tokens)
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记原子
|
||||
assert not any(
|
||||
atom.startswith('field::')
|
||||
for atom in schema_canonical_header_atoms(tokens, None)
|
||||
)
|
||||
|
||||
|
||||
def test_exact_phrase_hit_emits_field_marker():
|
||||
"""别名精确命中时短语整体替换为 field::<field_code>,不残留短语内单词。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{'requested ship date': 'requested_receipt_date'},
|
||||
)
|
||||
# 关键断言:命中段落被消费,仅剩语义标记原子,词级原子 requested/ship/date 不再出现
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_merged_cell_greedy_decomposition():
|
||||
"""合并格长文案按贪心最长短语分解为多个 field 标记原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:两个别名短语各自命中并消费整段,互不残留单词原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date', 'field::unit_price'})
|
||||
|
||||
|
||||
def test_greedy_prefers_longest_phrase():
|
||||
"""同一位置长短短语重叠时必须取最长短语(贪心最长匹配)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{
|
||||
'ship date': 'ship_date',
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:最长短语胜出且整段消费,短短语不产生任何残留 field/词级原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_case_insensitive_matching():
|
||||
"""表头与别名 key 大小写不同仍命中(casefold 同源词管线)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['UNIT PRICE'],
|
||||
{'Unit Price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:大小写差异不阻断短语命中,field_code 保留别名表原样
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_unmatched_words_kept_and_short_words_filtered():
|
||||
"""未命中别名的词沿用既有过滤:长度 >=3 且非虚词才保留为词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Total Amount ok the ab'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:total/amount 保留;'ok'/'ab' 过短被滤;'the' 为虚词被滤
|
||||
assert atoms == frozenset({'total', 'amount'})
|
||||
|
||||
mixed = schema_canonical_header_atoms(
|
||||
['Unit Price Remarks ok'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:同一 token 内 field 标记原子与词级原子可共存
|
||||
assert mixed == frozenset({'field::unit_price', 'remarks'})
|
||||
|
||||
|
||||
def test_empty_tokens_skipped():
|
||||
"""空串/纯空白 token(MinerU 空格占位)直接跳过且不影响其余 token。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['', ' ', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:空白 token 不产生原子也不中断匹配,后续 token 照常命中
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_chinese_alias_yields_no_field_atom():
|
||||
"""中文别名切词为空 → 自然跳过(有意行为:词级原子只保留 [a-z0-9])。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['数量', 'Qty'],
|
||||
{'数量': 'quantity'},
|
||||
)
|
||||
# 关键断言:中文别名不产生 field:: 原子;词级原子口径不变(qty 长度 >=3 保留)
|
||||
assert atoms == frozenset({'qty'})
|
||||
|
||||
|
||||
def test_casefold_collision_phrase_discarded():
|
||||
"""同一短语 casefold 后映射到多个 field_code → 整体弃用,回退词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{
|
||||
'Ship Date': 'ship_date',
|
||||
'ship date': 'requested_ship_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:歧义短语不得产出任何 field:: 原子;未命中单词走既有过滤保留
|
||||
assert atoms == frozenset({'ship', 'date'})
|
||||
|
||||
|
||||
def test_casefold_equal_duplicate_alias_kept():
|
||||
"""同短语重复别名但 field_code 仅大小写不同 → 不视为歧义,短语保留。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{'Ship Date': 'ship_date', 'SHIP DATE': 'SHIP_DATE'},
|
||||
)
|
||||
# 关键断言:casefold 视角同码不构成身份歧义,短语照常产出标记原子
|
||||
assert atoms == frozenset({'field::ship_date'})
|
||||
|
||||
|
||||
# --- PO_6075316 真实故障形状回归:别名契约 vs 表头原子硬互斥 ---
|
||||
|
||||
_SIGNATURE_TRAINING_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Arrival Date', 'Unit Price', 'Extension',
|
||||
]
|
||||
_PO6075316_OBSERVED_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Ship Date Unit Price', '', 'Extension',
|
||||
]
|
||||
_SCHEMA_V4_HEADER_TO_FIELD = {
|
||||
'Requested Receipt Date': 'requested_receipt_date',
|
||||
'Requested Arrival Date': 'requested_receipt_date',
|
||||
'Requested Ship Date': 'requested_receipt_date',
|
||||
'Unit Price': 'unit_price',
|
||||
'Extension': 'line_amount_with_tax',
|
||||
'Part Number': 'customer_part_number',
|
||||
'Vendor Item': 'part_number',
|
||||
'Quantity': 'qty',
|
||||
'LN': 'customer_po_line_no',
|
||||
}
|
||||
|
||||
|
||||
def _po6075316_signature() -> dict:
|
||||
"""训练签名(命中模板 HYVE)的明细表 header_tokens 形状。"""
|
||||
return {'table_patterns': [{'header_tokens': list(_SIGNATURE_TRAINING_TOKENS)}]}
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_passes_with_ship_date_alias_contract():
|
||||
"""PO_6075316 形状(日期换词+并格+空串)在含 Ship Date 别名契约下不再互斥。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:两侧经 Schema 别名归一后字段语义原子全等,硬互斥判定为不冲突
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is False
|
||||
# 佐证:'Requested Ship Date' 与 'Requested Arrival Date' 归一为同一标记原子;
|
||||
# 并格长文案贪心分解出日期+单价两个标记原子;空串 token(MinerU 占位)零原子。
|
||||
assert schema_canonical_header_atoms(
|
||||
observed['header_tokens'], _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) == schema_canonical_header_atoms(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_still_conflicts_without_alias_contract():
|
||||
"""同形状不传契约(或契约缺 Ship Date 别名)时互斥仍在——豁免效果来自别名。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:不传 header_to_field 时两侧退化词级原子,arrival≠ship,既有互斥零变化
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(), observed=observed,
|
||||
) is True
|
||||
contract_without_ship_alias = {
|
||||
key: value
|
||||
for key, value in _SCHEMA_V4_HEADER_TO_FIELD.items()
|
||||
if key != 'Requested Ship Date'
|
||||
}
|
||||
# 关键断言:契约缺 Ship Date 别名时观测侧 ship 退回词级原子,互斥依旧成立
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=contract_without_ship_alias,
|
||||
) is True
|
||||
|
||||
|
||||
def test_po6075316_foreign_date_word_not_merged_by_alias():
|
||||
"""日期列换成未配别名的真正异义词(Customer PO Date)时不得归并,互斥仍触发。"""
|
||||
observed = {'header_tokens': [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Customer PO Date Unit Price', '', 'Extension',
|
||||
]}
|
||||
# 关键断言:别名契约只归并已治理措辞,不同语义字段(客户 PO 日期)保持互斥
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is True
|
||||
|
||||
|
||||
# --- schema_canonical_header_tokens:序列语义 canonical 归一(二次机会门禁供料) ---
|
||||
|
||||
def test_tokens_none_or_empty_mapping_returns_input_list_unchanged():
|
||||
"""None/空 dict 时原样返回输入列表(零归一,与 atoms 的退化口径一致)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', '']
|
||||
# 关键断言:None 与空 dict 均不做任何归一,列表内容原样返回
|
||||
assert schema_canonical_header_tokens(tokens, None) == tokens
|
||||
assert schema_canonical_header_tokens(tokens, {}) == tokens
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记项
|
||||
assert not any(item.startswith('field::') for item in schema_canonical_header_tokens(tokens, None))
|
||||
|
||||
|
||||
def test_tokens_hit_phrase_collapses_to_single_item_and_keeps_order():
|
||||
"""命中片段坍缩为单个 field 标记列表项,且保持在原 token 的序列位置。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Requested Ship Date', 'Remarks', 'Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:命中短语各坍缩为单列表项并按原顺序交错排列,短语内单词不残留
|
||||
assert canonical == [
|
||||
'field::requested_receipt_date', 'remarks', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_sequence_semantics_keeps_duplicates_and_unmatched_words():
|
||||
"""序列语义:允许重复、未命中词原样保留——与 atoms 的集合语义形成对照。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Unit Price', 'Total Amount ok the ab', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:重复 token 各自产出标记项(不去重);total/amount 原词保序保留;
|
||||
# 'ok'/'ab' 过短、'the' 为虚词被滤(与 atoms 同一过滤口径)
|
||||
assert canonical == [
|
||||
'field::unit_price', 'total', 'amount', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_dedup_equals_atoms_same_source_semantics():
|
||||
"""同源语义:同一输入下 tokens 版去重即 atoms 版结果(同管线同短语匹配)。"""
|
||||
tokens = ['', ' ', 'Requested Ship Date Unit Price', 'Vendor Item#', 'ok the ab']
|
||||
mapping = {
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
'vendor item': 'part_number',
|
||||
}
|
||||
canonical = schema_canonical_header_tokens(tokens, mapping)
|
||||
atoms = schema_canonical_header_atoms(tokens, mapping)
|
||||
# 关键断言:序列版去重后与集合版逐项相等——两条路径完全同源,不得漂移
|
||||
assert set(canonical) == set(atoms)
|
||||
# 关键断言:空白 token 不产出列表项(与 atoms 跳过口径一致)
|
||||
assert len(canonical) == len([item for item in canonical if item])
|
||||
|
||||
|
||||
def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias():
|
||||
"""PO_6075316 形状在含 Ship Date 别名下两侧 canonical 序列逐项相等(保序)。"""
|
||||
canonical_expected = schema_canonical_header_tokens(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
canonical_observed = schema_canonical_header_tokens(
|
||||
_PO6075316_OBSERVED_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
# 关键断言:并格长文案贪心分解出的标记原子序列与训练侧完全一致(含顺序),
|
||||
# 供二次机会门禁按序列比较得出满配额软分
|
||||
assert canonical_expected == canonical_observed
|
||||
# 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住)
|
||||
assert canonical_expected[0] == 'field::customer_po_line_no'
|
||||
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
backend/tests/test_shipping_conversation_title.py
|
||||
|
||||
用途:验证订单抽取会话标题纯函数的派生规则(前缀剥离/截断/计数后缀/日期/回退)。
|
||||
依赖:纯函数,无 Flask/DB 夹具。
|
||||
逻辑:命名是内容派生的确定性函数,用逐条断言锁定规则,防止后续误改口径。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.shipping_notice.conversation_title import derive_order_extraction_title
|
||||
|
||||
|
||||
def test_strips_leading_mail_prefixes_and_appends_date():
|
||||
"""首个文件名循环剥离 Re/Fw/Fwd/回复/转发 前缀,末尾追加 MM-DD。"""
|
||||
title = derive_order_extraction_title(['回复:转发:FWD: PO#6075309.eml'], datetime(2026, 9, 15))
|
||||
assert title == 'PO#6075309 09-15'
|
||||
|
||||
|
||||
def test_multi_files_appends_count_suffix():
|
||||
"""文件总数大于 1 时追加「等 N 个文件」,N 按传入文件名总数计。"""
|
||||
title = derive_order_extraction_title(['PO#6075309.eml', 'invoice.pdf', 'list.pdf'], datetime(2026, 9, 15))
|
||||
assert title == 'PO#6075309 等 3 个文件 09-15'
|
||||
|
||||
|
||||
def test_truncates_long_name_to_24_chars():
|
||||
"""主名超过 24 字符截断,且不吞掉日期后缀。"""
|
||||
title = derive_order_extraction_title(['A' * 30 + '.pdf'], datetime(2026, 12, 31))
|
||||
assert title == 'A' * 24 + ' 12-31'
|
||||
|
||||
|
||||
def test_blank_filenames_fall_back_to_default():
|
||||
"""文件名全空(含空列表与纯空白项)回退写死标题「订单抽取」。"""
|
||||
assert derive_order_extraction_title([], datetime(2026, 9, 15)) == '订单抽取'
|
||||
assert derive_order_extraction_title(['', ' '], datetime(2026, 9, 15)) == '订单抽取'
|
||||
@@ -0,0 +1,227 @@
|
||||
"""
|
||||
backend/tests/test_shipping_done_line_report.py
|
||||
|
||||
用途:已完成通知明细行报表(done-lines)查询与专用导出的单测。
|
||||
依赖:pytest、openpyxl、ShippingNotice/OT/Snapshot/Artifact 夹具、done_line_report。
|
||||
逻辑:覆盖 12 字段映射(typed 列 + field_values_json 回源与回退)、可见性(非本人不可见、
|
||||
未上传成功不进报表)、客户/料号/发货通知日期筛选、分页、导出表头与留空行为。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
ShippingExportArtifact,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
)
|
||||
from app.services.shipping_notice.done_line_report import (
|
||||
DONE_REPORT_HEADERS,
|
||||
build_done_lines_xlsx,
|
||||
list_done_notice_lines,
|
||||
)
|
||||
|
||||
|
||||
def _seed_report_fixture(db, *, owner: int):
|
||||
"""最小报表夹具:一张已完成双行通知 + 一张仅 ready 未上传的通知(应被排除)。"""
|
||||
order = ShippingOrderTask(task_no="OT-DONE-LINE", source_type="direct_pdf", user_id=owner)
|
||||
pending_order = ShippingOrderTask(task_no="OT-DONE-LINE-PENDING", source_type="direct_pdf", user_id=owner)
|
||||
notice = ShippingNotice(task_no="SN-DONE-LINE", source_type="manual", user_id=owner)
|
||||
pending_notice = ShippingNotice(task_no="SN-DONE-LINE-PENDING", source_type="manual", user_id=owner)
|
||||
db.session.add_all([order, pending_order, notice, pending_notice])
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='DONELINE', display_name='DoneLine', version=1, status='published',
|
||||
storage_bucket='test', storage_key='done.xlsx', original_filename='done.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='DONELINE', display_name='DoneLine', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='DONELINE', display_name='DoneLine')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': []},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
|
||||
# 标准字段资产:约定出货日期(行级)与来源单号(表头级),值为 field_id 键 JSON。
|
||||
db.session.add(ShippingOrderField(
|
||||
id='f-req-date', field_code='required_date', scope='line', value_type='date',
|
||||
field_category='order_line', collection_mode='deterministic_context',
|
||||
asset_kind='system_standard', storage_mode='typed_column', storage_column='required_date',
|
||||
))
|
||||
db.session.add(ShippingOrderField(
|
||||
id='f-source-order', field_code='source_order_number', scope='header', value_type='string',
|
||||
field_category='order_header', collection_mode='deterministic_context',
|
||||
asset_kind='system_standard', storage_mode='json_only',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
customer_name='HYVE CS', customer_code='HC001', customer_po_number='306085',
|
||||
order_date=date(2026, 6, 1), required_date=date(2026, 6, 15),
|
||||
header_values_json={'f-source-order': '8301-2606010052'},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, line_no=1,
|
||||
part_number='B3-A08AR10000017-A6', qty=80, unit_price=1525.08,
|
||||
field_values_json={'f-req-date': '2026-06-15'},
|
||||
),
|
||||
ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=2, line_no=2,
|
||||
part_number='D4-A08AR12000001', qty=1000, unit_price=898.72,
|
||||
field_values_json={},
|
||||
),
|
||||
])
|
||||
order.order_snapshot_id = snapshot.id
|
||||
notice.order_task_id = order.id
|
||||
|
||||
extraction_two = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='e' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction_two)
|
||||
db.session.flush()
|
||||
pending_snapshot = ShippingOrderSnapshot(
|
||||
task_id=pending_order.id, extraction_id=extraction_two.id, schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
customer_name='PENDING CS', customer_code='PC001',
|
||||
)
|
||||
db.session.add(pending_snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=pending_snapshot.id, position=1, line_no=1, part_number='X-1', qty=1,
|
||||
))
|
||||
pending_order.order_snapshot_id = pending_snapshot.id
|
||||
pending_notice.order_task_id = pending_order.id
|
||||
|
||||
def add_artifact(target, *, artifact_no: str, status: str) -> None:
|
||||
"""为 Notice 建立报表口径所需的最小 Artifact。"""
|
||||
db.session.add(ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=target.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status=status,
|
||||
))
|
||||
|
||||
add_artifact(notice, artifact_no='ART-DONE-LINE', status='uploaded')
|
||||
add_artifact(pending_notice, artifact_no='ART-DONE-LINE-PENDING', status='ready')
|
||||
db.session.commit()
|
||||
return notice
|
||||
|
||||
|
||||
def test_list_done_notice_lines_maps_standard_fields(app):
|
||||
"""明细行平铺不按 OT 聚合;12 字段含 JSON 回源与表头回退,无数据源字段留空。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 88
|
||||
_seed_report_fixture(db, owner=owner)
|
||||
|
||||
result = list_done_notice_lines(owner, page=1, page_size=20)
|
||||
# 断言:仅 uploaded 通知进入报表;两行明细平铺,OT 不聚合。
|
||||
assert result["total"] == 2
|
||||
assert {item["line_no"] for item in result["items"]} == {1, 2}
|
||||
first = next(item for item in result["items"] if item["line_no"] == 1)
|
||||
# 断言:溯源编号 + 标准 12 字段映射。
|
||||
assert first["task_no"] == "SN-DONE-LINE"
|
||||
assert first["customer_name"] == "HYVE CS"
|
||||
assert first["customer_code"] == "HC001"
|
||||
assert first["order_date"] == "2026-06-01"
|
||||
assert first["part_number"] == "B3-A08AR10000017-A6"
|
||||
assert first["qty"] == 80.0
|
||||
# 行级 field_values_json 有值时优先于快照表头 typed 列。
|
||||
assert first["required_date"] == "2026-06-15"
|
||||
assert first["customer_po_number"] == "306085"
|
||||
assert first["source_order_number"] == "8301-2606010052"
|
||||
assert first["unit_price"] == 1525.08
|
||||
# 已用数量 / open qty 当前无数据源,契约留空。
|
||||
assert first["used_qty"] is None
|
||||
assert first["open_qty"] is None
|
||||
second = next(item for item in result["items"] if item["line_no"] == 2)
|
||||
# 断言:行级无 required_date 时回退快照表头 typed 列。
|
||||
assert second["required_date"] == "2026-06-15"
|
||||
assert second["source_order_number"] == "8301-2606010052"
|
||||
|
||||
# 断言:其他用户不可见(非管理员仅创建者)。
|
||||
assert list_done_notice_lines(999)["total"] == 0
|
||||
|
||||
|
||||
def test_list_done_notice_lines_filters_and_pagination(app):
|
||||
"""客户/料号/发货通知日期筛选与按明细行分页生效。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 89
|
||||
_seed_report_fixture(db, owner=owner)
|
||||
|
||||
# 客户模糊(大小写不敏感)。
|
||||
assert list_done_notice_lines(owner, customer="hyve")["total"] == 2
|
||||
assert list_done_notice_lines(owner, customer="不存在")["total"] == 0
|
||||
# 料号模糊(命中单行)。
|
||||
part_page = list_done_notice_lines(owner, part_number="B3-")
|
||||
assert part_page["total"] == 1
|
||||
assert part_page["items"][0]["part_number"] == "B3-A08AR10000017-A6"
|
||||
# 发货通知日期范围:今天闭区间命中;未来区间为空。
|
||||
today = datetime.utcnow().date()
|
||||
assert list_done_notice_lines(
|
||||
owner, notice_date_from=today.isoformat(), notice_date_to=today.isoformat(),
|
||||
)["total"] == 2
|
||||
tomorrow = (today + timedelta(days=1)).isoformat()
|
||||
assert list_done_notice_lines(owner, notice_date_from=tomorrow)["total"] == 0
|
||||
# 按明细行分页。
|
||||
page_one = list_done_notice_lines(owner, page=1, page_size=1)
|
||||
page_two = list_done_notice_lines(owner, page=2, page_size=1)
|
||||
assert page_one["total"] == 2
|
||||
assert {page_one["items"][0]["line_no"], page_two["items"][0]["line_no"]} == {1, 2}
|
||||
|
||||
|
||||
def test_build_done_lines_xlsx_writes_fixed_twelve_columns(app):
|
||||
"""导出严格 12 列标准格式:OT 编号不落列,无数据源列留空。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 90
|
||||
_seed_report_fixture(db, owner=owner)
|
||||
|
||||
stream, filename = build_done_lines_xlsx(owner)
|
||||
assert filename.startswith("done-lines-") and filename.endswith(".xlsx")
|
||||
workbook = load_workbook(stream)
|
||||
sheet = workbook.active
|
||||
rows = list(sheet.iter_rows(values_only=True))
|
||||
# 断言:表头为固定 12 列中文标准格式。
|
||||
assert tuple(rows[0]) == DONE_REPORT_HEADERS
|
||||
# 断言:两行明细,且不含 OT 编号列;数量/单价写数值,无数据源列留空。
|
||||
assert len(rows) == 3
|
||||
first_data = rows[1]
|
||||
assert first_data[0] == "HYVE CS"
|
||||
assert first_data[3] == 1
|
||||
assert first_data[4] == "B3-A08AR10000017-A6"
|
||||
assert first_data[5] == 80.0
|
||||
assert first_data[8] is None
|
||||
assert first_data[9] is None
|
||||
assert first_data[10] == "8301-2606010052"
|
||||
assert first_data[11] == 1525.08
|
||||
@@ -896,3 +896,260 @@ def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch
|
||||
with pytest.raises(RuntimeError, match='commit failed'):
|
||||
_commit_generated_export(str(path))
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def _build_multi_odm_notice(
|
||||
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
|
||||
):
|
||||
"""
|
||||
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
|
||||
|
||||
Args:
|
||||
odm_values: 单订单行场景下库存行命中的 ODM 值列表。
|
||||
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
|
||||
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
|
||||
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
|
||||
Returns:
|
||||
(notice, customer)。
|
||||
"""
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema); db.session.flush()
|
||||
part = _lookup_standard_fields('part_number')['part_number']
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||||
db.session.add(version); db.session.flush()
|
||||
draft = excel_template.create_draft(_workbook_upload(), {
|
||||
'template_code': 'ODMSCOPE', 'display_name': 'OdmScope',
|
||||
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
|
||||
{'sheet': 'Detail', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
|
||||
]},
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
profile_code='ODMSCOPE', display_name='OdmScope', version=1, status='published', file_format='xlsx',
|
||||
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
|
||||
)
|
||||
login = ShippingRpaProfile(
|
||||
profile_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', login_url='https://invalid',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add_all([parsing, login]); db.session.flush()
|
||||
db.session.add(ShippingInventorySource(
|
||||
source_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
customer = ShippingCustomer(
|
||||
standard_name='ODM范围客户', short_code='ODMSC', status='active',
|
||||
odm_ids=list(customer_odm_ids) if customer_odm_ids is not None else None,
|
||||
)
|
||||
db.session.add(customer); db.session.flush()
|
||||
ot = ShippingOrderTask(task_no='OT-ODMSCOPE', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(ot); db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction); db.session.flush()
|
||||
specs = line_specs or [{'part': 'PN-A', 'odm_values': odm_values}]
|
||||
snapshot_lines = []
|
||||
for index, spec in enumerate(specs, start=1):
|
||||
order_line = ShippingOrderLine(extraction_id=extraction.id, position=index, line_no=index)
|
||||
db.session.add(order_line); db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
|
||||
decision_status='accepted', resolved_value_json=spec['part'],
|
||||
)
|
||||
db.session.add(decision); db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
|
||||
value_text=spec['part'], decision_id=decision.id,
|
||||
))
|
||||
snapshot_lines.append((index, part.id, spec['part'], 1, f'100000000{index}'))
|
||||
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
|
||||
inventory_rows = []
|
||||
for spec in specs:
|
||||
for odm in spec['odm_values']:
|
||||
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
|
||||
storage_path=str(tmp_path / 'odm-scope.xlsx'),
|
||||
inventory_lines_json=inventory_rows,
|
||||
line_count=len(inventory_rows), share_mode='task_only', warehouse_id='DUB', source_code='ODMSCOPE',
|
||||
snapshot_status='ready',
|
||||
)
|
||||
db.session.add(inventory_file); db.session.flush()
|
||||
snapshot = _freeze_export_snapshot(
|
||||
ot, extraction, version,
|
||||
lines=snapshot_lines,
|
||||
customer_id=customer.id, inventory_file_id=inventory_file.id,
|
||||
)
|
||||
notice = _materialize_export_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
|
||||
)
|
||||
if choice_odm is not None:
|
||||
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
|
||||
match.chosen_odm_id = choice_odm
|
||||
db.session.flush()
|
||||
return notice, customer
|
||||
|
||||
|
||||
def test_export_narrows_odm_by_customer_range(app, tmp_path):
|
||||
"""客户 ODM ID 范围非空时,导出只取范围内库存行;范围命中唯一值写入表头。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['odm-2'],
|
||||
)
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_odm_range_excluding_all_raises_specific_error(app, tmp_path):
|
||||
"""客户范围把全部命中排除时,必须报指向客户数据的可行动错误而非「没有匹配」。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-9'],
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match='不在客户数据维护的 ODM ID 范围'):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_export_applies_notice_odm_choice(app, tmp_path):
|
||||
"""整单用户选择优先于多值冲突;选择经 casefold 归一后命中库存行。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], choice_odm='odm-2',
|
||||
)
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_auto_narrows_unique_feasible_odm_without_manual_choice(app, tmp_path):
|
||||
"""无范围、无选择时,整单唯一可行 ODM(各行命中交集恰一个)自动收敛。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
|
||||
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
|
||||
{'part': 'PN-B', 'odm_values': ['ODM-2']},
|
||||
])
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
|
||||
"""无范围、无选择且多值并存时维持折叠冲突阻断,等待用户整单选择。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'])
|
||||
|
||||
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
|
||||
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
|
||||
from app.core.errors import AppError
|
||||
from app.services.shipping_notice.notice_odm_choice_service import (
|
||||
notice_odm_options,
|
||||
set_notice_odm_choice,
|
||||
)
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-2', 'ODM-3'],
|
||||
)
|
||||
|
||||
options = notice_odm_options(task)
|
||||
|
||||
# [断言] 逐行候选是客户范围过滤后的集合,且保留库存行原始大小写。
|
||||
assert options['whitelist_applied'] is True
|
||||
assert options['customer_odm_ids'] == ['ODM-2', 'ODM-3']
|
||||
assert len(options['lines']) == 1
|
||||
assert options['lines'][0]['odm_values'] == ['ODM-2']
|
||||
assert options['lines'][0]['chosen_odm_id'] is None
|
||||
|
||||
snapshot_line_id = options['lines'][0]['snapshot_line_id']
|
||||
result = set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-2')
|
||||
|
||||
assert result['odm_id'] == 'ODM-2'
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
task_id=int(task.order_task_id), is_current=True,
|
||||
).all()
|
||||
assert matches and {m.chosen_odm_id for m in matches} == {'ODM-2'}
|
||||
options = notice_odm_options(task)
|
||||
assert options['lines'][0]['chosen_odm_id'] == 'ODM-2'
|
||||
|
||||
with pytest.raises(AppError) as exc:
|
||||
set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-9')
|
||||
assert getattr(exc.value, 'code', '') == 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
|
||||
|
||||
|
||||
def test_notice_odm_choice_syncs_same_snapshot_file_lines(app, tmp_path):
|
||||
"""同一快照文件的行:改任一行 ODM ID,其余行同步落库同一选择。"""
|
||||
from app.services.shipping_notice.notice_odm_choice_service import (
|
||||
notice_odm_options,
|
||||
set_notice_odm_choice,
|
||||
)
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
|
||||
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
|
||||
{'part': 'PN-B', 'odm_values': ['ODM-2', 'ODM-3']},
|
||||
])
|
||||
|
||||
options = notice_odm_options(task)
|
||||
# [断言] 每行有自己的候选;同文件两行的可行集=交集。
|
||||
by_sid = {str(item['snapshot_line_id']): item for item in options['lines']}
|
||||
assert len(by_sid) == 2
|
||||
assert options['lines'][0]['odm_values'] == ['ODM-1', 'ODM-2']
|
||||
|
||||
target_sid = options['lines'][0]['snapshot_line_id']
|
||||
result = set_notice_odm_choice(
|
||||
task, snapshot_line_id=target_sid, odm_id='ODM-2',
|
||||
)
|
||||
|
||||
# [断言] 同步范围=同一快照文件:两行当前匹配行写同一选择。
|
||||
assert result['synced_line_count'] == 2
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
task_id=int(task.order_task_id), is_current=True,
|
||||
).all()
|
||||
assert len(matches) == 2
|
||||
assert {m.chosen_odm_id for m in matches} == {'ODM-2'}
|
||||
options = notice_odm_options(task)
|
||||
assert all(item['chosen_odm_id'] == 'ODM-2' for item in options['lines'])
|
||||
|
||||
|
||||
def test_notice_odm_options_empty_when_template_ignores_odm(app, tmp_path):
|
||||
"""模板不消费 odm 字段时投影为空候选,不产生任何选择入口。"""
|
||||
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1'])
|
||||
options = notice_odm_options(task)
|
||||
assert options['odm_field_id'] is not None
|
||||
assert options['lines'] and options['lines'][0]['odm_values'] == ['ODM-1']
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
backend/tests/test_shipping_my_todo_stage_counts.py
|
||||
|
||||
用途:「我的待办」count 聚合扩展单测(阶段 tab 计数 + 已完成子终态拆分)。
|
||||
依赖:pytest、ShippingNotice / ShippingOrderTask / Artifact 夹具、query_service.count_my_todos。
|
||||
逻辑:覆盖 processing_stage 权威 / 人工原因归属 Gate / todo_category 兜底三路阶段归类;
|
||||
done 桶拆分为已核验上传成功与 复核驳回/作废 两类终态计数。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingExportArtifact,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.shipping_notice.constants import RS_REJECTED
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
|
||||
|
||||
def test_count_my_todos_reports_stage_counts_and_done_breakdown(app):
|
||||
"""阶段 tab 计数按权威口径归类;done 拆分为上传成功与驳回作废两类。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 77
|
||||
# [STEP] 四个待处理条目分别覆盖三路归类路径:
|
||||
# OT.stage 权威(waiting_review→订单复核)、原因映射(upload_rpa_failed→货代上传、
|
||||
# inventory_source_unresolved→通知准备)、类别兜底(artifact ready 人工上传→货代上传)。
|
||||
review_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-REVIEW", stage="waiting_review",
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
upload_rpa_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-UPLOAD-RPA", pending_human_reason="upload_rpa_failed",
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
inventory_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-INVENTORY", pending_human_reason="inventory_source_unresolved",
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
rejected_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-REJECTED", review_status=RS_REJECTED,
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
manual_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-MANUAL", source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
manual_notice = ShippingNotice(task_no="SN-STAGE-MANUAL", source_type="manual", user_id=owner)
|
||||
done_notice = ShippingNotice(task_no="SN-STAGE-DONE", source_type="manual", user_id=owner)
|
||||
rejected_notice = ShippingNotice(task_no="SN-STAGE-REJECTED", source_type="manual", user_id=owner)
|
||||
db.session.add_all([
|
||||
review_task, upload_rpa_task, inventory_task, rejected_task, manual_task,
|
||||
manual_notice, done_notice, rejected_notice,
|
||||
])
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='STAGE', display_name='Stage', version=1, status='published',
|
||||
storage_bucket='test', storage_key='stage.xlsx', original_filename='stage.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='STAGE', display_name='Stage', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='STAGE', display_name='Stage')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
manual_notice.order_task_id = manual_task.id
|
||||
rejected_notice.order_task_id = rejected_task.id
|
||||
|
||||
def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact:
|
||||
"""为 Notice 建立待办分类所需的最小正式 Excel Artifact。"""
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=notice.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status=status,
|
||||
)
|
||||
db.session.add(artifact)
|
||||
return artifact
|
||||
|
||||
# 人工上传待登记(ready→manual_upload);已完成(uploaded→done/upload_complete);
|
||||
# 驳回终态(ready 但 OT 复核驳回→done/reject_void)。
|
||||
add_artifact(manual_notice, artifact_no='ART-STAGE-MANUAL', status='ready')
|
||||
add_artifact(done_notice, artifact_no='ART-STAGE-DONE-UP', status='uploaded')
|
||||
add_artifact(rejected_notice, artifact_no='ART-STAGE-REJ', status='ready')
|
||||
db.session.commit()
|
||||
|
||||
counts = count_my_todos(owner)
|
||||
|
||||
# 断言:四个待处理条目按权威口径落入正确阶段 tab。
|
||||
assert counts["pending"] == 4
|
||||
assert counts["stage_counts"] == {
|
||||
"intake_parse": 0,
|
||||
"order_review": 1,
|
||||
"fulfillment_prep": 1,
|
||||
"freight_upload": 2,
|
||||
}
|
||||
# 断言:done 拆分——uploaded Artifact 计上传成功,OT 复核驳回计驳回作废。
|
||||
assert counts["done"] == 2
|
||||
assert counts["done_counts"] == {"upload_complete": 1, "reject_void": 1}
|
||||
|
||||
# 断言:terminal_kind 子视图过滤——两个终态子 tab 各自只取对应集合,互不重叠。
|
||||
upload_page = list_my_todos(owner, bucket="done", terminal_kind="upload_complete")
|
||||
assert {item["task_no"] for item in upload_page["items"]} == {"SN-STAGE-DONE"}
|
||||
reject_page = list_my_todos(owner, bucket="done", terminal_kind="reject_void")
|
||||
assert {item["task_no"] for item in reject_page["items"]} == {"SN-STAGE-REJECTED"}
|
||||
# 无过滤参数时保持既有行为:done 全量。
|
||||
assert list_my_todos(owner, bucket="done")["total"] == 2
|
||||
@@ -538,7 +538,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
db.session.refresh(task)
|
||||
|
||||
assert result['status'] == 'ok', result
|
||||
assert result['data']['stage'] == 'step5_match_inventory'
|
||||
assert result['data']['stage'] == 'inventory_matching'
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one()
|
||||
snapshot = db.session.get(ShippingInventoryFile, link.inventory_file_id)
|
||||
assert snapshot is not None
|
||||
|
||||
@@ -212,6 +212,35 @@ def test_reservation_region_requires_review_when_numbered_value_has_no_line_targ
|
||||
assert applied.review_reasons == ('line_field_unavailable',)
|
||||
|
||||
|
||||
def test_reservation_region_matches_line_by_printed_ln_number_not_position():
|
||||
"""LN 非连续(部分行已拆单)时必须按 LN 值定位逻辑行,禁止位置错配或误报越界。"""
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=extract_reservation_from_region_text(
|
||||
"Reservation L#1: 1000159370\nReservation L#2: 1000159366\n"
|
||||
"Reservation L#4: 1000159379\nReservation L#5: 1000159236"
|
||||
),
|
||||
header_field_id='header-reservation', line_field_id='line-reservation',
|
||||
line_count=4, line_numbers=[1, 2, 4, 5],
|
||||
)
|
||||
|
||||
assert applied.needs_review is False
|
||||
# 键是逻辑行序号:L#4→第 3 行(LN=4)、L#5→第 4 行(LN=5)。
|
||||
assert applied.line_values == {1: '1000159370', 2: '1000159366', 3: '1000159379', 4: '1000159236'}
|
||||
|
||||
|
||||
def test_reservation_region_flags_review_when_referenced_ln_number_is_absent():
|
||||
"""被引用的印刷行号在解析行中不存在时必须转复核,不得静默按位置写入。"""
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=extract_reservation_from_region_text("Reservation L#5: 1000159236"),
|
||||
header_field_id='header-reservation', line_field_id='line-reservation',
|
||||
line_count=2, line_numbers=[1, 2],
|
||||
)
|
||||
|
||||
assert applied.line_values == {}
|
||||
assert applied.needs_review is True
|
||||
assert applied.review_reasons == ('line_out_of_range',)
|
||||
|
||||
|
||||
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
|
||||
"""空订单或畸形行都不能被视为 Reservation 门禁通过。"""
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_conversation_title.py
|
||||
|
||||
用途:验证订单抽取新建会话按 Intake 资产文件名派生标题,且已存在会话标题一律不动。
|
||||
依赖:全局 Flask/SQLite 测试夹具(app)、Run service 的会话解析内部函数。
|
||||
逻辑:新建分支走 conversation_title 派生;追加归属等存量路径保持原标题(含「订单抽取」)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatSession, FileAsset, ShippingOrderIntake, User
|
||||
from app.services.shipping_notice.order_extraction_run_service import _resolve_conversation
|
||||
|
||||
|
||||
def _seed_user_agent(suffix: str) -> tuple[User, Agent]:
|
||||
"""构造用户与货代 Agent;suffix 保证同文件内多用例数据隔离。"""
|
||||
user = User(username=f'title-user-{suffix}', email=f'title-{suffix}@example.com', password_hash='x')
|
||||
agent = Agent(
|
||||
name=f'Title Agent {suffix}',
|
||||
agent_code='shipping_notice',
|
||||
runtime_provider='hybrid',
|
||||
dify_app_id=f'title-agent-{suffix}',
|
||||
dify_api_key='test-key',
|
||||
is_active=True,
|
||||
)
|
||||
user.agents.append(agent)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
return user, agent
|
||||
|
||||
|
||||
def _seed_intake(suffix: str, user: User, filename: str, conversation_id: str | None = None) -> ShippingOrderIntake:
|
||||
"""构造带资产文件名的已解析 Intake。"""
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-TITLE-{suffix}',
|
||||
owner_user_id=user.id,
|
||||
original_filename=filename,
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/{filename}',
|
||||
content_hash=(suffix.lower() * 64)[:64],
|
||||
file_size=10,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'SNI-TITLE-{suffix}',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
return intake
|
||||
|
||||
|
||||
def test_new_session_title_derives_from_intake_filenames(app):
|
||||
"""新建会话:标题 = 首个文件名(剥离邮件前缀)+ 等 N 个文件 + 日期后缀。"""
|
||||
user, agent = _seed_user_agent('NEW')
|
||||
first = _seed_intake('NEW1', user, 'RE: PO#6075309 for HOXIN.eml')
|
||||
second = _seed_intake('NEW2', user, 'invoice.pdf')
|
||||
|
||||
session = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[first, second])
|
||||
|
||||
# 日期后缀来自 utcnow,断言前缀避免对当天日期产生脆弱依赖。
|
||||
assert session.title.startswith('PO#6075309 for HOXIN 等 2 个文件 ')
|
||||
|
||||
|
||||
def test_existing_session_title_stays_untouched(app):
|
||||
"""已存在会话:即便标题仍是写死的「订单抽取」,Intake 归属也不改标题。"""
|
||||
user, agent = _seed_user_agent('KEEP')
|
||||
session = ChatSession(session_id='title-session-keep', user_id=user.id, agent_id=agent.id, title='订单抽取')
|
||||
db.session.add(session)
|
||||
db.session.flush()
|
||||
intake = _seed_intake('KEEP1', user, 'RE: PO#6075309.eml', conversation_id=session.session_id)
|
||||
|
||||
resolved = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[intake])
|
||||
|
||||
assert resolved.session_id == session.session_id
|
||||
assert resolved.title == '订单抽取'
|
||||
@@ -5,6 +5,7 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_extract_matching_signature,
|
||||
_observe_layout_features,
|
||||
_resolve_coordinate_transform,
|
||||
_signature_identity_header_tokens,
|
||||
match_frozen_coordinate_profiles,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile_signature import (
|
||||
@@ -1386,3 +1387,125 @@ def test_observe_layout_features_applies_business_row_clip():
|
||||
assert bbox is not None
|
||||
assert bbox[3] < 0.62
|
||||
assert bbox[3] > 0.50
|
||||
|
||||
|
||||
# --- PO_6075316 路由级合成回归:别名契约经二次机会门禁清空两道表头硬门禁 ---
|
||||
|
||||
# 训练签名(命中模板 HYVE)的明细表 header_tokens 形状。
|
||||
_PO6075316_TRAINING_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Arrival Date', 'Unit Price', 'Extension',
|
||||
]
|
||||
# 故障 PDF(PO_6075316)观测形状:日期词变更 + 相邻列并格 + 一个 MinerU 空串占位。
|
||||
_PO6075316_FAULT_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Ship Date Unit Price', '', 'Extension',
|
||||
]
|
||||
# Schema v4 相关别名(归一化 key → field_code),含治理后的 Requested Ship Date。
|
||||
_PO6075316_HEADER_TO_FIELD = {
|
||||
'Requested Receipt Date': 'requested_receipt_date',
|
||||
'Requested Arrival Date': 'requested_receipt_date',
|
||||
'Requested Ship Date': 'requested_receipt_date',
|
||||
'Unit Price': 'unit_price',
|
||||
'Extension': 'line_amount_with_tax',
|
||||
'Part Number': 'customer_part_number',
|
||||
'Vendor Item': 'part_number',
|
||||
'Quantity': 'qty',
|
||||
'LN': 'customer_po_line_no',
|
||||
}
|
||||
|
||||
|
||||
def _column_header_glyphs(tokens: list[str], *, x_start: float = 40.0, y0: float = 76.0, y1: float = 88.0, column_gap: float = 12.0) -> list[dict]:
|
||||
"""按列生成表头字符证据。
|
||||
|
||||
列内空格不额外步进(合并格文案保持为单一 span,空格由 boundary 恢复);
|
||||
列间留大间隔强制 positioned_token_spans 切分;空串列不产出字符。
|
||||
"""
|
||||
glyphs: list[dict] = []
|
||||
cursor = x_start
|
||||
for token in tokens:
|
||||
first_of_column = True
|
||||
for index, char in enumerate(token):
|
||||
if char == ' ':
|
||||
continue
|
||||
glyphs.append({
|
||||
'text': char,
|
||||
'bbox': {'x0': cursor, 'y0': y0, 'x1': cursor + 3, 'y1': y1},
|
||||
'boundary_before': 'none' if first_of_column else ('space' if index and token[index - 1] == ' ' else 'none'),
|
||||
})
|
||||
first_of_column = False
|
||||
cursor += 4.0
|
||||
cursor += column_gap
|
||||
return glyphs
|
||||
|
||||
|
||||
def _layout_with_column_header(tokens: list[str], *, page_width: float = 640) -> dict:
|
||||
"""以指定列 token 形状构造坐标 layout(沿用 _layout 骨架,整体替换表头字符)。"""
|
||||
layout = _layout()
|
||||
layout['coordinate_evidence']['pages']['1']['width'] = page_width
|
||||
header = _column_header_glyphs(tokens)
|
||||
layout['coordinate_evidence']['tables']['table-1'] = header
|
||||
layout['coordinate_evidence']['page_glyphs']['1'] = [
|
||||
*layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')],
|
||||
*header,
|
||||
]
|
||||
return layout
|
||||
|
||||
|
||||
def test_header_alias_contract_clears_all_po6075316_header_hard_gates():
|
||||
"""路由重放 PO_6075316:含 Ship Date 别名的契约清空 discriminator 与
|
||||
signature_conflict 两道表头硬门禁(二次机会:canonical 序列复评达标)。"""
|
||||
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
|
||||
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
|
||||
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
|
||||
|
||||
# 构造守卫:冻结签名 token 必须与训练形状逐字一致,防止证据管线漂移使断言空转。
|
||||
signature_body, _ = _extract_matching_signature(profile)
|
||||
assert _signature_identity_header_tokens(signature_body) == _PO6075316_TRAINING_TOKENS
|
||||
|
||||
with_contract = match_frozen_coordinate_profiles(
|
||||
profiles=[profile], layout=fault,
|
||||
header_to_field=_PO6075316_HEADER_TO_FIELD,
|
||||
)
|
||||
without_contract = match_frozen_coordinate_profiles(profiles=[profile], layout=fault)
|
||||
|
||||
contract_candidate = with_contract.candidates[0]
|
||||
plain_candidate = without_contract.candidates[0]
|
||||
# 关键断言:别名契约下第一道 discriminator 互斥被 canonical 原子全等豁免。
|
||||
assert 'profile_header_discriminator_conflict' not in contract_candidate.reason_codes
|
||||
# 关键断言:第二道 signature_conflict 门禁被二次机会清空——原始分被词级互斥
|
||||
# 压成 0 后,canonical 序列复用同一打分逻辑重估,effective >= 0.35 不再硬拒。
|
||||
assert 'profile_header_signature_conflict' not in contract_candidate.reason_codes
|
||||
# 关键断言:两道表头硬门禁全清后候选成为硬匹配(表头类原因码不为拦路面)。
|
||||
assert contract_candidate.hard_match is True
|
||||
# 关键断言:不传契约时同形状仍被词级原子互斥拒绝——互斥机制本身未被别名破坏。
|
||||
assert 'profile_header_discriminator_conflict' in plain_candidate.reason_codes
|
||||
|
||||
|
||||
def test_header_alias_contract_without_ship_date_alias_keeps_hard_rejection():
|
||||
"""反向用例:契约缺 Ship Date 别名时二次机会不生效,候选仍被表头硬门禁拒绝。
|
||||
|
||||
证明二次机会来自别名本身而非门禁放水。缺 Ship Date 别名时两侧 canonical
|
||||
原子不再全等,先触发 discriminator 分支——if/elif 结构下 signature_conflict
|
||||
分支被前置分支吸收(不得并列上报同根因),故拦路码为 discriminator;
|
||||
断言落点是「仍被硬拒」:hard_match False 且综合分归零。
|
||||
"""
|
||||
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
|
||||
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
|
||||
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
|
||||
contract_without_ship_alias = {
|
||||
key: value
|
||||
for key, value in _PO6075316_HEADER_TO_FIELD.items()
|
||||
if key != 'Requested Ship Date'
|
||||
}
|
||||
|
||||
partial = match_frozen_coordinate_profiles(
|
||||
profiles=[profile], layout=fault,
|
||||
header_to_field=contract_without_ship_alias,
|
||||
)
|
||||
candidate = partial.candidates[0]
|
||||
# 关键断言:缺 Ship Date 别名 → 跨措辞(ship vs arrival)无法归一 → 硬互斥仍在。
|
||||
assert 'profile_header_discriminator_conflict' in candidate.reason_codes
|
||||
# 关键断言:候选仍被硬拒(综合分归零、非硬匹配)——别名缺失绝不放行。
|
||||
assert candidate.hard_match is False
|
||||
assert candidate.score == 0.0
|
||||
@@ -372,7 +372,7 @@ def test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step(ap
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -2962,3 +2962,254 @@ def test_run_lineage_root_walk_loads_parent_runs_without_frozen_snapshot_columns
|
||||
for statement in point_loads:
|
||||
assert 'input_snapshot_json' not in statement
|
||||
assert 'result_json' not in statement
|
||||
|
||||
|
||||
def test_review_queue_flags_blocked_gate_cases_as_needs_attention(app):
|
||||
"""门禁 blocked_manual(如库存缺口)的已建任务单,队列必须下发 needs_attention=True。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NEEDS-ATTN')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-needs-attn',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-ATTN',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
task_id=task.id,
|
||||
review_case_id=case.id,
|
||||
status='active',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id,
|
||||
gate_code='inventory_sufficiency',
|
||||
sequence_no=16,
|
||||
status='blocked_manual',
|
||||
))
|
||||
task.active_process_execution_id = execution.id
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
queue = serialize_review_queue([run])
|
||||
|
||||
# 关键断言:库存缺口类门禁阻塞必须在队列可见,不再只依赖当前单的完整详情。
|
||||
assert queue['items'][0]['needs_attention'] is True
|
||||
assert queue['items'][0]['lifecycle_stage'] == 'fulfillment_prep'
|
||||
# 关键断言:needs_attention 抬升 summary needs_action 桶,不得被计成完成/在办。
|
||||
assert queue['summary'] == {'total': 1, 'needs_action': 1, 'processing': 0, 'completed': 0}
|
||||
|
||||
|
||||
def test_review_queue_waiting_external_gate_is_not_needs_attention(app):
|
||||
"""RPA 外部等待(waiting_external)属于系统在办,不得标记 needs_attention。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-WAIT-EXT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-WAIT-EXT',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-wait-ext',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-WAIT',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-WAIT-EXT',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='freight_uploading',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-REVIEW-QUEUE-WAIT-EXT',
|
||||
task_id=task.id,
|
||||
review_case_id=case.id,
|
||||
status='waiting_external',
|
||||
current_gate_code='freight_upload_rpa',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id,
|
||||
gate_code='freight_upload_rpa',
|
||||
sequence_no=18,
|
||||
status='waiting_external',
|
||||
))
|
||||
task.active_process_execution_id = execution.id
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
# 关键断言:外部等待是在办不是待办,图标应走进行中而非需人工。
|
||||
assert item['needs_attention'] is False
|
||||
|
||||
|
||||
def test_review_queue_without_execution_is_not_needs_attention(app):
|
||||
"""已建任务但尚无 Execution(或缓存未命中)时,needs_attention 必须为 False。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NO-EXEC')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-NO-EXEC',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-no-exec',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-NOEXEC',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-NO-EXEC',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
# 关键断言:无门禁事实时不臆造需人工标志。
|
||||
assert item['needs_attention'] is False
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_terminal_stage_as_completed(app):
|
||||
"""OT.stage=completed(通知完成)的已建任务单计入 completed,不再计入 processing。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-DONE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-DONE',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-done',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMDONE',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-SUM-DONE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='completed',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:summary 与五态图标同口径——confirmed+终态=completed 而非 processing。
|
||||
assert summary['total'] == 1
|
||||
assert summary['completed'] == 1
|
||||
assert summary['processing'] == 0
|
||||
assert summary['needs_action'] == 0
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_quality_issue_as_needs_action(app):
|
||||
"""quality_issue(文件质量异常)从 completed 改归 needs_action,与黄⚠图标一致。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-QI')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-QI',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-qi',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMQI',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
case.status = 'quality_issue'
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:质量异常是待办不是完成。
|
||||
assert summary['needs_action'] == 1
|
||||
assert summary['completed'] == 0
|
||||
assert summary['processing'] == 0
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_plain_confirmed_as_processing(app):
|
||||
"""已建任务、无阻塞、非终态的 confirmed 单计入 processing(对应转圈图标)。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-PROC')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-PROC',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-proc',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMPROC',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-SUM-PROC',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:已创建任务是在办不是完成。
|
||||
assert summary['processing'] == 1
|
||||
assert summary['completed'] == 0
|
||||
assert summary['needs_action'] == 0
|
||||
@@ -230,18 +230,18 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
# 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。
|
||||
uploaded = SimpleNamespace(
|
||||
id=None,
|
||||
current_step='step7_upload', upload_status='uploaded', export_file_path=None,
|
||||
current_step='freight_uploading', upload_status='uploaded', export_file_path=None,
|
||||
)
|
||||
# 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
current_step='step7_upload', upload_status='pending', export_file_path='/x.xlsx',
|
||||
current_step='freight_uploading', upload_status='pending', export_file_path='/x.xlsx',
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
|
||||
|
||||
matching = SimpleNamespace(
|
||||
current_step='step5_match', upload_status='', match_status='matching', export_file_path=None,
|
||||
current_step='inventory_matching', upload_status='', match_status='matching', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
|
||||
|
||||
|
||||
@@ -540,7 +540,7 @@ def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None
|
||||
owner_agent_id=int(agent.id),
|
||||
candidate_id=None,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -1660,7 +1660,7 @@ def test_summary_loads_process_execution_by_order_task_id_not_candidate_id(app)
|
||||
intake_id=intake.id,
|
||||
candidate_id=candidate.id,
|
||||
status='waiting_review',
|
||||
stage='step3_inventory_prepare',
|
||||
stage='inventory_fetching',
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
@@ -1876,6 +1876,73 @@ def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> No
|
||||
assert summary_leaf['intake_parse_authorized'] is False
|
||||
|
||||
|
||||
def test_summary_leaf_surfaces_primary_validation_issue_for_open_case(app) -> None:
|
||||
"""摘要叶子对建单前 Case 必须透传首要资格 issue,而非 review_case_{status} 状态码。
|
||||
|
||||
回归:批次进度中心对"客户尚未确认"等具体阻断只显示「订单草稿待处理」状态文案,
|
||||
原因是叶子摘要用 Case 状态拼 blocking_reason.code;资格评估已把冻结
|
||||
explainability(code/message/next_action)持久化进 draft.validation_result_json,
|
||||
摘要路径应透传该裁决(drafts_by_id 已批量加载,零额外查询)。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-LEAF-ISSUE-REASON',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUMMARY-ISSUE-REASON', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='summary-issue-reason',
|
||||
order_extraction_run_id=run.id, is_current_version=True,
|
||||
candidate_status='accepted', po_number='PO-SUMMARY-ISSUE-REASON',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
review_case = ensure_run_review_cases(run=run)[0]
|
||||
review_case.status = 'draft'
|
||||
draft = review_case.current_draft
|
||||
assert draft is not None
|
||||
# 模拟资格评估落库的首要阻断 issue(与 order_build_eligibility 持久化结构一致)
|
||||
draft.validation_result_json = {
|
||||
'can_build': False,
|
||||
'can_auto_create': False,
|
||||
'issues': [{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
'message': '客户尚未确认',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
}],
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
summary_leaf = next(
|
||||
child
|
||||
for rows in payload['conversation_processing']['status_groups'].values()
|
||||
for row in rows
|
||||
for child in row.get('aggregate_children', [])
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
|
||||
reason = summary_leaf['ui_state']['blocking_reason']
|
||||
# 关键断言:透传契约三元组;不得再是 review_case_draft 状态码
|
||||
assert reason['code'] == 'customer_unresolved'
|
||||
assert reason['message'] == '客户尚未确认'
|
||||
assert reason['next_action'] == 'confirm_customer'
|
||||
|
||||
|
||||
def test_summary_leaf_open_case_with_queued_stp_is_running_not_waiting_human(app) -> None:
|
||||
"""开放 Case 若已有 queued STP Job,摘要必须进系统处理中,不得误报待人工。
|
||||
|
||||
@@ -2860,7 +2927,7 @@ def test_single_order_task_work_item_includes_authoritative_lifecycle_ui_state(a
|
||||
conversation_id=session.session_id,
|
||||
intake_id=int(intake.id),
|
||||
extraction_run_id=int(run.id),
|
||||
current_step='step7_upload_freight',
|
||||
current_step='freight_uploading',
|
||||
status='automating',
|
||||
stage='freight_uploading',
|
||||
progress_version=1,
|
||||
@@ -3139,7 +3206,7 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
current_step='step7_upload_freight',
|
||||
current_step='freight_uploading',
|
||||
status='processing',
|
||||
stage='candidate_creating',
|
||||
progress_version=1,
|
||||
|
||||
@@ -36,21 +36,39 @@ def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage():
|
||||
)
|
||||
|
||||
|
||||
def test_legacy_step_key_stage_maps_to_fulfillment_prep():
|
||||
"""OT.stage 若残留 step5_match_inventory,生命周期必须进通知准备而非接收解析。"""
|
||||
def test_stage_mapping_rejects_checkpoint_legacy_keys():
|
||||
"""CheckPoint stepN_* 遗留键已全部清除:阶段映射只认 15 阶契约码。
|
||||
|
||||
历史缺陷:step_key 被写进 OT.stage,靠投影别名兜底;现写路径只产出契约码
|
||||
(set_task_step_progress 校验 + 存量迁移清洗),别名不得再存在。
|
||||
"""
|
||||
legacy_keys = [
|
||||
'step1_notice_submit',
|
||||
'step2_parse_confirm',
|
||||
'step3_inventory_prepare',
|
||||
'step5_match_inventory',
|
||||
'step6_generate_file',
|
||||
'step7_upload_freight',
|
||||
]
|
||||
for key in legacy_keys:
|
||||
assert key not in LIFECYCLE_STAGE_BY_PROCESSING_STAGE, (
|
||||
f"CheckPoint 遗留键 {key!r} 不得再进入阶段映射"
|
||||
)
|
||||
for stage_code in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
|
||||
assert not str(stage_code).startswith('step'), (
|
||||
f"阶段映射出现非契约键 {stage_code!r}"
|
||||
)
|
||||
# 契约码本身仍能正常映射:库存匹配属通知准备,processing_stage 权威生效。
|
||||
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
|
||||
|
||||
result = project_lifecycle(
|
||||
current_gate={'gate_code': 'task_creation', 'status': 'invalidated'},
|
||||
blocking_reason={'code': 'gate_invalidated'},
|
||||
has_candidate_context=True,
|
||||
processing_stage='step5_match_inventory',
|
||||
processing_stage='inventory_matching',
|
||||
)
|
||||
# processing_stage 权威高于错误的 task_creation 门禁。
|
||||
assert result['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert result['lifecycle_authority'] == 'processing_stage'
|
||||
current = next(e for e in result['lifecycle_entries'] if e['state'] == 'current')
|
||||
assert current['code'] == 'fulfillment_prep'
|
||||
|
||||
|
||||
def test_fifteen_stages_inventory_source_before_review():
|
||||
|
||||
@@ -283,7 +283,7 @@ def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(m
|
||||
id=1,
|
||||
order_task_id=9,
|
||||
upload_status='uploaded',
|
||||
current_step='step6_generate_file',
|
||||
current_step='excel_generating',
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
)
|
||||
|
||||
@@ -76,7 +76,7 @@ def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app):
|
||||
extraction_run_id=int(run.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
|
||||
@@ -91,7 +91,7 @@ def test_service_chain_customer_confirm_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.review_status = 'pending_confirm'
|
||||
notice.current_step = 'step4_match_inventory'
|
||||
notice.current_step = 'inventory_matching'
|
||||
notice.customer_id = 1
|
||||
db.session.commit()
|
||||
|
||||
@@ -112,7 +112,7 @@ def test_service_chain_inventory_match_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.match_status = 'matched'
|
||||
notice.current_step = 'step4_match_inventory'
|
||||
notice.current_step = 'inventory_matching'
|
||||
db.session.commit()
|
||||
|
||||
before, projection = _project_after_sync(notice, order_task, run)
|
||||
@@ -130,7 +130,7 @@ def test_service_chain_excel_generate_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.upload_status = 'pending'
|
||||
notice.current_step = 'step7_upload_freight'
|
||||
notice.current_step = 'freight_uploading'
|
||||
notice.export_file_path = '/tmp/fake-shipping.xlsx'
|
||||
db.session.commit()
|
||||
|
||||
@@ -148,7 +148,7 @@ def test_service_chain_freight_upload_retry_projection(app, workbench_chain_ids)
|
||||
"""
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.current_step = 'step7_upload_freight'
|
||||
notice.current_step = 'freight_uploading'
|
||||
notice.upload_status = 'failed'
|
||||
notice.export_file_path = '/tmp/fake-shipping.xlsx'
|
||||
db.session.commit()
|
||||
|
||||
Reference in new issue
Block a user