feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程

清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
hugo committed 2026-08-20 20:23:10 +08:00
1 parent 260465b72d
commit 1b6483a4ea
466 files changed
+32115 -33796

No files matched your search

@@ -6,6 +6,7 @@
from __future__ import annotations
import pytest
from sqlalchemy import UniqueConstraint
from app.models import (
@@ -33,6 +34,104 @@ def test_recovery_plan_has_idempotent_business_identity():
assert 'invalidation_plan_json' in ShippingProcessRecoveryPlan.__table__.c
def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
"""仅重生 Excel 只替代旧产物和未完成上传,不能重算库存或抹掉短缺放行事实。"""
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingInventoryParsingProfile,
ShippingInventoryVerification,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingOrderExtraction,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingProcessExecution,
ShippingReservation,
ShippingUploadAttempt,
)
from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only
task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', export_file_path='old.xlsx', export_file_name='old.xlsx')
template = ShippingExcelTemplate(
template_code='REGEN-ONLY', display_name='Regen only', version=1, status='published',
storage_bucket='test', storage_key='test/template.xlsx', original_filename='template.xlsx',
file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='REGEN-ONLY', display_name='Regen only', version=1,
status='published', file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='REGEN-ONLY', display_name='Regen only')
db.session.add_all([task, template, profile, schema])
db.session.flush()
schema_version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={},
)
db.session.add(schema_version)
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=schema_version.id, input_snapshot_hash='b' * 64, status='accepted',
)
execution = ShippingProcessExecution(
execution_no='SPE-EXCEL-REGEN-ONLY', task_id=task.id, status='blocked',
current_gate_code='manual_upload_handoff',
)
db.session.add_all([extraction, execution])
db.session.flush()
artifact = ShippingExportArtifact(
artifact_no='EXP-EXCEL-REGEN-ONLY', task_id=task.id, template_id=template.id,
order_schema_version_id=schema_version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path='old.xlsx', file_name='old.xlsx', file_checksum='d' * 64, file_size=1,
status='ready',
)
reservation = ShippingReservation(
task_id=task.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY',
part_number='PN-1', po_number_normalized='PO-1', required_qty=1,
status='artifact_reserved', current_artifact_id=None,
)
verification = ShippingInventoryVerification(task_id=task.id, status='completed', result_json={})
match = ShippingNoticeLineInventoryMatch(
task_id=task.id, line_key='line-1', reservation_id='RSV-EXCEL-REGEN-ONLY',
part_number='PN-1', match_result='matched', inventory_status='ready', is_current=True,
)
db.session.add_all([artifact, reservation, verification, match])
db.session.flush()
reservation.current_artifact_id = artifact.id
upload = ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=1, mode='manual',
idempotency_key='excel-regen-only', status='pending',
)
db.session.add(upload)
db.session.flush()
result = invalidate_excel_regeneration_only(
execution=execution,
attempt_id=17,
actor_id=9,
)
db.session.refresh(task)
db.session.refresh(artifact)
db.session.refresh(upload)
db.session.refresh(reservation)
db.session.refresh(verification)
db.session.refresh(match)
assert result['artifacts'] == [artifact.id]
assert result['uploads'] == [upload.id]
assert artifact.status == 'superseded'
assert upload.status == 'failed'
assert upload.invalidated_at is not None
assert reservation.status == 'available'
assert reservation.current_artifact_id is None
assert task.export_file_path is None
assert task.export_file_name is None
assert verification.status == 'completed'
assert match.is_current is True
def test_inventory_preparation_is_task_round_with_per_source_uniqueness():
"""准备轮次和逐源 Attempt 均必须保留不可混淆的唯一范围。"""
assert 'uq_shipping_inventory_preparation_task_attempt' in _unique_names(ShippingInventoryPreparationAttempt)
@@ -482,8 +581,8 @@ def test_batch_callback_inherits_authenticated_top_level_schema_version():
assert merged['task_no'] == 'SN-1'
def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
"""RPA 已耗尽时自动轮询必须终态化,Gate 才能退出系统处理中。"""
def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app):
"""历史 RPA 耗尽必须退出系统处理中,且不得封锁用户重试入口。"""
from app import db
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
@@ -528,7 +627,7 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
ShippingProcessGateAttempt.gate_id == gate.id,
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
).count() == 0
assert gate.status == 'blocked_manual'
assert gate.status == 'blocked_retryable'
assert gate.blocking_reason_code == 'inventory_rpa_exhausted'
db.session.refresh(execution)
# Gate 已进入可人工恢复的 blocked_manual;Execution 仍保持 active,
@@ -610,6 +709,83 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
assert attempt.job_id is None
def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rpa(app, monkeypatch):
"""已失败的准备轮次被旧 poll 领取时,必须保留超时并禁止再次调 RPA。"""
from app import db
from app.models import (
ShippingInventoryPreparationAttempt,
ShippingNotice,
ShippingProcessGate,
ShippingTaskEvent,
)
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.process_gate_job_service import claim_and_run_gate_attempt
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
queue_gate_attempt,
)
task = ShippingNotice(task_no='SN-POLL-KEEPS-RPA-TIMEOUT', pending_human_reason='inv_unavail')
db.session.add(task)
db.session.flush()
execution = ensure_execution_for_workflow_version(
task_id=task.id,
start_gate_code='inventory_preparation',
)
task.active_process_execution_id = execution.id
preparation = ShippingInventoryPreparationAttempt(
task_id=task.id,
execution_id=execution.id,
attempt_no=1,
status='failed',
input_snapshot_json={},
output_snapshot_json={},
)
db.session.add_all([
preparation,
ShippingTaskEvent(
task_id=task.id,
event_type='inventory_rpa_failed',
detail_json={'error': 'Crane scheduled report not ready for download within 300000ms'},
),
])
db.session.flush()
sync_fulfillment_gates_from_task(execution=execution)
gate = ShippingProcessGate.query.filter_by(
execution_id=execution.id,
gate_code='inventory_preparation',
).one()
assert gate.status == 'blocked_retryable'
assert gate.blocking_reason_code == 'inventory_rpa_timeout'
rpa_calls = {'count': 0}
monkeypatch.setattr(
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
lambda _payload: rpa_calls.__setitem__('count', rpa_calls['count'] + 1),
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='auto',
actor_type='system',
actor_id='external-wait-poll',
idempotency_key='poll-keeps-rpa-timeout-1',
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {'poll': True}},
)
db.session.commit()
result = claim_and_run_gate_attempt(attempt_id=attempt.id, worker_id='timeout-poll-worker')
db.session.refresh(gate)
db.session.refresh(execution)
assert result['skipped'] is False
assert rpa_calls['count'] == 0
assert gate.status == 'blocked_retryable'
assert gate.blocking_reason_code == 'inventory_rpa_timeout'
assert gate.next_action_code == 'retry_inventory_preparation'
assert execution.status == 'blocked'
def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch):
"""正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。"""
from app import db
@@ -941,6 +1117,146 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan():
assert plan.completed_at is not None
def test_excel_regeneration_completion_preserves_manual_upload_gate():
"""跨 Gate Excel 重生完成后,当前 Gate 20 必须继续等待人工上传且计划可关闭。"""
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
class Plan:
status = 'queued'
action_code = 'regenerate_excel_artifact'
resume_after_gate = 'manual_upload_handoff'
started_at = None
completed_at = None
failure_code = None
failure_detail_json = None
plan = Plan()
complete_recovery_plan_for_attempt(
plan=plan,
outcome='blocked_manual',
business_result_code='manual_upload_pending',
)
assert plan.status == 'succeeded'
assert plan.completed_at is not None
def test_manual_upload_excel_regeneration_returns_to_manual_handoff(monkeypatch):
"""Gate 20 触发 Excel 重生后,执行器必须作废旧产物并保持人工上传阻断。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
invalidated = {}
monkeypatch.setattr(
'app.services.shipping_notice.recovery_invalidation_service.invalidate_excel_regeneration_only',
lambda **kwargs: invalidated.update(kwargs) or {'artifacts': [10], 'uploads': [11]},
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
lambda _payload: {'status': 'ok'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._task_payload',
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
)
outcome = _handle_regenerate_excel(
execution=SimpleNamespace(execution_no='SPE-EXCEL-HANDOFF', task_id=1),
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
payload={'attempt_id': 3, 'actor_user_id': 9},
)
assert invalidated['attempt_id'] == 3
assert outcome['outcome'] == 'blocked_manual'
assert outcome['blocking_reason_code'] == 'manual_upload_pending'
assert outcome['output_snapshot']['invalidation']['artifacts'] == [10]
def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch):
"""Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
synced = []
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
lambda _payload: {'status': 'failed', 'message': 'template unavailable'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **kwargs: synced.append(kwargs),
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._task_payload',
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
)
execution = SimpleNamespace(execution_no='SPE-EXCEL-FAILED', task_id=1)
outcome = _handle_regenerate_excel(
execution=execution,
gate=SimpleNamespace(gate_code='artifact_generation'),
payload={'actor_user_id': 9},
)
assert outcome['outcome'] == 'blocked_retryable'
assert outcome['blocking_reason_code'] == 'artifact_generation_failed'
assert synced == [{
'execution': execution,
'actor_type': 'system',
'actor_id': 9,
}]
def test_executor_accepts_bound_cross_gate_excel_recovery_plan(monkeypatch):
"""已绑定的 Gate 20 Excel RecoveryPlan 必须能通过 Worker 归属复核。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_executor as executor
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._handle_regenerate_excel',
lambda **_: {'outcome': 'blocked_manual'},
)
monkeypatch.setattr(
executor.db.session,
'get',
lambda _model, _id: SimpleNamespace(
id=81,
execution_id=1,
current_gate='manual_upload_handoff',
action_code='regenerate_excel_artifact',
target_gate='artifact_generation',
resume_after_gate='manual_upload_handoff',
),
)
result = executor._dispatch_action(
execution=SimpleNamespace(id=1),
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
action_code='regenerate_excel_artifact',
payload={'recovery_plan_id': 81},
)
assert result['outcome'] == 'blocked_manual'
def test_executor_rejects_unbound_cross_gate_excel_recovery_plan():
"""Gate 20 的跨阶段 Excel 动作没有已绑定计划时必须 fail-closed。"""
from types import SimpleNamespace
from app.core.errors import ValidationError
from app.services.shipping_notice.process_gate_executor import _dispatch_action
with pytest.raises(ValidationError, match='Recovery plan is required'):
_dispatch_action(
execution=SimpleNamespace(id=1),
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
action_code='regenerate_excel_artifact',
payload={},
)
def test_inventory_rematch_shortage_is_business_result_not_technical_failure(monkeypatch):
"""库存 14、缺口 16 时,匹配 Attempt 成功收口到缺口复核。"""
from types import SimpleNamespace
@@ -973,8 +1289,10 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
payload={'actor_user_id': 1},
)
assert result['outcome'] == 'blocked_manual'
assert result['blocking_reason_code'] == 'inventory_shortage_review_required'
# 匹配动作已成功完成;库存缺口由 inventory_sufficiency Gate 单独阻断,
# 不能把业务缺口回写成 inventory_matching 的技术失败。
assert result['outcome'] == 'passed'
assert 'blocking_reason_code' not in result
assert result['effective_result_json']['shortage']['lines'][0] == {
'available_qty': 14,
'shortage_qty': 16,
@@ -984,7 +1302,7 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
def test_field_mapping_recovery_does_not_create_preparation_round(monkeypatch):
"""字段映射恢复必须停留在 mapping handler,不得误建库存准备轮次。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _dispatch_action
from app.services.shipping_notice import process_gate_executor as executor
called = {'preparation': 0, 'matching': 0}
monkeypatch.setattr(
@@ -995,9 +1313,20 @@ def test_field_mapping_recovery_does_not_create_preparation_round(monkeypatch):
'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_from_field_mapping',
lambda **_: {'outcome': 'blocked_manual'},
)
result = _dispatch_action(
execution=object(), gate=SimpleNamespace(gate_code='inventory_matching'),
action_code='retry_inventory_from_field_mapping', payload={},
monkeypatch.setattr(
executor.db.session,
'get',
lambda _model, _id: SimpleNamespace(
execution_id=1,
current_gate='inventory_matching',
action_code='retry_inventory_from_field_mapping',
target_gate='inventory_field_mapping',
resume_after_gate='inventory_matching',
),
)
result = executor._dispatch_action(
execution=SimpleNamespace(id=1), gate=SimpleNamespace(gate_code='inventory_matching'),
action_code='retry_inventory_from_field_mapping', payload={'recovery_plan_id': 7},
)
assert result['outcome'] == 'blocked_manual'
assert called['preparation'] == 0