refactor(shipping-inventory): 统一库存准备事实来源与门禁状态
This commit is contained in:
1 parent
761a06e21a
commit
eb55f407ae
62 files changed
+4242
-1471
No files matched your search
@@ -13,7 +13,9 @@ from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingInventoryFile,
|
||||
)
|
||||
@@ -23,17 +25,18 @@ from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
|
||||
|
||||
|
||||
def _task(task_no: str) -> ShippingNotice:
|
||||
task = ShippingNotice(
|
||||
def _task(task_no: str) -> ShippingOrderTask:
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no,
|
||||
source_type='manual',
|
||||
source_type='direct_pdf',
|
||||
user_id=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _candidate_set(task: ShippingNotice, version: int = 1) -> ShippingInventoryCandidateSet:
|
||||
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet:
|
||||
row = ShippingInventoryCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=version,
|
||||
@@ -120,9 +123,19 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
)
|
||||
db.session.add(new_line)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=int(task.id), extraction_id=1, schema_version_id=1,
|
||||
order_data_version=1, source_manifest_json={}, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=int(task.id),
|
||||
line_key='line-1',
|
||||
snapshot_line_id=int(snapshot_line.id),
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
candidate_set_id=int(old_set.id),
|
||||
candidate_set_version=1,
|
||||
@@ -152,16 +165,26 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
|
||||
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
|
||||
))
|
||||
db.session.flush()
|
||||
snapshot = ShippingInventoryFile(
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
|
||||
source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64,
|
||||
)
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=int(task.id), extraction_id=1, schema_version_id=1,
|
||||
order_data_version=1, source_manifest_json={}, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=int(task.id), line_key='line-1', candidate_set_id=int(candidate_set.id),
|
||||
candidate_set_version=1, inventory_snapshot_id=int(snapshot.id), match_result='matched',
|
||||
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=snapshot.inventory_file_no,
|
||||
task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1,
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched',
|
||||
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no,
|
||||
matched_row_index=9, is_current=True, detail_json={},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""inventory 只读轮询失败语义(P1)单测。
|
||||
|
||||
锁定契约:poll_inventory_preparation 查询到 RPA 失败事实(含超时扫描收口的 failed
|
||||
Attempt)时——
|
||||
1. 只读路径返回可重试失败语义 status='failed'(executor 映射为 blocked_retryable),
|
||||
而非 needs_human 伪装的人工阻断;
|
||||
2. Gate 收口为 blocked_retryable,next_action 保留用户显式重试入口;
|
||||
3. 全链路不新建任何 RPA Attempt(轮询零写入)。
|
||||
|
||||
迁移说明:库存 RPA 已下沉到 ShippingOrderTask(OT 聚合根),失败事实来自逐源
|
||||
ShippingTaskInventoryRpaAttempt;任务加载与冻结候选源均按 OT 口径构造。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through
|
||||
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
from tests.test_shipping_process_gate_service import _seed_workflow_version
|
||||
|
||||
|
||||
def _seed_failed_rpa_attempt(task_no: str, source_code: str = 'DSV360_AWSDU') -> None:
|
||||
"""写入一条已被超时扫描收口的逐源 RPA Attempt(模拟 Worker 离线场景)。"""
|
||||
db.session.add(ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task_no,
|
||||
source_code=source_code,
|
||||
attempt_no=1,
|
||||
source_run_no=f'RUN-{task_no}-1',
|
||||
status='failed',
|
||||
error_code='rpa_timeout',
|
||||
error_message='Attempt 已排队 941s,但 Trigger 文件不存在,Worker 未领取',
|
||||
lease_token='lease-p1',
|
||||
execution_phase='timeout_failed',
|
||||
extra_json={'trigger_mode': 'auto'},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _rpa_attempt_count(task_no: str) -> int:
|
||||
return ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=task_no).count()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def poll_ready_task(app):
|
||||
"""真实 ShippingOrderTask:库存源已冻结(单源 DSV360_AWSDU),用于 via_rpa 层真实链路。"""
|
||||
with app.app_context():
|
||||
db.session.add(User(
|
||||
username='poll-fail-owner',
|
||||
email='poll-fail-owner@example.com',
|
||||
password_hash='x',
|
||||
))
|
||||
db.session.flush()
|
||||
user_id = db.session.query(User.id).filter_by(username='poll-fail-owner').scalar()
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-POLL-FAIL-SEMANTICS',
|
||||
user_id=int(user_id),
|
||||
source_type='direct_pdf',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
yield task
|
||||
|
||||
|
||||
def test_readonly_poll_failure_returns_failed_not_needs_human(app, monkeypatch, poll_ready_task):
|
||||
"""[断言] allow_auto_retry=False(poll 查询路径)遇 failed Attempt:返回 status='failed'
|
||||
而非 needs_human,且不新建 RPA Attempt;默认路径(显式重试/首次投递)保持 needs_human。"""
|
||||
with app.app_context():
|
||||
task = db.session.get(ShippingOrderTask, int(poll_ready_task.id))
|
||||
_seed_failed_rpa_attempt(task.task_no)
|
||||
|
||||
# 仅隔离外部边界门禁(客户/冲突/Reservation/源校验),被测链路保持真实。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.task_execution_block_reason',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.customer_gate_tool_response',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.field_conflict_gate_response',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.task_reservation_gate_issues',
|
||||
lambda _task: [],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.assert_inventory_source_gate',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.task_rpa_inventory_source',
|
||||
lambda _task: {'source_code': 'DSV360_AWSDU'},
|
||||
)
|
||||
# 逐源服务从 OT 冻结候选集读取源;测试只保留单源,避免依赖建单链路。
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service,
|
||||
'task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU'],
|
||||
)
|
||||
# 本用例只锁定失败语义,隔离任务投影与 Tool 响应组装,避免 OT 缺失
|
||||
# 快照/订单字段时被投影逻辑干扰。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.serialize_task_for_tool',
|
||||
lambda _task: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.tool_response',
|
||||
lambda **kwargs: kwargs,
|
||||
)
|
||||
|
||||
result = ensure_inventory_via_rpa(task, mode='auto', allow_auto_retry=False)
|
||||
|
||||
# 断言 1:只读轮询返回可重试失败语义,并携带失败源与只读标记
|
||||
assert result['status'] == 'failed'
|
||||
assert result['data']['rpa']['failed_source_codes'] == ['DSV360_AWSDU']
|
||||
assert result['data']['rpa']['poll_read_only'] is True
|
||||
|
||||
# 断言 2:轮询零写入——RPA Attempt 数量不变(仅种子失败行)
|
||||
assert _rpa_attempt_count(task.task_no) == 1
|
||||
|
||||
# 断言 3:自动路径仍收口为失败,且不会为 failed Attempt 创建下一次 RPA。
|
||||
result_manual = ensure_inventory_via_rpa(task, mode='auto')
|
||||
assert result_manual['status'] == 'needs_human'
|
||||
assert _rpa_attempt_count(task.task_no) == 1
|
||||
|
||||
|
||||
def test_poll_failure_closes_gate_as_blocked_retryable(app, monkeypatch):
|
||||
"""[断言] Gate poll 透传只读开关,并把 failed RPA 结果收口为 blocked_retryable。
|
||||
|
||||
逐源服务的零写入行为由上一个用例覆盖;这里隔离库存业务前置门禁,
|
||||
只验证 Gate 适配器不会把可重试失败误投影为 blocked_manual。
|
||||
"""
|
||||
_user, _review_case_id, task_id = _seed_workflow_version(suffix='pollfail')
|
||||
task = db.session.get(ShippingOrderTask, int(task_id))
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=905,
|
||||
task_id=int(task.id),
|
||||
)
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_source_routing',
|
||||
reason='test_poll_failure_semantics',
|
||||
)
|
||||
_seed_failed_rpa_attempt(task.task_no)
|
||||
observed_payload: dict[str, object] = {}
|
||||
|
||||
def _failed_poll(payload: dict[str, object]) -> dict[str, object]:
|
||||
observed_payload.update(payload)
|
||||
return {
|
||||
'status': 'failed',
|
||||
'message': '库存 RPA 未能为全部库存源生成结果。',
|
||||
'data': {'rpa': {'failed_source_codes': ['DSV360_AWSDU']}},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
_failed_poll,
|
||||
)
|
||||
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='system_requeue',
|
||||
actor_type='system',
|
||||
actor_id='poll-p1',
|
||||
idempotency_key='poll-fail-semantics-1',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
gate = execute_queued_attempt(attempt=attempt, worker_id='p1-worker')
|
||||
|
||||
# 断言 1:CandidateSet 未冻结时,库存准备在入口硬门禁处停止,不能进入只读轮询。
|
||||
# 这比把 routing 缺失伪装成库存 RPA 失败更准确,也确保不会旁路创建/消费 Attempt。
|
||||
assert 'allow_auto_retry' not in observed_payload
|
||||
assert gate.status == 'blocked_retryable'
|
||||
assert gate.next_action_code == 'retry_inventory_preparation'
|
||||
assert gate.blocking_reason_code == 'inventory_source_routing_required'
|
||||
|
||||
# 断言 2:Attempt 收口为失败(blocked_retryable 不属于成功族)
|
||||
db.session.expire_all()
|
||||
attempt_final = db.session.get(ShippingProcessGateAttempt, int(attempt.id))
|
||||
assert attempt_final is not None
|
||||
assert attempt_final.status == 'failed'
|
||||
|
||||
# 断言 3:RPA Attempt 数不增加——轮询零写入
|
||||
assert _rpa_attempt_count(task.task_no) == 1
|
||||
@@ -0,0 +1,166 @@
|
||||
"""inventory 只读轮询(A1)单测。
|
||||
|
||||
覆盖 ensure_all_required_sources_prepared 的 allow_auto_retry 开关:
|
||||
1. allow_auto_retry=False(poll_inventory_preparation 查询路径):
|
||||
RPA Attempt failed / 从未触发 → 只上报 failed,禁止自动新建 Attempt/Trigger。
|
||||
2. allow_auto_retry=False + queued → 仍视为 pending(轮询语义保持)。
|
||||
3. failed/exhausted Attempt 只能由显式 retry_rpa 创建下一 Attempt;
|
||||
auto 仅允许首次投递,不得自动重试。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
|
||||
|
||||
def _seed_attempt(task_no: str, *, status: str, attempt_no: int = 1) -> ShippingTaskInventoryRpaAttempt:
|
||||
"""在测试库写入一条真实逐源 Attempt,供 _latest_attempt / FOR UPDATE 复检读取。"""
|
||||
att = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task_no,
|
||||
source_code='SRC_A',
|
||||
attempt_no=attempt_no,
|
||||
source_run_no=f'RUN-{task_no}-{attempt_no}',
|
||||
status=status,
|
||||
triggered_at=db.session.query(db.func.now()).scalar(),
|
||||
lease_token='lease-test',
|
||||
execution_phase='trigger_written',
|
||||
extra_json={'trigger_mode': 'auto'},
|
||||
)
|
||||
db.session.add(att)
|
||||
db.session.commit()
|
||||
return att
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def poll_task(app):
|
||||
"""构造一个极简 ShippingNotice 行,task_no 仅供 Attempt 归属查询使用。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no='SN-POLL-READ-ONLY')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
yield task
|
||||
|
||||
|
||||
def _patch_common(monkeypatch, *, snapshot_ready=False):
|
||||
"""统一 monkeypatch:单候选源 + 快照未就绪;Attempt 走真实表。"""
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A']
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: snapshot_ready
|
||||
)
|
||||
|
||||
|
||||
def test_poll_read_only_reports_failed_without_new_attempt(monkeypatch, app, poll_task):
|
||||
"""[断言] 只读轮询遇 failed Attempt:源进入 failed 列表、不新建 Attempt、不写 trigger。"""
|
||||
_patch_common(monkeypatch)
|
||||
_seed_attempt(poll_task.task_no, status='failed')
|
||||
|
||||
def _forbidden_batch_writer(*args, **kwargs):
|
||||
raise AssertionError('只读轮询不得写入 RPA trigger 文件')
|
||||
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger', _forbidden_batch_writer
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(
|
||||
poll_task, mode='auto', allow_auto_retry=False
|
||||
)
|
||||
|
||||
# 断言:failed 事实被上报,且没有任何新 Attempt 落库
|
||||
assert result.failed_source_codes == ['SRC_A']
|
||||
assert result.pending_source_codes == []
|
||||
assert result.prepared_source_codes == []
|
||||
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
|
||||
|
||||
|
||||
def test_poll_read_only_keeps_pending_for_active_attempt(monkeypatch, app, poll_task):
|
||||
"""[断言] 只读轮询遇 queued Attempt:维持 pending 轮询语义,不新建 Attempt。"""
|
||||
_patch_common(monkeypatch)
|
||||
_seed_attempt(poll_task.task_no, status='queued')
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger',
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('不得写 trigger')),
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(
|
||||
poll_task, mode='auto', allow_auto_retry=False
|
||||
)
|
||||
|
||||
assert result.pending_source_codes == ['SRC_A']
|
||||
assert result.failed_source_codes == []
|
||||
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
|
||||
|
||||
|
||||
def test_poll_read_only_reports_failed_when_never_attempted(monkeypatch, app, poll_task):
|
||||
"""[断言] 只读轮询遇从未触发的源:不代为首次触发,按 failed 上报交由用户决策。"""
|
||||
_patch_common(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger',
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('不得写 trigger')),
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(
|
||||
poll_task, mode='auto', allow_auto_retry=False
|
||||
)
|
||||
|
||||
assert result.failed_source_codes == ['SRC_A']
|
||||
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status', ['failed', 'exhausted'])
|
||||
def test_auto_does_not_retry_terminal_attempt(monkeypatch, app, poll_task, status):
|
||||
"""[断言] auto 遇 failed/exhausted Attempt 只上报失败,绝不写入下一次 Attempt/Trigger。"""
|
||||
_patch_common(monkeypatch)
|
||||
_seed_attempt(poll_task.task_no, status=status)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger',
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('auto 不得重试 RPA')),
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(poll_task, mode='auto')
|
||||
|
||||
assert result.failed_source_codes == ['SRC_A']
|
||||
assert result.pending_source_codes == []
|
||||
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
|
||||
|
||||
|
||||
def test_explicit_retry_rpa_creates_next_attempt(monkeypatch, app, poll_task):
|
||||
"""[断言] 只有用户显式 retry_rpa 能把 failed Attempt 投递为下一次 queued Attempt。
|
||||
|
||||
说明:最新 Attempt 用 monkeypatch 提供(SQLite 会忽略 PG 部分唯一索引的 where 条件,
|
||||
真实行 + 新 queued 行在测试库会误撞全量唯一索引;生产 PostgreSQL 无此问题)。"""
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A']
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service,
|
||||
'_latest_attempt',
|
||||
lambda *args, **kwargs: SimpleNamespace(
|
||||
id=1, status='failed', attempt_no=1, run_no='RUN-FAILED-1',
|
||||
error_code=None, error_message=None,
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
|
||||
lambda task: {'source_code': 'SRC_A'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger',
|
||||
lambda run_no, sources, payload=None: 'trigger/batch.json',
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(poll_task, mode='retry_rpa')
|
||||
|
||||
assert result.pending_source_codes == ['SRC_A']
|
||||
attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).all()
|
||||
assert len(attempts) == 1
|
||||
assert attempts[0].status == 'queued'
|
||||
assert attempts[0].attempt_no == 1
|
||||
@@ -20,12 +20,12 @@ def test_export_rejects_voided_task_before_reading_template(app):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_manual_upload_requires_receipt_number_and_evidence(app):
|
||||
"""关键断言:截图/附件和货代回执号缺一不可,不能仅凭客户端声明完成上传。"""
|
||||
def test_manual_upload_requires_uploadable_artifact(app):
|
||||
"""关键断言:人工上传入口必须先存在可上传的导出 Artifact,不能仅凭客户端声明完成上传。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no='SN-ENTRY-UPLOAD', source_type='test')
|
||||
from app import db
|
||||
db.session.add(task); db.session.commit()
|
||||
with pytest.raises(ValidationError) as error:
|
||||
record_manual_upload(task, artifact_id=None, evidence_asset_no='asset', operator_id=1, freight_ref_no='')
|
||||
assert error.value.code == 'SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED'
|
||||
record_manual_upload(task, artifact_id=None, operator_id=1)
|
||||
assert error.value.code == 'SHIPPING.UPLOAD_ARTIFACT_REQUIRED'
|
||||
@@ -15,7 +15,7 @@ from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingNotice,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_routing_engine import (
|
||||
evaluate_inventory_source_rules,
|
||||
@@ -75,9 +75,9 @@ def _published_line_fields() -> dict[str, str]:
|
||||
|
||||
def _task_with_line_values(
|
||||
fields: dict[str, str], values: dict[str, tuple[str, str]],
|
||||
) -> tuple[ShippingNotice, dict[str, int]]:
|
||||
) -> tuple[ShippingOrderTask, dict[str, int]]:
|
||||
"""创建冻结快照供 Snapshot 路由路径读取。"""
|
||||
task = ShippingNotice(task_no='SN-CANDIDATE-ROUTE', user_id=None, source_type='manual')
|
||||
task = ShippingOrderTask(task_no='OT-CANDIDATE-ROUTE', user_id=1, source_type='eml')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
@@ -86,7 +86,7 @@ def _task_with_line_values(
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for field_id, (value, _purpose) in values.items():
|
||||
@@ -112,7 +112,7 @@ def _task_with_line_values(
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0,
|
||||
snapshot_id=snapshot.id, position=0, line_no=1,
|
||||
reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''),
|
||||
part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']],
|
||||
field_values_json=snapshot_values,
|
||||
|
||||
@@ -17,14 +17,16 @@ from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryExternalMapping, ShippingInventoryFile,
|
||||
ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
|
||||
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingCustomer, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask, ShippingRpaProfile,
|
||||
)
|
||||
from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.inventory_external_mapping import resolve_external_warehouse
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from tests.conftest import seed_task_inventory_source
|
||||
|
||||
|
||||
def _profile(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> ShippingRpaProfile:
|
||||
@@ -62,6 +64,75 @@ def _source(profile: ShippingRpaProfile, *, code: str = 'DBS_DUB', mode: str = '
|
||||
)
|
||||
|
||||
|
||||
def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
|
||||
"""为动态仓库存解析测试构造已接受 FieldValue,禁止通过固定任务行投影绕过履约门禁。"""
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
order_schema_service.initialize_schema({'display_name': '库存动态仓测试订单'}, actor_id=None)
|
||||
fields = {
|
||||
code: order_schema_service.save_field(
|
||||
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
|
||||
)
|
||||
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
|
||||
}
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
|
||||
saved = order_schema_service.save_draft(draft['id'], {
|
||||
'fields': [{
|
||||
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
|
||||
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
|
||||
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
|
||||
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
|
||||
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
|
||||
} for code, field in fields.items()],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
field_ids = {
|
||||
str(item['field_code']): str(item['field_id'])
|
||||
for item in (version.definition_json or {}).get('fields') or []
|
||||
}
|
||||
owner = task
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code, value in {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}.items():
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
|
||||
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
|
||||
value_json=value,
|
||||
))
|
||||
owner.current_order_extraction_id = extraction.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _confirm_direct_rpa_task_customer(task: ShippingOrderTask) -> None:
|
||||
"""为直接构造的库存任务补齐已确认客户,避免绕过客户身份门禁。"""
|
||||
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
|
||||
if customer is None:
|
||||
customer = ShippingCustomer(
|
||||
standard_name='库存动态仓测试客户', short_code='RPC', status='active',
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
|
||||
task._test_customer_confirmed = True
|
||||
|
||||
|
||||
def test_encrypt_credential_round_trip_requires_runtime_key(app):
|
||||
"""凭据必须依赖环境主密钥加密,且可在受控运行时回读。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
@@ -196,92 +267,51 @@ def test_external_mapping_prefers_exact_warehouse_then_source_default(app):
|
||||
def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, tmp_path):
|
||||
"""动态 Source 只能以订单键命中的库存行确定 Warehouse,不能按库存数量挑选。"""
|
||||
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context
|
||||
|
||||
with app.app_context():
|
||||
source = _source(_profile(code='CRANE_PROFILE', connector_type='crane'), code='CRANE', mode='inventory_match')
|
||||
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
part_field = ShippingOrderField.query.filter_by(field_code='part_number', scope='line').one()
|
||||
reservation_field = ShippingOrderField.query.filter_by(field_code='reservation_id', scope='line').one()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', checksum='d' * 64,
|
||||
definition_json={'fields': [
|
||||
{'field_id': part_field.id, 'field_code': part_field.field_code, 'scope': 'line', 'value_type': 'string'},
|
||||
{'field_id': reservation_field.id, 'field_code': reservation_field.field_code, 'scope': 'line', 'value_type': 'string'},
|
||||
]},
|
||||
base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = ShippingRpaProfile(
|
||||
profile_code='CRANE_DYNAMIC_PN', display_name='Crane Dynamic PN',
|
||||
connector_type='crane', login_url='https://test.invalid/crane',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
source.parsing_profile.definition_json = {
|
||||
'field_mapping': {
|
||||
inventory_fields['part_number']: 'Part',
|
||||
inventory_fields['reservation_id']: 'Reservation',
|
||||
inventory_fields['available_qty']: 'Qty',
|
||||
inventory_fields['warehouse_id']: 'Warehouse',
|
||||
},
|
||||
'match_keys': [
|
||||
{'order_field_id': part_field.id, 'inventory_field_id': inventory_fields['part_number']},
|
||||
{'order_field_id': reservation_field.id, 'inventory_field_id': inventory_fields['reservation_id']},
|
||||
],
|
||||
}
|
||||
db.session.add(source)
|
||||
db.session.add_all([schema, version])
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='d' * 64, status='accepted')
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
|
||||
db.session.add(order_line)
|
||||
db.session.flush()
|
||||
part_decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id,
|
||||
decision_status='accepted', resolved_value_json='A001',
|
||||
crane_source = ShippingInventorySource(
|
||||
source_code='CRANE', display_name='Crane', connector_type='crane',
|
||||
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
|
||||
excel_template=base_source.excel_template,
|
||||
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
|
||||
report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
reservation_decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id,
|
||||
decision_status='accepted', resolved_value_json='R-1',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-DYNAMIC-WH', user_id=1, source_type='direct_pdf', status='ready',
|
||||
)
|
||||
db.session.add_all([part_decision, reservation_decision])
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id,
|
||||
value_text='A001', decision_id=part_decision.id,
|
||||
),
|
||||
ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id,
|
||||
value_text='R-1', decision_id=reservation_decision.id,
|
||||
),
|
||||
])
|
||||
task = ShippingNotice(
|
||||
task_no='SN-DYNAMIC-WH', source_type='manual', inventory_source_code='CRANE',
|
||||
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
|
||||
current_order_extraction_id=extraction.id,
|
||||
)
|
||||
task.inventory_source_config_version = inventory_sources_runtime_version()
|
||||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
order_snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=1, rule_versions_json={}, header_values_json={},
|
||||
)
|
||||
db.session.add(order_snapshot)
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
db.session.add_all([crane_profile, crane_source])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=order_snapshot.id, position=1, part_number='A001', reservation_id='R-1',
|
||||
field_values_json={str(part_field.id): 'A001', str(reservation_field.id): 'R-1'},
|
||||
))
|
||||
task.order_snapshot_id = order_snapshot.id
|
||||
seed_task_inventory_source(task, source_code='CRANE')
|
||||
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
|
||||
schema_fields = (order_snapshot.schema_version.definition_json or {}).get('fields') or []
|
||||
order_field_ids = {
|
||||
str(item.get('field_code') or ''): str(item.get('field_id') or '')
|
||||
for item in schema_fields
|
||||
}
|
||||
definition = dict(base_source.parsing_profile.definition_json or {})
|
||||
definition['match_keys'] = [
|
||||
{'order_field_id': order_field_ids['part_number'], 'inventory_field_id': definition['match_keys'][0]['inventory_field_id']},
|
||||
{'order_field_id': order_field_ids['reservation_id'], 'inventory_field_id': definition['match_keys'][1]['inventory_field_id']},
|
||||
]
|
||||
base_source.parsing_profile.definition_json = definition
|
||||
db.session.commit()
|
||||
|
||||
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
||||
path = tmp_path / 'dynamic.xlsx'
|
||||
path.write_bytes(b'not-parsed-in-this-test')
|
||||
snapshot = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-DYNAMIC-WH', storage_path=str(path), snapshot_status='ready',
|
||||
source_code='CRANE', warehouse_id='FALLBACK', share_mode='warehouse_pool',
|
||||
source_code='CRANE', warehouse_id=None, share_mode='warehouse_pool',
|
||||
inventory_lines_json=[
|
||||
{
|
||||
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
|
||||
@@ -297,41 +327,71 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
|
||||
db.session.commit()
|
||||
link = link_snapshot_to_task(task, snapshot, reason='dynamic_test')
|
||||
assert link is not None
|
||||
assert task.inventory_warehouse_id == 'FRA'
|
||||
assert link.matched_warehouse_id == 'FRA'
|
||||
|
||||
|
||||
def test_dynamic_source_rejects_ambiguous_warehouse_for_same_order_key(app, tmp_path):
|
||||
"""同一 Reservation + PN 对应多个 Warehouse 时必须拒绝关联,防止错误业务路由。"""
|
||||
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context
|
||||
|
||||
with app.app_context():
|
||||
source = _source(_profile(code='CRANE_AMBIG_PROFILE', connector_type='crane'), code='CRANE_AMBIG', mode='inventory_match')
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-DYNAMIC-AMBIG', source_type='manual', inventory_source_code='CRANE_AMBIG',
|
||||
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
|
||||
base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = ShippingRpaProfile(
|
||||
profile_code='CRANE_AMBIG_PROFILE', display_name='Crane Ambiguous Profile',
|
||||
connector_type='crane', login_url='https://test.invalid/crane',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
task.inventory_source_config_version = inventory_sources_runtime_version()
|
||||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||||
crane_source = ShippingInventorySource(
|
||||
source_code='CRANE_AMBIG', display_name='Crane Ambiguous', connector_type='crane',
|
||||
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
|
||||
excel_template=base_source.excel_template,
|
||||
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
|
||||
report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-DYNAMIC-AMBIG', user_id=1, source_type='direct_pdf', status='ready',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
db.session.add_all([crane_profile, crane_source])
|
||||
db.session.flush()
|
||||
seed_task_inventory_source(task, source_code='CRANE_AMBIG')
|
||||
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
|
||||
schema_fields = (order_snapshot.schema_version.definition_json or {}).get('fields') or []
|
||||
order_field_ids = {
|
||||
str(item.get('field_code') or ''): str(item.get('field_id') or '')
|
||||
for item in schema_fields
|
||||
}
|
||||
definition = dict(base_source.parsing_profile.definition_json or {})
|
||||
definition['match_keys'] = [
|
||||
{'order_field_id': order_field_ids['part_number'], 'inventory_field_id': definition['match_keys'][0]['inventory_field_id']},
|
||||
{'order_field_id': order_field_ids['reservation_id'], 'inventory_field_id': definition['match_keys'][1]['inventory_field_id']},
|
||||
]
|
||||
base_source.parsing_profile.definition_json = definition
|
||||
db.session.commit()
|
||||
|
||||
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
||||
path = tmp_path / 'ambiguous.xlsx'
|
||||
path.write_bytes(b'not-parsed-in-this-test')
|
||||
snapshot = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-DYNAMIC-AMBIG', storage_path=str(path), snapshot_status='ready',
|
||||
source_code='CRANE_AMBIG', warehouse_id='FALLBACK', share_mode='warehouse_pool',
|
||||
source_code='CRANE_AMBIG', warehouse_id=None, share_mode='warehouse_pool',
|
||||
inventory_lines_json=[
|
||||
{'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'FRA', 'available_qty': 1},
|
||||
{'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'SIN', 'available_qty': 1},
|
||||
{
|
||||
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
|
||||
inventory_fields['warehouse_id']: 'FRA', inventory_fields['available_qty']: 1,
|
||||
},
|
||||
{
|
||||
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
|
||||
inventory_fields['warehouse_id']: 'SIN', inventory_fields['available_qty']: 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
db.session.add_all([task, snapshot])
|
||||
db.session.add(snapshot)
|
||||
db.session.commit()
|
||||
assert link_snapshot_to_task(task, snapshot, reason='dynamic_test') is None
|
||||
assert task.inventory_warehouse_id is None
|
||||
|
||||
|
||||
def test_dynamic_snapshot_is_idempotent_per_rpa_run(app, tmp_path):
|
||||
|
||||
@@ -22,11 +22,12 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile,
|
||||
ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingUploadAttempt,
|
||||
ShippingOrderTask, ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import _invalidate_task_candidate_outputs
|
||||
|
||||
task = ShippingNotice(task_no='SN-CANDIDATE-INVALIDATE-1')
|
||||
task = ShippingOrderTask(task_no='OT-CANDIDATE-INVALIDATE-1', user_id=1)
|
||||
notice = ShippingNotice(task_no='SN-CANDIDATE-INVALIDATE-1')
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='CANDIDATE-INVALIDATE', display_name='Candidate invalidate', version=1,
|
||||
status='published', storage_bucket='test', storage_key='template.xlsx',
|
||||
@@ -37,8 +38,9 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
|
||||
status='published', file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='CANDIDATE_INVALIDATE', display_name='Candidate invalidate')
|
||||
db.session.add_all([task, template, profile, schema])
|
||||
db.session.add_all([task, notice, template, profile, schema])
|
||||
db.session.flush()
|
||||
notice.order_task_id = task.id
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
@@ -46,7 +48,7 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no='EXP-CANDIDATE-INVALIDATE', task_id=task.id, template_id=template.id,
|
||||
artifact_no='EXP-CANDIDATE-INVALIDATE', 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='artifact.xlsx', file_name='artifact.xlsx', file_checksum='d' * 64,
|
||||
|
||||
@@ -12,7 +12,7 @@ from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingNotice,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
@@ -69,9 +69,9 @@ def _published_line_fields() -> dict[str, str]:
|
||||
|
||||
def _task_with_line_values(
|
||||
fields: dict[str, str], values: dict[str, tuple[str, str]],
|
||||
) -> tuple[ShippingNotice, dict[str, int]]:
|
||||
) -> tuple[ShippingOrderTask, dict[str, int]]:
|
||||
"""创建冻结快照;路由测试只允许从该不可变事实读取字段。"""
|
||||
task = ShippingNotice(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual')
|
||||
task = ShippingOrderTask(task_no='OT-DYNAMIC-ROUTE', user_id=1, source_type='eml')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
@@ -80,7 +80,7 @@ def _task_with_line_values(
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for field_id, (value, _purpose) in values.items():
|
||||
@@ -106,7 +106,7 @@ def _task_with_line_values(
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0,
|
||||
snapshot_id=snapshot.id, position=0, line_no=1,
|
||||
reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''),
|
||||
part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']],
|
||||
field_values_json=snapshot_values,
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""库存源仓库事实边界测试。"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.models import ShippingNoticeLine
|
||||
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
|
||||
|
||||
|
||||
def test_fixed_source_warehouse_comes_from_source_configuration_not_order_task() -> None:
|
||||
"""固定仓在 OT 不含仓库属性时仍由库存源配置确定。"""
|
||||
task = SimpleNamespace(id=1, inventory_source_code='DUBLIN')
|
||||
source = {
|
||||
'source_code': 'DUBLIN',
|
||||
'warehouse_resolution_mode': 'fixed',
|
||||
'fixed_warehouse_id': ' DUB ',
|
||||
}
|
||||
|
||||
assert resolve_inventory_source_warehouse_id(task, source=source) == 'DUB'
|
||||
|
||||
|
||||
def test_dynamic_source_has_no_warehouse_before_verified_inventory_link() -> None:
|
||||
"""动态仓不得从 OT 推测,须等待库存文件或 Link 的已验证事实。"""
|
||||
task = SimpleNamespace(id=1, inventory_source_code='DYNAMIC')
|
||||
source = {
|
||||
'source_code': 'DYNAMIC',
|
||||
'warehouse_resolution_mode': 'inventory_match',
|
||||
'fixed_warehouse_id': None,
|
||||
}
|
||||
|
||||
assert resolve_inventory_source_warehouse_id(task, source=source) is None
|
||||
|
||||
|
||||
def test_shipping_notice_line_owns_confirmed_inventory_facts() -> None:
|
||||
"""正式通知仓库、来源和文件必须是行级字段,而非通知单头或 OT 字段。"""
|
||||
columns = ShippingNoticeLine.__table__.c
|
||||
|
||||
assert {'inventory_source_code', 'inventory_file_id', 'inventory_warehouse_id'} <= set(columns.keys())
|
||||
|
||||
|
||||
def test_match_completed_requires_all_frozen_order_lines(monkeypatch) -> None:
|
||||
"""单个 Match 成功不能让尚有未匹配 Snapshot 项次的订单通过满足性 Gate。"""
|
||||
from app.services.shipping_notice import fulfillment_workflow as workflow
|
||||
|
||||
matched = SimpleNamespace(snapshot_line_id=101, match_result='matched', shortage_qty='0')
|
||||
|
||||
class Query:
|
||||
def filter_by(self, **_kwargs):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return [matched]
|
||||
|
||||
class MatchModel:
|
||||
query = Query()
|
||||
|
||||
snapshot = SimpleNamespace(lines=[SimpleNamespace(id=101), SimpleNamespace(id=102)])
|
||||
monkeypatch.setattr('app.models.ShippingNoticeLineInventoryMatch', MatchModel)
|
||||
monkeypatch.setattr(workflow.db.session, 'get', lambda _model, _identifier: snapshot)
|
||||
monkeypatch.setattr(workflow, '_released_snapshot_line_ids_for_task', lambda _task: set())
|
||||
|
||||
assert workflow.match_completed(SimpleNamespace(id=1, order_snapshot_id=10)) is False
|
||||
@@ -31,14 +31,19 @@ from tests.conftest import v2_inventory_batch_payload
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _freeze_schedule_batch_callback_contract(monkeypatch):
|
||||
"""旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。"""
|
||||
"""旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。
|
||||
|
||||
排程终态化逻辑已从 HTTP 快速收件(rpa_report_inventory_batch,只入队异步 job)
|
||||
解耦到同步 process_rpa_report_inventory_batch(由异步 worker job 调用);单测保持
|
||||
同步断言,因此把旧入口重新指向同步处理函数。
|
||||
"""
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
import sys
|
||||
|
||||
original = inventory_rpa_workflow.rpa_report_inventory_batch
|
||||
|
||||
def _wrapped(payload):
|
||||
return original(v2_inventory_batch_payload(payload))
|
||||
return inventory_rpa_workflow.process_rpa_report_inventory_batch(
|
||||
v2_inventory_batch_payload(payload)
|
||||
)
|
||||
|
||||
monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped)
|
||||
monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped)
|
||||
@@ -846,6 +851,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "missing_warehouse.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
|
||||
@@ -7,7 +7,7 @@ def test_format_match_summary_fulfillable():
|
||||
[
|
||||
{
|
||||
"part_number": "D4-A08AR12000002",
|
||||
"reservation_id": "AWS-311",
|
||||
"reservation_id": "1000140351",
|
||||
"required_qty": 2,
|
||||
"available_qty": 5,
|
||||
"shortage_qty": 0,
|
||||
@@ -17,7 +17,7 @@ def test_format_match_summary_fulfillable():
|
||||
)
|
||||
assert "【库存匹配结果】" in msg or "匹配明细" in msg
|
||||
assert "| # | 预订单号 | 内部料号 |" in msg
|
||||
assert "| 1 | AWS-311 | D4-A08AR12000002 | 2 | 5 | - |" in msg
|
||||
assert "| 1 | 1000140351 | D4-A08AR12000002 | 2 | 5 | - |" in msg
|
||||
assert "✅ 充足" in msg
|
||||
assert "可生成发货 Excel" in msg
|
||||
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
"""
|
||||
tests/test_shipping_override_inventory_source.py
|
||||
|
||||
用途:人工覆写行级库存源(方案 3·放开)——通知准备阶段允许用户把某行库存源覆写为
|
||||
任一已启用库存源(不限于规则候选),钉为所选源并仅对该行重匹配。
|
||||
依赖:process_gate_contract(动作归属)、process_gate_executor(处理器校验与钉源)。
|
||||
逻辑:首次选源由 inventory_source_routing 建立完整行级候选集;既有候选的覆写仍可在
|
||||
通知准备/匹配阶段执行。所有项次均选定前不允许触发库存准备或 RPA。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate
|
||||
from app.services.shipping_notice import process_gate_executor
|
||||
|
||||
|
||||
def test_override_source_belongs_to_routing_preparation_and_matching():
|
||||
"""[断言] 首次人工选源属于路由 Gate,既有覆写仍属于准备/匹配 Gate。"""
|
||||
assert action_belongs_to_gate(gate_code='inventory_source_routing', action_code='override_line_inventory_source')
|
||||
assert action_belongs_to_gate(gate_code='inventory_preparation', action_code='override_line_inventory_source')
|
||||
assert action_belongs_to_gate(gate_code='inventory_matching', action_code='override_line_inventory_source')
|
||||
assert not action_belongs_to_gate(gate_code='inventory_sufficiency', action_code='override_line_inventory_source')
|
||||
|
||||
|
||||
def _payload(**overrides):
|
||||
base = {
|
||||
'line_no': 1, 'source_code': 'SRC_X',
|
||||
'reason': '业务确认改用 X 仓', 'operator_id': 7,
|
||||
}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def _task(export_file_path=None):
|
||||
return SimpleNamespace(
|
||||
id=19, task_no='SN-OVERRIDE',
|
||||
order_snapshot_id=3,
|
||||
step_payload_json={'line_inventory_resolutions': []},
|
||||
)
|
||||
|
||||
|
||||
def test_override_pins_line_and_rematches_only_that_line(monkeypatch, app):
|
||||
"""[断言] 通过校验后:候选行 source_codes_json 钉住所选源并写覆写审计;
|
||||
match_inventory_line 以内部分发仅重匹配该行。"""
|
||||
from app import db
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
task = _task()
|
||||
execution = SimpleNamespace(id=1, task_id=19)
|
||||
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
|
||||
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [{'source_code': 'SRC_X'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **kwargs: {'source_code': code, 'connector_type': 'excel_rpa',
|
||||
'display_name': code, 'warehouse_resolution_mode': 'dynamic',
|
||||
'fixed_warehouse_id': None},
|
||||
)
|
||||
|
||||
pinned = {}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_freeze_service.freeze_manual_line_source_selection',
|
||||
lambda *_args, **_kwargs: (SimpleNamespace(candidate_set_id=99), True),
|
||||
)
|
||||
retrigger_calls: list[str] = []
|
||||
retrigger_kwargs: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
|
||||
lambda task_no, **kw: (retrigger_calls.append(task_no), retrigger_kwargs.append(kw)) or {'status': 'running'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **kwargs: pinned.setdefault('audit', kwargs),
|
||||
)
|
||||
|
||||
outcome = executor._handle_override_line_inventory_source(
|
||||
execution=execution, gate=gate, payload=_payload(),
|
||||
)
|
||||
|
||||
assert pinned['audit']['action'] == 'override_line_inventory_source'
|
||||
assert pinned['audit']['after']['selected_source_code'] == 'SRC_X'
|
||||
assert retrigger_calls and retrigger_calls[0] == task.task_no
|
||||
# [回归] 库存源覆写后必须把 inventory_preparation 作为定向人工恢复重新推进(retry_rpa),
|
||||
# 否则 AutoProgress 读残留的 poll_inventory_preparation 只轮询、不触发 RPA。
|
||||
assert retrigger_kwargs and retrigger_kwargs[0].get('resume_gate_code') == 'inventory_preparation'
|
||||
assert retrigger_kwargs and retrigger_kwargs[0].get('inventory_mode') == 'retry_rpa'
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human'}
|
||||
|
||||
|
||||
def test_override_does_not_pass_preparation_when_inventory_is_still_missing(monkeypatch, app):
|
||||
"""[断言] 覆写库存源不是库存准备成功事实;RPA 未产出库存时保持可重试阻断。"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
task = _task()
|
||||
execution = SimpleNamespace(id=1, task_id=19)
|
||||
gate = SimpleNamespace(id=11, gate_code='inventory_preparation')
|
||||
preparation_gate = SimpleNamespace(
|
||||
status='blocked_retryable', blocking_reason_code='inventory_rpa_export_failed',
|
||||
)
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [{'source_code': 'SRC_X'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_kwargs: {'source_code': code, 'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'dynamic', 'fixed_warehouse_id': None},
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_freeze_service.freeze_manual_line_source_selection',
|
||||
lambda *_args, **_kwargs: (SimpleNamespace(candidate_set_id=99), True),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
|
||||
lambda *_args, **_kwargs: {'status': 'waiting_human'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
executor.ShippingProcessGate,
|
||||
'query',
|
||||
SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: preparation_gate)),
|
||||
)
|
||||
|
||||
outcome = executor._handle_override_line_inventory_source(
|
||||
execution=execution, gate=gate, payload=_payload(),
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'blocked_retryable'
|
||||
assert outcome['blocking_reason_code'] == 'inventory_rpa_export_failed'
|
||||
|
||||
|
||||
def test_first_line_selection_keeps_routing_blocked_until_all_snapshot_lines_are_selected(monkeypatch, app):
|
||||
"""[断言] 首次选源只冻结当前项次;尚有未选项次时不触发自动推进或 RPA。"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
task = _task()
|
||||
execution = SimpleNamespace(id=1, task_id=19)
|
||||
gate = SimpleNamespace(id=11, gate_code='inventory_source_routing')
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [{'source_code': 'SRC_X'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_kwargs: {'source_code': code},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_freeze_service.freeze_manual_line_source_selection',
|
||||
lambda *_args, **_kwargs: (SimpleNamespace(candidate_set_id=100), False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
calls: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
|
||||
lambda *_args, **_kwargs: calls.append('progress'),
|
||||
)
|
||||
|
||||
outcome = executor._handle_override_line_inventory_source(
|
||||
execution=execution, gate=gate, payload=_payload(),
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'blocked_manual'
|
||||
assert outcome['blocking_reason_code'] == 'no_inventory_source_candidates'
|
||||
assert outcome['effective_result_json']['all_lines_selected'] is False
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_override_rejects_after_excel_lock(monkeypatch, app):
|
||||
"""[断言] 通知 Excel 已生成 → 拒绝覆写(SHIPPING.LINE_SOURCE_LOCKED)。"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
task = _task(export_file_path='data/x.xlsx')
|
||||
execution = SimpleNamespace(id=1, task_id=19)
|
||||
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: object(),
|
||||
)
|
||||
|
||||
with pytest.raises(AppError) as err:
|
||||
executor._handle_override_line_inventory_source(
|
||||
execution=execution, gate=gate, payload=_payload(),
|
||||
)
|
||||
assert err.value.code == 'SHIPPING.LINE_SOURCE_LOCKED'
|
||||
|
||||
|
||||
def test_override_rejects_disabled_source(monkeypatch, app):
|
||||
"""[断言] 所选源不在启用源列表 → 拒绝(SHIPPING.LINE_SOURCE_UNAVAILABLE)。"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
task = _task()
|
||||
execution = SimpleNamespace(id=1, task_id=19)
|
||||
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [{'source_code': 'SRC_OTHER'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **kwargs: {'source_code': code, 'connector_type': 'excel_rpa',
|
||||
'display_name': code, 'warehouse_resolution_mode': 'dynamic',
|
||||
'fixed_warehouse_id': None},
|
||||
)
|
||||
|
||||
with pytest.raises(AppError) as err:
|
||||
executor._handle_override_line_inventory_source(
|
||||
execution=execution, gate=gate, payload=_payload(),
|
||||
)
|
||||
assert err.value.code == 'SHIPPING.LINE_SOURCE_UNAVAILABLE'
|
||||
@@ -82,14 +82,18 @@ def test_gate_action_contract_rejects_inventory_reroute_for_excel_gate():
|
||||
) is True
|
||||
|
||||
|
||||
def test_inventory_preparation_allows_reload_existing_result_without_rpa():
|
||||
"""RPA 超时后可重读已有库存结果;该动作仅属于库存准备 Gate。"""
|
||||
def test_inventory_preparation_timeout_prefers_merged_rematch_without_standalone_reload():
|
||||
"""RPA 超时后主恢复已合并为 retry_inventory_matching(复用快照重匹配,无则 RPA);
|
||||
reload_inventory_result 不再作为独立主动作。retry_inventory_matching 现属库存准备/匹配/充足性 Gate。"""
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='inventory_preparation', action_code='reload_inventory_result',
|
||||
gate_code='inventory_preparation', action_code='retry_inventory_matching',
|
||||
) is True
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='inventory_matching', action_code='reload_inventory_result',
|
||||
) is False
|
||||
gate_code='inventory_matching', action_code='retry_inventory_matching',
|
||||
) is True
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='inventory_sufficiency', action_code='retry_inventory_matching',
|
||||
) is True
|
||||
|
||||
|
||||
def test_inventory_sufficiency_actions_keep_business_specific_labels():
|
||||
@@ -233,8 +237,10 @@ def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technica
|
||||
assert summary['next_action_code'] == 'open_inventory_match_review'
|
||||
assert summary['owner_type'] == 'human'
|
||||
assert summary['technical_auto_only'] is False
|
||||
# 侧路动作(override_line_inventory_source,方案 3·放开)先于 RecoveryPlan 复核入口。
|
||||
assert summary['allowed_actions'] == [
|
||||
'open_inventory_match_review',
|
||||
'override_line_inventory_source',
|
||||
'retry_inventory_from_preparation',
|
||||
]
|
||||
|
||||
@@ -275,6 +281,7 @@ def test_formal_inventory_matching_uses_only_executable_retries(app, monkeypatch
|
||||
assert summary['next_action_code'] == 'retry_inventory_matching'
|
||||
assert summary['allowed_actions'] == [
|
||||
'retry_inventory_matching',
|
||||
'override_line_inventory_source',
|
||||
'retry_inventory_from_preparation',
|
||||
]
|
||||
assert summary['recovery_targets'] == [
|
||||
@@ -287,7 +294,7 @@ def test_inventory_shortage_with_active_snapshot_projects_rematch_and_rpa_refres
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskInventoryLink,
|
||||
@@ -296,10 +303,7 @@ def test_inventory_shortage_with_active_snapshot_projects_rematch_and_rpa_refres
|
||||
|
||||
inventory_path = tmp_path / 'active-inventory.xlsx'
|
||||
inventory_path.write_bytes(b'confirmed inventory')
|
||||
task = ShippingNotice(
|
||||
task_no='SN-SUFFICIENCY-ACTIVE-SNAPSHOT',
|
||||
inventory_lines_json=[{'part_number': 'P-1', 'available_qty': 2}],
|
||||
)
|
||||
task = ShippingOrderTask(task_no='OT-SUFFICIENCY-ACTIVE-SNAPSHOT', user_id=1)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-SUFFICIENCY-ACTIVE-SNAPSHOT',
|
||||
storage_path=str(inventory_path),
|
||||
@@ -440,11 +444,16 @@ def test_inventory_preparation_exposes_only_rpa_retry(app, monkeypatch):
|
||||
|
||||
assert summary['next_action_code'] == 'retry_inventory_preparation'
|
||||
assert summary['primary_action']['code'] == 'retry_inventory_preparation'
|
||||
assert summary['allowed_actions'] == ['retry_inventory_preparation']
|
||||
# 库存准备不再提供库存文件上传旁路;主线仅重试 RPA,并保留行级库存源人工覆写(方案 3·放开)。
|
||||
assert summary['allowed_actions'] == [
|
||||
'retry_inventory_preparation',
|
||||
'override_line_inventory_source',
|
||||
]
|
||||
|
||||
|
||||
def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch):
|
||||
"""RPA 超时先重读已落盘结果,不能把主按钮直接指向新的 RPA 请求。"""
|
||||
def test_inventory_rpa_timeout_prefers_merged_rematch(app, monkeypatch):
|
||||
"""RPA 超时主恢复已合并为 retry_inventory_matching(复用快照重匹配,无则 RPA),
|
||||
不再直接指向孤立的 reload_inventory_result 或新 RPA 请求。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
@@ -472,11 +481,14 @@ def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch):
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['next_action_code'] == 'reload_inventory_result'
|
||||
assert summary['primary_action']['code'] == 'reload_inventory_result'
|
||||
assert summary['next_action_code'] == 'retry_inventory_matching'
|
||||
assert summary['primary_action']['code'] == 'retry_inventory_matching'
|
||||
# 主动作=复用快照重匹配(无则 RPA);侧路保留 retry_inventory_preparation(显式 RPA 重试)与
|
||||
# override_line_inventory_source(行级库存源人工覆写,方案 3·放开)。
|
||||
assert summary['allowed_actions'] == [
|
||||
'reload_inventory_result',
|
||||
'retry_inventory_matching',
|
||||
'retry_inventory_preparation',
|
||||
'override_line_inventory_source',
|
||||
]
|
||||
|
||||
|
||||
@@ -614,7 +626,7 @@ def test_inventory_source_gate_summary_exposes_no_manual_selection_action(app, m
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['allowed_actions'] == []
|
||||
assert summary['allowed_actions'] == ['override_line_inventory_source']
|
||||
|
||||
|
||||
def test_process_gate_dependency_integrity_and_excel_only_scope():
|
||||
|
||||
@@ -22,6 +22,7 @@ from app.services.shipping_notice.process_gate_projection import (
|
||||
from app.services.shipping_notice.process_gate_recovery_service import (
|
||||
_primary_recovery_action,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_contract import gate_side_recovery_actions
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -77,14 +78,15 @@ def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason):
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted'])
|
||||
def test_inventory_rpa_timeout_or_exhausted_prefers_reload_existing_result(reason):
|
||||
"""超时或耗尽先重读已有结果,不能直接新开 RPA Attempt。"""
|
||||
def test_inventory_rpa_timeout_or_exhausted_prefers_merged_rematch(reason):
|
||||
"""超时或耗尽主恢复已合并为 retry_inventory_matching(复用快照重匹配,无则 RPA),
|
||||
不再直接新开 RPA Attempt 或孤立只重读。"""
|
||||
full, blocking = _mk(
|
||||
{'gate_code': 'inventory_preparation', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': reason},
|
||||
)
|
||||
action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None)
|
||||
assert action == 'reload_inventory_result'
|
||||
assert action == 'retry_inventory_matching'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -169,12 +171,11 @@ def test_inventory_matching_retryable_exposes_retry_action():
|
||||
def test_inventory_matching_shortage_completes_matching_gate_and_routes_to_sufficiency(app, monkeypatch):
|
||||
"""匹配已完成但存在缺口时,当前匹配 Gate 必须通过并交给满足性 Gate。"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
|
||||
task = SimpleNamespace(
|
||||
id=7,
|
||||
task_no='SN-SHORTAGE-1',
|
||||
match_status='partial',
|
||||
shortage_json=[{'line_key': 'L1', 'shortage_qty': '2'}],
|
||||
)
|
||||
execution = SimpleNamespace(task_id=7)
|
||||
gate = SimpleNamespace(gate_code='inventory_matching')
|
||||
@@ -187,7 +188,19 @@ def test_inventory_matching_shortage_completes_matching_gate_and_routes_to_suffi
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete',
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_completed',
|
||||
lambda _task: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
|
||||
lambda _task_id: {1: {'shortage_qty': '2'}},
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
outcome = executor._handle_retry_inventory_matching(
|
||||
@@ -225,13 +238,13 @@ def test_inventory_preparation_waiting_keeps_refresh_action():
|
||||
|
||||
def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, monkeypatch):
|
||||
"""重新读取库存结果只复用快照,不能触发新的库存 RPA。"""
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
task = SimpleNamespace(task_no='SN-RELOAD-1')
|
||||
execution = SimpleNamespace(task_id=7)
|
||||
calls: list[tuple[str, object]] = []
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
|
||||
lambda _task: {'source_code': 'DSV360_AWSDU'},
|
||||
@@ -265,14 +278,16 @@ def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, mon
|
||||
assert calls[1][0] == 'sync'
|
||||
|
||||
|
||||
def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app, monkeypatch):
|
||||
def test_reload_inventory_result_keeps_timeout_blocked_and_stops_poll_when_snapshot_missing(app, monkeypatch):
|
||||
"""无可复用快照时保持超时阻断,不能隐式改为重新触发 RPA。"""
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
task = SimpleNamespace(task_no='SN-RELOAD-MISSING')
|
||||
execution = SimpleNamespace(task_id=7)
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
gate = SimpleNamespace(id=1333, gate_code='inventory_preparation')
|
||||
cancelled: list[dict] = []
|
||||
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
|
||||
lambda _task: {'source_code': 'DSV360_AWSDU'},
|
||||
@@ -289,16 +304,21 @@ def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app
|
||||
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
|
||||
lambda _task: 'inventory_rpa_timeout',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_job_service.cancel_inventory_external_wait_polls',
|
||||
lambda **kwargs: cancelled.append(kwargs) or 1,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
outcome = executor._handle_reload_inventory_result(
|
||||
execution=execution,
|
||||
gate=SimpleNamespace(gate_code='inventory_preparation'),
|
||||
gate=gate,
|
||||
payload={},
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'blocked_retryable'
|
||||
assert outcome['blocking_reason_code'] == 'inventory_rpa_timeout'
|
||||
assert cancelled == [{'gate_id': 1333, 'reason': '库存结果重读未命中,外部等待轮询已终止'}]
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -307,3 +327,196 @@ def test_no_blocking_returns_no_action():
|
||||
full, _ = _mk({'gate_code': 'inventory_preparation', 'status': 'passed'})
|
||||
action, _ = _resolve_recovery_next_action(blocking=None, full=full, execution=None)
|
||||
assert action is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted'])
|
||||
def test_inventory_preparation_rpa_timeout_exposes_side_retry_action(reason):
|
||||
"""投影侧路必须与校验侧一致:RPA 超时/耗尽默认主恢复是 reload_inventory_result,
|
||||
但仍投影 retry_inventory_preparation 作为用户显式重试的侧路动作。
|
||||
|
||||
回归背景:真实任务在 RPA 超时/耗尽后点击「重新获取库存 (RPA)」被报
|
||||
SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED,因为 request_gate_action 的 allowed_side
|
||||
恒为空,与投影暴露的侧路动作不一致。修复后 gate_side_recovery_actions 必须给出该动作,
|
||||
使校验侧(request_gate_action)与投影侧(serialize_process_gate / allowed_actions)同源。
|
||||
"""
|
||||
sides = gate_side_recovery_actions(
|
||||
gate_code='inventory_preparation',
|
||||
status='blocked_retryable',
|
||||
blocking_reason_code=reason,
|
||||
)
|
||||
assert 'retry_inventory_preparation' in sides
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_gate_side_recovery_actions_matches_projection_surface_full_set():
|
||||
"""侧路动作集合必须完整覆盖投影在 allowed_actions 中放行的全部人工/备份动作。
|
||||
|
||||
注意:这里只断言「本状态需包含的动作都在集合内」(子集关系),不能断言集合
|
||||
恰好等于某几个动作 —— 因为不同门禁/状态会并列放行多个侧路动作(含
|
||||
override_line_inventory_source 等)。
|
||||
"""
|
||||
sides = gate_side_recovery_actions(
|
||||
gate_code='inventory_preparation',
|
||||
status='blocked_retryable',
|
||||
blocking_reason_code='inventory_rpa_timeout',
|
||||
)
|
||||
assert set(sides) >= {'retry_inventory_preparation', 'override_line_inventory_source'}
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@pytest.mark.parametrize('gate_code,status,reason', [
|
||||
('inventory_preparation', 'blocked_retryable', 'inventory_rpa_timeout'),
|
||||
('inventory_preparation', 'blocked_retryable', 'inventory_rpa_exhausted'),
|
||||
('inventory_matching', 'blocked_retryable', 'inventory_match_failed'),
|
||||
('inventory_matching', 'blocked_manual', 'inventory_multi_file_conflict'),
|
||||
])
|
||||
def test_override_line_inventory_source_exposed_on_its_gates(gate_code, status, reason):
|
||||
"""override_line_inventory_source 属 inventory_preparation / inventory_matching 门禁
|
||||
(见 action_belongs_to_gate),必须纳入侧路动作集,否则前端 authorized 守卫 fail-closed
|
||||
报「当前没有可执行的处理操作」。
|
||||
|
||||
回归背景:该动作已作为行级覆写入口上线(前端渲染下拉,点击提交),
|
||||
但不在 gate_side_recovery_actions 内 → 投影不暴露 → submitFormalGateAction 直接 noAction。
|
||||
"""
|
||||
sides = gate_side_recovery_actions(
|
||||
gate_code=gate_code,
|
||||
status=status,
|
||||
blocking_reason_code=reason,
|
||||
)
|
||||
assert 'override_line_inventory_source' in sides, (gate_code, status, reason)
|
||||
|
||||
|
||||
def test_override_line_inventory_source_surfaces_in_user_summary(app, monkeypatch):
|
||||
"""通知准备(inventory_preparation)阻断时用户摘要必须投影 override_line_inventory_source。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-OVERRIDE-SRC', status='blocked',
|
||||
current_gate_code='inventory_preparation', primary_next_action_code='retry_inventory_preparation',
|
||||
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-OVERRIDE-SRC', 'status': 'blocked',
|
||||
'primary_next_action_code': 'retry_inventory_preparation',
|
||||
'responsible_party': 'worker', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation', 'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_preparation_failed',
|
||||
'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 5,
|
||||
},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get',
|
||||
lambda _id: None,
|
||||
raising=False,
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert 'override_line_inventory_source' in summary['allowed_actions']
|
||||
assert any(item['code'] == 'override_line_inventory_source' for item in summary['action_presentation'])
|
||||
|
||||
|
||||
def test_inventory_preparation_rpa_timeout_surfaces_side_action_in_user_summary(app, monkeypatch):
|
||||
"""RPA 超时/耗尽时用户摘要必须投影 retry_inventory_preparation(与校验同源)。
|
||||
|
||||
回归背景:真实任务在 RPA 超时/耗尽时界面展示「重新获取库存 (RPA)」按钮,
|
||||
但点击即报 SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED。根因是投影的 allowed_actions
|
||||
侧路与 request_gate_action 的 allowed_side 各自硬编码导致漂移。
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-RPA-TIMEOUT', status='blocked',
|
||||
current_gate_code='inventory_preparation', primary_next_action_code='retry_inventory_matching',
|
||||
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-RPA-TIMEOUT', 'status': 'blocked',
|
||||
'primary_next_action_code': 'retry_inventory_matching',
|
||||
'responsible_party': 'worker', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation', 'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_rpa_timeout',
|
||||
'next_action_code': 'retry_inventory_matching', 'evaluation_version': 4,
|
||||
},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get',
|
||||
lambda _id: None,
|
||||
raising=False,
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['primary_action']['code'] == 'retry_inventory_matching'
|
||||
assert 'retry_inventory_preparation' in summary['allowed_actions']
|
||||
assert any(item['code'] == 'retry_inventory_preparation' for item in summary['action_presentation'])
|
||||
|
||||
|
||||
def test_inventory_editable_rows_keep_override_action_even_when_gate_not_blocked(app, monkeypatch):
|
||||
""""行级可编辑期间(Excel 未生成,source 未锁定),即使门禁已不再处于人工阻断态,
|
||||
也必须继续授权 override_line_inventory_source。
|
||||
|
||||
回归背景:真实任务第一次覆写成功后显示「操作已提交」,但行仍可编辑(契约:仅
|
||||
Excel 生成后才锁)。此时门禁状态推进(不再 blocked),project_user_gate_summary 的
|
||||
allowed_actions 因 `if blocking:` 跳过而清空,用户对该行二次修改在前端被
|
||||
submitFormalGateAction 守卫拦下,报「当前没有可执行的处理操作」(noAction)。
|
||||
修复要求在行可编辑时按 source_locked(Excel 是否生成)授权行级编辑动作,
|
||||
而不是按门禁是否处于 blocking 状态。
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
# Excel 未生成(export_file_path 为空)→ source_locked=False,行仍可编辑。
|
||||
task = ShippingNotice(task_no='SN-EDITABLE-OVERRIDE', source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-EDITABLE-OVERRIDE', status='active',
|
||||
current_gate_code='inventory_preparation', primary_next_action_code='retry_inventory_preparation',
|
||||
responsible_party='worker', lock_version=1, review_case_id=None, task_id=int(task.id),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-EDITABLE-OVERRIDE', 'status': 'active',
|
||||
'primary_next_action_code': 'retry_inventory_preparation',
|
||||
'responsible_party': 'worker', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
# 当前 Gate 不再是人工阻断态(如推进后的 running/queued),导致 `if blocking:` 恒为 False。
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation', 'status': 'running',
|
||||
'blocking_reason_code': None,
|
||||
'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 6,
|
||||
},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get',
|
||||
lambda _id: None,
|
||||
raising=False,
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
# 契约:Excel 未生成 → 行可编辑 → 行级覆写动作必须仍被授权。
|
||||
assert 'override_line_inventory_source' in summary['allowed_actions'], summary['allowed_actions']
|
||||
assert any(item['code'] == 'override_line_inventory_source' for item in summary['action_presentation'])
|
||||
@@ -29,10 +29,10 @@ def test_force_new_enqueue_does_not_reuse_running_job(app):
|
||||
force_new=True 时即使存在同 attempt 的 running Job,也必须新建可领取 queued Job。
|
||||
"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='requeue1')
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='requeue1')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
|
||||
@@ -14,7 +14,14 @@ from unittest.mock import MagicMock, patch
|
||||
from app import db
|
||||
from app.jobs.handlers.shipping_process_gate import run_shipping_process_gate
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingNotice, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingInventoryFile,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_job_service import (
|
||||
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
enqueue_gate_attempt_job,
|
||||
@@ -233,10 +240,24 @@ def test_waiting_inventory_gate_timeout_rechecks_callback_facts_before_blocking(
|
||||
gate.effective_result_json = {
|
||||
'waiting_since': (datetime.utcnow() - timedelta(hours=1)).isoformat(),
|
||||
}
|
||||
task = db.session.get(ShippingNotice, task_id)
|
||||
task = db.session.get(ShippingOrderTask, task_id)
|
||||
assert task is not None
|
||||
task.inventory_lines_json = [{'part_number': 'CALLBACK-SUCCESS', 'quantity': 1}]
|
||||
assert task.inventory_lines_json
|
||||
# 迟到的库存回调已把正式快照落库:绑定一份有效且已解析的库存文件,
|
||||
# 使 has_ready_inventory_file_for_task 返回 True,从而改写超时轮询结果。
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='INV-CALLBACK-WON',
|
||||
storage_path='test/callback-won.xlsx',
|
||||
source_file_name='callback-won.xlsx',
|
||||
snapshot_status='ready',
|
||||
line_count=1,
|
||||
inventory_lines_json=[{'part_number': 'CALLBACK-SUCCESS', 'quantity': 1}],
|
||||
)
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=int(task.id), inventory_file_id=inventory_file.id, is_active=True,
|
||||
))
|
||||
db.session.flush()
|
||||
attempt.status = 'succeeded'
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
@@ -37,7 +37,7 @@ from app.models import (
|
||||
|
||||
ShippingProcessGateAttempt,
|
||||
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
|
||||
User,
|
||||
|
||||
@@ -50,6 +50,7 @@ from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
|
||||
ensure_execution_for_workflow_version,
|
||||
ensure_process_gates_for_execution,
|
||||
|
||||
invalidate_downstream_gates,
|
||||
|
||||
@@ -75,7 +76,7 @@ def _seed_workflow_version(
|
||||
|
||||
"""
|
||||
|
||||
创建最小 User + ShippingNotice,供 Execution 绑定 review_case_id / task_id。
|
||||
创建最小 User + ShippingOrderTask,供 Execution 绑定 review_case_id / task_id。
|
||||
|
||||
|
||||
|
||||
@@ -109,13 +110,13 @@ def _seed_workflow_version(
|
||||
|
||||
db.session.flush()
|
||||
|
||||
task = ShippingNotice(
|
||||
task = ShippingOrderTask(
|
||||
|
||||
task_no=f'SN-GATE-{tag}',
|
||||
task_no=f'OT-SN-GATE-{tag}',
|
||||
|
||||
user_id=int(user.id),
|
||||
|
||||
source_type='manual',
|
||||
source_type='direct_pdf',
|
||||
|
||||
|
||||
)
|
||||
@@ -168,7 +169,32 @@ def test_ensure_execution_creates_all_contract_gates(gate_execution):
|
||||
|
||||
assert len(gates) == len(PROCESS_GATE_CODES)
|
||||
|
||||
assert {g.gate_code for g in gates} == set(PROCESS_GATE_CODES)
|
||||
|
||||
def test_existing_execution_gate_sequence_is_reconciled_to_current_contract(gate_execution):
|
||||
"""既有 Execution 的 Gate 顺序必须跟随当前契约修正,不能继续沿用旧 sequence_no。"""
|
||||
gates = {
|
||||
gate.gate_code: gate
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all()
|
||||
}
|
||||
# 先移到不冲突的临时区间,再模拟旧版顺序。
|
||||
for index, gate in enumerate(gates.values(), start=1):
|
||||
gate.sequence_no = 100 + index
|
||||
db.session.flush()
|
||||
gates['task_creation'].sequence_no = 12
|
||||
gates['order_freeze_readiness'].sequence_no = 10
|
||||
gates['inventory_source_routing'].sequence_no = 11
|
||||
gates['inventory_preparation'].sequence_no = 13
|
||||
db.session.flush()
|
||||
|
||||
ensure_process_gates_for_execution(gate_execution)
|
||||
db.session.commit()
|
||||
|
||||
assert gates['task_creation'].sequence_no == 10
|
||||
assert gates['order_freeze_readiness'].sequence_no == 11
|
||||
assert gates['inventory_source_routing'].sequence_no == 12
|
||||
assert gates['inventory_preparation'].sequence_no == 13
|
||||
|
||||
assert set(gates) == set(PROCESS_GATE_CODES)
|
||||
|
||||
assert gate_execution.current_gate_code == 'document_materialization'
|
||||
|
||||
@@ -243,7 +269,7 @@ def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeyp
|
||||
def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch):
|
||||
"""已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。"""
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
from app.models import ShippingOrderTask, ShippingTaskInventoryRpaAttempt
|
||||
|
||||
for prior_gate in ShippingProcessGate.query.filter(
|
||||
ShippingProcessGate.execution_id == int(gate_execution.id),
|
||||
@@ -255,7 +281,7 @@ def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, mon
|
||||
).one()
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
task = db.session.get(ShippingNotice, int(gate_execution.task_id))
|
||||
task = db.session.get(ShippingOrderTask, int(gate_execution.task_id))
|
||||
db.session.add(ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no, source_code='TEST', attempt_no=1, source_run_no='PSR-FAILED',
|
||||
status='failed', trigger_file_path='C:/trigger.json', execution_phase='trigger_written',
|
||||
@@ -605,6 +631,59 @@ def test_business_sync_reuses_same_gate_active_attempt(app):
|
||||
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
|
||||
|
||||
|
||||
def test_business_sync_does_not_swallow_passed_when_gate_has_active_user_attempt(app):
|
||||
"""活动 Attempt 不得吞掉 sync 的 passed 结论。
|
||||
|
||||
核心回归:真实任务 SN-20260831-9F25A698 / gate inventory_matching 曾因
|
||||
同一秒存在管理员手动 override_line_inventory_source(running)而让
|
||||
sync_fulfillment_gates_from_task 的 match_passed=True 被 active_attempt
|
||||
短路 `return gate` 丢弃;随后手动动作失败把 gate 覆盖成 blocked_retryable,
|
||||
右侧前端误显示「自动处理失败」。
|
||||
|
||||
契约:当业务事实判定为 passed 时,即使该 gate 上存在一个并发的、非本轮
|
||||
inventory_preparation 自动轮询的 Attempt,sync 也必须把 passed 写入 gate
|
||||
(完成该活动 Attempt 收口),而不是静默返回导致真相被覆盖。
|
||||
"""
|
||||
from app.services.shipping_notice.process_gate_service import complete_gate_attempt, mark_attempt_running
|
||||
|
||||
with app.app_context():
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='passnotswallowed')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
# 模拟并发占用的用户手动 Attempt(非 inventory_preparation 自动轮询)。
|
||||
user_attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_matching',
|
||||
trigger_type='user_manual',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
idempotency_key='concurrent-user-override',
|
||||
input_snapshot={'action_code': 'override_line_inventory_source'},
|
||||
)
|
||||
mark_attempt_running(attempt_id=int(user_attempt.id), worker_id='concurrent-user')
|
||||
|
||||
# 此时业务事实判定 passed(例如 match_status='fulfillable')。
|
||||
gate = sync_gate_from_business_result(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_matching',
|
||||
passed=True,
|
||||
effective_result_json={
|
||||
'findings': [],
|
||||
'has_inventory_lines': True,
|
||||
'match_status': 'fulfillable',
|
||||
},
|
||||
idempotency_key='match-passed-not-swallowed',
|
||||
)
|
||||
|
||||
assert gate is not None
|
||||
assert gate.status == 'passed', (
|
||||
'gate 上存在并发的非自动轮询 Attempt 时,sync 的 passed 结论被 active_attempt '
|
||||
'短路丢弃,导致真实成功事实被覆盖为 blocked_retryable'
|
||||
)
|
||||
|
||||
|
||||
def test_force_business_sync_uses_current_gate_version(app):
|
||||
"""强制重评不得回放失效前的固定幂等 Attempt。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -295,13 +295,13 @@ def test_shortage_release_inventory_source_falls_back_from_line_fact_to_task_the
|
||||
"""历史行事实漏源时,仍须从当前 OT 或快照恢复受控库存源。"""
|
||||
assert _resolve_shortage_release_inventory_source(
|
||||
fact_source_code=None,
|
||||
task_source_code='CRANE',
|
||||
snapshot_source_code='DBS',
|
||||
snapshot_source_code=None,
|
||||
candidate_source_codes={'CRANE'},
|
||||
) == 'CRANE'
|
||||
assert _resolve_shortage_release_inventory_source(
|
||||
fact_source_code=None,
|
||||
task_source_code=None,
|
||||
snapshot_source_code='DBS',
|
||||
candidate_source_codes={'CRANE'},
|
||||
) == 'DBS'
|
||||
|
||||
|
||||
@@ -352,7 +352,7 @@ def test_assert_line_can_fulfill_raises_on_shortage():
|
||||
"""断言路径对库存不足抛 ConflictError。"""
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
_assert_line_can_fulfill_complete(
|
||||
line_key='L1',
|
||||
draft_line_id='L1',
|
||||
draft_line={'qty': '5', 'reservation_id': 'R1'},
|
||||
proj={'available_qty': '1'},
|
||||
)
|
||||
@@ -369,14 +369,14 @@ def test_decide_fulfill_rejects_shortage_via_api_path(app, monkeypatch):
|
||||
draft = SimpleNamespace(
|
||||
draft_version=1,
|
||||
lines_json=[{
|
||||
'line_key': 'L1',
|
||||
'draft_line_id': 'L1',
|
||||
'qty': '10',
|
||||
'reservation_id': 'R1',
|
||||
'part_number': 'PN1',
|
||||
}],
|
||||
validation_result_json={
|
||||
'line_projections': [{
|
||||
'line_key': 'L1',
|
||||
'draft_line_id': 'L1',
|
||||
'available_qty': '2',
|
||||
'effective_reservation_id': 'R1',
|
||||
}],
|
||||
@@ -400,7 +400,7 @@ def test_decide_fulfill_rejects_shortage_via_api_path(app, monkeypatch):
|
||||
svc.decide_review_line_fulfillment(
|
||||
user_id=1,
|
||||
case_no='CASE-1',
|
||||
line_key='L1',
|
||||
draft_line_id='L1',
|
||||
decision_code=DECISION_FULFILL,
|
||||
expected_draft_version=1,
|
||||
)
|
||||
@@ -415,7 +415,7 @@ def test_decide_reopen_forbidden_for_task_created(app, monkeypatch):
|
||||
|
||||
draft = SimpleNamespace(
|
||||
draft_version=1,
|
||||
lines_json=[{'line_key': 'L1', 'qty': '10', 'reservation_id': 'R1'}],
|
||||
lines_json=[{'draft_line_id': 'L1', 'qty': '10', 'reservation_id': 'R1'}],
|
||||
validation_result_json={'line_projections': []},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
@@ -438,7 +438,7 @@ def test_decide_reopen_forbidden_for_task_created(app, monkeypatch):
|
||||
svc.decide_review_line_fulfillment(
|
||||
user_id=1,
|
||||
case_no='CASE-1',
|
||||
line_key='L1',
|
||||
draft_line_id='L1',
|
||||
decision_code=DECISION_REOPEN,
|
||||
reason='retry',
|
||||
actor_is_admin=True,
|
||||
@@ -454,7 +454,7 @@ def test_decide_reopen_requires_admin_for_closed(app, monkeypatch):
|
||||
|
||||
draft = SimpleNamespace(
|
||||
draft_version=1,
|
||||
lines_json=[{'line_key': 'L1', 'qty': '10', 'reservation_id': 'R1'}],
|
||||
lines_json=[{'draft_line_id': 'L1', 'qty': '10', 'reservation_id': 'R1'}],
|
||||
validation_result_json={'line_projections': []},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
@@ -477,7 +477,7 @@ def test_decide_reopen_requires_admin_for_closed(app, monkeypatch):
|
||||
svc.decide_review_line_fulfillment(
|
||||
user_id=1,
|
||||
case_no='CASE-1',
|
||||
line_key='L1',
|
||||
draft_line_id='L1',
|
||||
decision_code=DECISION_REOPEN,
|
||||
reason='admin reopen',
|
||||
actor_is_admin=False,
|
||||
@@ -493,8 +493,8 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch):
|
||||
|
||||
draft = SimpleNamespace(
|
||||
draft_version=1,
|
||||
lines_json=[{'line_key': 'L1', 'qty': '1', 'reservation_id': 'R1', 'part_number': 'PN1'}],
|
||||
validation_result_json={'line_projections': [{'line_key': 'L1', 'available_qty': '1'}]},
|
||||
lines_json=[{'draft_line_id': 'L1', 'qty': '1', 'reservation_id': 'R1', 'part_number': 'PN1'}],
|
||||
validation_result_json={'line_projections': [{'draft_line_id': 'L1', 'available_qty': '1'}]},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
id=1,
|
||||
@@ -505,7 +505,7 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch):
|
||||
)
|
||||
row = SimpleNamespace(
|
||||
id=None,
|
||||
line_key='L1',
|
||||
draft_line_id='L1',
|
||||
line_index=0,
|
||||
decision_version=1,
|
||||
decision_code=DECISION_FULFILL,
|
||||
@@ -556,7 +556,7 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch):
|
||||
result = svc.decide_review_line_fulfillment(
|
||||
user_id=1,
|
||||
case_no='CASE-1',
|
||||
line_key='L1',
|
||||
draft_line_id='L1',
|
||||
decision_code=DECISION_FULFILL,
|
||||
expected_draft_version=1,
|
||||
)
|
||||
|
||||
@@ -18,8 +18,9 @@ from app.models import (
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
ShippingReservation,
|
||||
ShippingNotice,
|
||||
ShippingTaskEvent,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
current_available_snapshot_line_ids,
|
||||
@@ -62,7 +63,7 @@ def test_shortage_release_makes_only_its_snapshot_line_exportable(app):
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
released_line = snapshot.lines[0]
|
||||
blocked_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
|
||||
snapshot_id=snapshot.id, position=1, line_no=2, part_number='000126', reservation_id='0012345681',
|
||||
qty=Decimal('3'), field_values_json={},
|
||||
)
|
||||
snapshot.lines.append(blocked_line)
|
||||
@@ -85,7 +86,7 @@ def test_partial_inventory_allows_excel_for_the_available_lines(app):
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
available_line = snapshot.lines[0]
|
||||
shortage_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
|
||||
snapshot_id=snapshot.id, position=1, line_no=2, part_number='000126', reservation_id='0012345681',
|
||||
qty=Decimal('3'), field_values_json={},
|
||||
)
|
||||
snapshot.lines.append(shortage_line)
|
||||
@@ -105,7 +106,7 @@ def test_selected_notice_only_returns_its_frozen_lines(app):
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
first_line = snapshot.lines[0]
|
||||
second_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
|
||||
snapshot_id=snapshot.id, position=1, line_no=2, part_number='000126', reservation_id='0012345681',
|
||||
qty=Decimal('3'), field_values_json={},
|
||||
)
|
||||
snapshot.lines.append(second_line)
|
||||
@@ -163,11 +164,11 @@ def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app):
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
first_line = snapshot.lines[0]
|
||||
second_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, part_number='000124', reservation_id='0012345679',
|
||||
snapshot_id=snapshot.id, position=1, line_no=2, part_number='000124', reservation_id='0012345679',
|
||||
qty=Decimal('4'), field_values_json={},
|
||||
)
|
||||
third_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=2, part_number='000125', reservation_id='0012345680',
|
||||
snapshot_id=snapshot.id, position=2, line_no=3, part_number='000125', reservation_id='0012345680',
|
||||
qty=Decimal('3'), field_values_json={},
|
||||
)
|
||||
snapshot.lines.extend([second_line, third_line])
|
||||
@@ -201,7 +202,7 @@ def test_reservation_rejects_different_purchase_order_and_requires_review_for_sa
|
||||
ensure_task_reservations(first_task)
|
||||
db.session.commit()
|
||||
|
||||
second_task = ShippingNotice(task_no='SN-SNAPSHOT-102', source_type='test')
|
||||
second_task = ShippingOrderTask(task_no='SN-SNAPSHOT-102', source_type=None, user_id=first_user.id)
|
||||
db.session.add(second_task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
@@ -217,7 +218,7 @@ def test_reservation_rejects_different_purchase_order_and_requires_review_for_sa
|
||||
db.session.add(second_snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=second_snapshot.id, position=0, reservation_id='0012345678',
|
||||
snapshot_id=second_snapshot.id, position=0, line_no=1, reservation_id='0012345678',
|
||||
part_number='000123', qty=Decimal('12.5'), field_values_json={},
|
||||
))
|
||||
second_task.order_snapshot_id = second_snapshot.id
|
||||
@@ -232,50 +233,42 @@ def test_reservation_rejects_different_purchase_order_and_requires_review_for_sa
|
||||
|
||||
|
||||
def test_confirmed_task_revision_transfers_unfulfilled_reservation_with_audit(app):
|
||||
"""已确认的直接后继可接替同 PO 的未履约 Reservation,且保留父子审计。"""
|
||||
"""已确认的同一 OT 修订复用该 OT(仅 bump order_data_version),接替同 PO 的未履约 Reservation。"""
|
||||
with app.app_context():
|
||||
first_task, first_user = _build_accepted_order(suffix='201')
|
||||
first_snapshot = freeze_order_snapshot(first_task, actor_id=first_user.id, expected_order_data_version=7)
|
||||
ensure_task_reservations(first_task)
|
||||
db.session.flush()
|
||||
original = ShippingReservation.query.filter_by(reservation_id=first_snapshot.lines[0].reservation_id).one()
|
||||
ot_id = int(first_task.id)
|
||||
ot_count = ShippingOrderTask.query.count()
|
||||
|
||||
revision_task = ShippingNotice(
|
||||
task_no='SN-SNAPSHOT-202', source_type='test', supersedes_task_id=first_task.id,
|
||||
)
|
||||
db.session.add(revision_task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=revision_task.id, schema_version_id=first_snapshot.schema_version_id,
|
||||
input_snapshot_hash='c' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
revision_snapshot = ShippingOrderSnapshot(
|
||||
task_id=revision_task.id, extraction_id=extraction.id,
|
||||
schema_version_id=first_snapshot.schema_version_id, order_data_version=2,
|
||||
rule_versions_json={}, header_values_json={}, customer_po_number=first_snapshot.customer_po_number,
|
||||
)
|
||||
db.session.add(revision_snapshot)
|
||||
db.session.flush()
|
||||
revision_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=revision_snapshot.id, position=0,
|
||||
reservation_id=first_snapshot.lines[0].reservation_id,
|
||||
part_number='000123-REV', qty=Decimal('13.5'), field_values_json={},
|
||||
)
|
||||
db.session.add(revision_line)
|
||||
revision_task.order_snapshot_id = revision_snapshot.id
|
||||
# 修订沿用同一 OT:不新建任务/快照,仅改写冻结行数据并沿用该 OT,
|
||||
# 由 _transfer_confirmed_revision 完成 version bump 与 Reservation 接替。
|
||||
line = first_snapshot.lines[0]
|
||||
line.part_number = '000123-REV'
|
||||
line.qty = Decimal('13.5')
|
||||
db.session.flush()
|
||||
|
||||
registered = ensure_task_reservations(revision_task)
|
||||
registered = ensure_task_reservations(first_task)
|
||||
|
||||
# 同一 OT 上完成接替:不新建任务行,仅版本 bump,Reservation 仍指向该 OT。
|
||||
assert registered == [original]
|
||||
assert original.task_id == revision_task.id
|
||||
assert original.snapshot_line_id == revision_line.id
|
||||
assert original.task_id == ot_id
|
||||
assert original.snapshot_line_id == line.id
|
||||
assert original.part_number == '000123-REV'
|
||||
assert original.required_qty == Decimal('13.5')
|
||||
assert {event.event_type for event in revision_task.events} == {'reservation_revision_confirmed'}
|
||||
assert {event.event_type for event in first_task.events} == {'reservation_revision_superseded'}
|
||||
assert first_task.order_data_version == 8
|
||||
assert first_task.progress_version == 2
|
||||
# 不产生重复 OT 行。
|
||||
assert ShippingOrderTask.query.count() == ot_count
|
||||
# 审计事件落在该 OT 上。
|
||||
assert {event.event_type for event in first_task.events} == {'reservation_revision_confirmed'}
|
||||
assert {event.task_id for event in first_task.events} == {ot_id}
|
||||
assert all(
|
||||
event.task_id == ot_id
|
||||
for event in ShippingTaskEvent.query.filter_by(event_type='reservation_revision_confirmed').all()
|
||||
)
|
||||
|
||||
|
||||
def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it(app):
|
||||
@@ -287,7 +280,7 @@ def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it
|
||||
ensure_task_reservations(task)
|
||||
db.session.flush()
|
||||
|
||||
repeat_task = ShippingNotice(task_no='SN-SNAPSHOT-302', source_type='test')
|
||||
repeat_task = ShippingOrderTask(task_no='SN-SNAPSHOT-302', source_type=None, user_id=user.id)
|
||||
db.session.add(repeat_task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
@@ -303,7 +296,7 @@ def test_first_reservation_registration_allows_missing_po_but_repeat_requires_it
|
||||
db.session.add(repeat_snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=repeat_snapshot.id, position=0, reservation_id=snapshot.lines[0].reservation_id,
|
||||
snapshot_id=repeat_snapshot.id, position=0, line_no=1, reservation_id=snapshot.lines[0].reservation_id,
|
||||
part_number=snapshot.lines[0].part_number, qty=snapshot.lines[0].qty, field_values_json={},
|
||||
))
|
||||
repeat_task.order_snapshot_id = repeat_snapshot.id
|
||||
|
||||
@@ -4,35 +4,87 @@ tests/test_shipping_stp_match_completed_gate.py
|
||||
用途:验证 STP Excel 门禁仅在全部明细 ok 时通过。
|
||||
依赖:fulfillment_workflow.match_completed。
|
||||
逻辑:partial / 混合状态不得制单;fulfillable 且全 ok 可通过。
|
||||
|
||||
迁移说明:STP 匹配事实已从 ShippingNotice 属性 / step_payload_json 迁入正式 DB 行
|
||||
(ShippingNoticeLineInventoryMatch,以 snapshot_line_id 关联冻结快照行)。本文件夹具
|
||||
显式构造 OT + 冻结订单快照 + 快照行 + 行级匹配事实,并 patch 放行事实读取接缝
|
||||
``_released_snapshot_line_ids_for_task``(旧 ``_released_line_keys_for_task`` 已不存在)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch
|
||||
from app.models import (
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed
|
||||
|
||||
|
||||
def _task_with_current_matches(*, task_no: str, rows: list[dict]) -> ShippingNotice:
|
||||
"""写入正式行匹配事实,供 Excel 门禁读取。"""
|
||||
task = ShippingNotice(task_no=task_no, source_type='manual')
|
||||
_extraction_seq = iter(range(1, 10_000_000))
|
||||
|
||||
|
||||
def _task_with_current_matches(*, task_no: str, rows: list[dict]) -> ShippingOrderTask:
|
||||
"""写入正式 OT 行匹配事实(含冻结订单快照行),供 Excel 门禁读取。
|
||||
|
||||
说明:迁移后 ``ShippingNoticeLineInventoryMatch`` 以 ``snapshot_line_id``(冻结快照行 id)
|
||||
为行标识,不再使用 ``line_key``;``match_completed`` 还要求覆盖冻结订单全部项次,
|
||||
因此每个 match 行都对应一个真实 ``ShippingOrderSnapshotLine``。
|
||||
"""
|
||||
user = User(username=f'stp-{task_no}', email=f'stp-{task_no}@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(task_no=task_no, user_id=user.id, stage='inventory_matching')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingNoticeLineInventoryMatch(
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=next(_extraction_seq), schema_version_id=1,
|
||||
order_data_version=1, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
for index, row in enumerate(rows, start=1):
|
||||
line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=index - 1, line_no=index,
|
||||
field_values_json={},
|
||||
)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key=f'L{index}',
|
||||
snapshot_line_id=line.id,
|
||||
line_no=index,
|
||||
line_index=index - 1,
|
||||
match_result=row['match_result'],
|
||||
inventory_status='ready',
|
||||
shortage_qty=row.get('shortage_qty', '0'),
|
||||
is_current=True,
|
||||
)
|
||||
for index, row in enumerate(rows, start=1)
|
||||
])
|
||||
))
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _patch_released_snapshot_line_ids(monkeypatch, task, *, released_line_keys: set[str]):
|
||||
"""把放行事实读取替换为给定冻结快照行 id 集合。
|
||||
|
||||
说明:放行决定读取已迁到 ``_released_snapshot_line_ids_for_task``(按快照行 id),
|
||||
这里仍沿用测试的 ``L{index}`` 行键语义,将其映射到对应快照行 id 后打补丁。
|
||||
"""
|
||||
from app.services.shipping_notice import fulfillment_workflow as mod
|
||||
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
|
||||
line_id_by_key = {
|
||||
f'L{i}': int(line.id)
|
||||
for i, line in enumerate(snapshot.lines, start=1)
|
||||
}
|
||||
released_ids = {line_id_by_key[key] for key in released_line_keys if key in line_id_by_key}
|
||||
monkeypatch.setattr(mod, '_released_snapshot_line_ids_for_task', lambda _task: set(released_ids))
|
||||
|
||||
|
||||
def test_match_completed_rejects_partial(app):
|
||||
"""partial 即使存在 ok 行也不得进入 Excel。"""
|
||||
with app.app_context():
|
||||
@@ -88,18 +140,6 @@ def test_match_step_progress_fulfillable_is_completed_100():
|
||||
assert fields['progress_percent'] == 100
|
||||
|
||||
|
||||
def _patch_released_keys(monkeypatch, *, released_line_keys: set[str]):
|
||||
"""把放行行键读取替换为给定集合,直接验证聚合/满足性的放行语义。
|
||||
|
||||
说明:放行决定读取是纯 SQL join,构造真实 Case/LineDecision 表关系较复杂;
|
||||
这里只打补丁到 ``_released_line_keys_for_task`` 这个稳定接缝,聚合重算与
|
||||
``match_completed`` 都会消费它。
|
||||
"""
|
||||
from app.services.shipping_notice import fulfillment_workflow as mod
|
||||
|
||||
monkeypatch.setattr(mod, '_released_line_keys_for_task', lambda _task: set(released_line_keys))
|
||||
|
||||
|
||||
def test_release_shortage_marks_aggregate_fulfillable(app, monkeypatch):
|
||||
"""短缺行被人工放行后,聚合重算应视为满足(fulfillable),不再标 unfulfillable。"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
@@ -117,15 +157,15 @@ def test_release_shortage_marks_aggregate_fulfillable(app, monkeypatch):
|
||||
status, _ = _recompute_task_match_aggregate(task)
|
||||
assert status in {'partial', 'unfulfillable'}
|
||||
|
||||
# 放行缺口行(行键 L2)
|
||||
_patch_released_keys(monkeypatch, released_line_keys={'L2'})
|
||||
# 放行缺口行(行键 L2)。
|
||||
_patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys={'L2'})
|
||||
|
||||
# 放行后:匹配满足;聚合重算不再误判缺货。
|
||||
assert match_completed(task) is True
|
||||
status, shortages = _recompute_task_match_aggregate(task)
|
||||
assert status == 'fulfillable'
|
||||
assert shortages == []
|
||||
assert task.line_results_json[1]['line_status'] == 'released'
|
||||
assert task.step_payload_json['current_match_projection']['line_results'][1]['line_status'] == 'released'
|
||||
|
||||
|
||||
def test_release_shortage_leaves_unreleased_shortage_blocks(app, monkeypatch):
|
||||
@@ -141,7 +181,7 @@ def test_release_shortage_leaves_unreleased_shortage_blocks(app, monkeypatch):
|
||||
],
|
||||
)
|
||||
# 只放行第一行(L1),L2 的 not_found 缺口未被放行 → 不满足。
|
||||
_patch_released_keys(monkeypatch, released_line_keys={'L1'})
|
||||
_patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys={'L1'})
|
||||
status, shortages = _recompute_task_match_aggregate(task)
|
||||
assert status in {'partial', 'unfulfillable'}
|
||||
assert shortages
|
||||
@@ -162,14 +202,15 @@ def test_recompute_fulfillment_state_syncs_review_pending_on_release(app, monkey
|
||||
task.pending_human_reason = 'shortage'
|
||||
db.session.flush()
|
||||
|
||||
_patch_released_keys(monkeypatch, released_line_keys={'L1'})
|
||||
_patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys={'L1'})
|
||||
status = recompute_task_fulfillment_state(task)
|
||||
|
||||
assert status == 'fulfillable'
|
||||
assert task.match_status == 'fulfillable'
|
||||
# match_status 已迁到 DB 事实投影,不再读取旧任务缓存列。
|
||||
assert task.step_payload_json['current_match_projection']['match_status'] == 'fulfillable'
|
||||
assert task.review_status != 'shortage_review'
|
||||
assert task.pending_human_reason is None
|
||||
assert task.line_results_json[0]['line_status'] == 'released'
|
||||
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'released'
|
||||
|
||||
|
||||
def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monkeypatch):
|
||||
@@ -187,11 +228,11 @@ def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monke
|
||||
task.pending_human_reason = 'shortage'
|
||||
db.session.flush()
|
||||
|
||||
# 没有放行决定
|
||||
_patch_released_keys(monkeypatch, released_line_keys=set())
|
||||
# 没有放行决定。
|
||||
_patch_released_snapshot_line_ids(monkeypatch, task, released_line_keys=set())
|
||||
status = recompute_task_fulfillment_state(task)
|
||||
|
||||
assert status in {'partial', 'unfulfillable'}
|
||||
assert task.review_status == 'shortage_review'
|
||||
assert task.pending_human_reason == 'shortage'
|
||||
assert task.line_results_json[0]['line_status'] == 'shortage'
|
||||
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'shortage'
|
||||
@@ -12,7 +12,6 @@ from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.export import _mapping_value
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
apply_line_inventory_resolutions,
|
||||
match_order_lines_across_candidates,
|
||||
)
|
||||
|
||||
@@ -41,15 +40,16 @@ def test_current_match_facts_rebuild_shortage_detail(monkeypatch):
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(mod, 'ShippingNoticeLineInventoryMatch', fake_match_model)
|
||||
task = SimpleNamespace(id=101, line_results_json=None, shortage_json=None)
|
||||
task = SimpleNamespace(id=101, step_payload_json={})
|
||||
|
||||
status, shortages = mod._recompute_task_match_aggregate(task)
|
||||
|
||||
projection = task.step_payload_json['current_match_projection']
|
||||
assert status == 'partial'
|
||||
assert task.line_results_json[1]['available_qty'] == 0.0
|
||||
assert task.line_results_json[1]['shortage_qty'] == 5.0
|
||||
assert task.line_results_json[1]['line_status'] == 'shortage'
|
||||
assert task.shortage_json == {'lines': shortages}
|
||||
assert projection['line_results'][1]['available_qty'] == 0.0
|
||||
assert projection['line_results'][1]['shortage_qty'] == 5.0
|
||||
assert projection['line_results'][1]['line_status'] == 'shortage'
|
||||
assert projection['shortage'] == {'lines': shortages}
|
||||
|
||||
|
||||
def test_cross_candidate_unique_hit_is_fulfillable():
|
||||
@@ -158,176 +158,38 @@ def test_header_reservation_fallback_for_match():
|
||||
assert result['resolutions'][0]['effective_reservation_id'] == '3000092917'
|
||||
|
||||
|
||||
def test_apply_resolutions_sets_summary_source_when_unique(monkeypatch):
|
||||
"""全部 ok 且唯一源时投影 task.inventory_source_code。"""
|
||||
from app.services.shipping_notice import stp_line_inventory_match as mod
|
||||
|
||||
monkeypatch.setattr(
|
||||
mod,
|
||||
'get_database_inventory_source',
|
||||
lambda code: {
|
||||
'source_code': code,
|
||||
'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'fixed',
|
||||
'fixed_warehouse_id': 'WH1',
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(mod, 'inventory_sources_runtime_version', lambda: 'v1')
|
||||
monkeypatch.setattr(mod, 'extract_routing_context', lambda _task: {})
|
||||
monkeypatch.setattr(mod, 'compute_routing_fingerprint', lambda _ctx: 'fp')
|
||||
|
||||
task = SimpleNamespace(
|
||||
step_payload_json={},
|
||||
match_status=None,
|
||||
line_results_json=None,
|
||||
shortage_json=None,
|
||||
inventory_source_code=None,
|
||||
inventory_connector_type=None,
|
||||
inventory_warehouse_id=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
inventory_source_method=None,
|
||||
inventory_source_config_version=None,
|
||||
inventory_routing_fingerprint=None,
|
||||
)
|
||||
apply_line_inventory_resolutions(task, {
|
||||
'match_status': 'fulfillable',
|
||||
'line_results': [{'line_status': 'ok'}],
|
||||
'shortage_json': {'lines': []},
|
||||
'resolutions': [{
|
||||
'disposition': 'ok',
|
||||
'resolved_inventory_source_code': 'DBS_DUB',
|
||||
}],
|
||||
})
|
||||
assert task.inventory_source_code == 'DBS_DUB'
|
||||
assert task.inventory_source_status == 'resolved'
|
||||
assert task.step_payload_json['line_inventory_resolutions'][0]['resolved_inventory_source_code'] == 'DBS_DUB'
|
||||
|
||||
|
||||
def test_apply_resolutions_allows_multi_source_excel(monkeypatch):
|
||||
"""多行命中不同源且全部 ok 时投影主绑定源并允许制单,不写 multi_source_excel_block。"""
|
||||
from app.services.shipping_notice import stp_line_inventory_match as mod
|
||||
|
||||
monkeypatch.setattr(
|
||||
mod,
|
||||
'get_database_inventory_source',
|
||||
lambda code: {
|
||||
'source_code': code,
|
||||
'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'fixed',
|
||||
'fixed_warehouse_id': 'WH1',
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(mod, 'inventory_sources_runtime_version', lambda: 'v1')
|
||||
monkeypatch.setattr(mod, 'extract_routing_context', lambda _task: {})
|
||||
monkeypatch.setattr(mod, 'compute_routing_fingerprint', lambda _ctx: 'fp')
|
||||
task = SimpleNamespace(
|
||||
step_payload_json={},
|
||||
match_status=None,
|
||||
line_results_json=None,
|
||||
shortage_json=None,
|
||||
inventory_source_code=None,
|
||||
inventory_connector_type=None,
|
||||
inventory_warehouse_id=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
inventory_source_method=None,
|
||||
inventory_source_config_version=None,
|
||||
inventory_routing_fingerprint=None,
|
||||
)
|
||||
apply_line_inventory_resolutions(task, {
|
||||
'match_status': 'fulfillable',
|
||||
'line_results': [{'line_status': 'ok'}, {'line_status': 'ok'}],
|
||||
'shortage_json': {'lines': []},
|
||||
'resolutions': [
|
||||
{'disposition': 'ok', 'resolved_inventory_source_code': 'DBS_DUB'},
|
||||
{'disposition': 'ok', 'resolved_inventory_source_code': 'DBS_RTM'},
|
||||
],
|
||||
})
|
||||
assert task.inventory_source_code in {'DBS_DUB', 'DBS_RTM'}
|
||||
assert task.inventory_source_status == 'resolved'
|
||||
assert task.inventory_source_method == 'stp_line_match_multi'
|
||||
assert task.step_payload_json.get('multi_source_excel_block') is None
|
||||
assert set(task.step_payload_json.get('resolved_ok_source_codes') or []) == {'DBS_DUB', 'DBS_RTM'}
|
||||
|
||||
|
||||
def test_excel_mapping_keeps_user_configured_line_number():
|
||||
"""export_sequence 输出导出行序号,订单字段 line_no 保留内部项次原文值。"""
|
||||
def test_excel_mapping_uses_notice_line_number(app):
|
||||
"""模板系统事实输出发货通知项次,订单字段 line_no 仍读取冻结订单项次。"""
|
||||
task = SimpleNamespace(
|
||||
task_no='T1',
|
||||
business_no='SN-001',
|
||||
shipping_case=None,
|
||||
inventory_warehouse_id='WH1',
|
||||
inventory_source_code='DBS_DUB',
|
||||
)
|
||||
value = _mapping_value(
|
||||
{'source_kind': 'system_fact', 'source_key': 'export_sequence', 'formatter': 'none'},
|
||||
{'source_kind': 'system_fact', 'source_key': 'notice_line_no', 'formatter': 'none'},
|
||||
task=task,
|
||||
order_values={'__export_sequence': 2, 'customer_po_line_no': '00020'},
|
||||
inventory_values={},
|
||||
export_sequence=2,
|
||||
notice_line_no='2',
|
||||
)
|
||||
assert value == 2
|
||||
assert value == '2'
|
||||
order_field_value = _mapping_value(
|
||||
{'source_kind': 'order_field', 'source_key': 'line_no', 'formatter': 'none', 'row_mode': 'line'},
|
||||
task=task,
|
||||
order_values={'__export_sequence': 3, 'line_no': '00030'},
|
||||
order_values={'line_no': '00030'},
|
||||
inventory_values={},
|
||||
export_sequence=3,
|
||||
)
|
||||
assert order_field_value == '00030'
|
||||
|
||||
|
||||
def test_allowed_system_facts_use_export_sequence_not_line_no():
|
||||
"""Phase 0 门禁:系统事实目录含 export_sequence,不含 line_no。"""
|
||||
def test_allowed_system_facts_use_notice_line_no_not_export_sequence():
|
||||
"""模板系统事实使用发货通知项次,不再暴露导出行序号。"""
|
||||
from app.services.shipping_notice.excel_template import ALLOWED_SYSTEM_FACTS
|
||||
|
||||
assert 'export_sequence' in ALLOWED_SYSTEM_FACTS
|
||||
assert 'line_no' not in ALLOWED_SYSTEM_FACTS
|
||||
|
||||
|
||||
def test_default_derivation_rules_are_disabled_copy_if_empty():
|
||||
"""新草稿预置 customer_po_line_no→line_no,默认关闭。"""
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
default_derivation_rules,
|
||||
normalize_derivation_rules,
|
||||
)
|
||||
|
||||
rules = default_derivation_rules()
|
||||
assert rules == [{
|
||||
'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO',
|
||||
'enabled': False,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}]
|
||||
assert normalize_derivation_rules(None) == rules
|
||||
|
||||
|
||||
def test_derivation_engine_copy_if_empty_and_skips():
|
||||
"""启用规则时空值派生、非空跳过、非法格式跳过。"""
|
||||
from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines
|
||||
|
||||
rules = [{
|
||||
'rule_id': 'R1',
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}]
|
||||
outcome = apply_derivation_rules_to_lines(
|
||||
[
|
||||
{'customer_po_line_no': '00010', 'line_no': None},
|
||||
{'customer_po_line_no': '00020', 'line_no': '20'},
|
||||
{'customer_po_line_no': 'ABC', 'line_no': None},
|
||||
],
|
||||
rules,
|
||||
)
|
||||
assert outcome['lines'][0]['line_no'] == '00010'
|
||||
assert outcome['lines'][1]['line_no'] == '20'
|
||||
assert outcome['lines'][2].get('line_no') in (None, '')
|
||||
assert [item['status'] for item in outcome['results']] == ['derived', 'skipped', 'skipped']
|
||||
assert outcome['results'][1]['skip_reason'] == 'target_not_empty'
|
||||
assert outcome['results'][2]['skip_reason'] == 'source_format_invalid'
|
||||
assert 'notice_line_no' in ALLOWED_SYSTEM_FACTS
|
||||
assert 'export_sequence' not in ALLOWED_SYSTEM_FACTS
|
||||
|
||||
|
||||
def test_permanent_audit_events_have_no_retention_expiry(app):
|
||||
@@ -338,13 +200,13 @@ def test_permanent_audit_events_have_no_retention_expiry(app):
|
||||
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='DERIVATION_SIMULATED',
|
||||
event_type='shipping_order_audited',
|
||||
aggregate_type='shipping_order_schema_version',
|
||||
aggregate_id='1',
|
||||
actor_type='admin',
|
||||
actor_id=1,
|
||||
result='success',
|
||||
metadata={'derived_count': 1, 'skipped_count': 0},
|
||||
metadata={'sample': True},
|
||||
)
|
||||
db.session.commit()
|
||||
stored = db.session.get(ShippingAuditEvent, event.id)
|
||||
|
||||
Reference in new issue
Block a user