feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与 枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa 持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀, 上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
ffc0d4a430
commit
39fe3c05f2
453 files changed
+17945
-8646
No files matched your search
@@ -35,17 +35,17 @@ def terminal_configuration_test_run(app):
|
||||
"""预置一个已终态的配置测试运行 + 批次,供 configuration-test 三端点走 OK envelope 路径。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryValidationBatch,
|
||||
FreightRpaOnhandConfigurationTestRun,
|
||||
FreightRpaSource,
|
||||
FreightRpaOnhandValidationBatch,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
batch = ShippingInventoryValidationBatch(batch_no='CONFIG-BATCH-ENV-TEST', status='running', total_count=1)
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
batch = FreightRpaOnhandValidationBatch(batch_no='CONFIG-BATCH-ENV-TEST', status='running', total_count=1)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
run = ShippingInventoryConfigurationTestRun(
|
||||
run_no='CONFIG-ENV-TEST-RUN', validation_batch_id=batch.id, inventory_source_id=source.id,
|
||||
run = FreightRpaOnhandConfigurationTestRun(
|
||||
run_no='CONFIG-ENV-TEST-RUN', validation_batch_id=batch.id, source_id=source.id,
|
||||
source_config_version=source.config_version,
|
||||
rpa_profile_config_version=source.rpa_profile.config_version,
|
||||
status='completed', stage='current_profile_verified', result_json={},
|
||||
|
||||
@@ -664,21 +664,21 @@ def _seed_parse_failed_inbound_file(source_code: str):
|
||||
from uuid import uuid4
|
||||
|
||||
from app.models import (
|
||||
ShippingInventorySource,
|
||||
ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
FreightRpaSource,
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code).one()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=source.id, source_code=source.source_code,
|
||||
source = FreightRpaSource.query.filter_by(source_code=source_code).one()
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type, warehouse_id=source.fixed_warehouse_id,
|
||||
callback_id=f"receipt-retry-{uuid4().hex[:12]}", status="success",
|
||||
config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
report = ShippingReceiptReportFile(
|
||||
report = FreightRpaInboundReportFile(
|
||||
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
|
||||
storage_key=f"shipping/receipt/retry-{unit.id}.xlsx",
|
||||
original_filename="retry.xlsx", file_size=16,
|
||||
@@ -699,14 +699,14 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header
|
||||
def fake_sync(*, source_code, business_date, now):
|
||||
# 断言意图:重解析路径 sync 恰好 1 次;成功链路清除解析失败标记使投影回
|
||||
# ready(请求会话内重查后清除并 commit,保证端点再解析可见)。
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.services.in_transit_transfer.source_file_status import clear_inbound_parse_failure
|
||||
|
||||
called["sync"] += 1
|
||||
file = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(ShippingReceiptReportFile.unit_run.has(source_code=source_code))
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(FreightRpaInboundReportFile.unit_run.has(source_code=source_code))
|
||||
.first()
|
||||
)
|
||||
if file is not None:
|
||||
|
||||
+48
-39
@@ -90,7 +90,7 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
|
||||
)
|
||||
if request.node.get_closest_marker("auto_rpa"):
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||||
monkeypatch.setattr(
|
||||
@@ -102,7 +102,7 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
lambda: None,
|
||||
)
|
||||
return
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
|
||||
# 货代自动上传默认 fail-closed;单测与产品默认一致关闭。
|
||||
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
|
||||
@@ -123,9 +123,9 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
def _shipping_test_default_destination(monkeypatch, request):
|
||||
"""
|
||||
为未提供目的地线索的发货通知单测注入 Dublin,以唯一命中 DSV360_AWSDU。
|
||||
标记 inventory_source_gate 的用例跳过,避免干扰库存源门禁专项测试。
|
||||
标记 onhand_source_gate 的用例跳过,避免干扰库存源门禁专项测试。
|
||||
"""
|
||||
if request.node.get_closest_marker("inventory_source_gate"):
|
||||
if request.node.get_closest_marker("onhand_source_gate"):
|
||||
return
|
||||
|
||||
from app.services.shipping_notice import extract as extract_mod
|
||||
@@ -170,9 +170,9 @@ def seed_task_inventory_source(
|
||||
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
|
||||
if owner is None:
|
||||
raise ValueError('test task must be linked to ShippingOrderTask')
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_candidates_for_task
|
||||
from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
from app.services.shipping_notice.onhand_candidate_freeze_service import freeze_candidates_for_task
|
||||
from app.services.shipping_notice.onhand_source_rules import InventorySourceAdjudication
|
||||
from app.services.shipping_notice.onhand_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
@@ -391,7 +391,7 @@ def seed_rpa_inventory_trigger(
|
||||
run_no: str = "RUN-TEST-001",
|
||||
trigger_path: str | None = None,
|
||||
) -> None:
|
||||
"""测试辅助:写入 inventory_rpa_triggered 事件,供单任务回调 run_no 校验。"""
|
||||
"""测试辅助:写入 onhand_rpa_triggered 事件,供单任务回调 run_no 校验。"""
|
||||
from app import db
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
@@ -401,7 +401,7 @@ def seed_rpa_inventory_trigger(
|
||||
trigger = trigger_path or f"inventory_export_batch_{run_no}.json"
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_triggered",
|
||||
"onhand_rpa_triggered",
|
||||
{"trigger": trigger, "run_no": run_no, "attempt": 1, "manual_retry_round": False},
|
||||
)
|
||||
|
||||
@@ -448,10 +448,10 @@ def inventory_csv_with_warehouse(
|
||||
|
||||
def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]:
|
||||
"""构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
|
||||
source_code = next(iter(task_frozen_onhand_source_codes(task)), '')
|
||||
source = get_database_inventory_source(source_code) or {}
|
||||
return {
|
||||
"source_code": str(source_code or ""),
|
||||
@@ -461,7 +461,7 @@ def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]:
|
||||
|
||||
def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
|
||||
"""构造定时 batch 成功回调 item 的 Source/Warehouse 身份(与数据库配置一致)。"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(source_code)
|
||||
if not source:
|
||||
@@ -492,10 +492,10 @@ def rpa_callback_payload(
|
||||
status: str = "success",
|
||||
) -> dict:
|
||||
"""构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
|
||||
|
||||
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
|
||||
source_code = next(iter(task_frozen_onhand_source_codes(task)), '')
|
||||
source = get_database_inventory_source(source_code) or {}
|
||||
return {
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
@@ -528,7 +528,7 @@ def pytest_configure(config):
|
||||
)
|
||||
config.addinivalue_line(
|
||||
"markers",
|
||||
"inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
|
||||
"onhand_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
|
||||
)
|
||||
config.addinivalue_line(
|
||||
"markers",
|
||||
@@ -572,13 +572,17 @@ def app():
|
||||
|
||||
|
||||
def _seed_test_inventory_configuration() -> None:
|
||||
"""为发货测试创建数据库库存源与发布路由规则,测试运行期不读取 YAML。"""
|
||||
"""为发货测试创建数据库库存源、在手报表配置与发布路由规则,测试运行期不读取 YAML。
|
||||
|
||||
s18 起:报表路径/查询条件/解析方案挂在 FreightRpaOnhandReportConfig 上,
|
||||
站点行只剩连接、模板绑定与启停。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
|
||||
ShippingRpaProfile,
|
||||
ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaOnhandReportConfig,
|
||||
FreightRpaParsingProfile, FreightRpaSource, FreightRpaProfile,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import (
|
||||
from app.services.shipping_notice.onhand_structure_fingerprint import (
|
||||
FINGERPRINT_VERSION,
|
||||
compatibility_fingerprint,
|
||||
exact_fingerprint,
|
||||
@@ -586,24 +590,24 @@ def _seed_test_inventory_configuration() -> None:
|
||||
)
|
||||
|
||||
# 各测试显式创建所需用户字段;生产目录本身保持零预置。
|
||||
if not ShippingInventoryField.query.filter_by(field_code='part_number').first():
|
||||
if not FreightRpaOnhandField.query.filter_by(field_code='part_number').first():
|
||||
db.session.add_all([
|
||||
ShippingInventoryField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10),
|
||||
ShippingInventoryField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20),
|
||||
ShippingInventoryField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30),
|
||||
ShippingInventoryField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40),
|
||||
ShippingInventoryField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100),
|
||||
ShippingInventoryField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110),
|
||||
ShippingInventoryField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120),
|
||||
ShippingInventoryField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130),
|
||||
ShippingInventoryField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140),
|
||||
FreightRpaOnhandField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10),
|
||||
FreightRpaOnhandField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20),
|
||||
FreightRpaOnhandField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30),
|
||||
FreightRpaOnhandField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40),
|
||||
FreightRpaOnhandField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100),
|
||||
FreightRpaOnhandField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110),
|
||||
FreightRpaOnhandField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120),
|
||||
FreightRpaOnhandField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130),
|
||||
FreightRpaOnhandField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140),
|
||||
])
|
||||
|
||||
db.session.flush()
|
||||
inventory_fields = {
|
||||
item.field_code: item
|
||||
for item in ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.field_code.in_([
|
||||
for item in FreightRpaOnhandField.query.filter(
|
||||
FreightRpaOnhandField.field_code.in_([
|
||||
'part_number', 'reservation_id', 'available_qty', 'warehouse_id',
|
||||
])
|
||||
).all()
|
||||
@@ -641,7 +645,7 @@ def _seed_test_inventory_configuration() -> None:
|
||||
checksum = hashlib.sha256(
|
||||
json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
).hexdigest()
|
||||
parsing_profile = ShippingInventoryParsingProfile(
|
||||
parsing_profile = FreightRpaParsingProfile(
|
||||
profile_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published',
|
||||
file_format='xlsx', definition_json=definition, checksum=checksum,
|
||||
structure_definition_json=structure,
|
||||
@@ -658,14 +662,20 @@ def _seed_test_inventory_configuration() -> None:
|
||||
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
|
||||
)
|
||||
|
||||
profile = ShippingRpaProfile(
|
||||
profile = FreightRpaProfile(
|
||||
profile_code='DBS_DUB_TEST', display_name='DBS Dublin', connector_type='dbs',
|
||||
login_url='https://test.invalid/dbs', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
source = ShippingInventorySource(
|
||||
source = FreightRpaSource(
|
||||
source_code='DSV360_AWSDU', display_name='DBS Dublin AWSDU', connector_type='dbs',
|
||||
rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template,
|
||||
rpa_profile=profile, excel_template=excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU',
|
||||
enabled=True,
|
||||
)
|
||||
# s18 起报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig,站点行不再承载。
|
||||
report_config = FreightRpaOnhandReportConfig(
|
||||
source=source,
|
||||
parsing_profile=parsing_profile,
|
||||
report_path_json={
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
|
||||
@@ -673,9 +683,8 @@ def _seed_test_inventory_configuration() -> None:
|
||||
query_parameters_json=[
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': True, 'select_all': False},
|
||||
],
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add_all([profile, parsing_profile, excel_template, source])
|
||||
db.session.add_all([profile, parsing_profile, excel_template, source, report_config])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ def test_claim_next_shipping_claims_inventory_callback_process_job(app):
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
domain='shipping_notice',
|
||||
job_type=JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS.value,
|
||||
job_type=JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS.value,
|
||||
status='queued',
|
||||
payload_json={'callback_id': 'callback-test'},
|
||||
)
|
||||
@@ -79,7 +79,7 @@ def test_claim_next_shipping_claims_inventory_callback_process_job(app):
|
||||
|
||||
assert claimed is not None
|
||||
assert claimed['id'] == job.id
|
||||
assert claimed['job_type'] == JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS
|
||||
assert claimed['job_type'] == JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS
|
||||
|
||||
|
||||
def test_claim_next_transfer_claims_run_job(app):
|
||||
|
||||
+164
-144
@@ -2,7 +2,7 @@
|
||||
tests/services/admin/test_shipping_inventory_service.py
|
||||
|
||||
用途:验证库存主数据管理服务的安全性和关键业务约束。
|
||||
依赖:Flask app/db、shipping_inventory_service、库存配置模型。
|
||||
依赖:Flask app/db、shipping_onhand_admin_service、库存配置模型。
|
||||
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
|
||||
"""
|
||||
|
||||
@@ -12,16 +12,16 @@ from cryptography.fernet import Fernet
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.services.admin import shipping_inventory_service
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
from app.services.admin import shipping_onhand_admin_service
|
||||
from app.services.shipping_notice import onhand_parsing_profile
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
ShippingInventoryStructureAnalysis,
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaSource,
|
||||
FreightRpaSourceParsingBindingAudit,
|
||||
FreightRpaOnhandStructureAnalysis,
|
||||
)
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict:
|
||||
|
||||
def _sample_evidence() -> int:
|
||||
"""创建最小表头证据,确保库存源服务测试不绕过解析方案样本门禁。"""
|
||||
item = ShippingInventoryStructureAnalysis(
|
||||
item = FreightRpaOnhandStructureAnalysis(
|
||||
source_kind='sample_upload', source_file_name='service-sample.xlsx', storage_path=None,
|
||||
file_checksum='b' * 64, file_format='xlsx', analysis_status='ready',
|
||||
structure_json={'candidates': [{
|
||||
@@ -88,13 +88,13 @@ def _parsing_profile() -> dict:
|
||||
)
|
||||
inventory_fields = {
|
||||
item.field_code: str(item.id)
|
||||
for item in ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
|
||||
ShippingInventoryField.status == 'active',
|
||||
for item in FreightRpaOnhandField.query.filter(
|
||||
FreightRpaOnhandField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
|
||||
FreightRpaOnhandField.status == 'active',
|
||||
).all()
|
||||
}
|
||||
assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'}
|
||||
draft = inventory_parsing_profile.save_draft({
|
||||
draft = onhand_parsing_profile.save_draft({
|
||||
'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx',
|
||||
'sample_analysis_id': _sample_evidence(),
|
||||
'definition': {
|
||||
@@ -110,7 +110,7 @@ def _parsing_profile() -> dict:
|
||||
}],
|
||||
},
|
||||
}, actor_id=None)
|
||||
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
|
||||
return onhand_parsing_profile.publish(draft['id'], actor_id=None)
|
||||
|
||||
|
||||
def _excel_template_id() -> int:
|
||||
@@ -133,17 +133,21 @@ def _excel_template_id() -> int:
|
||||
def _source_data(profile_id: int, *, parsing_profile_id: int | None = None, code: str = 'DBS_DUB', connector_type: str = 'dbs') -> dict:
|
||||
return {
|
||||
'source_code': code, 'display_name': code, 'connector_type': connector_type,
|
||||
'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'],
|
||||
'rpa_profile_id': profile_id,
|
||||
'excel_template_id': _excel_template_id(),
|
||||
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB',
|
||||
'snapshot_ttl_seconds': 3600, 'enabled': True,
|
||||
'report_path_json': {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
|
||||
# s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行,站点载荷不再平铺。
|
||||
'onhand_report_config': {
|
||||
'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'],
|
||||
'report_path_json': {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
|
||||
},
|
||||
'query_parameters_json': [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
|
||||
],
|
||||
},
|
||||
'query_parameters_json': [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -160,7 +164,7 @@ def test_profile_credentials_are_not_returned(app):
|
||||
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
payload = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
assert payload['password_configured'] is True
|
||||
assert payload['username_masked'] == 'configured'
|
||||
assert 'password' not in payload
|
||||
@@ -174,7 +178,7 @@ def test_profile_rejects_page_operation_configuration(app):
|
||||
payload = _profile_data()
|
||||
payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.save_profile(payload, actor_id=None)
|
||||
shipping_onhand_admin_service.save_profile(payload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_CONFIG_INVALID'
|
||||
|
||||
|
||||
@@ -182,10 +186,10 @@ def test_multiple_dbs_profiles_bind_independent_sources(app):
|
||||
"""同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
|
||||
second = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
|
||||
first_source = shipping_inventory_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None)
|
||||
second_source = shipping_inventory_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None)
|
||||
first = shipping_onhand_admin_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
|
||||
second = shipping_onhand_admin_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
|
||||
first_source = shipping_onhand_admin_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None)
|
||||
second_source = shipping_onhand_admin_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None)
|
||||
assert first_source['rpa_profile_id'] == first['id']
|
||||
assert second_source['rpa_profile_id'] == second['id']
|
||||
|
||||
@@ -194,34 +198,36 @@ def test_source_rejects_profile_connector_mismatch(app):
|
||||
"""库存源不能绑定不同 Driver 的 Profile。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH'
|
||||
shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH'
|
||||
|
||||
|
||||
def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
|
||||
"""禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
|
||||
login = shipping_onhand_admin_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
|
||||
payload = _source_data(login['id'], code='DRAFT_SOURCE')
|
||||
payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
|
||||
draft = shipping_inventory_service.save_source(payload, actor_id=None)
|
||||
payload.update({'enabled': False, 'excel_template_id': None})
|
||||
payload['onhand_report_config']['parsing_profile_id'] = None
|
||||
draft = shipping_onhand_admin_service.save_source(payload, actor_id=None)
|
||||
assert draft['enabled'] is False
|
||||
assert draft['parsing_profile_id'] is None
|
||||
assert draft['onhand_report_config']['parsing_profile_id'] is None
|
||||
assert draft['excel_template_id'] is None
|
||||
|
||||
payload.update({'enabled': True})
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id'])
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED'
|
||||
shipping_onhand_admin_service.save_source(payload, actor_id=None, source_id=draft['id'])
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'
|
||||
# 拒绝后回滚脏会话(等价于请求边界回滚):s18 服务在赋值后才触发启用门禁,
|
||||
# 不回滚会让后续查询的 autoflush 把 enabled=True + 空模板撞 CHECK。
|
||||
db.session.rollback()
|
||||
|
||||
payload.update({
|
||||
'parsing_profile_id': _parsing_profile()['id'],
|
||||
'excel_template_id': _excel_template_id(),
|
||||
})
|
||||
enabled = shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id'])
|
||||
payload['onhand_report_config']['parsing_profile_id'] = _parsing_profile()['id']
|
||||
payload['excel_template_id'] = _excel_template_id()
|
||||
enabled = shipping_onhand_admin_service.save_source(payload, actor_id=None, source_id=draft['id'])
|
||||
assert enabled['enabled'] is True
|
||||
|
||||
|
||||
@@ -229,22 +235,23 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
|
||||
"""普通保存只能保留停用站点;独立启用动作必须返回尚未完成的硬门槛。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
|
||||
login = shipping_onhand_admin_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
|
||||
payload = _source_data(login['id'], code='ACTIVATION_SOURCE')
|
||||
payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
|
||||
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
|
||||
payload.update({'enabled': False, 'excel_template_id': None})
|
||||
payload['onhand_report_config']['parsing_profile_id'] = None
|
||||
draft = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
|
||||
assert draft['activation']['ready'] is False
|
||||
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
|
||||
payload['enabled'] = True
|
||||
saved = shipping_inventory_service.save_source(
|
||||
saved = shipping_onhand_admin_service.save_source(
|
||||
payload, actor_id=None, source_id=draft['id'], allow_enable_transition=False,
|
||||
)
|
||||
assert saved['enabled'] is False
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
shipping_inventory_service.activate_source(draft['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
|
||||
shipping_onhand_admin_service.activate_source(draft['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED'
|
||||
assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
|
||||
|
||||
@@ -252,18 +259,23 @@ def test_activation_status_exposes_only_hard_gate_checks(app):
|
||||
"""启用门禁仅暴露连接/解析/发货模板硬门槛,不再包含测试导出或后续准备项。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
|
||||
login = shipping_onhand_admin_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
|
||||
payload = {
|
||||
'source_code': 'CHECKS_SOURCE', 'display_name': 'Checks Source', 'connector_type': 'dbs',
|
||||
'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None,
|
||||
'rpa_profile_id': login['id'], 'excel_template_id': None,
|
||||
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
|
||||
'report_path_json': {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inventory', 'report_name': 'On Hand',
|
||||
# s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行。
|
||||
'onhand_report_config': {
|
||||
'parsing_profile_id': None,
|
||||
'report_path_json': {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inventory', 'report_name': 'On Hand',
|
||||
},
|
||||
'query_parameters_json': [],
|
||||
},
|
||||
'query_parameters_json': [], 'enabled': False,
|
||||
'enabled': False,
|
||||
}
|
||||
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
|
||||
draft = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
|
||||
|
||||
checks = {item['code']: item for item in draft['activation']['checks']}
|
||||
|
||||
@@ -280,11 +292,11 @@ def test_enabled_source_rejects_disabled_rpa_profile(app):
|
||||
"""启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(
|
||||
profile = shipping_onhand_admin_service.save_profile(
|
||||
{**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None,
|
||||
)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None)
|
||||
shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLED'
|
||||
|
||||
|
||||
@@ -292,10 +304,11 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app):
|
||||
"""数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
assert source['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv'
|
||||
assert source['query_parameters_json'] == [
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
# s18 起报表路径/查询条件挂在响应的 onhand_report_config 嵌套对象上。
|
||||
assert source['onhand_report_config']['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv'
|
||||
assert source['onhand_report_config']['query_parameters_json'] == [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
|
||||
]
|
||||
|
||||
@@ -304,52 +317,54 @@ def test_source_rejects_driver_selector_in_business_parameters(app):
|
||||
"""业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
payload = _source_data(profile['id'])
|
||||
payload['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
|
||||
payload['onhand_report_config']['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.save_source(payload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
|
||||
shipping_onhand_admin_service.save_source(payload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID'
|
||||
|
||||
|
||||
def test_crane_source_rejects_dbs_report_path(app):
|
||||
"""动态仓 Crane 库存源不得误填 DBS 四级报表路径。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
|
||||
payload = _source_data(profile['id'], code='CRANE', connector_type='crane')
|
||||
payload['warehouse_resolution_mode'] = 'inventory_match'
|
||||
payload['fixed_warehouse_id'] = None
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.save_source(payload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
|
||||
shipping_onhand_admin_service.save_source(payload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID'
|
||||
|
||||
|
||||
def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app):
|
||||
"""停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
|
||||
login = shipping_onhand_admin_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
|
||||
payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE')
|
||||
payload.update({'enabled': False, 'parsing_profile_id': None})
|
||||
source = shipping_inventory_service.save_source(payload, actor_id=7, allow_enable_transition=False)
|
||||
payload.update({'enabled': False})
|
||||
payload['onhand_report_config']['parsing_profile_id'] = None
|
||||
source = shipping_onhand_admin_service.save_source(payload, actor_id=7, allow_enable_transition=False)
|
||||
profile = _parsing_profile()
|
||||
|
||||
bound = shipping_inventory_service.bind_source_parsing_profile(
|
||||
bound = shipping_onhand_admin_service.bind_source_parsing_profile(
|
||||
[source['id']], profile['id'], actor_id=7, operation='direct',
|
||||
)
|
||||
|
||||
# 关键断言:直接绑定只配置解析定义,绝不绕过独立启用门禁。
|
||||
assert bound[0]['enabled'] is False
|
||||
assert bound[0]['parsing_profile_id'] == profile['id']
|
||||
# s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。
|
||||
assert bound[0]['onhand_report_config']['parsing_profile_id'] == profile['id']
|
||||
assert bound[0]['config_version'] == source['config_version'] + 1
|
||||
audit = ShippingInventorySourceParsingBindingAudit.query.one()
|
||||
audit = FreightRpaSourceParsingBindingAudit.query.one()
|
||||
assert audit.operation == 'direct'
|
||||
# 关键断言:审计保留系统动作说明,不要求管理员额外填写“绑定原因”。
|
||||
assert audit.reason == '管理员直接绑定已发布解析方案'
|
||||
assert audit.before_snapshot_json['parsing_profile_id'] is None
|
||||
assert audit.after_snapshot_json['parsing_profile_id'] == profile['id']
|
||||
history = shipping_inventory_service.get_source_parsing_binding_audits(source['id'])
|
||||
history = shipping_onhand_admin_service.get_source_parsing_binding_audits(source['id'])
|
||||
assert history[0]['actor_id'] == 7
|
||||
assert history[0]['source_config_version_after'] == bound[0]['config_version']
|
||||
|
||||
@@ -358,33 +373,36 @@ def test_bulk_parsing_profile_binding_allows_enabled_sites(app):
|
||||
"""批量绑定允许包含已启用站点;全部预检通过后原子写入。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
|
||||
login = shipping_onhand_admin_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
|
||||
disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED')
|
||||
disabled_payload.update({'enabled': False, 'parsing_profile_id': None})
|
||||
disabled = shipping_inventory_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False)
|
||||
enabled = shipping_inventory_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None)
|
||||
disabled_payload.update({'enabled': False})
|
||||
disabled_payload['onhand_report_config']['parsing_profile_id'] = None
|
||||
disabled = shipping_onhand_admin_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False)
|
||||
enabled = shipping_onhand_admin_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None)
|
||||
profile = _parsing_profile()
|
||||
|
||||
bound = shipping_inventory_service.bind_source_parsing_profile(
|
||||
bound = shipping_onhand_admin_service.bind_source_parsing_profile(
|
||||
[disabled['id'], enabled['id']], profile['id'], actor_id=None,
|
||||
reason='批量迁移同类报表', operation='bulk',
|
||||
)
|
||||
|
||||
# 关键断言:已启用站点可直接换绑;两站同步写入且留下审计。
|
||||
assert {row['id'] for row in bound} == {disabled['id'], enabled['id']}
|
||||
assert all(row['parsing_profile_id'] == profile['id'] for row in bound)
|
||||
assert db.session.get(ShippingInventorySource, enabled['id']).enabled is True
|
||||
assert ShippingInventorySourceParsingBindingAudit.query.count() == 2
|
||||
# s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。
|
||||
assert all(row['onhand_report_config']['parsing_profile_id'] == profile['id'] for row in bound)
|
||||
assert db.session.get(FreightRpaSource, enabled['id']).enabled is True
|
||||
assert FreightRpaSourceParsingBindingAudit.query.count() == 2
|
||||
|
||||
|
||||
def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app):
|
||||
"""直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
|
||||
login = shipping_onhand_admin_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
|
||||
payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE')
|
||||
payload.update({'enabled': False, 'parsing_profile_id': None})
|
||||
source = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
|
||||
payload.update({'enabled': False})
|
||||
payload['onhand_report_config']['parsing_profile_id'] = None
|
||||
source = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
|
||||
template = db.session.get(ShippingExcelTemplate, source['excel_template_id'])
|
||||
template.definition_json = {
|
||||
'filename_pattern': '{business_no}.xlsx',
|
||||
@@ -393,50 +411,51 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.bind_source_parsing_profile(
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile(
|
||||
[source['id']], _parsing_profile()['id'], actor_id=None,
|
||||
reason='模板字段契约预检', operation='direct',
|
||||
)
|
||||
|
||||
# 关键断言:模板依赖缺失必须在绑定时拒绝,不能产生半成品站点绑定。
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID'
|
||||
assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None
|
||||
assert ShippingInventorySourceParsingBindingAudit.query.count() == 0
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID'
|
||||
# s18 起解析绑定归 onhand_report_config 配置行;被拒后配置行必须保持未绑定。
|
||||
assert db.session.get(FreightRpaSource, source['id']).onhand_report_config.parsing_profile_id is None
|
||||
assert FreightRpaSourceParsingBindingAudit.query.count() == 0
|
||||
|
||||
|
||||
def test_published_rule_cannot_be_mutated_in_place(app):
|
||||
"""发布规则必须依靠新版本演进,避免改写历史任务依据。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
|
||||
source = shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
|
||||
reservation_field_id = _published_route_field_id()
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
rule = shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Reservation starts with 1', 'scope': 'line',
|
||||
'priority': 100, 'match_mode': 'all', 'action_type': 'add_source_candidates',
|
||||
'action_payload_json': {'source_codes': [source['source_code']]}, 'version': 1,
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
}, actor_id=None)
|
||||
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
|
||||
shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None)
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
shipping_inventory_service.save_rule({
|
||||
shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Changed', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
}, actor_id=None, rule_id=rule['id'])
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_IMMUTABLE'
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_IMMUTABLE'
|
||||
|
||||
|
||||
def test_draft_rule_update_keeps_the_same_draft(app):
|
||||
"""草稿更新应原地替换条件,不能偷偷新增同版本规则记录。"""
|
||||
with app.app_context():
|
||||
reservation_field_id = _published_route_field_id()
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
rule = shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'Before', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'DUB'}],
|
||||
}, actor_id=None)
|
||||
updated = shipping_inventory_service.save_rule({
|
||||
updated = shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'After', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'FRA'}],
|
||||
@@ -450,7 +469,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
|
||||
"""列表、长度和空值操作符必须保存受控值类型,不能把配置错误拖到运行期。"""
|
||||
with app.app_context():
|
||||
reservation_field_id = _published_route_field_id()
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
rule = shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'RSV_IN', 'rule_name': 'Reservation list', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': ['1001', '1002']}],
|
||||
@@ -458,106 +477,107 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
|
||||
assert rule['conditions'][0]['expected_value_json'] == ['1001', '1002']
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.save_rule({
|
||||
shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'RSV_BAD_IN', 'rule_name': 'Invalid list', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': '1001'}],
|
||||
}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_CONDITION_INVALID'
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_CONDITION_INVALID'
|
||||
|
||||
|
||||
def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
|
||||
"""未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
|
||||
shipping_inventory_service.delete_profile(unused['id'])
|
||||
assert all(item['profile_code'] != 'UNUSED' for item in shipping_inventory_service.list_profiles())
|
||||
unused = shipping_onhand_admin_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
|
||||
shipping_onhand_admin_service.delete_profile(unused['id'])
|
||||
assert all(item['profile_code'] != 'UNUSED' for item in shipping_onhand_admin_service.list_profiles())
|
||||
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
shipping_inventory_service.delete_profile(profile['id'])
|
||||
shipping_onhand_admin_service.delete_profile(profile['id'])
|
||||
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DELETE_BLOCKED'
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
shipping_inventory_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id'])
|
||||
shipping_onhand_admin_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id'])
|
||||
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLE_BLOCKED'
|
||||
|
||||
reservation_field_id = _published_route_field_id()
|
||||
rule = shipping_inventory_service.save_rule({
|
||||
rule = shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'RETIRE_ME', 'rule_name': 'Retire me', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
}, actor_id=None)
|
||||
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
|
||||
retired = shipping_inventory_service.retire_rule(rule['id'], actor_id=None)
|
||||
shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None)
|
||||
retired = shipping_onhand_admin_service.retire_rule(rule['id'], actor_id=None)
|
||||
assert retired['status'] == 'retired'
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
shipping_inventory_service.delete_draft_rule(rule['id'])
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_DELETE_BLOCKED'
|
||||
shipping_onhand_admin_service.delete_draft_rule(rule['id'])
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_DELETE_BLOCKED'
|
||||
|
||||
|
||||
def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
|
||||
"""发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
|
||||
source = shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None)
|
||||
disabled_payload = _source_data(profile['id'], code='DISABLED_ROUTE_SOURCE')
|
||||
disabled_payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
|
||||
shipping_inventory_service.save_source(disabled_payload, actor_id=None)
|
||||
disabled_payload.update({'enabled': False, 'excel_template_id': None})
|
||||
disabled_payload['onhand_report_config']['parsing_profile_id'] = None
|
||||
shipping_onhand_admin_service.save_source(disabled_payload, actor_id=None)
|
||||
|
||||
reservation_field_id = _published_route_field_id()
|
||||
missing_rule = shipping_inventory_service.save_rule({
|
||||
missing_rule = shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'MISSING_SOURCE', 'rule_name': 'Missing source rule', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['MISSING_SOURCE']},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
|
||||
}, actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.publish_rule(missing_rule['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID'
|
||||
shipping_onhand_admin_service.publish_rule(missing_rule['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_SOURCE_INVALID'
|
||||
|
||||
disabled_rule = shipping_inventory_service.save_rule({
|
||||
disabled_rule = shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'DISABLED_SOURCE', 'rule_name': 'Disabled source rule', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DISABLED_ROUTE_SOURCE']},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '2'}],
|
||||
}, actor_id=None)
|
||||
assert shipping_inventory_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published'
|
||||
assert shipping_onhand_admin_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published'
|
||||
|
||||
valid_rule = shipping_inventory_service.save_rule({
|
||||
valid_rule = shipping_onhand_admin_service.save_rule({
|
||||
'rule_code': 'VALID_SOURCE', 'rule_name': 'Valid source rule', 'scope': 'line',
|
||||
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
|
||||
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '9'}],
|
||||
}, actor_id=None)
|
||||
assert shipping_inventory_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published'
|
||||
assert shipping_onhand_admin_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published'
|
||||
|
||||
|
||||
def test_active_default_external_mapping_is_unique_per_source(app):
|
||||
"""同一库存源同一货代仓库身份只能有一条启用的映射。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
payload = {
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
'external_organization_code': None, 'external_site_code': 'EU01',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
|
||||
'in_transit_warehouse_code': 'TZR2', 'enabled': True,
|
||||
}
|
||||
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
|
||||
shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None)
|
||||
with pytest.raises(ConflictError):
|
||||
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
|
||||
shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None)
|
||||
|
||||
|
||||
def test_external_mapping_allows_empty_freight_warehouse(app):
|
||||
"""货代仓库改为可选:空值保存为 NULL(空库位默认映射行),供 inventory_match 源兜底匹配。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
# [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。
|
||||
mapping = shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
|
||||
mapping = shipping_onhand_admin_service.save_external_mapping({
|
||||
'source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
|
||||
'in_transit_warehouse_code': 'tzr2', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
@@ -569,12 +589,12 @@ def test_external_mapping_requires_in_transit_warehouse_code(app):
|
||||
"""在途仓编码是在途调拨拨出库位来源——缺省必须在保存端拒绝(fail-closed 前置)。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
# [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。
|
||||
with pytest.raises(ValidationError):
|
||||
shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
shipping_onhand_admin_service.save_external_mapping({
|
||||
'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
|
||||
@@ -583,10 +603,10 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app):
|
||||
"""配置端小写货代仓应与收料文件仓库值(大写归一后)使用同一精确映射身份。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
mapping = shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub',
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
mapping = shipping_onhand_admin_service.save_external_mapping({
|
||||
'source_id': source['id'], 'freight_warehouse_id': 'dub',
|
||||
'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01',
|
||||
'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
@@ -597,32 +617,32 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
|
||||
"""连接级上传配置(upload_config_json)变更不递增 config_version。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
base_version = profile['config_version']
|
||||
upload_cfg = {
|
||||
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
|
||||
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
|
||||
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
|
||||
}
|
||||
updated = shipping_inventory_service.save_profile(
|
||||
updated = shipping_onhand_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
assert updated['config_version'] == base_version
|
||||
assert updated['upload_config_json']['enabled'] is True
|
||||
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
|
||||
bumped = shipping_inventory_service.save_profile(
|
||||
bumped = shipping_onhand_admin_service.save_profile(
|
||||
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
assert bumped['config_version'] == base_version + 1
|
||||
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
|
||||
with pytest.raises(ValidationError):
|
||||
shipping_inventory_service.save_profile(
|
||||
shipping_onhand_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
shipping_inventory_service.save_profile(
|
||||
shipping_onhand_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
@@ -1,9 +1,12 @@
|
||||
"""freight_rpa 包 import 边界适应度测试。
|
||||
|
||||
用途:锁死阶段 A 验收标准——freight_rpa 不寄生业务编排。
|
||||
用途:锁死阶段 B 验收标准——freight_rpa 不寄生业务编排。
|
||||
依赖:app/services/freight_rpa 包、ast。
|
||||
逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败;
|
||||
白名单是 RPA 归档/凭据所需的两块业务工具(阶段 B 收敛为零)。
|
||||
白名单为空集(批次 B Task 6 起审计写入已下沉本包
|
||||
common/report_audit,包内不再引用任何 shipping_notice 业务模块;
|
||||
历史 file_assets 白名单条目随迁移一并删除——包内只引用
|
||||
app.services.file_assets,不属 shipping_notice 命名空间)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,10 +15,9 @@ from pathlib import Path
|
||||
|
||||
PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa"
|
||||
|
||||
ALLOWED_SHIPPING_NOTICE = {
|
||||
"app.services.shipping_notice.audit_service",
|
||||
"app.services.shipping_notice.file_assets",
|
||||
}
|
||||
# 空集:freight_rpa 禁止 import 任何 app.services.shipping_notice.* 模块
|
||||
# (审计写入走本包 common/report_audit;模型 import 走 app.models,不在此列)。
|
||||
ALLOWED_SHIPPING_NOTICE: set[str] = set()
|
||||
|
||||
|
||||
def _imported_modules(path: Path) -> set[str]:
|
||||
@@ -28,7 +30,6 @@ def _imported_modules(path: Path) -> set[str]:
|
||||
mods.add(node.module)
|
||||
return mods
|
||||
|
||||
|
||||
def test_freight_rpa_import_boundary():
|
||||
assert PKG.exists(), "freight_rpa 包不存在"
|
||||
violations: list[str] = []
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"""tests/services/freight_rpa/test_report_fact_dispatch.py
|
||||
|
||||
用途:锁定阶段 B Task 6——inbound 回调「先提交文件/终态,再投递事实」的顺序契约。
|
||||
依赖:pytest、tests/conftest 的 app 夹具(种子站点 DSV360_AWSDU)、
|
||||
app.core.errors.AppError、app.services.freight_rpa.reports.facts.ReportFact、
|
||||
freight_rpa.reports.dispatch.register_report_handler(Task 6 新增)、
|
||||
freight_rpa.inbound.report_archive.ingest_inbound_callback。
|
||||
逻辑:(1)处理函数抛异常时已 commit 的归档文件行仍在(不回滚)且异常原样外抛;
|
||||
(2)同一 unit_run_id + sha256 重复回调不插第二行,事实仍重复投递 ok=True
|
||||
(供处理函数重试);(3)kind 未注册处理函数时 404
|
||||
FREIGHT_RPA.SINK_NOT_REGISTERED,已提交文件行不受影响;
|
||||
(4)empty 终态同样先 commit 再投递 ok=False 事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
|
||||
SEED_SOURCE_CODE = "DSV360_AWSDU"
|
||||
|
||||
# 归档 IO 替身的注入字节:_fake_archive_io 夹具把它喂给
|
||||
# _read_inbound_callback_file,_success_payload 按需覆写。
|
||||
_FAKE_FILE_BYTES: dict[str, bytes] = {"data": b"abc"}
|
||||
|
||||
# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。
|
||||
_CALLBACK_SEQ: dict[str, int] = {"n": 0}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(app):
|
||||
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
|
||||
from app import db
|
||||
|
||||
return db.session
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_report_handlers():
|
||||
"""每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。
|
||||
|
||||
[断言意图] 缺处理器用例必须跑在"干净注册表"上——否则前序用例注册的
|
||||
inbound 处理函数会让 404 用例假绿。
|
||||
"""
|
||||
from app.services.freight_rpa.reports import dispatch as dispatch_module
|
||||
|
||||
saved = dict(dispatch_module._REPORT_HANDLERS)
|
||||
dispatch_module._REPORT_HANDLERS.clear()
|
||||
yield
|
||||
dispatch_module._REPORT_HANDLERS.clear()
|
||||
dispatch_module._REPORT_HANDLERS.update(saved)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fake_archive_io(monkeypatch):
|
||||
"""替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。
|
||||
|
||||
核心逻辑:与旧回调测试同一 monkeypatch 姿态(patch report_archive 模块属性),
|
||||
使 ingest 的 success 分支可脱离真实文件系统与对象存储走完全程。
|
||||
"""
|
||||
from app.services.freight_rpa.inbound import report_archive
|
||||
|
||||
monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: _FAKE_FILE_BYTES["data"])
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
|
||||
def _next_callback_id(prefix: str) -> str:
|
||||
"""生成跨用例唯一的 callback_id(满足 unit run 唯一约束)。"""
|
||||
_CALLBACK_SEQ["n"] += 1
|
||||
return f"{prefix}-{_CALLBACK_SEQ['n']}"
|
||||
|
||||
|
||||
def _awaiting_unit(*, source_code: str = "DSV"):
|
||||
"""构造一个处于 awaiting_rpa 的 inbound 执行单元(挂种子站点满足外键)。
|
||||
|
||||
核心逻辑:source_code 列允许测试值(如 "DSV"),source_id 外键挂种子站点
|
||||
DSV360_AWSDU——与 test_report_queries.py 的 _inbound_file 同构。
|
||||
"""
|
||||
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
|
||||
|
||||
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
|
||||
return FreightRpaInboundUnitRun(
|
||||
source_id=source.id,
|
||||
source_code=source_code,
|
||||
connector_type="dbs",
|
||||
callback_id=_next_callback_id("report-fact-dispatch"),
|
||||
status="awaiting_rpa",
|
||||
config_snapshot_json={},
|
||||
)
|
||||
|
||||
|
||||
def _success_payload(unit, *, sha256_file: bytes = b"abc") -> dict:
|
||||
"""构造通过 schema 校验的 success 回调载荷;sha256_file 即被模拟读取的 xlsx 字节。"""
|
||||
_FAKE_FILE_BYTES["data"] = sha256_file
|
||||
return {
|
||||
"schema_version": "freight_rpa.inbound.v1",
|
||||
"callback_id": unit.callback_id,
|
||||
"status": "success",
|
||||
"file_path": f"receipt_{unit.id or 'x'}.xlsx",
|
||||
"original_filename": "receipt.xlsx",
|
||||
"sha256": hashlib.sha256(sha256_file).hexdigest(),
|
||||
}
|
||||
|
||||
|
||||
def test_handler_failure_keeps_committed_file(app, db_session, monkeypatch):
|
||||
"""处理函数失败绝不回滚已 commit 的归档文件行,异常原样外抛(不吞)。"""
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
|
||||
unit = _awaiting_unit(source_code="DSV")
|
||||
db_session.add(unit)
|
||||
db_session.commit()
|
||||
|
||||
def boom(fact: ReportFact) -> None:
|
||||
raise RuntimeError("handler down")
|
||||
|
||||
register_report_handler("inbound", boom)
|
||||
with pytest.raises(RuntimeError, match="handler down"):
|
||||
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
|
||||
# [断言意图] 异常外抛但文件行已提交:count==1 锁死「先 commit 再投递」顺序。
|
||||
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
|
||||
|
||||
|
||||
def test_second_delivery_does_not_insert_another_file(app, db_session):
|
||||
"""同一回调重放不插第二行文件,事实仍重复投递(同一 file_id、ok=True)。"""
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
register_report_handler("inbound", seen.append)
|
||||
unit = _awaiting_unit(source_code="DSV")
|
||||
db_session.add(unit)
|
||||
db_session.commit()
|
||||
payload = _success_payload(unit, sha256_file=b"abc")
|
||||
ingest_inbound_callback(payload)
|
||||
ingest_inbound_callback(payload)
|
||||
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
|
||||
# [断言意图] 幂等重放仍两次投递 ok=True 事实(同一 file_id),供处理函数重试。
|
||||
assert [fact.file_id for fact in seen] == [seen[0].file_id, seen[0].file_id]
|
||||
assert all(fact.ok is True for fact in seen)
|
||||
|
||||
|
||||
def test_missing_handler_raises_sink_not_registered(app, db_session):
|
||||
"""kind 未注册处理函数 → 404 FREIGHT_RPA.SINK_NOT_REGISTERED,文件行已提交。"""
|
||||
from app.core.errors import AppError
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
|
||||
unit = _awaiting_unit(source_code="DSV")
|
||||
db_session.add(unit)
|
||||
db_session.commit()
|
||||
with pytest.raises(AppError) as exc:
|
||||
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
|
||||
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
|
||||
# [断言意图] 分发失败不回滚归档:文件行保留,Worker 重试整笔回调即可补投递。
|
||||
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
|
||||
|
||||
|
||||
def test_empty_callback_dispatches_failure_fact(app, db_session):
|
||||
"""empty 终态同样先 commit 再投递 ok=False 事实(error_code 随载荷落库值)。"""
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
register_report_handler("inbound", seen.append)
|
||||
unit = _awaiting_unit(source_code="DSV")
|
||||
db_session.add(unit)
|
||||
db_session.commit()
|
||||
result = ingest_inbound_callback(
|
||||
{
|
||||
"schema_version": "freight_rpa.inbound.v1",
|
||||
"callback_id": unit.callback_id,
|
||||
"status": "empty",
|
||||
"error_code": "no_receipt_data",
|
||||
"error_message": "no_receipt_data",
|
||||
}
|
||||
)
|
||||
assert result["status"] == "empty"
|
||||
assert len(seen) == 1
|
||||
fact = seen[0]
|
||||
# [断言意图] empty 是合法业务结果 → ok=False + error_code=no_receipt_data 的事实。
|
||||
assert fact.report_kind == "inbound"
|
||||
assert fact.source_code == "DSV"
|
||||
assert fact.ok is False
|
||||
assert fact.file_id is None
|
||||
assert fact.sha256 is None
|
||||
assert fact.error_code == "no_receipt_data"
|
||||
assert fact.error_message == "no_receipt_data"
|
||||
@@ -0,0 +1,282 @@
|
||||
"""tests/services/freight_rpa/test_report_queries.py
|
||||
|
||||
用途:锁定阶段 B Task 3——freight_rpa.reports 只读查询模块的行为契约。
|
||||
依赖:pytest、app fixture(tests/conftest)、app.core.errors、
|
||||
app.services.freight_rpa.reports(待实现模块)。
|
||||
逻辑:覆盖(1)latest_usable_inbound_file 的可用门禁——未删除、当天
|
||||
(Asia/Shanghai 业务日)抓取、未过期、最新优先;(2)require_report_kind 的
|
||||
白名单校验;(3)站点/在手/入站配置只读视图;(4)按 storage_key 读文件
|
||||
字节 + 缺文件 NotFoundError;(5)解析失败三列的标记与清除(仅 flush
|
||||
不 commit)。(6)业务日窗口内外的定向拒收/放行。
|
||||
时间口径:查询的 now 参数显式传 naive UTC;文件 created_at 也按 naive UTC
|
||||
存入,两者用同一业务日窗口锚点(now=2026-10-05 12:00 UTC → 上海业务日
|
||||
10-05,UTC 窗口 [10-04 16:00, 10-05 16:00))。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.services.freight_rpa.reports import (
|
||||
clear_inbound_parse_failure,
|
||||
get_inbound_config,
|
||||
get_onhand_config,
|
||||
get_site,
|
||||
latest_usable_inbound_file,
|
||||
mark_inbound_parse_failure,
|
||||
read_inbound_file_bytes,
|
||||
require_report_kind,
|
||||
)
|
||||
|
||||
SEED_SOURCE_CODE = "DSV360_AWSDU"
|
||||
|
||||
# 业务日窗口锚点(naive UTC):2026-10-05 12:00 UTC = 上海 10-05 20:00,
|
||||
# 对应业务日 2026-10-05 的 UTC 存储窗口 [10-04 16:00, 10-05 16:00)。
|
||||
FROZEN_NOW = datetime(2026, 10, 5, 12, 0, 0)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(app):
|
||||
"""复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。"""
|
||||
from app import db
|
||||
|
||||
return db.session
|
||||
|
||||
|
||||
def _inbound_file(*, source_code: str, sha256: str, created_at: datetime, **overrides):
|
||||
"""构造一条挂在指定 source_code 执行单元下的入站归档文件(含 unit run)。
|
||||
|
||||
核心逻辑:外键要求文件必须挂在 FreightRpaInboundUnitRun 下,unit run 再挂
|
||||
种子站点(DSV360_AWSDU);source_code 写进 unit run 列(非外键,允许 "DSV"
|
||||
等测试值),便于验证查询按 unit run 的 source_code 过滤。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun, FreightRpaSource
|
||||
|
||||
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
source_id=source.id,
|
||||
source_code=source_code,
|
||||
connector_type="dbs",
|
||||
callback_id=f"test-callback:{source_code}:{sha256[:8]}",
|
||||
status="success",
|
||||
config_snapshot_json={},
|
||||
**overrides,
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
report_file = FreightRpaInboundReportFile(
|
||||
unit_run_id=unit.id,
|
||||
storage_provider="minio",
|
||||
storage_bucket="test",
|
||||
storage_key=f"freight_rpa/inbound/{source_code}/{sha256[:12]}.xlsx",
|
||||
original_filename=f"{sha256[:8]}.xlsx",
|
||||
file_size=16,
|
||||
sha256=sha256,
|
||||
created_at=created_at,
|
||||
)
|
||||
db.session.add(report_file)
|
||||
return report_file
|
||||
|
||||
|
||||
def test_latest_usable_inbound_file_returns_newest(app, db_session):
|
||||
"""同一业务日窗口内的两份可用文件 → 按 created_at 倒序取最新一份。
|
||||
|
||||
[断言意图] 两份文件的 created_at 均落在 FROZEN_NOW 的业务日 UTC 窗口
|
||||
([10-04 16:00, 10-05 16:00))内,证明「最新优先」在当天门禁内生效,
|
||||
而不是因为当天新鲜度被丢掉才命中。
|
||||
"""
|
||||
older = _inbound_file(source_code="DSV", sha256="a" * 64, created_at=datetime(2026, 10, 4, 18, 0, 0))
|
||||
newer = _inbound_file(source_code="DSV", sha256="b" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0))
|
||||
db_session.add_all([older, newer])
|
||||
db_session.commit()
|
||||
view = latest_usable_inbound_file("DSV", now=FROZEN_NOW)
|
||||
assert view is not None
|
||||
assert view.file_id == newer.id
|
||||
assert view.sha256 == "b" * 64
|
||||
|
||||
|
||||
def test_latest_usable_inbound_file_rejects_out_of_business_day(app, db_session):
|
||||
"""「当天(Asia/Shanghai 业务日)抓取」是可用门禁的一部分:隔日文件不可用。
|
||||
|
||||
[断言意图] 同一份文件(expries 为空、未删除)在非当天业务日查 → None;
|
||||
把判定时刻推回文件被抓取的那个业务日 → 又可用;差异只能来自当天窗口,
|
||||
锁死修复轮补回的新鲜度条件。
|
||||
"""
|
||||
report = _inbound_file(source_code="STL", sha256="0" * 64, created_at=datetime(2026, 10, 3, 10, 0, 0))
|
||||
db_session.commit()
|
||||
|
||||
# FROZEN_NOW(业务日 10-05)下,10-03 抓取的文件是隔日旧文件 → 不可用。
|
||||
assert latest_usable_inbound_file("STL", now=FROZEN_NOW) is None
|
||||
# 业务日 10-03 的窗口为 UTC [10-02 16:00, 10-03 16:00):10-03 10:00 UTC 在窗口内 → 可用。
|
||||
in_day_now = datetime(2026, 10, 3, 12, 0, 0)
|
||||
view = latest_usable_inbound_file("STL", now=in_day_now)
|
||||
assert view is not None
|
||||
assert view.file_id == report.id
|
||||
|
||||
|
||||
def test_latest_usable_inbound_file_skips_deleted_and_expired(app, db_session):
|
||||
"""已删除/已过期的文件不得被当作可用文件返回;同来源保留最新可用一份。"""
|
||||
# [断言意图] 三份文件都在 FROZEN_NOW 的业务日窗口内,且已删除/已过期两份
|
||||
# 更新——若门禁失效,“最新优先”会先命中它们;断言只能命中唯一的可用文件。
|
||||
usable = _inbound_file(source_code="CRN", sha256="c" * 64, created_at=datetime(2026, 10, 4, 20, 0, 0))
|
||||
deleted = _inbound_file(source_code="CRN", sha256="d" * 64, created_at=datetime(2026, 10, 5, 1, 0, 0))
|
||||
deleted.archive_deleted_at = datetime(2026, 10, 5, 5, 0, 0)
|
||||
expired = _inbound_file(source_code="CRN", sha256="e" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0))
|
||||
# 保留期早于判定时刻(仍未被清理任务删除)→ 过期不可用。
|
||||
expired.archive_expires_at = FROZEN_NOW - timedelta(hours=1)
|
||||
db_session.add_all([usable, deleted, expired])
|
||||
db_session.commit()
|
||||
|
||||
view = latest_usable_inbound_file("CRN", now=FROZEN_NOW)
|
||||
assert view is not None
|
||||
assert view.sha256 == "c" * 64
|
||||
assert view.source_code == "CRN"
|
||||
assert view.storage_key.endswith(f"{'c' * 12}.xlsx")
|
||||
assert view.original_filename == f"{'c' * 8}.xlsx"
|
||||
assert view.created_at == datetime(2026, 10, 4, 20, 0, 0)
|
||||
|
||||
|
||||
def test_latest_usable_inbound_file_no_match_returns_none(app, db_session):
|
||||
"""来源无任何归档文件(或全部不可用)时返回 None,不抛异常。"""
|
||||
assert latest_usable_inbound_file("NOPE") is None
|
||||
|
||||
|
||||
def test_report_kind_rejects_shipment():
|
||||
with pytest.raises(ValidationError):
|
||||
require_report_kind("shipment")
|
||||
assert require_report_kind("outbound") == "outbound"
|
||||
|
||||
|
||||
def test_get_site_returns_view_of_seeded_source(app):
|
||||
"""get_site 返回站点连接与模板绑定的只读视图;未知来源返回 None。"""
|
||||
view = get_site(SEED_SOURCE_CODE)
|
||||
assert view is not None
|
||||
assert view.source_code == SEED_SOURCE_CODE
|
||||
assert view.display_name == "DBS Dublin AWSDU"
|
||||
assert view.connector_type == "dbs"
|
||||
assert view.excel_template_id is not None
|
||||
assert view.enabled is True
|
||||
assert get_site("NOPE") is None
|
||||
|
||||
|
||||
def test_get_onhand_config_returns_report_definition(app):
|
||||
"""get_onhand_config 返回 s18 起挂在配置行上的报表路径/查询条件/解析方案。"""
|
||||
config = get_onhand_config(SEED_SOURCE_CODE)
|
||||
assert config is not None
|
||||
assert config.report_path_json.get("program_group") == "Bison"
|
||||
assert config.query_parameters_json == [
|
||||
{"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "required": True, "select_all": False},
|
||||
]
|
||||
assert config.parsing_profile_id is not None
|
||||
# [断言意图] 未知来源与存在但未配置报表的来源都必须返回 None(fail-closed)。
|
||||
assert get_onhand_config("NOPE") is None
|
||||
|
||||
|
||||
def test_get_inbound_config_returns_none_without_config_row(app):
|
||||
"""种子站点没有入站报表配置行 → get_inbound_config 返回 None。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaInboundReportConfig, FreightRpaSource
|
||||
|
||||
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
|
||||
assert get_inbound_config(SEED_SOURCE_CODE) is None
|
||||
# [断言意图] 补一条配置行后即可读出三个字段(与在手配置视图同构)。
|
||||
db.session.add(FreightRpaInboundReportConfig(
|
||||
source=source,
|
||||
report_path_json={"program_group": "Bison", "report_name": "Receipt"},
|
||||
query_parameters_json=[{"name": "Date", "mode": "range"}],
|
||||
parsing_profile_id=None,
|
||||
))
|
||||
db.session.commit()
|
||||
config = get_inbound_config(SEED_SOURCE_CODE)
|
||||
assert config is not None
|
||||
assert config.report_path_json["report_name"] == "Receipt"
|
||||
assert config.query_parameters_json == [{"name": "Date", "mode": "range"}]
|
||||
assert config.parsing_profile_id is None
|
||||
|
||||
|
||||
def test_read_inbound_file_bytes_reads_by_storage_key(app, db_session, monkeypatch):
|
||||
"""read_inbound_file_bytes 按文件的 storage_key 调 file_asset_storage 读取。"""
|
||||
from app.services.freight_rpa.reports import queries as queries_module
|
||||
|
||||
report_file = _inbound_file(source_code="DSV", sha256="f" * 64, created_at=datetime(2026, 10, 6))
|
||||
db_session.commit()
|
||||
|
||||
captured: dict[str, bytes] = {}
|
||||
|
||||
def fake_get_bytes(storage_key):
|
||||
captured["key"] = storage_key
|
||||
return b"xlsx-bytes"
|
||||
|
||||
monkeypatch.setattr(queries_module.file_asset_storage, "get_bytes", fake_get_bytes)
|
||||
|
||||
assert read_inbound_file_bytes(report_file.id) == b"xlsx-bytes"
|
||||
assert captured["key"] == report_file.storage_key
|
||||
|
||||
|
||||
def test_read_inbound_file_bytes_missing_file_raises(app):
|
||||
"""文件 id 不存在 → NotFoundError(fail-closed,不吞 404)。"""
|
||||
with pytest.raises(NotFoundError):
|
||||
read_inbound_file_bytes(999999)
|
||||
|
||||
|
||||
def test_mark_and_clear_inbound_parse_failure_roundtrip(app, db_session):
|
||||
"""mark 写入三列并 flush(不 commit 由调用方决定);clear 清空恢复。"""
|
||||
from datetime import timedelta
|
||||
|
||||
report_file = _inbound_file(source_code="DSV", sha256="9" * 64, created_at=datetime(2026, 10, 7))
|
||||
db_session.commit()
|
||||
file_id = report_file.id
|
||||
|
||||
mark_inbound_parse_failure(
|
||||
file_id,
|
||||
error_code="X" * 80,
|
||||
error_message="m" * 2500,
|
||||
)
|
||||
# [断言意图] 只 flush 不 commit——新开的同一事务查询立即可见,且列宽截断生效。
|
||||
from app import db
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
|
||||
marked = db.session.get(FreightRpaInboundReportFile, file_id)
|
||||
assert marked.parse_failed_at is not None
|
||||
assert marked.parse_failed_at > datetime.utcnow() - timedelta(minutes=1)
|
||||
assert marked.parse_error_code == "X" * 64
|
||||
assert marked.parse_error_message == "m" * 2000
|
||||
db_session.commit()
|
||||
|
||||
clear_inbound_parse_failure(file_id)
|
||||
cleared = db.session.get(FreightRpaInboundReportFile, file_id)
|
||||
assert cleared.parse_failed_at is None
|
||||
assert cleared.parse_error_code is None
|
||||
assert cleared.parse_error_message is None
|
||||
db_session.commit()
|
||||
|
||||
|
||||
def test_mark_inbound_parse_failure_missing_file_raises(app):
|
||||
"""文件 id 不存在 → NotFoundError,与其他按 id 操作一致。"""
|
||||
with pytest.raises(NotFoundError):
|
||||
mark_inbound_parse_failure(999999, error_code="E", error_message="m")
|
||||
|
||||
|
||||
def test_import_boundary_no_business_module_imports():
|
||||
"""本模块(发货与调拨读报表唯一入口)不得 import shipping_notice / in_transit_transfer。"""
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
pkg = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa" / "reports"
|
||||
assert pkg.exists()
|
||||
for py in pkg.rglob("*.py"):
|
||||
tree = ast.parse(py.read_text(encoding="utf-8"))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
mods = [a.name for a in node.names]
|
||||
elif isinstance(node, ast.ImportFrom) and node.module:
|
||||
mods = [node.module]
|
||||
else:
|
||||
continue
|
||||
for mod in mods:
|
||||
assert not mod.startswith("app.services.shipping_notice"), f"{py.name}: {mod}"
|
||||
assert not mod.startswith("app.services.in_transit_transfer"), f"{py.name}: {mod}"
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/tests/services/freight_rpa/test_upload_trigger_contract.py
|
||||
|
||||
用途:锁死 upload trigger 写入契约——action 与心跳能力 freight_rpa_upload 对齐,schema 为 freight_rpa.upload.v1。
|
||||
依赖:app.services.freight_rpa.upload.trigger_io、Flask app fixture。
|
||||
逻辑:断言模块常量;write_upload_trigger 落盘后 JSON 的 action/schema_version 与常量一致。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.freight_rpa.common.worker_heartbeat import FREIGHT_RPA_UPLOAD_CAPABILITY
|
||||
from app.services.freight_rpa.upload import trigger_io
|
||||
|
||||
|
||||
def test_upload_trigger_constants_align_with_heartbeat_capability():
|
||||
"""upload action 必须与 Worker 心跳能力串 freight_rpa_upload 一致。"""
|
||||
assert trigger_io.SCHEMA == "freight_rpa.upload.v1"
|
||||
assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == "freight_rpa_upload"
|
||||
assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == FREIGHT_RPA_UPLOAD_CAPABILITY
|
||||
assert "outbound_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD
|
||||
assert "shipment_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD
|
||||
|
||||
|
||||
def test_write_upload_trigger_persists_freight_upload_action(app, tmp_path):
|
||||
"""落盘 trigger JSON 的 action/schema_version 须与模块常量一致。"""
|
||||
export_file = tmp_path / "queue_src" / "SN-001.xlsx"
|
||||
export_file.parent.mkdir(parents=True)
|
||||
export_file.write_bytes(b"fake-xlsx")
|
||||
|
||||
upload_queue = tmp_path / "upload_queue"
|
||||
upload_trigger = tmp_path / "upload_triggers"
|
||||
upload_queue.mkdir()
|
||||
upload_trigger.mkdir()
|
||||
|
||||
with app.app_context():
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
|
||||
queue_path, trigger_path, callback_id = trigger_io.write_upload_trigger(
|
||||
"TASK-UP-1",
|
||||
str(export_file),
|
||||
attempt_id=10,
|
||||
artifact_id=20,
|
||||
connector_type="dbs",
|
||||
callback_id="upload-cb-1",
|
||||
)
|
||||
|
||||
assert queue_path
|
||||
assert trigger_path
|
||||
assert callback_id == "upload-cb-1"
|
||||
|
||||
payload = json.loads(Path(trigger_path).read_text(encoding="utf-8"))
|
||||
# [断言意图] Worker 侧不校验 action 字面量,但双侧契约文档须与心跳能力 freight_rpa_upload 对齐。
|
||||
assert payload["action"] == trigger_io.ACTION_FREIGHT_RPA_UPLOAD
|
||||
assert payload["schema_version"] == trigger_io.SCHEMA
|
||||
assert payload["action"] == "freight_rpa_upload"
|
||||
assert payload["schema_version"] == "freight_rpa.upload.v1"
|
||||
@@ -15,7 +15,7 @@ import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
FREIGHT_UPLOAD_CAPABILITY,
|
||||
FREIGHT_RPA_UPLOAD_CAPABILITY,
|
||||
ONHAND_EXPORT_CAPABILITY,
|
||||
INBOUND_EXPORT_CAPABILITY,
|
||||
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
|
||||
@@ -306,7 +306,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
|
||||
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
@@ -337,7 +337,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
total, success, failed, skipped, _details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
|
||||
total, success, failed, skipped, _details, errors, logs = run_freight_rpa_onhand_schedule(task, run)
|
||||
assert total >= 1
|
||||
assert success == 0
|
||||
assert failed >= 1
|
||||
@@ -461,20 +461,20 @@ def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app,
|
||||
)
|
||||
)
|
||||
result = check_freight_upload_rpa_ready()
|
||||
# 关键断言:缺少 freight_upload 能力必须阻断自动上传。
|
||||
# 关键断言:缺少 freight_rpa_upload 能力必须阻断自动上传。
|
||||
assert result.ready is False
|
||||
assert any("missing_freight_upload_capability" in reason for reason in result.reasons)
|
||||
assert any("missing_freight_rpa_upload_capability" in reason for reason in result.reasons)
|
||||
|
||||
|
||||
def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
|
||||
"""Worker 声明 freight_upload 且目录/凭据齐全时应 ready。"""
|
||||
"""Worker 声明 freight_rpa_upload 且目录/凭据齐全时应 ready。"""
|
||||
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
_heartbeat_payload(
|
||||
trigger_dir=str(upload_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
|
||||
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_RPA_UPLOAD_CAPABILITY],
|
||||
)
|
||||
)
|
||||
result = check_freight_upload_rpa_ready()
|
||||
|
||||
@@ -129,8 +129,9 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
|
||||
"""建「启用来源 + 已发布 inbound 解析规则 + 收料配置绑定」全套种子(幂等)。
|
||||
|
||||
用途:清空并重新解析(spec §6)服务/端点用例的来源侧种子;来源自身
|
||||
parsing_profile(在手口径)按约束置最小占位行,真实重建规则挂
|
||||
ShippingReceiptReportConfig.parsing_profile_id(与运行期口径一致)。
|
||||
在手解析绑定(在手口径)按约束置最小占位配置行(s18 起归
|
||||
FreightRpaOnhandReportConfig),真实重建规则挂
|
||||
FreightRpaInboundReportConfig.parsing_profile_id(与运行期口径一致)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
@@ -140,29 +141,30 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
|
||||
sheet_name / header_row_index: definition_json 结构参数。
|
||||
status: 入站规则状态(缺省 published;用例可注入 draft 验证 abort)。
|
||||
Returns:
|
||||
(ShippingInventorySource, ShippingInventoryParsingProfile) 元组。
|
||||
(FreightRpaSource, FreightRpaParsingProfile) 元组。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingRpaProfile,
|
||||
ShippingReceiptReportConfig,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaSource,
|
||||
FreightRpaProfile,
|
||||
FreightRpaInboundReportConfig,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
|
||||
source = FreightRpaSource.query.filter_by(source_code=source_code).first()
|
||||
if source is not None:
|
||||
config = source.receipt_report_config
|
||||
config = source.inbound_report_config
|
||||
return source, (config.parsing_profile if config else None)
|
||||
|
||||
resolved_code = profile_code or f"MV_{source_code}"
|
||||
onhand = ShippingInventoryParsingProfile(
|
||||
onhand = FreightRpaParsingProfile(
|
||||
purpose="onhand", profile_code=f"ONHAND_{source_code}", display_name=source_code,
|
||||
version=1, status="published", file_format="xlsx",
|
||||
definition_json={}, structure_definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
purpose="inbound", profile_code=resolved_code, display_name=resolved_code,
|
||||
version=version, status=status, file_format="xlsx",
|
||||
definition_json={
|
||||
@@ -172,7 +174,7 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
|
||||
},
|
||||
structure_definition_json={},
|
||||
)
|
||||
rpa = ShippingRpaProfile(
|
||||
rpa = FreightRpaProfile(
|
||||
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="dbs",
|
||||
login_url="https://test.invalid/dbs", login_config_json={"auth_mode": "password"},
|
||||
)
|
||||
@@ -182,15 +184,20 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None =
|
||||
storage_key=f"test/{source_code}/template.xlsx", original_filename="template.xlsx",
|
||||
file_checksum="0" * 64, definition_json={}, definition_checksum="0" * 64,
|
||||
)
|
||||
source = ShippingInventorySource(
|
||||
source = FreightRpaSource(
|
||||
source_code=source_code, display_name=source_code, connector_type="dbs",
|
||||
rpa_profile=rpa, parsing_profile=onhand, excel_template=template,
|
||||
rpa_profile=rpa, excel_template=template,
|
||||
warehouse_resolution_mode="fixed", fixed_warehouse_id="AWSDU", enabled=True,
|
||||
)
|
||||
db.session.add_all([onhand, profile, rpa, template, source])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, parsing_profile_id=profile.id))
|
||||
# s18 起在手解析方案绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载。
|
||||
db.session.add(FreightRpaOnhandReportConfig(
|
||||
source_id=source.id, parsing_profile_id=onhand.id,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
db.session.add(FreightRpaInboundReportConfig(
|
||||
source_id=source.id, parsing_profile_id=profile.id))
|
||||
db.session.commit()
|
||||
return source, profile
|
||||
|
||||
@@ -213,20 +220,20 @@ def seed_reparse_archive_file(source, *, sha: str, storage_key: str, created_at:
|
||||
archive_deleted_at: 清理时间;None=未清理。
|
||||
callback_id: 收料执行单元回调键(缺省按 sha 派生保证唯一)。
|
||||
Returns:
|
||||
已入库的 ShippingReceiptReportFile。
|
||||
已入库的 FreightRpaInboundReportFile。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun
|
||||
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=source.id, source_code=source.source_code,
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type,
|
||||
callback_id=callback_id or f"cb-{sha[:12]}",
|
||||
status="success", config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
report = ShippingReceiptReportFile(
|
||||
report = FreightRpaInboundReportFile(
|
||||
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
|
||||
storage_key=storage_key, original_filename=f"{callback_id or 'cb'}.xlsx",
|
||||
file_size=16, sha256=sha, created_at=created_at,
|
||||
|
||||
@@ -57,24 +57,24 @@ def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str):
|
||||
sha: 归档文件 sha256(与 Fake 仓库 checksum 保持同值,模拟同一份文件)。
|
||||
callback_id: 收料执行单元回调键(唯一约束,用例间取不同值)。
|
||||
Returns:
|
||||
已入库的 ShippingReceiptReportFile。
|
||||
已入库的 FreightRpaInboundReportFile。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventorySource,
|
||||
ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
FreightRpaSource,
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code="DSV360_AWSDU").one()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=source.id, source_code=source_code,
|
||||
source = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
source_id=source.id, source_code=source_code,
|
||||
connector_type="dbs", callback_id=callback_id,
|
||||
status="success", config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
report = ShippingReceiptReportFile(
|
||||
report = FreightRpaInboundReportFile(
|
||||
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
|
||||
storage_key=f"shipping/receipt/{callback_id}.xlsx",
|
||||
original_filename=f"{callback_id}.xlsx", file_size=16, sha256=sha,
|
||||
@@ -262,7 +262,7 @@ def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m
|
||||
# 独立 commit 落到当前可用文件(parse_failed 三列),来源投影转 parse_failed;
|
||||
# 同步数据已回滚(桥隔离保持)。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.services.in_transit_transfer import evidence_sync
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
@@ -282,7 +282,7 @@ def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m
|
||||
assert ok is False # [断言意图] 同步失败被吞(桥隔离)
|
||||
assert TransferMovementLedger.query.count() == 0 # [断言意图] 坏行未落档(同步数据已回滚)
|
||||
db.session.expire_all() # 标记经桥内独立 commit:失效缓存重读
|
||||
row = db.session.query(ShippingReceiptReportFile).filter_by(id=report.id).one()
|
||||
row = db.session.query(FreightRpaInboundReportFile).filter_by(id=report.id).one()
|
||||
assert row.parse_failed_at is not None # [断言意图] 失败事实已落库
|
||||
assert row.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
assert row.parse_error_message
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
"""tests/services/in_transit_transfer/test_inbound_report_handler.py
|
||||
|
||||
用途:阶段 B Task 7——inbound 报表事实处理函数(handle_inbound_report)的契约测试:
|
||||
未注册不推进、处理函数先失败后成功只推进一次且文件只留一行、无等待任务时回调成功、
|
||||
同来源两单元分属两排程 run 时收口只打「本次回调收尾的单元」的 run(修复轮)。
|
||||
依赖:app(SQLite)fixture、freight_rpa.reports.dispatch(注册表)、
|
||||
freight_rpa.inbound.report_archive.ingest_inbound_callback(归档+投递入口)、
|
||||
in_transit_transfer.inbound_callback_bridge / TransferSourceJob(调拨侧事实)。
|
||||
逻辑:复刻 test_report_fact_dispatch 的注册表隔离与归档 IO 替身——组合根
|
||||
(create_app→register_inbound_sinks)启动即注册 handle_inbound_report,
|
||||
未注册用例必须先清空注册表,否则 404 断言假绿;success 归档走替身 IO
|
||||
(drop 根读取返回注入字节、MinIO 上传 no-op),不依赖真实文件系统;
|
||||
收口定位用例构造两个 awaiting 排程 run(各挂一个同来源单元),
|
||||
对旧单元回调后断言只有旧 run 被收口、新 run 保持等待。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(app):
|
||||
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
|
||||
from app import db
|
||||
|
||||
return db.session
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_report_handlers():
|
||||
"""每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。
|
||||
|
||||
[断言意图] 未注册用例必须跑在"干净注册表"上——组合根启动已注册
|
||||
handle_inbound_report,不清空会让 FREIGHT_RPA.SINK_NOT_REGISTERED 断言假绿。
|
||||
"""
|
||||
from app.services.freight_rpa.reports import dispatch as dispatch_module
|
||||
|
||||
saved = dict(dispatch_module._REPORT_HANDLERS)
|
||||
dispatch_module._REPORT_HANDLERS.clear()
|
||||
yield
|
||||
dispatch_module._REPORT_HANDLERS.clear()
|
||||
dispatch_module._REPORT_HANDLERS.update(saved)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fake_archive_io(monkeypatch):
|
||||
"""替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。
|
||||
|
||||
核心逻辑:与 test_report_fact_dispatch 同一 monkeypatch 姿态(patch
|
||||
report_archive 模块属性),使 success 归档分支脱离真实文件系统与对象存储。
|
||||
"""
|
||||
from app.services.freight_rpa.inbound import report_archive
|
||||
|
||||
monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: b"handler-bytes")
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
|
||||
# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。
|
||||
_CALLBACK_SEQ: dict[str, int] = {"n": 0}
|
||||
|
||||
|
||||
def _next_callback_id() -> str:
|
||||
"""生成跨用例唯一的 callback_id(unit run 唯一约束)。"""
|
||||
_CALLBACK_SEQ["n"] += 1
|
||||
return f"inbound-handler-{_CALLBACK_SEQ['n']}"
|
||||
|
||||
|
||||
def _waiting_job(source_code: str):
|
||||
"""构造一个未落库的 waiting_rpa_callback 来源任务(先建 TransferRun 满足外键)。
|
||||
|
||||
核心逻辑:TransferRun 只 add+flush(拿 run_id);TransferSourceJob 由调用方
|
||||
add+commit——与用例体里的 db_session.add(job) 契约一致。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import TransferRun, TransferSourceJob
|
||||
|
||||
run = TransferRun(
|
||||
run_no=f"RUN-HANDLER-{_next_callback_id()}",
|
||||
business_date="2026-09-17",
|
||||
status="preparing_files",
|
||||
trigger_type="manual",
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
return TransferSourceJob(run_id=run.id, source_code=source_code, status="waiting_rpa_callback")
|
||||
|
||||
|
||||
def _success_payload_for(source_code: str) -> dict:
|
||||
"""构造一个挂种子站点的 awaiting 单元及其 success 回调载荷(可通过 schema 校验)。
|
||||
|
||||
核心逻辑:source_code 列允许测试值(如 "DSV",与调拨任务匹配),source_id
|
||||
外键挂 conftest 种子站点 DSV360_AWSDU;替身 IO 注入字节与 sha256 对齐。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
|
||||
|
||||
anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
source_id=anchor.id,
|
||||
source_code=source_code,
|
||||
connector_type="dbs",
|
||||
callback_id=_next_callback_id(),
|
||||
status="awaiting_rpa",
|
||||
config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.commit()
|
||||
data = b"handler-bytes"
|
||||
return {
|
||||
"schema_version": "freight_rpa.inbound.v1",
|
||||
"callback_id": unit.callback_id,
|
||||
"status": "success",
|
||||
"file_path": f"receipt_{unit.id}.xlsx",
|
||||
"original_filename": "receipt.xlsx",
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
}
|
||||
|
||||
|
||||
def test_unregistered_transfer_handler_leaves_job_waiting(app, db_session):
|
||||
"""未注册处理函数:归档 404 后调拨任务必须原地保持 waiting_rpa_callback。"""
|
||||
from app.core.errors import AppError
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
|
||||
job = _waiting_job(source_code="DSV")
|
||||
db_session.add(job)
|
||||
db_session.commit()
|
||||
# 不注册 handle_inbound_report
|
||||
with pytest.raises(AppError) as exc:
|
||||
ingest_inbound_callback(_success_payload_for("DSV"))
|
||||
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
|
||||
db_session.refresh(job)
|
||||
assert job.status == "waiting_rpa_callback"
|
||||
|
||||
|
||||
def test_handler_fail_then_success_advances_once(app, db_session, monkeypatch):
|
||||
"""处理函数先失败后成功:文件只留一行,调拨任务只推进一次到 file_ready。"""
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
|
||||
|
||||
job = _waiting_job(source_code="DSV")
|
||||
db_session.add(job)
|
||||
db_session.commit()
|
||||
calls = {"n": 0}
|
||||
|
||||
def flaky(fact: ReportFact) -> None:
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 1:
|
||||
raise RuntimeError("once")
|
||||
handle_inbound_report(fact)
|
||||
|
||||
register_report_handler("inbound", flaky)
|
||||
payload = _success_payload_for("DSV")
|
||||
with pytest.raises(RuntimeError):
|
||||
ingest_inbound_callback(payload)
|
||||
ingest_inbound_callback(payload)
|
||||
db_session.refresh(job)
|
||||
assert job.status == "file_ready"
|
||||
assert FreightRpaInboundReportFile.query.count() == 1
|
||||
|
||||
|
||||
def test_no_waiting_job_is_success(app, db_session):
|
||||
"""无等待中的调拨任务:处理函数照常成功返回,且不产生任何调拨来源任务行。"""
|
||||
from app.models import TransferSourceJob
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
|
||||
|
||||
register_report_handler("inbound", handle_inbound_report)
|
||||
ingest_inbound_callback(_success_payload_for("DSV"))
|
||||
assert TransferSourceJob.query.filter_by(source_code="DSV").count() == 0
|
||||
|
||||
|
||||
def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaiting: bool = True):
|
||||
"""构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_receipt_rpa 等待态。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
task = ScheduleTask(
|
||||
schedule_no=schedule_no, name=f'Receipt {schedule_no}', schedule_type='platform_job',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
)
|
||||
db_session.add(task)
|
||||
db_session.flush()
|
||||
run = ScheduleRun(
|
||||
run_no=run_no, schedule_task_id=task.id, status='running', total_count=1,
|
||||
success_count=0, failed_count=0, skipped_count=0,
|
||||
response_summary_json={'awaiting_receipt_rpa': awaiting},
|
||||
)
|
||||
db_session.add(run)
|
||||
db_session.commit()
|
||||
return run
|
||||
|
||||
|
||||
def _unit_on_run(db_session, run, *, callback_id: str):
|
||||
"""在指定排程 run 下造一个挂种子站点的 awaiting 收料单元(source_code=DSV)。"""
|
||||
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
|
||||
|
||||
anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
schedule_run_id=run.id, source_id=anchor.id, source_code="DSV",
|
||||
connector_type="dbs", callback_id=callback_id,
|
||||
status="awaiting_rpa", config_snapshot_json={},
|
||||
)
|
||||
db_session.add(unit)
|
||||
db_session.commit()
|
||||
return unit
|
||||
|
||||
|
||||
def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch):
|
||||
"""同来源两个单元分属两个排程 run:本回调收尾的单元(按文件反查)只收口它自己的 run。
|
||||
|
||||
[断言意图] 修复「按来源取最新单元」的错位:旧逻辑会把收口打到更新单元的 run,
|
||||
本回调刚完成的 run 永久滞留 awaiting_receipt_rpa。
|
||||
"""
|
||||
from app.models import ScheduleRun
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file",
|
||||
lambda _path: b"handler-bytes",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
register_report_handler("inbound", handle_inbound_report)
|
||||
|
||||
run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-OLD", run_no="RUN-ONHAND-OLD")
|
||||
run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-NEW", run_no="RUN-ONHAND-NEW")
|
||||
unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-old")
|
||||
_unit_on_run(db_session, run_new, callback_id="inbound-handler-new")
|
||||
|
||||
ingest_inbound_callback({
|
||||
"schema_version": "freight_rpa.inbound.v1",
|
||||
"callback_id": unit_old.callback_id,
|
||||
"status": "success",
|
||||
"file_path": "receipt_old.xlsx",
|
||||
"original_filename": "receipt.xlsx",
|
||||
"sha256": hashlib.sha256(b"handler-bytes").hexdigest(),
|
||||
})
|
||||
|
||||
db_session.rollback()
|
||||
db_session.expire_all()
|
||||
# [断言意图] 本回调收尾的是旧单元:只有旧 run 被收口(全终态 → success)。
|
||||
refreshed_old = db_session.get(ScheduleRun, run_old.id)
|
||||
assert refreshed_old.status == "success"
|
||||
assert not (refreshed_old.response_summary_json or {}).get("awaiting_receipt_rpa")
|
||||
# 新单元的 run 原样保持等待态——未被本次回调误收口。
|
||||
refreshed_new = db_session.get(ScheduleRun, run_new.id)
|
||||
assert refreshed_new.status == "running"
|
||||
assert (refreshed_new.response_summary_json or {}).get("awaiting_receipt_rpa") is True
|
||||
|
||||
|
||||
def test_finalize_targets_failed_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch):
|
||||
"""同来源两单元、同失败错误文本、分属两 run:失败回调只收口本单元(unit_run_id)的 run。
|
||||
|
||||
[断言意图] 修复「按来源+终态+错误文本取最新单元」的错位:错误文本碰撞时旧回调
|
||||
会收口新单元的 run,本回调刚失败的 run 永久滞留 awaiting_receipt_rpa。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import ScheduleRun, FreightRpaInboundUnitRun
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file",
|
||||
lambda _path: b"handler-bytes",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
register_report_handler("inbound", handle_inbound_report)
|
||||
|
||||
run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-OLD", run_no="RUN-FAIL-OLD")
|
||||
run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-NEW", run_no="RUN-FAIL-NEW")
|
||||
unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-fail-old")
|
||||
unit_new = _unit_on_run(db_session, run_new, callback_id="inbound-handler-fail-new")
|
||||
# [RED 场景] 新单元已先以同错误文本终态失败落库——旧逻辑按 (来源, 终态, 错误文本)
|
||||
# 取最新单元会命中新单元,把收口打到新 run。
|
||||
unit_new.status = "failed"
|
||||
unit_new.error_code = "RPA_TEST_FAIL"
|
||||
unit_new.error_message = "boom"
|
||||
unit_new.finished_at = datetime.utcnow()
|
||||
db_session.commit()
|
||||
|
||||
result = ingest_inbound_callback({
|
||||
"schema_version": "freight_rpa.inbound.v1",
|
||||
"callback_id": unit_old.callback_id,
|
||||
"status": "failed",
|
||||
"error_code": "RPA_TEST_FAIL",
|
||||
"error_message": "boom",
|
||||
})
|
||||
assert result["status"] == "failed"
|
||||
|
||||
db_session.rollback()
|
||||
db_session.expire_all()
|
||||
# [断言意图] 只有旧单元的 run 被收口(唯一单元终态失败 → failed、awaiting 清除)。
|
||||
refreshed_old = db_session.get(ScheduleRun, run_old.id)
|
||||
assert refreshed_old.status == "failed"
|
||||
assert not (refreshed_old.response_summary_json or {}).get("awaiting_receipt_rpa")
|
||||
refreshed_saved_old = db_session.get(FreightRpaInboundUnitRun, unit_old.id)
|
||||
assert refreshed_saved_old.status == "failed"
|
||||
assert refreshed_saved_old.error_code == "RPA_TEST_FAIL"
|
||||
# 新单元的 run 原样保持等待态——未被本次回调误收口(新单元自身终态由其回调收口)。
|
||||
refreshed_new = db_session.get(ScheduleRun, run_new.id)
|
||||
assert refreshed_new.status == "running"
|
||||
assert (refreshed_new.response_summary_json or {}).get("awaiting_receipt_rpa") is True
|
||||
@@ -0,0 +1,36 @@
|
||||
"""tests/services/in_transit_transfer/test_inbound_report_read_boundary.py
|
||||
|
||||
用途:锁定阶段 B Task 4——in_transit_transfer 包不得引用 freight_rpa 报表模型
|
||||
(站点与报表文件/配置的读取一律改走 app.services.freight_rpa.reports
|
||||
只读入口,业务方只按 source_code / file_id 消费)。
|
||||
依赖:pathlib(纯文本扫描;无 app/DB fixture,秒级运行)。
|
||||
逻辑:对包内全部 .py 逐文件做 banned 字符串扫描(含注释/docstring——模型名
|
||||
出现在任何位置都算引用面),命中即 fail 并按「文件名: 模型名」逐条列出,
|
||||
防止调拨域绕过只读入口直接 import 报表模型造成域间漂移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_in_transit_does_not_import_rpa_report_models():
|
||||
"""in_transit_transfer 包内任何 .py 不得出现 freight_rpa 报表模型名。
|
||||
|
||||
banned 集合与计划 Task 4 冻结一致:入站归档文件、入站报表配置、库存站点、
|
||||
在手报表配置四类模型自本任务起归 freight_rpa 域读写;调拨域(含注释与
|
||||
docstring)不得再引用其类名——命中即边界破坏,须收敛到
|
||||
freight_rpa.reports.queries 的只读函数。
|
||||
"""
|
||||
root = Path(__file__).resolve().parents[3] / "app" / "services" / "in_transit_transfer"
|
||||
banned = ("FreightRpaInboundReportFile", "FreightRpaInboundReportConfig",
|
||||
"FreightRpaSource", "FreightRpaOnhandReportConfig")
|
||||
hits = []
|
||||
for path in root.rglob("*.py"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
for name in banned:
|
||||
if name in text:
|
||||
hits.append(f"{path.name}: {name}")
|
||||
# [断言意图] hits 必须为空:任一命中都意味着调拨域仍在直接引用
|
||||
# freight_rpa 报表模型(import、类型标注或文档残句),边界未闭合。
|
||||
assert hits == []
|
||||
@@ -1,10 +1,10 @@
|
||||
"""真实收料 RPA 触发服务测试。
|
||||
|
||||
用途:验证 trigger_inbound_rpa / trigger_inbound_rpa_batch 按来源装配收料 trigger unit
|
||||
并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||
并调用写者;触发先落 FreightRpaInboundUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
|
||||
依赖:app(SQLite)fixture、inbound_trigger_service.trigger_inbound_rpa(_batch)、
|
||||
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
|
||||
既有测试种子(FreightRpaProfile/FreightRpaSource)。
|
||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False;
|
||||
批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批,
|
||||
parse_failed 先本地重解析不触发 RPA)。
|
||||
@@ -14,7 +14,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import (
|
||||
trigger_inbound_rpa,
|
||||
trigger_inbound_rpa_batch,
|
||||
@@ -24,10 +24,10 @@ from app.services.in_transit_transfer.inbound_trigger_service import (
|
||||
@pytest.fixture
|
||||
def receipt_source():
|
||||
"""复用种子来源并为其创建收料配置。"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
assert source is not None
|
||||
config = ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id,
|
||||
config = FreightRpaInboundReportConfig(
|
||||
source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
|
||||
)
|
||||
@@ -67,7 +67,7 @@ def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source):
|
||||
|
||||
def test_trigger_inbound_rpa_disabled_source_fails_closed(app):
|
||||
"""来源停用 → ok=False,不写 trigger。"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
source.enabled = False
|
||||
from app import db
|
||||
|
||||
@@ -84,9 +84,9 @@ def test_trigger_inbound_rpa_missing_config_fails_closed(app):
|
||||
|
||||
|
||||
def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
|
||||
"""触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
|
||||
"""触发必须先落 FreightRpaInboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
@@ -101,22 +101,22 @@ def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receip
|
||||
reason="transfer_retry_inbound", writer=fake_writer,
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
|
||||
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
|
||||
assert unit.status == "awaiting_rpa"
|
||||
# [断言意图] 按需触发无排程 run,schedule_run_id 必须为 NULL——
|
||||
# PostgreSQL 上 FK 禁止 0 占位(SQLite 测试库不强制 FK,需显式守住列可空契约)。
|
||||
assert unit.schedule_run_id is None
|
||||
assert ShippingReceiptRpaUnitRun.__table__.columns['schedule_run_id'].nullable is True
|
||||
assert FreightRpaInboundUnitRun.__table__.columns['schedule_run_id'].nullable is True
|
||||
assert captured["units"][0]["unit_run_id"] == unit.id
|
||||
assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id
|
||||
|
||||
|
||||
def _bind_published_inbound_profile(config: ShippingReceiptReportConfig) -> None:
|
||||
def _bind_published_inbound_profile(config: FreightRpaInboundReportConfig) -> None:
|
||||
"""给收料配置绑定一条已发布 inbound 规则(仅满足守卫校验,不参与解析)。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
from app.models import FreightRpaParsingProfile
|
||||
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
purpose='inbound', profile_code='MOVE_TRIGGER_STD', display_name='入站解析规则',
|
||||
version=1, status='published', file_format='xlsx',
|
||||
definition_json={'sheet_name': None, 'header_row_index': 1,
|
||||
@@ -135,8 +135,8 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
with app.app_context():
|
||||
config = ShippingReceiptReportConfig.query.filter_by(
|
||||
inventory_source_id=receipt_source.id).one()
|
||||
config = FreightRpaInboundReportConfig.query.filter_by(
|
||||
source_id=receipt_source.id).one()
|
||||
_bind_published_inbound_profile(config)
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
|
||||
@@ -165,15 +165,15 @@ def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_
|
||||
|
||||
def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
|
||||
outcome = trigger_inbound_rpa(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17",
|
||||
reason="transfer_retry_inbound", writer=lambda *a, **k: None,
|
||||
)
|
||||
assert outcome["ok"] is False
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
|
||||
ShippingReceiptRpaUnitRun.id.desc()).first()
|
||||
unit = FreightRpaInboundUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
|
||||
FreightRpaInboundUnitRun.id.desc()).first()
|
||||
assert unit.status == "failed"
|
||||
assert unit.error_code == "RPA_INBOUND_TRIGGER_UNAVAILABLE"
|
||||
|
||||
@@ -185,28 +185,35 @@ def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, rec
|
||||
|
||||
@pytest.fixture
|
||||
def second_receipt_source(app):
|
||||
"""再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定
|
||||
解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。"""
|
||||
"""再造一个启用来源 + 收料配置(批量用例需要多来源);s18 起启用态要求
|
||||
Excel 模板绑定(ck_freight_rpa_sources_enabled_template),解析绑定复用种子源配置行。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig
|
||||
from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaInboundReportConfig
|
||||
|
||||
seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
profile = ShippingRpaProfile(
|
||||
seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
profile = FreightRpaProfile(
|
||||
profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs',
|
||||
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
source = ShippingInventorySource(
|
||||
source = FreightRpaSource(
|
||||
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
|
||||
rpa_profile=profile,
|
||||
parsing_profile=seed.parsing_profile, excel_template=seed.excel_template,
|
||||
excel_template=seed.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
enabled=True,
|
||||
)
|
||||
# s18 起在手解析绑定/报表路径归配置行,复用种子源绑定形态。
|
||||
seed_config = seed.onhand_report_config
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=source,
|
||||
parsing_profile=seed_config.parsing_profile if seed_config is not None else None,
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
query_parameters_json=[],
|
||||
)
|
||||
db.session.add_all([profile, source])
|
||||
db.session.flush() # 先取 source.id(新建对象 flush 前无主键)
|
||||
config = ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id,
|
||||
config = FreightRpaInboundReportConfig(
|
||||
source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
query_parameters_json=[],
|
||||
)
|
||||
@@ -217,7 +224,7 @@ def second_receipt_source(app):
|
||||
|
||||
def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
|
||||
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
|
||||
calls: list = []
|
||||
|
||||
@@ -238,7 +245,7 @@ def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt
|
||||
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
|
||||
callback_ids = {u['callback_id'] for u in calls[0]['units']}
|
||||
assert len(callback_ids) == 2
|
||||
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
|
||||
rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_(
|
||||
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
|
||||
assert {row.status for row in rows} == {'awaiting_rpa'}
|
||||
assert all(row.schedule_run_id is None for row in rows)
|
||||
@@ -278,7 +285,7 @@ def test_trigger_inbound_rpa_batch_all_invalid_no_trigger(app):
|
||||
|
||||
def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
|
||||
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
|
||||
outcome = trigger_inbound_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
|
||||
@@ -286,7 +293,7 @@ def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, rece
|
||||
)
|
||||
assert outcome['ok'] is False and outcome['triggered'] is False
|
||||
assert outcome['error_code'] == 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
|
||||
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
|
||||
rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_(
|
||||
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
|
||||
assert {row.status for row in rows} == {'failed'}
|
||||
assert {row.error_code for row in rows} == {'RPA_INBOUND_TRIGGER_UNAVAILABLE'}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码;
|
||||
inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配,
|
||||
匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。
|
||||
依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。
|
||||
依赖:app fixture 种子站点、FreightRpaOnhandExternalMapping、DefaultRouteResolver。
|
||||
逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。
|
||||
"""
|
||||
|
||||
@@ -13,18 +13,18 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource
|
||||
from app.services.in_transit_transfer.deps import DefaultRouteResolver
|
||||
from app.services.in_transit_transfer.matching_service import RouteNotResolvedError
|
||||
|
||||
|
||||
def _seed_mapping(
|
||||
source: ShippingInventorySource, *, freight_warehouse_id: str | None,
|
||||
source: FreightRpaSource, *, freight_warehouse_id: str | None,
|
||||
in_transit_warehouse_code: str = 'TZT-01',
|
||||
) -> ShippingInventoryExternalMapping:
|
||||
) -> FreightRpaOnhandExternalMapping:
|
||||
"""在既有种子来源上挂一条启用映射。"""
|
||||
mapping = ShippingInventoryExternalMapping(
|
||||
inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id,
|
||||
mapping = FreightRpaOnhandExternalMapping(
|
||||
source_id=source.id, freight_warehouse_id=freight_warehouse_id,
|
||||
external_system_code='TOPGP', external_organization_code='TGHX',
|
||||
external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓',
|
||||
in_transit_warehouse_code=in_transit_warehouse_code, enabled=True,
|
||||
@@ -34,12 +34,13 @@ def _seed_mapping(
|
||||
return mapping
|
||||
|
||||
|
||||
def _seed_inventory_match_source() -> ShippingInventorySource:
|
||||
def _seed_inventory_match_source() -> FreightRpaSource:
|
||||
"""以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。"""
|
||||
template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = ShippingInventorySource(
|
||||
template = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
# s18 起站点行不再承载 parsing_profile_id;路由解析只读外部映射,无需在手配置行。
|
||||
source = FreightRpaSource(
|
||||
source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane',
|
||||
rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id,
|
||||
rpa_profile_id=template.rpa_profile_id,
|
||||
excel_template_id=template.excel_template_id,
|
||||
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True,
|
||||
)
|
||||
@@ -51,7 +52,7 @@ def _seed_inventory_match_source() -> ShippingInventorySource:
|
||||
def test_fixed_source_uses_single_mapping_in_transit_code(app):
|
||||
"""fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。"""
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
# 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。
|
||||
_seed_mapping(source, freight_warehouse_id='TZR2')
|
||||
|
||||
@@ -118,7 +119,7 @@ def test_inventory_match_fails_closed_without_any_match(app):
|
||||
def test_route_resolver_fails_closed_without_in_transit_code(app):
|
||||
"""映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。"""
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='')
|
||||
|
||||
with pytest.raises(RouteNotResolvedError):
|
||||
|
||||
@@ -46,12 +46,12 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
|
||||
"""创建可参与收料的最小库存源(rpa_profile_id 非空,须先建 Profile)。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingRpaProfile,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaSource,
|
||||
FreightRpaProfile,
|
||||
)
|
||||
|
||||
profile = ShippingRpaProfile(
|
||||
profile = FreightRpaProfile(
|
||||
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="crane",
|
||||
login_url="https://test.invalid/login", login_config_json={"auth_mode": "password"},
|
||||
)
|
||||
@@ -62,7 +62,7 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
|
||||
"rpa_profile_id": profile.id, "enabled": enabled,
|
||||
}
|
||||
if enabled:
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
parsing = FreightRpaParsingProfile(
|
||||
profile_code=f"PARSE_{source_code}", display_name=source_code, version=1,
|
||||
status="published", file_format="xlsx",
|
||||
definition_json={"field_mapping": {}, "match_keys": []},
|
||||
@@ -79,27 +79,35 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
|
||||
db.session.add_all([parsing, template])
|
||||
db.session.flush()
|
||||
source_kwargs.update(
|
||||
parsing_profile_id=parsing.id, excel_template_id=template.id,
|
||||
excel_template_id=template.id,
|
||||
warehouse_resolution_mode="fixed", fixed_warehouse_id="WH1",
|
||||
)
|
||||
else:
|
||||
source_kwargs.update(warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None)
|
||||
source = ShippingInventorySource(**source_kwargs)
|
||||
source = FreightRpaSource(**source_kwargs)
|
||||
db.session.add(source)
|
||||
if enabled:
|
||||
# s18 起解析方案绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行;
|
||||
# 经关系级联随站点一并入库。
|
||||
from app.models import FreightRpaOnhandReportConfig
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=source, parsing_profile=parsing,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
return source
|
||||
|
||||
|
||||
def test_list_inbound_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
|
||||
"""缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。"""
|
||||
from app.models import ShippingReceiptReportConfig
|
||||
from app.models import FreightRpaInboundReportConfig
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
|
||||
|
||||
enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True)
|
||||
_make_receipt_source(transfer_db, "DBS_OFF", enabled=False)
|
||||
_make_receipt_source(transfer_db, "CRANE_NOCONF", enabled=True)
|
||||
transfer_db.session.flush()
|
||||
transfer_db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=enabled.id, report_path_json={}, query_parameters_json=[],
|
||||
transfer_db.session.add(FreightRpaInboundReportConfig(
|
||||
source_id=enabled.id, report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
transfer_db.session.commit()
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile),
|
||||
按来源投影 ready/fetching/failed/expired/parse_failed/none,并验证解析失败
|
||||
标记 record/clear 的往返语义。调拨不维护独立抓取状态表。
|
||||
依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
|
||||
依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
|
||||
逻辑:有当天(业务日)抓取且未过期文件→ready(若标记解析失败→parse_failed);
|
||||
有进行中单元→fetching;最新单元失败终态→failed;
|
||||
保留期已到或隔日旧文件(未清理)→expired;否则→none。
|
||||
@@ -25,9 +25,9 @@ SOURCE_CODE = 'DSV360_AWSDU'
|
||||
def receipt_unit_run():
|
||||
"""构造一条收料执行单元(含排程/来源上下文)。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-SOURCE-STATUS', name='Source status test', schedule_type='platform_job',
|
||||
owner_user_id=1, cron_expr='0 8 * * *', job_params={},
|
||||
@@ -37,8 +37,8 @@ def receipt_unit_run():
|
||||
run = ScheduleRun(run_no='RUN-SOURCE-STATUS', schedule_task_id=task.id, status='awaiting_callback')
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
schedule_run_id=run.id, source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-status-001',
|
||||
status='awaiting_rpa', config_snapshot_json={},
|
||||
)
|
||||
@@ -64,7 +64,7 @@ def test_running_unit_is_fetching(app, receipt_unit_run):
|
||||
def test_failed_latest_unit_is_failed(app, receipt_unit_run):
|
||||
"""最新单元为失败终态且无文件 → failed。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
|
||||
receipt_unit_run.status = 'failed'
|
||||
db.session.commit()
|
||||
@@ -75,11 +75,11 @@ def test_failed_latest_unit_is_failed(app, receipt_unit_run):
|
||||
def test_report_file_is_ready(app, receipt_unit_run):
|
||||
"""有收料归档文件 → ready,且带 file_no/sha256。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
digest = hashlib.sha256(b'receipt workbook').hexdigest()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
db.session.add(FreightRpaInboundReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/test.xlsx', original_filename='receipt.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
@@ -96,10 +96,10 @@ def test_expired_report_is_expired(app, receipt_unit_run):
|
||||
"""保留期已到但清理任务未删 → expired,不得误报 ready。"""
|
||||
# [断言意图] 过期判定只看 archive_expires_at,不依赖保留期清理任务是否已落位。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
db.session.add(FreightRpaInboundReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
|
||||
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
|
||||
@@ -115,17 +115,17 @@ def test_newer_valid_report_wins_over_expired(app, receipt_unit_run):
|
||||
"""过期文件之后又抓到未过期文件 → 以最新未过期文件为准(ready)。"""
|
||||
# [断言意图] ready 查询过滤掉过期记录后仍按 created_at/id 倒序取最新一条。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
digest = hashlib.sha256(b'fresh workbook').hexdigest()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
db.session.add(FreightRpaInboundReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
|
||||
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
|
||||
archive_expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
))
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
db.session.add(FreightRpaInboundReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/fresh.xlsx', original_filename='fresh.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
@@ -143,10 +143,10 @@ def test_stale_report_is_expired(app, receipt_unit_run):
|
||||
# [断言意图] 新鲜度按 Asia/Shanghai 业务日窗口判定(UTC 库存时间须换算):
|
||||
# 隔日抓取的文件对 D+1 预检是旧数据,投影 expired 引导重试重抓。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
db.session.add(FreightRpaInboundReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/stale.xlsx', original_filename='stale.xlsx',
|
||||
file_size=16, sha256=hashlib.sha256(b'stale workbook').hexdigest(),
|
||||
@@ -161,11 +161,11 @@ def test_stale_report_is_expired(app, receipt_unit_run):
|
||||
def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_unit_run):
|
||||
"""可用归档文件若已标记 parse_failed_at → file_status=parse_failed 且不可当 ready。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
digest = hashlib.sha256(b'bad workbook').hexdigest()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
db.session.add(FreightRpaInboundReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/bad.xlsx', original_filename='bad.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
@@ -183,7 +183,7 @@ def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_uni
|
||||
def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
|
||||
"""record 写入三列;clear 清空后投影回 ready。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
clear_inbound_parse_failure,
|
||||
record_inbound_parse_failure,
|
||||
@@ -192,7 +192,7 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
digest = hashlib.sha256(b'roundtrip').hexdigest()
|
||||
report = ShippingReceiptReportFile(
|
||||
report = FreightRpaInboundReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/ok.xlsx', original_filename='ok.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
@@ -228,14 +228,14 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
|
||||
门禁)永久锁死;回收后必须翻转 failed 解锁重新触发 RPA。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
from app.models import FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
db.session.add(ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=None, inventory_source_id=source.id, source_code=source.source_code,
|
||||
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
db.session.add(FreightRpaInboundUnitRun(
|
||||
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', callback_id='inbound-orphan-status', status='awaiting_rpa',
|
||||
config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=5),
|
||||
))
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
可空成分 NOT NULL + default ''/transfer_executed 默认 false/
|
||||
source_file_id FK ON DELETE SET NULL(文件清理后档事实留存)。
|
||||
依赖:app_ctx(根 conftest app fixture 上下文别名)、transfer_db(SQLite 内存库)、
|
||||
models/in_transit_transfer、models/shipping_receipt_report。
|
||||
models/in_transit_transfer、models/shipping_inbound_report。
|
||||
逻辑:纯元数据断言(不落库)+ 真库往返(默认值/唯一约束/FK SET NULL 行为)。
|
||||
"""
|
||||
|
||||
@@ -15,7 +15,7 @@ from sqlalchemy import inspect, text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.models.in_transit_transfer import TransferMovementLedger
|
||||
|
||||
# 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维):8 成分全部 NOT NULL,
|
||||
@@ -106,13 +106,13 @@ def test_scope_indexes_declared(app_ctx):
|
||||
|
||||
|
||||
def test_source_file_fk_on_delete_set_null(app_ctx):
|
||||
"""source_file_id FK 指向 shipping_receipt_report_files 且 ON DELETE SET NULL(档事实留存)。"""
|
||||
"""source_file_id FK 指向 freight_rpa_inbound_report_files 且 ON DELETE SET NULL(档事实留存)。"""
|
||||
cols = _column_map()
|
||||
fk = next(
|
||||
fk for fk in TransferMovementLedger.__table__.foreign_keys
|
||||
if fk.parent.name == 'source_file_id'
|
||||
)
|
||||
assert fk.target_fullname == 'shipping_receipt_report_files.id'
|
||||
assert fk.target_fullname == 'freight_rpa_inbound_report_files.id'
|
||||
assert fk.ondelete == 'SET NULL'
|
||||
assert cols['source_file_id'].nullable is True
|
||||
|
||||
@@ -164,17 +164,17 @@ def test_duplicate_natural_key_rejected(transfer_db):
|
||||
|
||||
def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
|
||||
"""source_file relationship 可导航;来源文件删除后档记录留存且 source_file_id 置 NULL。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
|
||||
unit_run = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行
|
||||
unit_run = FreightRpaInboundUnitRun(
|
||||
source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行
|
||||
source_code='DBS-AWSBI',
|
||||
connector_type='rpa',
|
||||
callback_id='CB-LEDGER-001',
|
||||
)
|
||||
db.session.add(unit_run)
|
||||
db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(
|
||||
report_file = FreightRpaInboundReportFile(
|
||||
unit_run_id=unit_run.id,
|
||||
storage_provider='minio',
|
||||
storage_bucket='receipts',
|
||||
@@ -198,7 +198,7 @@ def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
|
||||
db.session.commit()
|
||||
|
||||
loaded = db.session.get(TransferMovementLedger, ledger.id)
|
||||
assert loaded.source_file.id == report_file.id # relationship 目标 ShippingReceiptReportFile
|
||||
assert loaded.source_file.id == report_file.id # relationship 目标 FreightRpaInboundReportFile
|
||||
|
||||
# ON DELETE SET NULL 行为:开启 SQLite FK 强制后原样删文件(文件资产保留策略)。
|
||||
# PRAGMA 是连接级开关且事务内为 no-op:必须走 AUTOCOMMIT 连接执行,归还连接池
|
||||
@@ -208,7 +208,7 @@ def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
|
||||
with db.engine.connect().execution_options(isolation_level='AUTOCOMMIT') as conn:
|
||||
conn.execute(text('PRAGMA foreign_keys=ON'))
|
||||
conn.execute(
|
||||
text('DELETE FROM shipping_receipt_report_files WHERE id = :id'),
|
||||
text('DELETE FROM freight_rpa_inbound_report_files WHERE id = :id'),
|
||||
{'id': file_id},
|
||||
)
|
||||
conn.execute(text('PRAGMA foreign_keys=OFF'))
|
||||
|
||||
+26
-26
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
tests/services/shipping_notice/test_inventory_candidate_projection.py
|
||||
tests/services/shipping_notice/test_onhand_candidate_projection.py
|
||||
|
||||
用途:验证正式 Task 的 active CandidateSet 读取、缺失阻断与版本化候选事实投影。
|
||||
依赖:Flask app fixture、ShippingNotice / CandidateSet / CandidateLine ORM、候选 projector。
|
||||
@@ -10,19 +10,19 @@ from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingOnhandCandidateLine,
|
||||
ShippingOnhandCandidateSet,
|
||||
ShippingOnhandCandidateSource,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingInventoryFile,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
FreightRpaOnhandReportFile,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import (
|
||||
project_inventory_candidate_facts,
|
||||
)
|
||||
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
|
||||
from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines
|
||||
|
||||
|
||||
def _task(task_no: str) -> ShippingOrderTask:
|
||||
@@ -36,8 +36,8 @@ def _task(task_no: str) -> ShippingOrderTask:
|
||||
return task
|
||||
|
||||
|
||||
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet:
|
||||
row = ShippingInventoryCandidateSet(
|
||||
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingOnhandCandidateSet:
|
||||
row = ShippingOnhandCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=version,
|
||||
lifecycle_status='frozen',
|
||||
@@ -50,12 +50,12 @@ def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInvento
|
||||
return row
|
||||
|
||||
|
||||
def test_prepare_candidate_inventory_lines_blocks_without_active_set(app):
|
||||
def test_prepare_candidate_onhand_lines_blocks_without_active_set(app):
|
||||
with app.app_context():
|
||||
task = _task('SN-CAND-001')
|
||||
db.session.commit()
|
||||
|
||||
result = prepare_candidate_inventory_lines(task)
|
||||
result = prepare_candidate_onhand_lines(task)
|
||||
|
||||
assert result['status'] == 'blocked'
|
||||
assert result['error_code'] == 'inventory_candidates_missing'
|
||||
@@ -66,13 +66,13 @@ def test_project_inventory_candidate_facts_reads_current_structured_set(app):
|
||||
with app.app_context():
|
||||
task = _task('SN-CAND-002')
|
||||
candidate_set = _candidate_set(task, version=2)
|
||||
source = ShippingInventoryCandidateSource(
|
||||
source = ShippingOnhandCandidateSource(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
source_code='DBS_DUB',
|
||||
candidate_order=1,
|
||||
candidate_origin='rule',
|
||||
)
|
||||
line = ShippingInventoryCandidateLine(
|
||||
line = ShippingOnhandCandidateLine(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
line_no=1,
|
||||
source_line_no='00010',
|
||||
@@ -99,14 +99,14 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
with app.app_context():
|
||||
task = _task('SN-CAND-003')
|
||||
old_set = _candidate_set(task, version=1)
|
||||
old_line = ShippingInventoryCandidateLine(
|
||||
old_line = ShippingOnhandCandidateLine(
|
||||
candidate_set_id=int(old_set.id),
|
||||
line_no=1,
|
||||
source_codes_json=['DBS_OLD'],
|
||||
)
|
||||
db.session.add(old_line)
|
||||
db.session.flush()
|
||||
new_set = ShippingInventoryCandidateSet(
|
||||
new_set = ShippingOnhandCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=2,
|
||||
lifecycle_status='frozen',
|
||||
@@ -116,7 +116,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
db.session.flush()
|
||||
task.active_inventory_candidate_set_id = int(new_set.id)
|
||||
db.session.flush()
|
||||
new_line = ShippingInventoryCandidateLine(
|
||||
new_line = ShippingOnhandCandidateLine(
|
||||
candidate_set_id=int(new_set.id),
|
||||
line_no=1,
|
||||
source_codes_json=['DBS_NEW'],
|
||||
@@ -132,7 +132,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
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(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=int(task.id),
|
||||
snapshot_line_id=int(snapshot_line.id),
|
||||
line_no=1,
|
||||
@@ -141,8 +141,8 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
candidate_set_version=1,
|
||||
candidate_line_id=int(old_line.id),
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
inventory_source_code='DBS_OLD',
|
||||
onhand_status='ready',
|
||||
source_code='DBS_OLD',
|
||||
is_current=True,
|
||||
allowed_source_codes_snapshot=['DBS_OLD'],
|
||||
detail_json={'disposition': 'ok'},
|
||||
@@ -161,12 +161,12 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
|
||||
with app.app_context():
|
||||
task = _task('SN-CAND-EVIDENCE')
|
||||
candidate_set = _candidate_set(task)
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
db.session.add(ShippingOnhandCandidateLine(
|
||||
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
|
||||
))
|
||||
db.session.flush()
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_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)
|
||||
@@ -180,11 +180,11 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
|
||||
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(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
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,
|
||||
candidate_set_version=1, onhand_snapshot_id=int(inventory_file.id), match_result='matched',
|
||||
onhand_status='ready', source_code='DBS_DUB', matched_file_no=inventory_file.onhand_file_no,
|
||||
matched_row_index=9, is_current=True, detail_json={},
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,791 @@
|
||||
"""tests/services/shipping_notice/test_onhand_report_handler.py
|
||||
|
||||
用途:阶段 B Task 7 修复轮——onhand 报表事实投递接线与处理函数契约测试:
|
||||
单回调/批量 worker 在文件行 commit 后投递事实(先 commit 再投递、处理函数
|
||||
失败外抛且文件行保留)、success 事实 settle 等待中的候选准备并同步门禁
|
||||
(处理函数自行 commit、重放不重复候选行)、失败事实不发明候选行;
|
||||
修复轮 2 补批量契约:单文件处理函数失败不跳过其余文件投递与排程收口、
|
||||
Job 意外异常 requeue 可重试;修复轮 3 补:失败点回滚半途写(不被后续
|
||||
commit 持久化)、drop 文件清理先于错误外抛、Job 重试「只重投失败文件」
|
||||
通道(callback_id 已消费拦不住重投、未完成绝不返回 ok)。
|
||||
依赖:app(SQLite)fixture、freight_rpa.reports.dispatch / facts、
|
||||
freight_rpa.onhand.report_store(候选 settle 所绑文件行的唯一插入入口)、
|
||||
onhand_rpa_workflow(回调入口 + 重试通道/专用异常)、onhand_recovery_service
|
||||
(候选准备表)、jobs.handlers.freight_rpa_onhand_callback_process(Job 收口)。
|
||||
逻辑:直接处理函数用例以 monkeypatch 替身 gate 同步记录调用(不断言 Gate 全链);
|
||||
e2e 投递用例复用 test_shipping_notice_inventory_rpa_workflow 的动态订单/
|
||||
客户确认/库存源种子 harness,跑通 rpa_report_inventory /
|
||||
process_rpa_report_inventory_batch 全程后在注册表注入记录器断言事实字段;
|
||||
批量失败用例以替身 finalize 记录收口调用(内部预存在 NameError 与本契约无关)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import inventory_xlsx_with_warehouse
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(app):
|
||||
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
|
||||
from app import db
|
||||
|
||||
return db.session
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fake_gate_sync(monkeypatch):
|
||||
"""替身门禁同步:记录 (execution_id) 调用序列,不跑 Gate 全链(聚焦候选/提交契约)。"""
|
||||
calls: list[int] = []
|
||||
|
||||
def _record(**kwargs):
|
||||
calls.append(int(kwargs['execution'].id))
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
_record,
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def _seed_waiting_preparation(db_session, *, task_no: str, execution_no: str):
|
||||
"""构造「任务 + 活动执行 + 等待中候选准备轮次(waiting SourceAttempt)」。
|
||||
|
||||
Returns:
|
||||
(task, execution, preparation, source_row) 四元组。
|
||||
"""
|
||||
from app.models import (
|
||||
ShippingOnhandPreparationAttempt,
|
||||
ShippingOnhandPreparationSourceAttempt,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
)
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no, user_id=1, source_type='direct_pdf', status='ready',
|
||||
)
|
||||
db_session.add(task)
|
||||
db_session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no=execution_no, task_id=task.id, status='active',
|
||||
)
|
||||
db_session.add(execution)
|
||||
db_session.flush()
|
||||
task.active_process_execution_id = execution.id
|
||||
preparation = ShippingOnhandPreparationAttempt(
|
||||
task_id=task.id, attempt_no=1, status='waiting_external',
|
||||
)
|
||||
db_session.add(preparation)
|
||||
db_session.flush()
|
||||
source_row = ShippingOnhandPreparationSourceAttempt(
|
||||
preparation_attempt_id=preparation.id, source_code='DSV360_AWSDU', status='waiting',
|
||||
)
|
||||
db_session.add(source_row)
|
||||
db_session.commit()
|
||||
return task, execution, preparation, source_row
|
||||
|
||||
|
||||
def _onhand_file_id(*, source_code: str = 'DSV360_AWSDU') -> int:
|
||||
"""经唯一插入入口 report_store 落一行 ready onhand 报表文件并 commit,返回 file_id。"""
|
||||
from app import db
|
||||
from app.services.freight_rpa.onhand.report_store import insert_onhand_report
|
||||
from app.services.shipping_notice.onhand_file_store import generate_inventory_file_no
|
||||
|
||||
file_id = insert_onhand_report(
|
||||
onhand_file_no=generate_inventory_file_no(),
|
||||
storage_path='handler://onhand-report-fact.xlsx',
|
||||
source_code=source_code,
|
||||
snapshot_status='ready',
|
||||
file_sha256='a' * 64,
|
||||
)
|
||||
db.session.commit()
|
||||
return file_id
|
||||
|
||||
|
||||
def test_onhand_fact_settles_waiting_candidates_and_syncs_gates(app, db_session, _fake_gate_sync):
|
||||
"""success 事实:settle 等待候选(ready + 绑文件)→ 聚合准备轮次 → 门禁同步 → 自行 commit。"""
|
||||
from app.models import ShippingOnhandPreparationAttempt, ShippingOnhandPreparationSourceAttempt
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
|
||||
|
||||
task, execution, preparation, source_row = _seed_waiting_preparation(
|
||||
db_session, task_no='OT-ONHAND-FACT-SETTLE', execution_no='EX-ONHAND-FACT-SETTLE',
|
||||
)
|
||||
file_id = _onhand_file_id()
|
||||
|
||||
handle_onhand_report(ReportFact(
|
||||
report_kind='onhand', source_code='DSV360_AWSDU',
|
||||
file_id=file_id, sha256='a' * 64, ok=True,
|
||||
))
|
||||
|
||||
# [断言意图] 处理函数必须自行 commit:rollback + expire_all 后 settle 仍可见。
|
||||
db_session.rollback()
|
||||
db_session.expire_all()
|
||||
refreshed_source = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
|
||||
assert refreshed_source.status == 'ready'
|
||||
assert refreshed_source.onhand_file_id == file_id
|
||||
refreshed_prep = db_session.get(ShippingOnhandPreparationAttempt, preparation.id)
|
||||
assert refreshed_prep.status == 'succeeded'
|
||||
assert refreshed_prep.completed_at is not None
|
||||
# [断言意图] 门禁同步覆盖 settle 受影响的准备轮次任务(execution 绑定同任务)。
|
||||
assert _fake_gate_sync == [execution.id]
|
||||
|
||||
# [重放] 同一事实重复投递:等待集已空——不重复 settle、不重复候选行(幂等)。
|
||||
handle_onhand_report(ReportFact(
|
||||
report_kind='onhand', source_code='DSV360_AWSDU',
|
||||
file_id=file_id, sha256='a' * 64, ok=True,
|
||||
))
|
||||
db_session.rollback()
|
||||
db_session.expire_all()
|
||||
assert ShippingOnhandPreparationSourceAttempt.query.count() == 1
|
||||
assert db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id).onhand_file_id == file_id
|
||||
assert db_session.get(ShippingOnhandPreparationAttempt, preparation.id).status == 'succeeded'
|
||||
|
||||
|
||||
def test_onhand_failure_fact_invents_no_candidate_rows(app, db_session, _fake_gate_sync):
|
||||
"""失败/空事实:无文件可挂——不发明候选行(SourceAttempt 保持 waiting、不绑文件),仅重投影门禁。"""
|
||||
from app.models import ShippingOnhandPreparationSourceAttempt
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
|
||||
|
||||
task, execution, preparation, source_row = _seed_waiting_preparation(
|
||||
db_session, task_no='OT-ONHAND-FACT-FAIL', execution_no='EX-ONHAND-FACT-FAIL',
|
||||
)
|
||||
|
||||
handle_onhand_report(ReportFact(
|
||||
report_kind='onhand', source_code='DSV360_AWSDU',
|
||||
file_id=None, sha256=None, ok=False,
|
||||
error_code='rpa_export_failed', error_message='boom',
|
||||
))
|
||||
|
||||
db_session.rollback()
|
||||
db_session.expire_all()
|
||||
# [断言意图] 失败事实没有文件身份:不得发明/改写候选行——仍是唯一一行、
|
||||
# 状态保持 waiting、未绑定任何文件;门禁重投影(失败路径门禁更新归处理函数)。
|
||||
assert ShippingOnhandPreparationSourceAttempt.query.count() == 1
|
||||
refreshed = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
|
||||
assert refreshed.status == 'waiting'
|
||||
assert refreshed.onhand_file_id is None
|
||||
assert _fake_gate_sync == [execution.id]
|
||||
|
||||
|
||||
def _seed_direct_rpa_task(db, *, task_no: str, run_no: str, sample) -> None:
|
||||
"""复用动态订单 harness:直建 OT + 动态订单 + 客户确认 + 库存源种子 + RPA 触发种子。"""
|
||||
from app.models import ShippingOrderTask
|
||||
from tests.conftest import seed_rpa_inventory_trigger, seed_task_inventory_source
|
||||
from tests.test_shipping_notice_inventory_rpa_workflow import (
|
||||
_attach_dynamic_order,
|
||||
_confirm_direct_rpa_task_customer,
|
||||
)
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no, 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='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
|
||||
seed_rpa_inventory_trigger(task, run_no=run_no)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _stub_structure_validation(monkeypatch):
|
||||
"""替身结构校验:onhand_structure_drift 仍读已删站点列(Task 2 已记录的 deferred
|
||||
minor,legacy 套件待 s18 改写)——与本修复无关;本测试聚焦 commit 后投递接线。
|
||||
|
||||
返回与真实 validate_production_inventory_structure 同形状的确定性解析参数:
|
||||
field_mapping 用 conftest 种子字段 ID 对齐样例 xlsx 列头
|
||||
(Warehouse ID / SKU / Reservation ID / Qty,表头行 1,默认 sheet)。
|
||||
"""
|
||||
from app.models import FreightRpaOnhandField
|
||||
|
||||
fields = {
|
||||
row.field_code: row
|
||||
for row in FreightRpaOnhandField.query.filter(
|
||||
FreightRpaOnhandField.field_code.in_(
|
||||
['part_number', 'reservation_id', 'available_qty', 'warehouse_id'],
|
||||
)
|
||||
)
|
||||
}
|
||||
structure_check = {
|
||||
'field_mapping': {
|
||||
str(fields['part_number'].id): 'SKU',
|
||||
str(fields['reservation_id'].id): 'Reservation ID',
|
||||
str(fields['available_qty'].id): 'Qty',
|
||||
str(fields['warehouse_id'].id): 'Warehouse ID',
|
||||
},
|
||||
'header_row_index': 1,
|
||||
'sheet_name': 'Sheet',
|
||||
'level': 'exact',
|
||||
'difference': {},
|
||||
'warnings': [],
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.onhand_structure_drift.validate_production_inventory_structure',
|
||||
lambda **_kwargs: structure_check,
|
||||
)
|
||||
|
||||
|
||||
def test_single_callback_dispatches_onhand_fact_after_file_commit(app, tmp_path, monkeypatch):
|
||||
"""rpa_report_inventory:文件行 commit 后同请求投递 onhand 事实,字段与已提交行对齐。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory
|
||||
from tests.conftest import rpa_callback_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'onhand-fact.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
register_report_handler('onhand', seen.append)
|
||||
|
||||
with app.app_context():
|
||||
from app.models import ShippingOrderTask
|
||||
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-DISPATCH', run_no='RUN-ONHAND-FACT', sample=sample)
|
||||
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-DISPATCH').one()
|
||||
result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT'))
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='RUN-ONHAND-FACT', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
assert result.get('status') == 'ok'
|
||||
# [断言意图] commit 后投递:恰好一条事实、字段与已提交文件行逐项对齐。
|
||||
assert len(seen) == 1
|
||||
fact = seen[0]
|
||||
assert fact.report_kind == 'onhand'
|
||||
assert fact.ok is True
|
||||
assert fact.file_id == snap.id
|
||||
assert fact.source_code == 'DSV360_AWSDU'
|
||||
assert fact.sha256 == snap.file_sha256
|
||||
# 文件行已提交:rollback 后重查仍在(先 commit 再投递的顺序契约)。
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
|
||||
|
||||
|
||||
def test_single_callback_handler_failure_propagates_and_keeps_file_row(app, tmp_path, monkeypatch):
|
||||
"""处理函数抛错:异常原样外抛(不折进 post_commit_warnings),已提交文件行保留。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingOrderTask
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory
|
||||
from tests.conftest import rpa_callback_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'onhand-fact-fail.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
def boom(_fact) -> None:
|
||||
raise RuntimeError('onhand handler down')
|
||||
|
||||
register_report_handler('onhand', boom)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-RAISE', run_no='RUN-ONHAND-FACT-RAISE', sample=sample)
|
||||
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-RAISE').one()
|
||||
|
||||
# [断言意图] 异常必须外抛(供 Worker 重试整笔回调),绝不折进 warnings 后返回 ok。
|
||||
with pytest.raises(RuntimeError, match='onhand handler down'):
|
||||
rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT-RAISE'))
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='RUN-ONHAND-FACT-RAISE', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
# [断言意图] 处理函数失败不回滚已提交文件行。
|
||||
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
|
||||
|
||||
|
||||
def test_batch_worker_dispatches_onhand_fact_after_commit(app, tmp_path, monkeypatch):
|
||||
"""process_rpa_report_inventory_batch:整批事务 commit 后逐文件投递 onhand 事实。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'onhand-fact-batch.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
register_report_handler('onhand', seen.append)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-BATCH', run_no='RUN-ONHAND-FACT-BATCH', sample=sample)
|
||||
task_no = 'OT-ONHAND-FACT-BATCH'
|
||||
|
||||
result = process_rpa_report_inventory_batch(v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-FACT-BATCH',
|
||||
'trigger_type': 'on_demand',
|
||||
'results': [scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample), task_no=task_no,
|
||||
)],
|
||||
}))
|
||||
assert result.get('status') == 'ok'
|
||||
assert result.get('data', {}).get('success_count') == 1
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='RUN-ONHAND-FACT-BATCH', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
# [断言意图] 整批 commit 后逐文件投递:恰一条 ok=True 事实,file_id 对齐已提交行。
|
||||
assert [fact.file_id for fact in seen] == [snap.id]
|
||||
assert all(fact.report_kind == 'onhand' and fact.ok is True for fact in seen)
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
|
||||
|
||||
|
||||
def test_batch_handler_failure_does_not_skip_remaining_dispatch_or_finalize(app, tmp_path, monkeypatch):
|
||||
"""批量内单文件处理函数失败:其余已提交文件仍投递、排程收口仍执行、错误仍外抛、文件行保留。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample_a = drop_dir / 'onhand-fact-batch-a.xlsx'
|
||||
sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
sample_b = drop_dir / 'onhand-fact-batch-b.xlsx'
|
||||
sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
# [断言意图·观测点] 排程收口必须仍被调用(内部预存在 NameError 与本契约无关)。
|
||||
finalize_calls: list = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_rpa_onhand_finalize.finalize_shipping_inventory_schedule_run',
|
||||
lambda schedule_run_id, **_kwargs: (
|
||||
finalize_calls.append(schedule_run_id)
|
||||
or {'ok': True, 'schedule_finalize_status': 'finalized'}
|
||||
),
|
||||
)
|
||||
# [断言意图·观测点] 首个文件处理函数失败,第二个必须照常收到事实。
|
||||
seen: list[ReportFact] = []
|
||||
calls = {'n': 0}
|
||||
|
||||
def flaky(fact: ReportFact) -> None:
|
||||
calls['n'] += 1
|
||||
seen.append(fact)
|
||||
if calls['n'] == 1:
|
||||
raise RuntimeError('onhand handler down mid-batch')
|
||||
|
||||
register_report_handler('onhand', flaky)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-ONHAND-BATCH-FAIL', name='Onhand batch fail', schedule_type='platform_job',
|
||||
platform_api_path='freight-rpa-onhand', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ONHAND-BATCH-FAIL', schedule_task_id=task.id, status='running',
|
||||
total_count=2, success_count=0, failed_count=0, skipped_count=0,
|
||||
response_summary_json={'awaiting_rpa': True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
# [断言意图] 处理函数异常必须外抛(调用方/Job 见到失败)——但不得因此跳过
|
||||
# 其余文件投递与排程收口(断言在 pytest.raises 之后进行)。
|
||||
with pytest.raises(RuntimeError, match='onhand handler down mid-batch'):
|
||||
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-BATCH-FAIL',
|
||||
'schedule_run_id': run.id,
|
||||
'trigger_type': 'scheduled',
|
||||
'results': [
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-BATCH-FAIL-A',
|
||||
),
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-BATCH-FAIL-B',
|
||||
),
|
||||
],
|
||||
}))
|
||||
|
||||
snaps = FreightRpaOnhandReportFile.query.filter(
|
||||
FreightRpaOnhandReportFile.snapshot_status == 'ready',
|
||||
FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B')),
|
||||
).order_by(FreightRpaOnhandReportFile.id).all()
|
||||
# [断言意图] 两个文件行都已落库并保留(commit 先于投递,失败不回滚)。
|
||||
assert [snap.rpa_run_no for snap in snaps] == ['SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B']
|
||||
# [断言意图] 两个文件的事实都投递了(首文件失败不跳过次文件投递)。
|
||||
assert [fact.file_id for fact in seen] == [snap.id for snap in snaps]
|
||||
# [断言意图] 排程收口仍执行(不被处理函数失败跳过)。
|
||||
assert finalize_calls == [run.id]
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
assert {db.session.get(FreightRpaOnhandReportFile, snap.id) is not None for snap in snaps} == {True}
|
||||
|
||||
|
||||
def test_callback_process_job_requeues_on_unexpected_exception(app, monkeypatch):
|
||||
"""Job 意外异常(含批量 commit 后处理函数失败重抛)必须可重试 requeue,而非终态 failed。"""
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers import freight_rpa_onhand_callback_process as handler
|
||||
from app.models import Job
|
||||
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
domain='shipping_notice',
|
||||
job_type='freight_rpa_onhand_callback_process',
|
||||
status='running',
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
business_ref='inventory-callback:retryable-check',
|
||||
payload_json={'callback_id': 'retryable-check'},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
def _boom(_payload):
|
||||
raise RuntimeError('dispatch re-raise after commit')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch',
|
||||
_boom,
|
||||
)
|
||||
|
||||
handler.run_shipping_inventory_callback_process(
|
||||
JobContext(config={}, logger=None, extras={}), {'job_id': job.id},
|
||||
)
|
||||
db_session = db.session
|
||||
db_session.expire_all()
|
||||
# [断言意图] retryable=True → requeue(attempts 未耗尽时回到 queued 等待重试),
|
||||
# 绝不落终态 failed——批量文件行已提交,重放按幂等契约补齐收口。
|
||||
refreshed = db_session.get(Job, job.id)
|
||||
assert refreshed.status == 'queued'
|
||||
|
||||
|
||||
def test_batch_handler_failure_rolls_back_partial_writes_and_next_file_dispatches(app, db_session, tmp_path, monkeypatch):
|
||||
"""批量内处理函数「先 bind 候选再抛错」:半途 flush 写必须回滚(不得被后续 commit 持久化),次文件照常投递。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingOnhandPreparationSourceAttempt
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample_a = drop_dir / 'rollback-a.xlsx'
|
||||
sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
sample_b = drop_dir / 'rollback-b.xlsx'
|
||||
sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
calls = {'n': 0}
|
||||
|
||||
def bind_then_raise_or_settle(fact: ReportFact) -> None:
|
||||
calls['n'] += 1
|
||||
seen.append(fact)
|
||||
if calls['n'] == 1:
|
||||
# [RED 场景] 模拟「先 bind 候选再抛错」的处理函数:半途 flush(不 commit)。
|
||||
from app.models import ShippingOnhandPreparationSourceAttempt as _Row
|
||||
|
||||
row = (
|
||||
_Row.query.filter_by(source_code='DSV360_AWSDU')
|
||||
.order_by(_Row.id)
|
||||
.first()
|
||||
)
|
||||
row.status = 'ready'
|
||||
row.onhand_file_id = int(fact.file_id)
|
||||
db.session.flush()
|
||||
raise RuntimeError('bind then raise mid-batch')
|
||||
# 次文件走真实处理函数:内部 settle(等待集)→ 门禁同步 → 自行 commit。
|
||||
handle_onhand_report(fact)
|
||||
|
||||
register_report_handler('onhand', bind_then_raise_or_settle)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_task, _execution, _preparation, source_row = _seed_waiting_preparation(
|
||||
db_session, task_no='OT-ONHAND-ROLLBACK', execution_no='EX-ONHAND-ROLLBACK',
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match='bind then raise mid-batch'):
|
||||
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-ROLLBACK',
|
||||
'trigger_type': 'on_demand',
|
||||
'results': [
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-ROLLBACK-A',
|
||||
),
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-ROLLBACK-B',
|
||||
),
|
||||
],
|
||||
}))
|
||||
|
||||
snaps = FreightRpaOnhandReportFile.query.filter(
|
||||
FreightRpaOnhandReportFile.snapshot_status == 'ready',
|
||||
FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-ROLLBACK-A', 'SR-ROLLBACK-B')),
|
||||
).order_by(FreightRpaOnhandReportFile.id).all()
|
||||
# [断言意图] 次文件照常投递:两个已提交文件的事实都送达处理函数。
|
||||
assert [fact.file_id for fact in seen] == [snap.id for snap in snaps]
|
||||
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
# [断言意图] 首文件半途 bind 已回滚——不得被次文件处理函数的 commit 持久化成
|
||||
# file-A 绑定;次文件真实 settle 落到 file B(等待集在回滚后原样可 settle)。
|
||||
refreshed = db.session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
|
||||
assert refreshed.status == 'ready'
|
||||
assert refreshed.onhand_file_id == snaps[1].id
|
||||
|
||||
|
||||
def test_batch_handler_failure_still_flushes_drop_file_cleanup_before_raise(app, tmp_path, monkeypatch):
|
||||
"""处理函数抛错:drop 文件清理(消费标记+移动/入队)必须先于错误外抛完成。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'cleanup-before-raise.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
def boom(_fact) -> None:
|
||||
raise RuntimeError('onhand handler down cleanup')
|
||||
|
||||
register_report_handler('onhand', boom)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-CLEANUP', run_no='RUN-ONHAND-CLEANUP', sample=sample)
|
||||
|
||||
with pytest.raises(RuntimeError, match='onhand handler down cleanup'):
|
||||
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-CLEANUP',
|
||||
'trigger_type': 'on_demand',
|
||||
'results': [scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-CLEANUP',
|
||||
)],
|
||||
}))
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='RUN-ONHAND-CLEANUP', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
# [断言意图] 错误已外抛,但 drop 文件清理先行完成:消费标记/移动先于重抛,
|
||||
# 文件离开 drop 根、落入 processed 归档(移动失败时则入持久化 cleanup 队列)。
|
||||
assert not sample.exists()
|
||||
assert (drop_dir / 'processed' / sample.name).exists()
|
||||
|
||||
|
||||
def test_batch_retry_channel_redispatches_file_despite_consumed_callback_id(app, tmp_path, monkeypatch):
|
||||
"""重试通道:task-linked 项 Attempt 已消费 callback_id(整批重放必被跳过)时,失败文件仍重投事实。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingOrderTask, FreightRpaOnhandTaskAttempt
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import (
|
||||
OnhandReportDispatchAfterCommitError,
|
||||
process_rpa_report_inventory_batch,
|
||||
)
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'retry-callback-id.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
calls = {'n': 0}
|
||||
|
||||
def flaky(fact: ReportFact) -> None:
|
||||
calls['n'] += 1
|
||||
seen.append(fact)
|
||||
if calls['n'] == 1:
|
||||
raise RuntimeError('onhand handler down first pass')
|
||||
|
||||
register_report_handler('onhand', flaky)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-RETRY', run_no='RUN-ONHAND-RETRY', sample=sample)
|
||||
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-RETRY').one()
|
||||
candidate_set_id = int(task.active_inventory_candidate_set_id or 1)
|
||||
# [RED 场景] 结构化 per-source Attempt(v2 身份字段与回调 item 对齐):
|
||||
# pass 1 的回调确认会把 attempt.callback_id 写入——整批重放随即被 replay 检查跳过。
|
||||
# source_run_no 用与批量 run_no 不同的 PSR 轮次号(与真实 Worker 形态一致:
|
||||
# run_no=批量轮次、source_run_no=逐源轮次——run_no 消费标记按 source_run_no
|
||||
# 匹配,不会误吞本 Attempt)。
|
||||
attempt = FreightRpaOnhandTaskAttempt(
|
||||
task_no='OT-ONHAND-RETRY',
|
||||
source_code='DSV360_AWSDU',
|
||||
attempt_no=1,
|
||||
source_run_no='PSR-ONHAND-RETRY-1',
|
||||
status='queued',
|
||||
triggered_at=datetime.utcnow(),
|
||||
lease_token='test-lease-token',
|
||||
execution_phase='trigger_written',
|
||||
extra_json={
|
||||
'trigger_mode': 'test',
|
||||
'candidate_set_id': candidate_set_id,
|
||||
'execution_id': 1,
|
||||
'gate_id': 1,
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.commit()
|
||||
|
||||
batch_payload = v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-RETRY',
|
||||
'trigger_type': 'on_demand',
|
||||
'results': [dict(
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-RETRY',
|
||||
),
|
||||
callback_id='test-callback:RUN-ONHAND-RETRY',
|
||||
source_run_no='PSR-ONHAND-RETRY-1',
|
||||
attempt_no=1,
|
||||
lease_token='test-lease-token',
|
||||
candidate_set_id=candidate_set_id,
|
||||
execution_id=1,
|
||||
gate_id=1,
|
||||
)],
|
||||
})
|
||||
|
||||
# [STEP 1] 首轮:文件落地+回调确认(写 callback_id)+投递失败 → 专用异常携带清单外抛。
|
||||
with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo:
|
||||
process_rpa_report_inventory_batch(batch_payload)
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='PSR-ONHAND-RETRY-1', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
assert excinfo.value.failed_files == [{
|
||||
'source_code': 'DSV360_AWSDU',
|
||||
'file_id': snap.id,
|
||||
'sha256': (snap.file_sha256 or None),
|
||||
}]
|
||||
# [断言意图·RED 场景] Attempt 已消费 callback_id——整批重放会被 replay 检查跳过。
|
||||
db.session.expire(attempt)
|
||||
assert str(attempt.callback_id or '').strip()
|
||||
armed_callback_id = str(attempt.callback_id)
|
||||
|
||||
# [STEP 2] 整批重放(不带重试清单):item 被 replay 检查跳过——不落地、不投递,
|
||||
# 证明整批重放无法补投(这正是「只重投失败文件」通道存在的原因)。
|
||||
replay_result = process_rpa_report_inventory_batch(dict(batch_payload))
|
||||
assert [fact.file_id for fact in seen] == [snap.id]
|
||||
assert replay_result.get('data', {}).get('created') == []
|
||||
assert armed_callback_id == str(
|
||||
FreightRpaOnhandTaskAttempt.query.filter_by(
|
||||
task_no='OT-ONHAND-RETRY', source_code='DSV360_AWSDU',
|
||||
).order_by(FreightRpaOnhandTaskAttempt.id.desc()).first().callback_id or '',
|
||||
)
|
||||
|
||||
# [STEP 3] 重试通道(Job 处理器写回的 retry_dispatch_files):只重投失败文件。
|
||||
retry_payload = {**batch_payload, 'retry_dispatch_files': excinfo.value.failed_files}
|
||||
result = process_rpa_report_inventory_batch(retry_payload)
|
||||
assert result.get('status') == 'ok'
|
||||
assert result.get('data', {}).get('result_status') == 'retried'
|
||||
# [断言意图] 同一 file_id 的事实再次送达处理函数(callback_id 已消费拦不住重投)。
|
||||
assert [fact.file_id for fact in seen] == [snap.id, snap.id]
|
||||
|
||||
|
||||
def test_batch_retry_channel_reraises_while_handler_still_failing(app, monkeypatch):
|
||||
"""重试通道:处理函数仍未成功时必须继续携带清单重抛,绝不在未完成时返回 ok。"""
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import (
|
||||
OnhandReportDispatchAfterCommitError,
|
||||
process_rpa_report_inventory_batch,
|
||||
)
|
||||
|
||||
def boom(_fact) -> None:
|
||||
raise RuntimeError('onhand handler still down')
|
||||
|
||||
register_report_handler('onhand', boom)
|
||||
|
||||
with app.app_context():
|
||||
file_id = _onhand_file_id()
|
||||
marker = {'source_code': 'DSV360_AWSDU', 'file_id': file_id, 'sha256': None}
|
||||
|
||||
# [断言意图] 处理函数持续失败:重试通道继续抛专用异常(携带同一未成功清单,
|
||||
# Job 据此继续 requeue 直至 attempts 耗尽落终态 failed)——绝不返回 ok。
|
||||
with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo:
|
||||
process_rpa_report_inventory_batch({'retry_dispatch_files': [marker]})
|
||||
assert excinfo.value.failed_files == [marker]
|
||||
|
||||
|
||||
def test_callback_process_job_records_failed_files_for_retry(app, monkeypatch):
|
||||
"""Job 收口:投递失败重抛的清单写回 payload(retry_dispatch_files)并 requeue 可重试。"""
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers import freight_rpa_onhand_callback_process as handler
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import OnhandReportDispatchAfterCommitError
|
||||
|
||||
marker = {'source_code': 'DSV360_AWSDU', 'file_id': 4242, 'sha256': 'a' * 64}
|
||||
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
domain='shipping_notice',
|
||||
job_type='freight_rpa_onhand_callback_process',
|
||||
status='running',
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
business_ref='inventory-callback:dispatch-retry-check',
|
||||
payload_json={'callback_id': 'dispatch-retry-check'},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
def _raise_dispatch_error(_payload):
|
||||
raise OnhandReportDispatchAfterCommitError(
|
||||
'onhand handler down after commit', failed_files=[dict(marker)],
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch',
|
||||
_raise_dispatch_error,
|
||||
)
|
||||
|
||||
handler.run_shipping_inventory_callback_process(
|
||||
JobContext(config={}, logger=None, extras={}), {'job_id': job.id},
|
||||
)
|
||||
db.session.expire_all()
|
||||
# [断言意图] 清单写回 payload(重试只重投这些文件)+ requeue 可重试。
|
||||
refreshed = db.session.get(Job, job.id)
|
||||
assert refreshed.status == 'queued'
|
||||
assert refreshed.payload_json['retry_dispatch_files'] == [marker]
|
||||
@@ -418,7 +418,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta
|
||||
|
||||
facts = _project_case_formal_gate_facts({
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_source_routing',
|
||||
'gate_code': 'onhand_source_routing',
|
||||
'status': 'pending',
|
||||
'blocking_reason_code': None,
|
||||
'next_action_code': None,
|
||||
@@ -430,7 +430,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta
|
||||
|
||||
assert facts is not None
|
||||
current_gate, blocking_reason, user_status = facts
|
||||
assert current_gate['gate_code'] == 'inventory_source_routing'
|
||||
assert current_gate['gate_code'] == 'onhand_source_routing'
|
||||
assert blocking_reason['code'] is None
|
||||
assert user_status == 'running'
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""
|
||||
tests/services/shipping_notice/test_report_model_boundary.py
|
||||
|
||||
用途:阶段 B Task 5 边界门禁——禁止发货域(shipping_notice)源码直接构造
|
||||
货代 RPA 报表模型行(FreightRpaOnhandReportFile / FreightRpaInboundReportFile /
|
||||
FreightRpaInboundReportConfig 的构造调用)。插入必须经
|
||||
freight_rpa/onhand/report_store,读取/下载必须走 freight_rpa/reports 查询面。
|
||||
依赖:无运行时依赖(纯文件系统扫描);backend/app/services/shipping_notice 源码。
|
||||
逻辑:rglob 全部 *.py 逐文件搜禁词构造片段;命中即失败并列出文件与片段,
|
||||
保证违规时能一眼定位,而不是只报一个计数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_shipping_notice_does_not_construct_rpa_report_rows():
|
||||
root = Path(__file__).resolve().parents[3] / "app" / "services" / "shipping_notice"
|
||||
banned_snippets = ("FreightRpaOnhandReportFile(", "FreightRpaInboundReportFile(", "FreightRpaInboundReportConfig(")
|
||||
hits = []
|
||||
for path in root.rglob("*.py"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
for snippet in banned_snippets:
|
||||
if snippet in text:
|
||||
hits.append(f"{path.name}: {snippet}")
|
||||
# 关键断言:三类 RPA 报表行的构造调用必须全部消失(插入已收敛进 report_store)。
|
||||
assert hits == []
|
||||
@@ -0,0 +1,202 @@
|
||||
"""
|
||||
tests/test_admin_freight_rpa_onhand_config.py
|
||||
|
||||
用途:锁定 s18 后库存站点启用门禁与在手报表配置行(FreightRpaOnhandReportConfig)的服务层行为。
|
||||
依赖:conftest 的 app fixture(建表并播种 TEST_RUNTIME 配置)、app.core.errors.ValidationError、
|
||||
shipping_onhand_admin_service(assert_onhand_source_can_enable / save_onhand_report_config /
|
||||
save_receipt_report_config)、FreightRpaOnhandReportConfig / FreightRpaSource 等模型。
|
||||
逻辑:验证启用中站点缺模板/缺配置行/缺解析绑定时 fail-closed;保存在手配置只写配置行、
|
||||
不写站点已删除的三列,并递增配置行 config_version;在手与入站两侧解析方案 purpose 互斥。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaParsingProfile, FreightRpaProfile,
|
||||
)
|
||||
from app.services.admin.shipping_onhand_admin_service import (
|
||||
assert_onhand_source_can_enable, save_onhand_report_config, save_receipt_report_config,
|
||||
)
|
||||
|
||||
# 站点/连接编码自增,保证同一测试内多次构造不撞唯一约束。
|
||||
_SOURCE_SEQUENCE = itertools.count(1)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(app):
|
||||
"""复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。"""
|
||||
from app import db
|
||||
|
||||
return db.session
|
||||
|
||||
|
||||
def _source(*, enabled: bool, excel_template_id: int | None) -> FreightRpaSource:
|
||||
"""构造最小可落库的库存站点(fixed 仓库模式 + 专用连接 Profile),不自动 add 进会话。
|
||||
|
||||
Args:
|
||||
enabled: 站点启用位;True 时调用方需自行保证模板/配置满足门禁或预期拒绝。
|
||||
excel_template_id: 发货模板外键;SQLite 测试库不强制外键,允许指向不存在的模板 id。
|
||||
|
||||
Returns:
|
||||
FreightRpaSource: 未加入会话的站点对象,由调用方决定是否落库。
|
||||
"""
|
||||
from app import db
|
||||
|
||||
sequence = next(_SOURCE_SEQUENCE)
|
||||
profile = FreightRpaProfile(
|
||||
profile_code=f'TASK2_PROFILE_{sequence}', display_name=f'Task2 Profile {sequence}',
|
||||
connector_type='dbs', login_url='https://test.invalid/dbs',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
return FreightRpaSource(
|
||||
source_code=f'TASK2_SOURCE_{sequence}', display_name=f'Task2 Source {sequence}',
|
||||
connector_type='dbs', rpa_profile_id=profile.id, excel_template_id=excel_template_id,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU',
|
||||
enabled=enabled,
|
||||
)
|
||||
|
||||
|
||||
def _published_onhand_profile_id() -> int:
|
||||
"""读取 conftest 播种的已发布在手解析方案(TEST_RUNTIME,purpose='onhand')。"""
|
||||
profile = FreightRpaParsingProfile.query.filter_by(
|
||||
profile_code='TEST_RUNTIME', status='published',
|
||||
).first()
|
||||
assert profile is not None and profile.purpose == 'onhand'
|
||||
return profile.id
|
||||
|
||||
|
||||
def _published_inbound_profile_id(db_session) -> int:
|
||||
"""创建最小已发布入站解析方案,用于验证在手侧 fail-closed 拒绝跨 purpose 绑定。"""
|
||||
profile = FreightRpaParsingProfile(
|
||||
purpose='inbound', profile_code='TASK2_INBOUND', display_name='Task2 Inbound',
|
||||
version=1, status='published', file_format='xlsx', definition_json={'field_mapping': {}},
|
||||
)
|
||||
db_session.add(profile)
|
||||
db_session.commit()
|
||||
return profile.id
|
||||
|
||||
|
||||
def test_enabled_source_requires_onhand_profile_and_template(app, db_session):
|
||||
"""启用中站点缺发货模板必须被服务层拒绝。
|
||||
|
||||
[断言意图] 该状态同时违反 ck_freight_rpa_sources_enabled_template(enabled ⇒ 模板非空),
|
||||
SQLite/PG 在 INSERT 时即拦截、无法落库,故按 save_source 提交前的调用形态验证未落库对象,
|
||||
与任务书原测试语义一致(服务层门禁先于数据库约束给出可解释错误码)。
|
||||
"""
|
||||
source = _source(enabled=True, excel_template_id=None)
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
assert_onhand_source_can_enable(source)
|
||||
assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED"
|
||||
|
||||
|
||||
def test_enabled_source_requires_onhand_report_config_row(app, db_session):
|
||||
"""启用中站点缺在手配置行时拒绝启用:配置行缺失是跨表状态,站点 CHECK 管不到。"""
|
||||
source = _source(enabled=True, excel_template_id=9)
|
||||
db_session.add(source)
|
||||
db_session.commit()
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
assert_onhand_source_can_enable(source)
|
||||
assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED"
|
||||
|
||||
|
||||
def test_enabled_source_requires_onhand_profile_binding(app, db_session):
|
||||
"""配置行存在但未绑解析方案时同样拒绝启用。"""
|
||||
source = _source(enabled=True, excel_template_id=9)
|
||||
db_session.add(source)
|
||||
db_session.commit()
|
||||
db_session.add(FreightRpaOnhandReportConfig(source=source))
|
||||
db_session.commit()
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
assert_onhand_source_can_enable(source)
|
||||
assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED"
|
||||
|
||||
|
||||
def test_enabled_source_with_full_onhand_config_passes_gate(app, db_session):
|
||||
"""配置行 + 解析绑定 + 模板齐备的启用站点通过门禁(正向路径回归)。"""
|
||||
source = _source(enabled=True, excel_template_id=9)
|
||||
db_session.add(source)
|
||||
db_session.commit()
|
||||
db_session.add(FreightRpaOnhandReportConfig(
|
||||
source=source, parsing_profile_id=_published_onhand_profile_id(),
|
||||
))
|
||||
db_session.commit()
|
||||
assert assert_onhand_source_can_enable(source) is None
|
||||
|
||||
|
||||
def test_save_onhand_report_config_does_not_write_source_columns(app, db_session):
|
||||
"""保存在手配置只写配置行,不写站点已删除的 report_path_json 等三列。"""
|
||||
source = _source(enabled=False, excel_template_id=9)
|
||||
db_session.add(source)
|
||||
db_session.commit()
|
||||
save_onhand_report_config(source.id, {
|
||||
"report_path_json": {"menu": "stock"},
|
||||
"query_parameters_json": [],
|
||||
"parsing_profile_id": _published_onhand_profile_id(),
|
||||
}, actor_id=1)
|
||||
db_session.refresh(source)
|
||||
assert not hasattr(source, "report_path_json")
|
||||
config = FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).one()
|
||||
assert config.report_path_json == {"menu": "stock"}
|
||||
assert config.parsing_profile.purpose == "onhand"
|
||||
|
||||
|
||||
def test_save_onhand_report_config_updates_row_and_bumps_config_version(app, db_session):
|
||||
"""已有配置行走更新并递增 config_version,行身份保持不变。"""
|
||||
source = _source(enabled=False, excel_template_id=9)
|
||||
db_session.add(source)
|
||||
db_session.commit()
|
||||
first = save_onhand_report_config(source.id, {
|
||||
"report_path_json": {"menu": "stock"},
|
||||
"query_parameters_json": [],
|
||||
"parsing_profile_id": _published_onhand_profile_id(),
|
||||
}, actor_id=1)
|
||||
second = save_onhand_report_config(source.id, {
|
||||
"report_path_json": {"menu": "stock2"},
|
||||
"query_parameters_json": [],
|
||||
"parsing_profile_id": _published_onhand_profile_id(),
|
||||
}, actor_id=1)
|
||||
assert second["id"] == first["id"]
|
||||
row = FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).one()
|
||||
assert row.report_path_json == {"menu": "stock2"}
|
||||
# [断言意图] 首次插入默认 1,第二次保存必须递增为 2(任务书:有则更新并递增 config_version)。
|
||||
assert row.config_version == 2
|
||||
|
||||
|
||||
def test_save_onhand_report_config_rejects_non_onhand_parsing_profile(app, db_session):
|
||||
"""入站解析方案不得绑进在手配置;fail-closed 且不留下半写的配置行。"""
|
||||
source = _source(enabled=False, excel_template_id=9)
|
||||
db_session.add(source)
|
||||
db_session.commit()
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
save_onhand_report_config(source.id, {
|
||||
"report_path_json": {},
|
||||
"query_parameters_json": [],
|
||||
"parsing_profile_id": _published_inbound_profile_id(db_session),
|
||||
}, actor_id=1)
|
||||
assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED"
|
||||
assert FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).count() == 0
|
||||
|
||||
|
||||
def test_save_receipt_report_config_keeps_inbound_only_binding(app, db_session):
|
||||
"""收料配置保存继续只接受 purpose='inbound' 的解析方案(在手/入站互斥回归)。"""
|
||||
source = _source(enabled=False, excel_template_id=9)
|
||||
db_session.add(source)
|
||||
db_session.commit()
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
save_receipt_report_config(source.id, {
|
||||
# 先给合法 DBS 四段路径,确保失败点落在解析绑定校验(purpose 互斥)而非路径校验。
|
||||
"report_path_json": {
|
||||
"program_group": "Bison", "program_label": "AWSBI",
|
||||
"report_group": "Inbound", "report_name": "Receipt Detail",
|
||||
},
|
||||
"query_parameters_json": [],
|
||||
"parsing_profile_id": _published_onhand_profile_id(),
|
||||
}, actor_id=1)
|
||||
assert exc.value.code == "SHIPPING.INBOUND_PROFILE_INVALID"
|
||||
@@ -0,0 +1,86 @@
|
||||
"""
|
||||
tests/test_admin_freight_rpa_routes.py
|
||||
|
||||
用途:锁定货代 RPA 管理路由已迁到 /api/admin/freight-rpa/,旧 shipping-notice 管理路径 404。
|
||||
依赖:Flask 测试客户端、admin blueprint、User。
|
||||
逻辑:只断言路径注册与管理员可达;权限表存量字符串不在本测试更新。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _headers(username: str, role: str) -> dict[str, str]:
|
||||
"""构造遗留 Header 认证上下文,匹配现有管理 API 测试方式。"""
|
||||
return {'X-Username': username, 'X-Role': role}
|
||||
|
||||
|
||||
def _rules(app) -> set[str]:
|
||||
"""收集已注册的 URL 规则,用来断言旧路径没有双路由。"""
|
||||
return {rule.rule for rule in app.url_map.iter_rules()}
|
||||
|
||||
|
||||
def test_freight_rpa_admin_routes_moved_and_old_paths_404(app, client):
|
||||
"""新 sources 路径对管理员成功;旧 sources 与 inventory-fields 404;onhand/fields 已注册。"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
db.session.add(User(
|
||||
username='freight-rpa-admin',
|
||||
email='freight-rpa-admin@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
headers = _headers('freight-rpa-admin', 'admin')
|
||||
listed = client.get('/api/admin/freight-rpa/sources', headers=headers)
|
||||
# [断言意图] 管理员读取新 sources 列表必须走统一成功 envelope。
|
||||
assert listed.status_code == 200
|
||||
body = listed.get_json()
|
||||
assert body['success'] is True
|
||||
assert isinstance(body['data'], list)
|
||||
|
||||
# [断言意图] 旧库存源路径无兼容路由。
|
||||
assert client.get('/api/admin/shipping-notice/sources', headers=headers).status_code == 404
|
||||
# [断言意图] 旧字段目录路径无兼容路由。
|
||||
assert client.get('/api/admin/shipping-notice/inventory-fields', headers=headers).status_code == 404
|
||||
|
||||
rules = _rules(app)
|
||||
# [断言意图] 字段目录已挂到 onhand/fields,且旧规则不在 url map。
|
||||
assert '/api/admin/freight-rpa/onhand/fields' in rules
|
||||
assert '/api/admin/shipping-notice/inventory-fields' not in rules
|
||||
assert '/api/admin/shipping-notice/sources' not in rules
|
||||
# [断言意图] 任务表里的旧前缀都不能再注册(含其子路径)。
|
||||
retired_prefixes = (
|
||||
'/api/admin/shipping-notice/sources',
|
||||
'/api/admin/shipping-notice/source-validation-batches',
|
||||
'/api/admin/shipping-notice/snapshots',
|
||||
'/api/admin/shipping-notice/export-records',
|
||||
'/api/admin/shipping-notice/routing-rules',
|
||||
'/api/admin/shipping-notice/routing-fields',
|
||||
'/api/admin/shipping-notice/inventory-fields',
|
||||
'/api/admin/shipping-notice/configuration-catalog',
|
||||
'/api/admin/shipping-notice/parsing-profiles',
|
||||
'/api/admin/shipping-notice/inventory-structure-analyses',
|
||||
'/api/admin/shipping-notice/external-mappings',
|
||||
)
|
||||
for rule in rules:
|
||||
for prefix in retired_prefixes:
|
||||
assert rule != prefix and not rule.startswith(prefix + '/'), rule
|
||||
assert '/api/admin/freight-rpa/sources/<int:source_id>/inbound-report-config' in rules
|
||||
assert '/api/admin/freight-rpa/onhand/validation-batches' in rules
|
||||
|
||||
fields = client.get('/api/admin/freight-rpa/onhand/fields', headers=headers)
|
||||
assert fields.status_code == 200
|
||||
assert fields.get_json()['success'] is True
|
||||
|
||||
# [断言意图] 临时会话只改词根,仍留在 shipping-notice;Excel 模板与异动字段不动。
|
||||
assert '/api/admin/shipping-notice/temporary-onhand-sessions' in rules
|
||||
assert '/api/admin/shipping-notice/temporary-inventory-sessions' not in rules
|
||||
assert '/api/admin/shipping-notice/excel-templates' in rules
|
||||
assert '/api/admin/shipping-notice/movement-fields' in rules
|
||||
# [断言意图] rpa-profiles 仍在 freight-rpa,不重复注册到 shipping-notice。
|
||||
assert '/api/admin/freight-rpa/rpa-profiles' in rules
|
||||
assert '/api/admin/shipping-notice/rpa-profiles' not in rules
|
||||
@@ -26,7 +26,7 @@ from app.models import (
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
ShippingNotice,
|
||||
User,
|
||||
)
|
||||
@@ -148,12 +148,12 @@ def _notice_with_customer(*, task_no: str, customer_id: int, business_no: str |
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
onhand_status='ready',
|
||||
is_current=True,
|
||||
))
|
||||
notice = ShippingNotice(task_no=task_no, business_no=business_no, order_task_id=task.id)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
tests/test_admin_shipping_inventory.py
|
||||
|
||||
用途:验证货代库存后台的只读快照/导出记录接口及管理员权限。
|
||||
用途:验证货代 RPA 管理端只读快照/导出记录、配置目录与站点保存接口。
|
||||
依赖:Flask 测试客户端、库存文件和排程运行模型。
|
||||
逻辑:库存快照来自库存文件;没有库存文件的失败 RPA 运行也必须出现在导出记录中。
|
||||
逻辑:请求打到 /api/admin/freight-rpa/;快照来自在手文件,失败排程即使没有文件也出现在导出记录中。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,8 +12,8 @@ from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, User
|
||||
from app.models import ShippingInventorySource, ShippingRpaProfile
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, User
|
||||
from app.models import FreightRpaSource, FreightRpaProfile
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
@@ -39,8 +39,8 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p
|
||||
_create_users()
|
||||
snapshot_file = Path(tmp_path) / 'snapshot.xlsx'
|
||||
snapshot_file.write_bytes(b'admin-snapshot')
|
||||
file_record = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-ADMIN-READY', storage_path=str(snapshot_file), source_code='DBS_DUB',
|
||||
file_record = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-ADMIN-READY', storage_path=str(snapshot_file), source_code='DBS_DUB',
|
||||
warehouse_id='DUB', snapshot_status='ready', identity_status='verified',
|
||||
exported_at=datetime(2026, 7, 17, 10, 0, 0), rpa_run_no='RUN-READY-01',
|
||||
)
|
||||
@@ -57,23 +57,23 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
for path in ('/api/admin/shipping-notice/snapshots', '/api/admin/shipping-notice/export-records'):
|
||||
for path in ('/api/admin/freight-rpa/onhand/snapshots', '/api/admin/freight-rpa/onhand/export-records'):
|
||||
forbidden = client.get(path, headers=_headers('inventory-user', 'user'))
|
||||
assert forbidden.status_code == 403
|
||||
assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN'
|
||||
|
||||
snapshots = client.get('/api/admin/shipping-notice/snapshots', headers=_headers('inventory-admin', 'admin'))
|
||||
snapshots = client.get('/api/admin/freight-rpa/onhand/snapshots', headers=_headers('inventory-admin', 'admin'))
|
||||
assert snapshots.status_code == 200
|
||||
snapshot_rows = parse_api_data(snapshots.get_json())
|
||||
assert snapshot_rows[0]['inventory_file_no'] == 'SIF-ADMIN-READY'
|
||||
assert 'storage_path' not in snapshot_rows[0]
|
||||
assert snapshot_rows[0]['download_available'] is True
|
||||
|
||||
downloaded = client.get('/api/admin/shipping-notice/snapshots/1/download', headers=_headers('inventory-admin', 'admin'))
|
||||
downloaded = client.get('/api/admin/freight-rpa/onhand/snapshots/1/download', headers=_headers('inventory-admin', 'admin'))
|
||||
assert downloaded.status_code == 200
|
||||
assert downloaded.data == b'admin-snapshot'
|
||||
|
||||
exports = client.get('/api/admin/shipping-notice/export-records', headers=_headers('inventory-admin', 'admin'))
|
||||
exports = client.get('/api/admin/freight-rpa/onhand/export-records', headers=_headers('inventory-admin', 'admin'))
|
||||
assert exports.status_code == 200
|
||||
export_rows = parse_api_data(exports.get_json())
|
||||
failed_row = next(item for item in export_rows if item['rpa_run_no'] == 'RUN-FAILED-01')
|
||||
@@ -104,7 +104,7 @@ def test_inventory_configuration_catalog_is_admin_only_and_backend_controlled(ap
|
||||
}], 'expected_lock_version': draft['lock_version']})
|
||||
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
|
||||
path = '/api/admin/shipping-notice/configuration-catalog'
|
||||
path = '/api/admin/freight-rpa/onhand/configuration-catalog'
|
||||
forbidden = client.get(path, headers=_headers('inventory-user', 'user'))
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
@@ -128,8 +128,8 @@ def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app
|
||||
order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
|
||||
for path in (
|
||||
'/api/admin/shipping-notice/routing-fields',
|
||||
'/api/admin/shipping-notice/configuration-catalog',
|
||||
'/api/admin/freight-rpa/onhand/routing-fields',
|
||||
'/api/admin/freight-rpa/onhand/configuration-catalog',
|
||||
):
|
||||
response = client.get(path, headers=_headers('inventory-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
@@ -143,7 +143,7 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
profile = ShippingRpaProfile(
|
||||
profile = FreightRpaProfile(
|
||||
profile_code='API_ACTIVATION_LOGIN', display_name='API Activation', connector_type='dbs',
|
||||
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
|
||||
)
|
||||
@@ -162,7 +162,7 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
|
||||
},
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
created = client.post('/api/admin/shipping-notice/sources', json=payload, headers=_headers('inventory-admin', 'admin'))
|
||||
created = client.post('/api/admin/freight-rpa/sources', json=payload, headers=_headers('inventory-admin', 'admin'))
|
||||
assert created.status_code == 201
|
||||
source = parse_api_data(created.get_json())
|
||||
assert source['enabled'] is False
|
||||
@@ -171,12 +171,12 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
|
||||
assert 'configuration_test' not in {item['code'] for item in source['activation']['checks']}
|
||||
|
||||
activation = client.post(
|
||||
f"/api/admin/shipping-notice/sources/{source['id']}/activate",
|
||||
f"/api/admin/freight-rpa/sources/{source['id']}/activate",
|
||||
json={}, headers=_headers('inventory-admin', 'admin'),
|
||||
)
|
||||
assert activation.status_code == 409
|
||||
error = parse_api_error(activation.get_json())
|
||||
assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
|
||||
assert error['code'] == 'SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED'
|
||||
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
|
||||
|
||||
@@ -185,25 +185,25 @@ def test_latest_inventory_configuration_test_is_admin_only(app, client):
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
profile = ShippingRpaProfile(
|
||||
profile = FreightRpaProfile(
|
||||
profile_code='API_LATEST_TEST_LOGIN', display_name='Latest Test', connector_type='dbs',
|
||||
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
|
||||
)
|
||||
db.session.add(profile)
|
||||
source = ShippingInventorySource(
|
||||
# s18 起站点行不再承载报表路径/查询条件;本用例只验证权限与空 envelope,无需配置行。
|
||||
source = FreightRpaSource(
|
||||
source_code='API_LATEST_TEST_SOURCE', display_name='Latest Test Source', connector_type='dbs',
|
||||
rpa_profile=profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
||||
query_parameters_json=[], enabled=False,
|
||||
enabled=False,
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
source_id = source.id
|
||||
|
||||
forbidden = client.get(f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest')
|
||||
forbidden = client.get(f'/api/admin/freight-rpa/sources/{source_id}/test-export/latest')
|
||||
assert forbidden.status_code in {401, 403}
|
||||
response = client.get(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest',
|
||||
f'/api/admin/freight-rpa/sources/{source_id}/test-export/latest',
|
||||
headers=_headers('inventory-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
"""
|
||||
收料报表配置管理接口测试。
|
||||
|
||||
用途:验证站点内独立收料配置的权限、DBS/Crane 规则及不可影响库存配置的边界。
|
||||
用途:验证站点内独立入站报表配置的权限、DBS/Crane 规则及不可影响在手配置的边界。
|
||||
依赖:Flask 管理 API、库存站点测试种子、货代统一审计事件。
|
||||
逻辑:配置保存只更新 shipping_receipt_report_configs,并留存前后快照审计。
|
||||
逻辑:请求打到 /api/admin/freight-rpa/sources/<id>/inbound-report-config;保存只更新入站配置并留存前后快照审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingAuditEvent, ShippingInventorySource, User
|
||||
from app.models import ShippingAuditEvent, FreightRpaSource, User
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
|
||||
@@ -49,21 +49,23 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
# s18 起在手报表路径/查询条件归 onhand_report_config 配置行,站点行不再承载。
|
||||
onhand_config = source.onhand_report_config
|
||||
inventory_before = {
|
||||
'path': dict(source.report_path_json), 'parameters': list(source.query_parameters_json),
|
||||
'path': dict(onhand_config.report_path_json), 'parameters': list(onhand_config.query_parameters_json),
|
||||
'config_version': source.config_version,
|
||||
}
|
||||
|
||||
forbidden = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
|
||||
json=_dbs_payload(), headers=_headers('receipt-user', 'user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
|
||||
json=_dbs_payload(), headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
@@ -74,13 +76,14 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
assert config['report_path_json']['report_group'] == 'Inbound'
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.get(source_id)
|
||||
# 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义。
|
||||
assert source.report_path_json == inventory_before['path']
|
||||
assert source.query_parameters_json == inventory_before['parameters']
|
||||
source = FreightRpaSource.query.get(source_id)
|
||||
# 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义(s18 起读配置行)。
|
||||
onhand_config = source.onhand_report_config
|
||||
assert onhand_config.report_path_json == inventory_before['path']
|
||||
assert onhand_config.query_parameters_json == inventory_before['parameters']
|
||||
assert source.config_version == inventory_before['config_version']
|
||||
audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
|
||||
event_type='shipping_inbound_report_config_saved', aggregate_id=str(source_id),
|
||||
).one()
|
||||
assert audit.before_snapshot_json is None
|
||||
assert audit.after_snapshot_json['query_parameters_json'][0]['values'] == ['AWSDU', 'AWSDU-02']
|
||||
@@ -91,17 +94,18 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
dbs_id = dbs.id
|
||||
from app import db
|
||||
crane_profile = dbs.rpa_profile.__class__(
|
||||
profile_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane',
|
||||
login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
# s18 起站点行不再承载报表路径/查询条件;收料配置测试无需在手配置行。
|
||||
crane_source = FreightRpaSource(
|
||||
source_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane',
|
||||
rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE',
|
||||
report_path_json={}, query_parameters_json=[], enabled=False,
|
||||
enabled=False,
|
||||
)
|
||||
db.session.add(crane_source)
|
||||
db.session.commit()
|
||||
@@ -110,7 +114,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
invalid_date = _dbs_payload()
|
||||
invalid_date['query_parameters_json'] = [{'name': 'Report Date', 'mode': 'single', 'values': ['2026-08-19'], 'required': False, 'select_all': False}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config',
|
||||
json=invalid_date, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
@@ -119,7 +123,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
invalid_selector = _dbs_payload()
|
||||
invalid_selector['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': [], 'selector': '#owner'}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config',
|
||||
json=invalid_selector, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
@@ -129,7 +133,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
missing_warehouse = _dbs_payload()
|
||||
missing_warehouse['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config',
|
||||
json=missing_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
@@ -139,7 +143,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
empty_warehouse = _dbs_payload()
|
||||
empty_warehouse['query_parameters_json'] = [{'name': 'Warehouse', 'mode': 'multi_text', 'values': [], 'required': False, 'select_all': False}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config',
|
||||
json=empty_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
@@ -151,7 +155,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config',
|
||||
json=invalid_crane, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
@@ -161,9 +165,9 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
def _create_parsing_profile(profile_code: str, *, status: str, purpose: str):
|
||||
"""创建入站/在手解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
from app.models import FreightRpaParsingProfile
|
||||
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
purpose=purpose, profile_code=profile_code, display_name=f'{profile_code} 规则',
|
||||
version=1, status=status, file_format='xlsx',
|
||||
definition_json={'sheet_name': 'Movement', 'header_row_index': 1,
|
||||
@@ -181,14 +185,14 @@ def test_receipt_config_binds_published_inbound_profile(app, client):
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
profile = _create_parsing_profile('CRANE_MOVE_STD', status='published', purpose='inbound')
|
||||
profile_id = profile.id
|
||||
|
||||
payload = {**_dbs_payload(), 'parsing_profile_id': profile_id}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
|
||||
json=payload, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
@@ -200,7 +204,7 @@ def test_receipt_config_binds_published_inbound_profile(app, client):
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
|
||||
event_type='shipping_inbound_report_config_saved', aggregate_id=str(source_id),
|
||||
).order_by(ShippingAuditEvent.id.desc()).first()
|
||||
assert audit.metadata_json['parsing_profile_id'] == profile_id
|
||||
|
||||
@@ -210,7 +214,7 @@ def test_receipt_config_rejects_draft_or_non_inbound_profile(app, client):
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
draft = _create_parsing_profile('MOVE_DRAFT', status='draft', purpose='inbound')
|
||||
onhand_profile = _create_parsing_profile('INV_PUBLISHED', status='published', purpose='onhand')
|
||||
@@ -218,7 +222,7 @@ def test_receipt_config_rejects_draft_or_non_inbound_profile(app, client):
|
||||
|
||||
for profile_id in cases:
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
@@ -232,20 +236,20 @@ def test_receipt_config_empty_profile_id_unbinds(app, client):
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
profile = _create_parsing_profile('MOVE_UNBIND', status='published', purpose='inbound')
|
||||
profile_id = profile.id
|
||||
|
||||
bound = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert bound.status_code == 200
|
||||
|
||||
unbound = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': None},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
@@ -260,15 +264,16 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
from app import db
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = dbs.rpa_profile.__class__(
|
||||
profile_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane',
|
||||
login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
# s18 起站点行不再承载报表路径/查询条件;收料配置测试无需在手配置行。
|
||||
crane_source = FreightRpaSource(
|
||||
source_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane',
|
||||
rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE',
|
||||
report_path_json={}, query_parameters_json=[], enabled=False,
|
||||
enabled=False,
|
||||
)
|
||||
db.session.add(crane_source)
|
||||
db.session.commit()
|
||||
@@ -279,7 +284,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config',
|
||||
json=default_query, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
@@ -289,7 +294,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
{'name': 'material', 'mode': 'single', 'values': ['PN-01'], 'required': False, 'select_all': False},
|
||||
]}
|
||||
rejected = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config',
|
||||
json=configured, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert rejected.status_code == 400
|
||||
@@ -299,22 +304,22 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
def test_retire_rejects_profile_bound_by_receipt_report_config(app):
|
||||
"""绑定收料报表配置的 published 解析 Profile 退役必须被拒(退役守卫补查)。
|
||||
|
||||
背景:retire 此前只核查库存源(ShippingInventorySource)绑定,遗漏了
|
||||
收料报表配置(ShippingReceiptReportConfig.parsing_profile_id)——入站文件
|
||||
背景:retire 此前只核查库存源(FreightRpaSource)绑定,遗漏了
|
||||
收料报表配置(FreightRpaInboundReportConfig.parsing_profile_id)——入站文件
|
||||
解析链会因规则退役静默失去规则。守卫补查后两者任一绑定都返回
|
||||
SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED。
|
||||
SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportConfig
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
from app.models import FreightRpaInboundReportConfig
|
||||
from app.services.shipping_notice import onhand_parsing_profile
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
profile = _create_parsing_profile('MOVE_RETIRE_GUARD', status='published', purpose='inbound')
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, parsing_profile_id=profile.id,
|
||||
db.session.add(FreightRpaInboundReportConfig(
|
||||
source_id=source.id, parsing_profile_id=profile.id,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -322,8 +327,8 @@ def test_retire_rejects_profile_bound_by_receipt_report_config(app):
|
||||
|
||||
# 关键断言:仅绑定收料配置(无库存源绑定)也必须拒绝退役,沿用既有错误码。
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
inventory_parsing_profile.retire(profile_id)
|
||||
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED'
|
||||
onhand_parsing_profile.retire(profile_id)
|
||||
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED'
|
||||
|
||||
# 关键断言:被拒后 Profile 状态保持 published,不得被半退役。
|
||||
assert ShippingReceiptReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1
|
||||
assert FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1
|
||||
@@ -197,7 +197,7 @@ def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, clie
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_inventory_file',
|
||||
'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_onhand_file',
|
||||
fake_upload_inventory,
|
||||
)
|
||||
res = client.post(
|
||||
|
||||
@@ -22,7 +22,7 @@ from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryParsingProfile,
|
||||
FreightRpaParsingProfile,
|
||||
ShippingNotice,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
@@ -154,7 +154,7 @@ def _attach_ready_export_artifact(notice: ShippingNotice) -> None:
|
||||
from app.models import ShippingOrderSchemaVersion, ShippingOrderExtraction
|
||||
|
||||
template = _template_row()
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code='REBIND_PROFILE', display_name='Rebind profile', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
|
||||
@@ -10,27 +10,29 @@ def _headers(username: str, role: str) -> dict[str, str]:
|
||||
def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client, monkeypatch):
|
||||
"""排程接收人可下载原样文件;非接收人不可通过猜测 ID 越权。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-download-user', email='receipt-download@example.com', role='user', status='active')
|
||||
other = User(username='receipt-other-user', email='receipt-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-DL', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-download', status='success', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-download', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/download.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='b' * 64)
|
||||
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/download.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='b' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
file_id = report_file.id
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_access.file_asset_storage.get_bytes', lambda _key: b'xlsx')
|
||||
# 阶段 B Task 5:inbound_report_access 改经 freight_rpa/reports.read_inbound_file_bytes 读字节,
|
||||
# monkeypatch 目标随之改到存储单例本身(所有 import 方共享同一实例,补丁全链路生效)。
|
||||
monkeypatch.setattr('app.services.file_assets.storage.file_asset_storage.get_bytes', lambda _key: b'xlsx')
|
||||
|
||||
allowed = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-download-user', 'user'))
|
||||
denied = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-other-user', 'user'))
|
||||
allowed = client.get(f'/api/workspace/inbound-report-files/{file_id}/download', headers=_headers('receipt-download-user', 'user'))
|
||||
denied = client.get(f'/api/workspace/inbound-report-files/{file_id}/download', headers=_headers('receipt-other-user', 'user'))
|
||||
assert allowed.status_code == 200
|
||||
assert allowed.data == b'xlsx'
|
||||
assert denied.status_code == 403
|
||||
@@ -39,62 +41,62 @@ def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client,
|
||||
def test_receipt_recipient_lists_only_own_archived_files(app, client):
|
||||
"""接收人文件列表仅返回本人排程归档,并且不得泄露对象存储定位。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-list-user', email='receipt-list@example.com', role='user', status='active')
|
||||
other = User(username='receipt-list-other', email='receipt-list-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
db.session.add_all([own_run, other_run]); db.session.flush()
|
||||
own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-list-own', status='success', config_snapshot_json={})
|
||||
other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-list-other', status='success', config_snapshot_json={})
|
||||
own_unit = FreightRpaInboundUnitRun(schedule_run_id=own_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-list-own', status='success', config_snapshot_json={})
|
||||
other_unit = FreightRpaInboundUnitRun(schedule_run_id=other_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-list-other', status='success', config_snapshot_json={})
|
||||
db.session.add_all([own_unit, other_unit]); db.session.flush()
|
||||
own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='d' * 64)
|
||||
db.session.add_all([own_file, ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-other.xlsx', original_filename='other.xlsx', file_size=4, sha256='e' * 64)])
|
||||
own_file = FreightRpaInboundReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='d' * 64)
|
||||
db.session.add_all([own_file, FreightRpaInboundReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-other.xlsx', original_filename='other.xlsx', file_size=4, sha256='e' * 64)])
|
||||
db.session.commit()
|
||||
own_file_id = own_file.id
|
||||
|
||||
response = client.get('/api/workspace/receipt-report-files', headers=_headers('receipt-list-user', 'user'))
|
||||
response = client.get('/api/workspace/inbound-report-files', headers=_headers('receipt-list-user', 'user'))
|
||||
|
||||
assert response.status_code == 200
|
||||
items = response.get_json()['data']['items']
|
||||
# 关键断言:列表投影不能泄露非接收人的文件或对象存储定位。
|
||||
assert [item['id'] for item in items] == [own_file_id]
|
||||
assert 'storage_key' not in items[0]
|
||||
assert items[0]['download_url'].endswith(f'/receipt-report-files/{own_file_id}/download')
|
||||
assert items[0]['download_url'].endswith(f'/inbound-report-files/{own_file_id}/download')
|
||||
|
||||
|
||||
def test_receipt_file_list_filters_before_applying_limit(app):
|
||||
"""其他人的新文件再多,也不能挤掉接收人较早的可见归档。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User
|
||||
from app.services.shipping_notice.inbound_report_access import list_receipt_report_files
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-limit-user', email='receipt-limit@example.com', role='user', status='active')
|
||||
other = User(username='receipt-limit-other', email='receipt-limit-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
db.session.add_all([own_run, other_run]); db.session.flush()
|
||||
own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-limit-own', status='success', config_snapshot_json={})
|
||||
other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-limit-other', status='success', config_snapshot_json={})
|
||||
own_unit = FreightRpaInboundUnitRun(schedule_run_id=own_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-limit-own', status='success', config_snapshot_json={})
|
||||
other_unit = FreightRpaInboundUnitRun(schedule_run_id=other_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-limit-other', status='success', config_snapshot_json={})
|
||||
db.session.add_all([own_unit, other_unit]); db.session.flush()
|
||||
own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/limit-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='f' * 64)
|
||||
own_file = FreightRpaInboundReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/limit-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='f' * 64)
|
||||
db.session.add(own_file); db.session.flush()
|
||||
for index in range(3):
|
||||
db.session.add(ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'receipt/limit-other-{index}.xlsx', original_filename=f'other-{index}.xlsx', file_size=4, sha256=f'{index + 1}' * 64))
|
||||
db.session.add(FreightRpaInboundReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'receipt/limit-other-{index}.xlsx', original_filename=f'other-{index}.xlsx', file_size=4, sha256=f'{index + 1}' * 64))
|
||||
db.session.commit()
|
||||
|
||||
items = list_receipt_report_files(recipient, limit=1)
|
||||
@@ -106,26 +108,26 @@ def test_receipt_file_list_filters_before_applying_limit(app):
|
||||
def test_admin_can_resend_without_reexporting(app, client, monkeypatch):
|
||||
"""管理员重发只调用文件投递,不创建 RPA 单元或 trigger。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
admin = User(username='receipt-resend-admin', email='receipt-resend-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RESEND', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-resend', status='success', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-resend', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/resend.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='c' * 64)
|
||||
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/resend.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='c' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
file_id = report_file.id
|
||||
calls = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.deliver_inbound_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0})
|
||||
|
||||
response = client.post(f'/api/admin/receipt-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin'))
|
||||
response = client.post(f'/api/admin/inbound-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
assert calls == [(file_id, True)]
|
||||
|
||||
@@ -133,27 +135,27 @@ def test_admin_can_resend_without_reexporting(app, client, monkeypatch):
|
||||
def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, client, monkeypatch):
|
||||
"""失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, User
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
admin = User(username='receipt-retry-admin', email='receipt-retry-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RETRY', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
failed = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []})
|
||||
failed = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []})
|
||||
db.session.add(failed); db.session.commit()
|
||||
failed_id = failed.id
|
||||
captured = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.write_inbound_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json')
|
||||
|
||||
response = client.post(f'/api/admin/receipt-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin'))
|
||||
response = client.post(f'/api/admin/inbound-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
with app.app_context():
|
||||
retry = ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=failed_id).one()
|
||||
retry = FreightRpaInboundUnitRun.query.filter_by(retry_of_id=failed_id).one()
|
||||
assert retry.status == 'awaiting_rpa'
|
||||
assert retry.callback_id != 'receipt-failed'
|
||||
assert captured and captured[0][1][0]['callback_id'] == retry.callback_id
|
||||
@@ -162,24 +164,24 @@ def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, clien
|
||||
def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client):
|
||||
"""管理员可见失败单元用于人工补偿;该接口会记录管理员查看审计。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun, User
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
admin = User(username='receipt-units-admin', email='receipt-units-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-UNITS', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
unit_id = unit.id
|
||||
|
||||
response = client.get('/api/admin/receipt-rpa-units?status=failed', headers=_headers('receipt-units-admin', 'admin'))
|
||||
response = client.get('/api/admin/inbound-rpa-units?status=failed', headers=_headers('receipt-units-admin', 'admin'))
|
||||
|
||||
assert response.status_code == 200
|
||||
assert [item['id'] for item in response.get_json()['data']['items']] == [unit_id]
|
||||
with app.app_context():
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_units_listed').count() == 1
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_units_listed').count() == 1
|
||||
@@ -7,17 +7,43 @@ import hashlib
|
||||
import pytest
|
||||
|
||||
|
||||
def _register_legacy_terminal_handler(unit):
|
||||
"""注册测试用 inbound 事实处理函数,复刻拆分前的终态收尾(桥 + 证据同步 + finalize)。
|
||||
|
||||
核心逻辑:Task 6 起 ingest_inbound_callback 不再收 on_terminal 钩子,本文件
|
||||
的桥接/进度断言改经 register_report_handler 注入留守的
|
||||
inbound_report_storage._finish_inbound_callback_terminal(Task 7 将平移为
|
||||
in_transit_transfer 的 handle_inbound_report);fact → 旧钩子实参逐字段换算,
|
||||
行为与拆分前逐点一致。
|
||||
"""
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.shipping_notice.inbound_report_storage import _finish_inbound_callback_terminal
|
||||
|
||||
def _handle(fact) -> None:
|
||||
_finish_inbound_callback_terminal(
|
||||
unit,
|
||||
ok=fact.ok,
|
||||
file_no=str(fact.file_id) if fact.file_id is not None else None,
|
||||
file_sha256=fact.sha256,
|
||||
error_code=fact.error_code,
|
||||
error_message=fact.error_message,
|
||||
)
|
||||
|
||||
register_report_handler("inbound", _handle)
|
||||
return _handle
|
||||
|
||||
|
||||
def test_receipt_unit_processing_and_batch_progress(app):
|
||||
"""开始导出标记 processing;每笔完成后 batch-progress 抬升排程计数。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import (
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import (
|
||||
mark_receipt_unit_processing,
|
||||
report_receipt_batch_progress,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-LIVE', name='Receipt live progress', schedule_type='platform_job',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
@@ -31,8 +57,8 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
schedule_run_id=run.id, source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-live-progress',
|
||||
status='awaiting_rpa', config_snapshot_json={},
|
||||
)
|
||||
@@ -46,7 +72,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
})
|
||||
assert marked['updated'] is True
|
||||
db.session.expire_all()
|
||||
assert db.session.get(ShippingReceiptRpaUnitRun, unit.id).status == 'processing'
|
||||
assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'processing'
|
||||
|
||||
progressed = report_receipt_batch_progress({
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
@@ -66,11 +92,11 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
|
||||
"""success 回调在 finalize 前须回写 ScheduleRun 进度计数(对齐 empty/failed)。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-PROG', name='Receipt progress', schedule_type='platform_job',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
@@ -84,8 +110,8 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
schedule_run_id=run.id, source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-progress',
|
||||
status='awaiting_rpa', config_snapshot_json={},
|
||||
)
|
||||
@@ -99,6 +125,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
|
||||
'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
_register_legacy_terminal_handler(unit)
|
||||
payload = {
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.callback_id,
|
||||
@@ -117,39 +144,40 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
|
||||
def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch):
|
||||
"""同一 callback 重放只归档一条收料文件,绝不创建库存快照。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
_register_legacy_terminal_handler(unit)
|
||||
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
first = ingest_receipt_callback(payload)
|
||||
second = ingest_receipt_callback(payload)
|
||||
assert first['file_id'] == second['file_id']
|
||||
assert ShippingInventoryFile.query.count() == 0
|
||||
assert FreightRpaOnhandReportFile.query.count() == 0
|
||||
|
||||
|
||||
def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
|
||||
"""收料回调 success 落归档后,必须推进调拨 waiting 来源任务(B3 接线)。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun
|
||||
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB2', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge', status='awaiting_rpa', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit)
|
||||
transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E', business_date='2026-09-17', status='preparing_files', trigger_type='manual')
|
||||
db.session.add(transfer_run); db.session.flush()
|
||||
@@ -157,6 +185,7 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
|
||||
db.session.add(job); db.session.commit()
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
_register_legacy_terminal_handler(unit)
|
||||
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
|
||||
result = ingest_receipt_callback(payload)
|
||||
@@ -170,21 +199,22 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
|
||||
def test_ingest_failed_advance_is_durable(app):
|
||||
"""failed 回调推进调拨任务后必须已 commit——rollback 不得丢弃该推进(B3 持久性)。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun
|
||||
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB3', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge-durable', status='awaiting_rpa', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge-durable', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit)
|
||||
transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E-FAIL', business_date='2026-09-17', status='preparing_files', trigger_type='manual')
|
||||
db.session.add(transfer_run); db.session.flush()
|
||||
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
|
||||
db.session.add(job); db.session.commit()
|
||||
_register_legacy_terminal_handler(unit)
|
||||
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
|
||||
|
||||
result = ingest_receipt_callback(payload)
|
||||
@@ -221,11 +251,11 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
[断言意图] 单元 status=empty 且 error_code/error_message 为 no_receipt_data,供管理端展示跳过原因。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-EMPTY',
|
||||
name='Receipt empty',
|
||||
@@ -239,9 +269,9 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-EMPTY', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
schedule_run_id=run.id,
|
||||
inventory_source_id=source.id,
|
||||
source_id=source.id,
|
||||
source_code=source.source_code,
|
||||
connector_type='dbs',
|
||||
warehouse_id='AWSDU',
|
||||
@@ -251,6 +281,7 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.commit()
|
||||
_register_legacy_terminal_handler(unit)
|
||||
|
||||
result = ingest_receipt_callback({
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
@@ -261,7 +292,7 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
})
|
||||
assert result['status'] == 'empty'
|
||||
db.session.expire_all()
|
||||
saved = db.session.get(ShippingReceiptRpaUnitRun, unit.id)
|
||||
saved = db.session.get(FreightRpaInboundUnitRun, unit.id)
|
||||
assert saved is not None
|
||||
assert saved.status == 'empty'
|
||||
assert saved.error_code == 'no_receipt_data'
|
||||
|
||||
@@ -7,22 +7,22 @@ def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipient
|
||||
"""同一文件只向排程接收人发送一次,重放不会重复调用企微。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun, User,
|
||||
)
|
||||
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-recipient', email='recipient@example.com', role='user', status='active', wecom_userid='receipt-user')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-notify-callback', status='success', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-notify-callback', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64)
|
||||
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.upload_wecom_temp_media', lambda *_args: 'media-1')
|
||||
@@ -38,28 +38,28 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch):
|
||||
"""企微投递失败也必须保留接收人、时间、失败码和文件身份审计。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun, User,
|
||||
)
|
||||
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-unbound-recipient', email='receipt-unbound@example.com', role='user', status='active')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY-FAIL', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-notify-fail', status='success', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-notify-fail', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64)
|
||||
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
|
||||
outcome = deliver_inbound_file(report_file.id)
|
||||
|
||||
assert outcome['failed_count'] == 1
|
||||
audit = ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_file_notification_attempted', aggregate_id=str(report_file.id)).one()
|
||||
audit = ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_file_notification_attempted', aggregate_id=str(report_file.id)).one()
|
||||
# 审计结果遵循统一枚举;业务投递状态仍保留为 failed。
|
||||
assert audit.result == 'failure'
|
||||
assert audit.after_snapshot_json['error_code'] == 'WECOM_USER_UNBOUND'
|
||||
@@ -68,18 +68,18 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch):
|
||||
def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *, awaiting: bool = True):
|
||||
"""构造一个收料排程任务+run+成功单元+归档文件的最小通知夹具。"""
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True} if awaiting else None)
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id=callback_id, status='success', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id=callback_id, status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'{callback_id}.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='c' * 64)
|
||||
report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'{callback_id}.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='c' * 64)
|
||||
db.session.add(report_file)
|
||||
db.session.commit()
|
||||
return task, run, report_file
|
||||
@@ -115,7 +115,7 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_
|
||||
"""收料 run 终态后经通用排程出口一次性发 textcard+收料 ZIP;重复归集不重发。"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives')
|
||||
@@ -157,23 +157,23 @@ def test_receipt_finalize_generates_summary_excel(app, tmp_path):
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
unit_ok = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={})
|
||||
unit_empty = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={})
|
||||
unit_fail = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={})
|
||||
unit_ok = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={})
|
||||
unit_empty = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={})
|
||||
unit_fail = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={})
|
||||
db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush()
|
||||
db.session.add(ShippingReceiptReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64))
|
||||
db.session.add(FreightRpaInboundReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64))
|
||||
db.session.commit()
|
||||
|
||||
outcome = finalize_receipt_schedule_run_if_complete(run.id)
|
||||
|
||||
@@ -8,26 +8,27 @@ from datetime import datetime, timedelta
|
||||
def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, monkeypatch):
|
||||
"""一源一单元:有/无 Warehouse 条件均产出 unit;多值 Warehouse 不拆分。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingRpaProfile
|
||||
from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaProfile
|
||||
from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule
|
||||
|
||||
with app.app_context():
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = ShippingRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'})
|
||||
crane = ShippingInventorySource(
|
||||
dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = FreightRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'})
|
||||
# s18 起站点行不再承载解析绑定/报表路径/查询条件;入站排程只读 FreightRpaInboundReportConfig。
|
||||
crane = FreightRpaSource(
|
||||
source_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', rpa_profile=crane_profile,
|
||||
parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
excel_template=dbs.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', enabled=True,
|
||||
)
|
||||
empty_dbs = ShippingInventorySource(
|
||||
empty_dbs = FreightRpaSource(
|
||||
source_code='DSV360_EMPTY_QP', display_name='Empty QP', connector_type='dbs', rpa_profile=dbs.rpa_profile,
|
||||
parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='EMPTY', report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
excel_template=dbs.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='EMPTY', enabled=True,
|
||||
)
|
||||
db.session.add_all([
|
||||
crane, empty_dbs,
|
||||
ShippingReceiptReportConfig(
|
||||
inventory_source_id=dbs.id,
|
||||
FreightRpaInboundReportConfig(
|
||||
source_id=dbs.id,
|
||||
report_path_json={
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
|
||||
@@ -39,11 +40,11 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
])
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingReceiptReportConfig(
|
||||
inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[],
|
||||
FreightRpaInboundReportConfig(
|
||||
source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[],
|
||||
),
|
||||
ShippingReceiptReportConfig(
|
||||
inventory_source_id=empty_dbs.id,
|
||||
FreightRpaInboundReportConfig(
|
||||
source_id=empty_dbs.id,
|
||||
report_path_json={
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
|
||||
@@ -62,7 +63,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_inbound_rpa_job.write_inbound_export_batch_trigger',
|
||||
'app.services.schedule.freight_rpa_inbound_job.write_inbound_export_batch_trigger',
|
||||
lambda run_no, units, payload: captured.update(run_no=run_no, units=units, payload=payload) or 'receipt-trigger.json',
|
||||
)
|
||||
total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run)
|
||||
@@ -94,14 +95,14 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
"""收料 Worker 离线时排程立即 failed,不写 trigger、不落 unit。"""
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaInboundUnitRun
|
||||
from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id,
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add(FreightRpaInboundReportConfig(
|
||||
source_id=source.id,
|
||||
report_path_json={
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
|
||||
@@ -121,7 +122,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
|
||||
trigger_calls = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_inbound_rpa_job.assert_receipt_rpa_worker_ready',
|
||||
'app.services.schedule.freight_rpa_inbound_job.assert_receipt_rpa_worker_ready',
|
||||
lambda: (_ for _ in ()).throw(ServiceUnavailableError(
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
code='RPA.WORKER_OFFLINE',
|
||||
@@ -129,7 +130,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_inbound_rpa_job.write_inbound_export_batch_trigger',
|
||||
'app.services.schedule.freight_rpa_inbound_job.write_inbound_export_batch_trigger',
|
||||
lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json',
|
||||
)
|
||||
|
||||
@@ -140,7 +141,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
assert details == []
|
||||
assert errors == ['receipt worker offline']
|
||||
assert trigger_calls == []
|
||||
assert ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0
|
||||
assert FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0
|
||||
failed_log = next(log for log in logs if isinstance(log, dict) and log.get('status') == 'failed')
|
||||
assert failed_log['detail'].get('reasons') == ['no_worker_heartbeat']
|
||||
assert not any(
|
||||
@@ -152,19 +153,19 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
"""动态排程选项只暴露库存站点已启用且已配置收料的站点。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id,
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add(FreightRpaInboundReportConfig(
|
||||
source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'},
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['A'], 'required': False, 'select_all': False}],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
options = list_job_options('shipping_receipt_sources')
|
||||
options = list_job_options('freight_rpa_inbound_sources')
|
||||
|
||||
assert any(item['value'] == source.source_code for item in options)
|
||||
|
||||
@@ -172,17 +173,17 @@ def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
"""无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={})
|
||||
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
|
||||
assert recover_stale_receipt_rpa_schedule_runs(task) == 1
|
||||
@@ -191,8 +192,8 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
assert run.status == 'failed'
|
||||
assert unit.status == 'failed'
|
||||
assert unit.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT'
|
||||
assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1
|
||||
assert FreightRpaInboundUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1
|
||||
|
||||
|
||||
def test_receipt_trigger_is_published_atomically(app, tmp_path):
|
||||
@@ -210,17 +211,17 @@ def test_receipt_trigger_is_published_atomically(app, tmp_path):
|
||||
def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app):
|
||||
"""全量扫描(每轮 tick 路径)无需任务再次执行/进程重启即可收口超时收料 run。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={}))
|
||||
db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={}))
|
||||
db.session.commit()
|
||||
|
||||
# [断言意图] 全量扫描不依赖 task 入参、进程重启或同排程再次执行(点B 修复口径);
|
||||
@@ -234,19 +235,19 @@ def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app):
|
||||
def test_receipt_recovery_respects_fresh_activity_of_long_batch(app):
|
||||
"""长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
# 单元1:30 秒前终态(笔间活动新鲜);单元2:45 秒前进入 processing(在飞,started_at 为锚)
|
||||
db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30)))
|
||||
db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='B', callback_id='receipt-long-run', status='processing', config_snapshot_json={}, started_at=datetime.utcnow() - timedelta(seconds=45)))
|
||||
db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30)))
|
||||
db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='B', callback_id='receipt-long-run', status='processing', config_snapshot_json={}, started_at=datetime.utcnow() - timedelta(seconds=45)))
|
||||
db.session.commit()
|
||||
|
||||
# [断言意图] run.started_at(30min 前) 已远超 60s 窗,但最后活动仅 30~45s——
|
||||
@@ -273,27 +274,27 @@ def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only():
|
||||
def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
|
||||
"""按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。"""
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
from app.models import ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
# 单元1:排队 5 分钟从未被领取(created_at 为锚,queued 分支);单元2:领取后
|
||||
# 静默 5 分钟(started_at 为锚);单元3:30 秒前刚领取(健康在跑,不得误杀)。
|
||||
stale_queued = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs',
|
||||
stale_queued = FreightRpaInboundUnitRun(
|
||||
source_id=source.id, source_code=source.source_code, connector_type='dbs',
|
||||
callback_id='inbound-orphan-queued', status='queued', config_snapshot_json={},
|
||||
created_at=datetime.utcnow() - timedelta(minutes=5),
|
||||
)
|
||||
stale_processing = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs',
|
||||
stale_processing = FreightRpaInboundUnitRun(
|
||||
source_id=source.id, source_code=source.source_code, connector_type='dbs',
|
||||
callback_id='inbound-orphan-processing', status='processing', config_snapshot_json={},
|
||||
created_at=datetime.utcnow() - timedelta(minutes=6),
|
||||
started_at=datetime.utcnow() - timedelta(minutes=5),
|
||||
)
|
||||
fresh_processing = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs',
|
||||
fresh_processing = FreightRpaInboundUnitRun(
|
||||
source_id=source.id, source_code=source.source_code, connector_type='dbs',
|
||||
callback_id='inbound-orphan-fresh', status='processing', config_snapshot_json={},
|
||||
created_at=datetime.utcnow() - timedelta(seconds=45),
|
||||
started_at=datetime.utcnow() - timedelta(seconds=30),
|
||||
@@ -315,10 +316,10 @@ def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
|
||||
assert stale_queued.finished_at is not None
|
||||
assert stale_processing.status == 'failed'
|
||||
assert fresh_processing.status == 'processing'
|
||||
assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=stale_queued.id).count() == 0
|
||||
assert FreightRpaInboundUnitRun.query.filter_by(retry_of_id=stale_queued.id).count() == 0
|
||||
# [断言意图] 审计须含失败结果与 before/after 快照——与 run 级回收同语义由测试锁定。
|
||||
timeout_event = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_receipt_rpa_callback_timeout', aggregate_id=str(stale_queued.id),
|
||||
event_type='shipping_inbound_rpa_callback_timeout', aggregate_id=str(stale_queued.id),
|
||||
).one()
|
||||
assert timeout_event.result == 'failure'
|
||||
assert (timeout_event.after_snapshot_json or {}).get('status') == 'failed'
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
"""
|
||||
tests/test_freight_rpa_batch_s_grep_gate.py
|
||||
|
||||
用途:批次 S 生产路径 grep 门禁。白名单外的旧表名、旧 admin inventory 路径、
|
||||
ShippingInventory 类名(含 camelCase 助手)、outbound_upload 必须为零。
|
||||
依赖:backend/app 与 frontend/src 源码(只读)。不读 docs/superpowers,不读历史迁移。
|
||||
逻辑:pytest 调用本文件扫描器。ALLOWED_TOKENS 只有两个 HTTP 工具名。
|
||||
四个任务/行级类名已改为 Onhand,旧名整词现在失败。
|
||||
缩写约束名因下划线前缀不是整词。履约 shipment、movement、中文「库存」不在禁词正则里。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
SCAN_ROOTS = (
|
||||
REPO / "backend" / "app",
|
||||
REPO / "frontend" / "src",
|
||||
)
|
||||
SKIP_PARTS = frozenset({
|
||||
"node_modules",
|
||||
"__pycache__",
|
||||
".venv",
|
||||
"dist",
|
||||
"contract_payment",
|
||||
"contract-payment",
|
||||
})
|
||||
SOURCE_SUFFIXES = frozenset({".py", ".ts", ".vue", ".js", ".json", ".yml", ".yaml"})
|
||||
|
||||
# 词边界整词。函数名 list_shipping_inventory_sources、缩写约束 uq_shipping_inventory_*
|
||||
# 前面还有下划线,不是独立表名,不会命中。
|
||||
PREFIX_TOKEN_RE = re.compile(r"\bshipping_(?:inventory|receipt)_[a-z0-9_]+\b")
|
||||
# 29 表里不以 shipping_inventory_ / shipping_receipt_ 开头、但已改名的表。
|
||||
EXTRA_RETIRED_TABLES = (
|
||||
"shipping_rpa_profiles",
|
||||
"shipping_task_inventory_rpa_attempts",
|
||||
"shipping_task_inventory_links",
|
||||
"shipping_temporary_inventory_sessions",
|
||||
"shipping_notice_line_inventory_matches",
|
||||
"shipping_notice_inventory_verifications",
|
||||
"shipping_notice_inventory_verification_lines",
|
||||
)
|
||||
EXTRA_TABLE_RE = re.compile(r"\b(?:" + "|".join(EXTRA_RETIRED_TABLES) + r")\b")
|
||||
# 无前导词边界:getShippingInventory* / listShippingInventory* / shippingInventory* 都要命中。
|
||||
CLASS_RE = re.compile(r"(?i)shippinginventory[a-z0-9_]*")
|
||||
PATH_RE = re.compile(r"/api/admin/shipping-notice/inventory-")
|
||||
UPLOAD_RE = re.compile(r"\boutbound_upload\b")
|
||||
EXPLANATION_RE = re.compile(r"retired|legacy|废弃|退役|曾用|旧名|旧表|原表|原名|已改名")
|
||||
RETIRED_CLASS_RE = re.compile(
|
||||
r"\b(?:ShippingTaskInventoryLink|ShippingTaskInventoryRpaAttempt|"
|
||||
r"ShippingTemporaryInventorySession|ShippingNoticeLineInventoryMatch)\b"
|
||||
)
|
||||
|
||||
# 只放行两个 HTTP 工具名。movement / shipment_* 不靠把模块名塞进这里。
|
||||
ALLOWED_TOKENS = frozenset({
|
||||
"ensure_inventory",
|
||||
"upload_inventory_file",
|
||||
})
|
||||
|
||||
ONHAND_CLASS_FILES = (
|
||||
REPO / "backend" / "app" / "models" / "shipping.py",
|
||||
REPO / "backend" / "app" / "models" / "shipping_onhand_task_rpa_attempts.py",
|
||||
REPO / "backend" / "app" / "models" / "shipping_temporary_onhand.py",
|
||||
REPO / "backend" / "app" / "models" / "shipping_notice_line_onhand_match.py",
|
||||
)
|
||||
|
||||
|
||||
def _is_allowed(token: str) -> bool:
|
||||
"""两个 HTTP 工具名,以及 movement / shipment 履约词。"""
|
||||
if token in ALLOWED_TOKENS:
|
||||
return True
|
||||
lowered = token.lower()
|
||||
if lowered == "movement" or lowered.startswith("movement_") or "_movement" in lowered:
|
||||
return True
|
||||
if (
|
||||
lowered.startswith("shipment_")
|
||||
or "_shipment_" in lowered
|
||||
or lowered.endswith("_shipment")
|
||||
or lowered == "generate_shipment_excel"
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _is_explaining_comment(line: str) -> bool:
|
||||
"""整行是注释,并且在解释退役名,才从门禁里放过。"""
|
||||
stripped = line.lstrip()
|
||||
if not stripped.startswith(("#", "//", "*", "/*", "<!--")):
|
||||
return False
|
||||
return EXPLANATION_RE.search(stripped) is not None
|
||||
|
||||
|
||||
def _should_skip(path: Path) -> bool:
|
||||
"""contract_payment 路径与依赖目录不扫。shipment 发货款在这条路径里。"""
|
||||
return any(part in SKIP_PARTS for part in path.parts)
|
||||
|
||||
|
||||
def violations_in_text(text: str, *, source: str = "<snippet>") -> list[str]:
|
||||
"""
|
||||
从一段源码抽出批次 S 禁词。
|
||||
|
||||
核心逻辑:解释退役名的注释行跳过;其余行收集前缀整词、额外旧表名、
|
||||
shippinginventory 驼峰标识(含 getShippingInventory*)、旧 admin 路径和 outbound_upload。
|
||||
只有 ALLOWED_TOKENS 与 movement / shipment 履约词放行。
|
||||
|
||||
Args:
|
||||
text: 单个源文件正文,或相对路径(用来抓文件名里的旧表名)。
|
||||
source: 违规定位前缀。
|
||||
|
||||
Returns:
|
||||
`source:line:token` 列表。空列表表示这段文本通过。
|
||||
"""
|
||||
found: list[str] = []
|
||||
for index, line in enumerate(text.splitlines() or [text], 1):
|
||||
if _is_explaining_comment(line):
|
||||
continue
|
||||
for match in PREFIX_TOKEN_RE.finditer(line):
|
||||
token = match.group(0)
|
||||
if not _is_allowed(token):
|
||||
found.append(f"{source}:{index}:{token}")
|
||||
for match in EXTRA_TABLE_RE.finditer(line):
|
||||
token = match.group(0)
|
||||
if not _is_allowed(token):
|
||||
found.append(f"{source}:{index}:{token}")
|
||||
for match in CLASS_RE.finditer(line):
|
||||
name = match.group(0)
|
||||
if not _is_allowed(name):
|
||||
found.append(f"{source}:{index}:{name}")
|
||||
for match in RETIRED_CLASS_RE.finditer(line):
|
||||
found.append(f"{source}:{index}:{match.group(0)}")
|
||||
if PATH_RE.search(line):
|
||||
found.append(f"{source}:{index}:/api/admin/shipping-notice/inventory-")
|
||||
if UPLOAD_RE.search(line):
|
||||
found.append(f"{source}:{index}:outbound_upload")
|
||||
return found
|
||||
|
||||
|
||||
def scan_production_paths() -> list[str]:
|
||||
"""
|
||||
扫描 backend/app 与 frontend/src。
|
||||
|
||||
核心逻辑:跳过 contract_payment 目录;文件名与正文用同一套规则。
|
||||
docs/superpowers 与 backend/migrations 不在扫描根里,历史迁移保持原样。
|
||||
|
||||
Returns:
|
||||
全部违规定位。空列表表示生产路径通过门禁。
|
||||
"""
|
||||
violations: list[str] = []
|
||||
for root in SCAN_ROOTS:
|
||||
for path in root.rglob("*"):
|
||||
if not path.is_file() or path.suffix.lower() not in SOURCE_SUFFIXES:
|
||||
continue
|
||||
if _should_skip(path):
|
||||
continue
|
||||
relative = path.relative_to(REPO).as_posix()
|
||||
violations.extend(violations_in_text(relative, source=relative))
|
||||
text = path.read_text(encoding="utf-8")
|
||||
violations.extend(violations_in_text(text, source=relative))
|
||||
return violations
|
||||
|
||||
|
||||
def test_batch_s_production_paths_are_clean():
|
||||
"""生产代码里,白名单之外不再出现批次 S 禁词。"""
|
||||
violations = scan_production_paths()
|
||||
# 关键断言:门禁失败时列出定位,避免只报一个计数。
|
||||
assert not violations, "batch S grep gate:\n" + "\n".join(violations[:40])
|
||||
|
||||
|
||||
def test_scan_roots_leave_history_and_migrations_alone():
|
||||
"""门禁根只有 backend/app 与 frontend/src,不改写历史文档和旧迁移。"""
|
||||
posix = [path.relative_to(REPO).as_posix() for path in SCAN_ROOTS]
|
||||
# 关键断言:s17 迁移可以同时出现旧名和新名,本门禁不读迁移目录。
|
||||
assert posix == ["backend/app", "frontend/src"]
|
||||
assert not (REPO / "docs" / "superpowers").is_relative_to(SCAN_ROOTS[0])
|
||||
|
||||
|
||||
def test_allowed_tokens_are_only_tool_routes():
|
||||
"""白名单只含两个 HTTP 工具名。任务类名不再豁免。"""
|
||||
# 关键断言:模块名、步骤 id、审计事件和旧任务类名不能再靠白名单过门。
|
||||
assert ALLOWED_TOKENS == {"ensure_inventory", "upload_inventory_file"}
|
||||
|
||||
|
||||
def test_retired_table_token_fails():
|
||||
"""独立旧表名(含 __tablename__)必须失败。"""
|
||||
text = "__tablename__ = 'shipping_inventory_sources'\n"
|
||||
# 关键断言:引号构成词边界,表名整词命中。
|
||||
assert violations_in_text(text) == ["<snippet>:1:shipping_inventory_sources"]
|
||||
extra = "chosen = shipping_notice_line_inventory_matches.chosen_odm_id\n"
|
||||
assert "shipping_notice_line_inventory_matches" in violations_in_text(extra)[0]
|
||||
|
||||
|
||||
def test_retired_name_comment_is_allowed():
|
||||
"""解释退役名的注释可以出现旧词;代码行即使带注释也不放行。"""
|
||||
comment = "# retired table shipping_inventory_sources,已改名 freight_rpa_sources\n"
|
||||
assert violations_in_text(comment) == []
|
||||
coded = "__tablename__ = 'shipping_inventory_sources' # retired\n"
|
||||
# 关键断言:赋值仍是活代码,尾注释不能把表名洗白。
|
||||
assert violations_in_text(coded)
|
||||
|
||||
|
||||
def test_abbreviated_constraint_and_prefixed_function_are_not_table_tokens():
|
||||
"""不含完整旧表名的缩写约束,以及带前缀的函数名,不当作整词表名。"""
|
||||
text = (
|
||||
"name='uq_shipping_inventory_mapping_file_version'\n"
|
||||
"Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id')\n"
|
||||
"def list_shipping_inventory_sources():\n"
|
||||
" pass\n"
|
||||
)
|
||||
# 关键断言:下划线前缀没有词边界,缩写约束和函数名不误伤。
|
||||
assert violations_in_text(text) == []
|
||||
|
||||
|
||||
def test_bare_module_token_and_camel_case_helper_fail():
|
||||
"""独立模块名和 camelCase ShippingInventory 助手必须失败。"""
|
||||
module = violations_in_text("return shipping_inventory_service.list_sources()\n")
|
||||
helper = violations_in_text("export const getShippingInventoryFields = () => 1\n")
|
||||
# 关键断言:不再把 shipping_inventory_service 放进白名单;驼峰助手同样命中。
|
||||
assert module == ["<snippet>:1:shipping_inventory_service"]
|
||||
assert any(item.endswith(":getShippingInventoryFields") or "ShippingInventoryFields" in item for item in helper)
|
||||
|
||||
|
||||
def test_unknown_prefix_token_fails():
|
||||
"""白名单没点名的新 shipping_inventory_ / shipping_receipt_ 整词仍然失败。"""
|
||||
text = "cache_key = 'shipping_inventory_brand_new_widget'\n"
|
||||
assert violations_in_text(text) == ["<snippet>:1:shipping_inventory_brand_new_widget"]
|
||||
|
||||
|
||||
def test_shipping_inventory_class_name_fails_and_onhand_classes_exist():
|
||||
"""ShippingInventory 类名与四个旧任务类名失败;替换后的 Onhand 类名存在且不失败。"""
|
||||
assert violations_in_text("export type ShippingInventoryField = {\n") == [
|
||||
"<snippet>:1:ShippingInventoryField",
|
||||
]
|
||||
assert "ShippingInventoryFields" in violations_in_text(
|
||||
"export const getShippingInventoryFields = () => 1\n"
|
||||
)[0]
|
||||
retired = "\n".join(
|
||||
f"class {name}(Base):"
|
||||
for name in (
|
||||
"ShippingTaskInventoryLink",
|
||||
"ShippingTaskInventoryRpaAttempt",
|
||||
"ShippingTemporaryInventorySession",
|
||||
"ShippingNoticeLineInventoryMatch",
|
||||
)
|
||||
)
|
||||
# 关键断言:旧类名整词现在失败,不再放行。
|
||||
assert len(violations_in_text(retired)) == 4
|
||||
current = (
|
||||
"ShippingTaskOnhandLink",
|
||||
"FreightRpaOnhandTaskAttempt",
|
||||
"ShippingTemporaryOnhandSession",
|
||||
"ShippingNoticeLineOnhandMatch",
|
||||
)
|
||||
assert violations_in_text("\n".join(f"class {name}(Base):" for name in current)) == []
|
||||
for path, name in zip(ONHAND_CLASS_FILES, current, strict=True):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert f"class {name}" in text
|
||||
assert "ShippingTaskInventory" not in text
|
||||
assert "ShippingTemporaryInventory" not in text
|
||||
assert "ShippingNoticeLineInventory" not in text
|
||||
|
||||
|
||||
def test_old_admin_inventory_path_and_outbound_upload_fail():
|
||||
"""旧管理路径与 outbound_upload 动作必须失败;freight_upload 不是禁词。"""
|
||||
path = "url = '/api/admin/shipping-notice/inventory-fields'\n"
|
||||
assert "/api/admin/shipping-notice/inventory-" in violations_in_text(path)[0]
|
||||
upload = "action = 'outbound_upload'\n"
|
||||
assert violations_in_text(upload) == ["<snippet>:1:outbound_upload"]
|
||||
# 关键断言:正确的上传动作不在禁词里。
|
||||
assert violations_in_text("action = 'freight_upload'\n") == []
|
||||
|
||||
|
||||
def test_do_not_touch_terms_are_not_forbidden():
|
||||
"""履约 shipment、movement、工具路由和中文库存文案不被扫成待改。"""
|
||||
text = "\n".join([
|
||||
"def generate_shipment_excel():",
|
||||
" return 'shipment_notice.xlsx'",
|
||||
"purpose = 'movement'",
|
||||
"def ensure_inventory():",
|
||||
" return 'upload_inventory_file'",
|
||||
'{"label": "库存"}',
|
||||
])
|
||||
# 关键断言:这些词不在批次 S 禁词正则里。
|
||||
assert violations_in_text(text) == []
|
||||
# contract_payment 目录整棵跳过,避免发货款 shipment 被误伤。
|
||||
assert _should_skip(REPO / "backend" / "app" / "services" / "contract_payment" / "foo.py")
|
||||
assert not _should_skip(REPO / "backend" / "app" / "services" / "shipping_notice" / "foo.py")
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
backend/tests/test_freight_rpa_class_names.py
|
||||
|
||||
用途:锁住货代 RPA 模型的类名、表名和站点关系属性名。
|
||||
依赖:app.models 里拆出的 freight_rpa_* 模型模块。
|
||||
逻辑:被 pytest 直接导入;不连数据库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import app.models as models
|
||||
from app.models.freight_rpa_config import (
|
||||
FreightRpaOnhandExternalMapping,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaSource,
|
||||
)
|
||||
from app.models.freight_rpa_inbound_report import (
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
from app.models.freight_rpa_onhand_report_file import FreightRpaOnhandReportFile
|
||||
from app.models.freight_rpa_onhand_task_attempts import FreightRpaOnhandTaskAttempt
|
||||
|
||||
|
||||
def test_freight_rpa_classes_keep_existing_table_names():
|
||||
"""类名换成 FreightRpa 后,表名仍是规格里的 freight_rpa_*。"""
|
||||
assert FreightRpaSource.__tablename__ == "freight_rpa_sources"
|
||||
assert FreightRpaOnhandReportFile.__tablename__ == "freight_rpa_onhand_report_files"
|
||||
assert FreightRpaInboundReportFile.__tablename__ == "freight_rpa_inbound_report_files"
|
||||
assert FreightRpaInboundUnitRun.__tablename__ == "freight_rpa_inbound_rpa_unit_runs"
|
||||
|
||||
|
||||
def test_site_relationships_drop_inventory_and_receipt_names():
|
||||
"""站点关系改叫 source / inbound_report_config,索引名不在这个测试里改。"""
|
||||
assert "source" in FreightRpaOnhandReportConfig.__mapper__.relationships
|
||||
assert "inventory_source" not in FreightRpaOnhandReportConfig.__mapper__.relationships
|
||||
assert "source" in FreightRpaInboundReportConfig.__mapper__.relationships
|
||||
assert "source" in FreightRpaInboundUnitRun.__mapper__.relationships
|
||||
assert "inbound_report_config" in FreightRpaSource.__mapper__.relationships
|
||||
assert "receipt_report_config" not in FreightRpaSource.__mapper__.relationships
|
||||
assert "source" in FreightRpaOnhandExternalMapping.__mapper__.relationships
|
||||
assert FreightRpaOnhandTaskAttempt.__tablename__ == "freight_rpa_onhand_task_rpa_attempts"
|
||||
|
||||
|
||||
def test_old_shipping_class_names_are_not_exported():
|
||||
"""旧类名不留别名。发货任务关联类仍叫 ShippingTaskOnhandLink。"""
|
||||
assert not hasattr(models, "ShippingOnhandSource")
|
||||
assert not hasattr(models, "ShippingOnhandFile")
|
||||
assert not hasattr(models, "ShippingInboundReportFile")
|
||||
assert not hasattr(models, "ShippingParsingProfile")
|
||||
assert hasattr(models, "FreightRpaSource")
|
||||
assert hasattr(models, "FreightRpaOnhandReportFile")
|
||||
assert hasattr(models, "ShippingTaskOnhandLink")
|
||||
assert hasattr(models, "ShippingUploadAttempt")
|
||||
@@ -47,6 +47,17 @@ def test_build_heartbeat_payload_inbound_worker_declares_inbound_export(monkeypa
|
||||
assert payload["worker_id"].endswith("-inbound")
|
||||
|
||||
|
||||
def test_build_heartbeat_payload_adds_freight_rpa_upload_when_upload_enabled(monkeypatch):
|
||||
"""开启上传时心跳能力是 freight_rpa_upload,不再上报 freight_upload。"""
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
payload = module.build_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\onhand_triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\onhand_drop",
|
||||
)
|
||||
assert payload["capabilities"] == ["onhand_export", "freight_rpa_upload"]
|
||||
|
||||
|
||||
def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
|
||||
@@ -275,7 +275,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_batch_scheduled.json"
|
||||
# 与 run_shipping_inventory_rpa_schedule 写入的 trigger 形状一致:
|
||||
# 与 run_freight_rpa_onhand_schedule 写入的 trigger 形状一致:
|
||||
# batch 级无 task_no,逐源无 task_no/source_run_no/lease_token/candidate_set_id/execution_id/gate_id。
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
@@ -335,7 +335,7 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
|
||||
drop_dir.mkdir()
|
||||
run_no = "CONFIG-DSV360_AWSBI_BYAWSPRD01-20260909020428918536"
|
||||
trigger_path = trigger_dir / f"inventory_export_batch_{run_no}.json"
|
||||
# 与 inventory_configuration_test.start_test_export 写入形状一致:
|
||||
# 与 onhand_configuration_test.start_test_export 写入形状一致:
|
||||
# trigger_type=configuration_test,无 task_no / gate_id / execution_id 等生产身份。
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
@@ -677,7 +677,7 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp
|
||||
def _load_worker_logging():
|
||||
"""加载 scripts/freight_rpa/common/worker_logging.py 供单测直接断言。
|
||||
|
||||
历史背景:文件日志实现(tee/轮转/时间戳)原内置于 inventory_rpa_worker.py,
|
||||
历史背景:文件日志实现(tee/轮转/时间戳)原内置于 onhand_rpa_worker.py,
|
||||
已提取为公共模块;Worker 内部私有名(_configure_file_logging 等)已删除,
|
||||
日志行为用例统一改测公共接口,行为断言保持等价。
|
||||
"""
|
||||
|
||||
@@ -37,7 +37,7 @@ def test_user_mode_wait_upload_handoff():
|
||||
def test_user_mode_must_human():
|
||||
assert derive_user_mode(
|
||||
user_status='waiting_human',
|
||||
gate_code='inventory_matching',
|
||||
gate_code='onhand_matching',
|
||||
review_status=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) == 'must_human'
|
||||
@@ -46,7 +46,7 @@ def test_user_mode_must_human():
|
||||
def test_user_mode_auto():
|
||||
assert derive_user_mode(
|
||||
user_status='running',
|
||||
gate_code='inventory_preparation',
|
||||
gate_code='onhand_preparation',
|
||||
review_status=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) == 'auto_continue'
|
||||
@@ -59,7 +59,7 @@ def test_position_review_dispositions():
|
||||
|
||||
|
||||
def test_position_fulfillment():
|
||||
assert derive_position(gate_code='inventory_preparation', review_status=None) == 'inventory_pending'
|
||||
assert derive_position(gate_code='onhand_preparation', review_status=None) == 'inventory_pending'
|
||||
assert derive_position(gate_code='artifact_generation', review_status=None) == 'export_ready'
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ def test_fetch_gate_positions_batched(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='inventory_matching',
|
||||
stage='onhand_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
ot_b = ShippingOrderTask(
|
||||
@@ -99,7 +99,7 @@ def test_fetch_gate_positions_batched(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='processing',
|
||||
stage='inventory_fetching',
|
||||
stage='onhand_fetching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add_all([ot_a, ot_b])
|
||||
@@ -109,21 +109,21 @@ def test_fetch_gate_positions_batched(app):
|
||||
execution_no='SPE-GATE-POS-A',
|
||||
task_id=int(ot_a.id),
|
||||
status='blocked',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
current_gate_code='onhand_sufficiency',
|
||||
),
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-GATE-POS-B',
|
||||
task_id=int(ot_b.id),
|
||||
status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
current_gate_code='onhand_preparation',
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
result = fetch_gate_positions([int(ot_a.id), int(ot_b.id), 999999])
|
||||
assert result[int(ot_a.id)]['current_gate_code'] == 'inventory_sufficiency'
|
||||
assert result[int(ot_a.id)]['current_gate_code'] == 'onhand_sufficiency'
|
||||
assert result[int(ot_a.id)]['status'] == 'blocked'
|
||||
assert result[int(ot_b.id)]['current_gate_code'] == 'inventory_preparation'
|
||||
assert result[int(ot_b.id)]['current_gate_code'] == 'onhand_preparation'
|
||||
assert 999999 not in result
|
||||
|
||||
|
||||
@@ -140,11 +140,11 @@ def test_early_stop_uses_derive_user_mode(monkeypatch):
|
||||
'current_gate': {
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_shortage_review_required',
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
'gate_code': 'onhand_sufficiency',
|
||||
},
|
||||
'responsible_party': 'owner',
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_gate_code': 'inventory_sufficiency',
|
||||
'current_gate_code': 'onhand_sufficiency',
|
||||
'status': 'blocked',
|
||||
},
|
||||
)
|
||||
@@ -153,9 +153,9 @@ def test_early_stop_uses_derive_user_mode(monkeypatch):
|
||||
|
||||
def test_entry_user_mode_inventory_prep_retryable_stays_auto(monkeypatch):
|
||||
"""
|
||||
回归:候选已冻结但尚未取库存时,sync 可能把 inventory_preparation 投影为
|
||||
回归:候选已冻结但尚未取库存时,sync 可能把 onhand_preparation 投影为
|
||||
blocked_retryable + inventory_file_empty;自动推进入口不得判 must_human 早停,
|
||||
否则永远进不了 ensure_inventory(复用快照 / 触发 RPA)。
|
||||
否则永远进不了 ensure_onhand(复用快照 / 触发 RPA)。
|
||||
"""
|
||||
from app.services.shipping_notice import progress_workflow as pw
|
||||
|
||||
@@ -169,16 +169,16 @@ def test_entry_user_mode_inventory_prep_retryable_stays_auto(monkeypatch):
|
||||
'current_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
'gate_code': 'inventory_preparation',
|
||||
'gate_code': 'onhand_preparation',
|
||||
},
|
||||
'current_blocking_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
'gate_code': 'inventory_preparation',
|
||||
'gate_code': 'onhand_preparation',
|
||||
},
|
||||
'responsible_party': 'worker',
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_gate_code': 'inventory_preparation',
|
||||
'current_gate_code': 'onhand_preparation',
|
||||
'status': 'blocked',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
},
|
||||
@@ -199,20 +199,20 @@ def test_entry_user_mode_inventory_prep_exhausted_still_must_human(monkeypatch):
|
||||
lambda t: {
|
||||
'current_blocking_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_rpa_exhausted',
|
||||
'gate_code': 'inventory_preparation',
|
||||
'blocking_reason_code': 'onhand_rpa_exhausted',
|
||||
'gate_code': 'onhand_preparation',
|
||||
},
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_gate_code': 'inventory_preparation',
|
||||
'current_gate_code': 'onhand_preparation',
|
||||
'status': 'blocked',
|
||||
'blocking_reason_code': 'inventory_rpa_exhausted',
|
||||
'blocking_reason_code': 'onhand_rpa_exhausted',
|
||||
},
|
||||
)
|
||||
assert pw._entry_user_mode(FakeTask()) == 'must_human'
|
||||
|
||||
|
||||
def test_position_inventory_sufficiency():
|
||||
assert derive_position(gate_code='inventory_sufficiency', review_status=None) == 'shortage_review'
|
||||
assert derive_position(gate_code='onhand_sufficiency', review_status=None) == 'shortage_review'
|
||||
|
||||
|
||||
def test_todo_category_from_gate_positions():
|
||||
@@ -227,14 +227,14 @@ def test_todo_category_from_gate_positions():
|
||||
)
|
||||
assert (
|
||||
_todo_category_from_gate(
|
||||
{'current_gate_code': 'inventory_preparation', 'status': 'active'},
|
||||
{'current_gate_code': 'onhand_preparation', 'status': 'active'},
|
||||
None,
|
||||
)
|
||||
== 'in_progress'
|
||||
)
|
||||
assert (
|
||||
_todo_category_from_gate(
|
||||
{'current_gate_code': 'inventory_sufficiency', 'status': 'blocked'},
|
||||
{'current_gate_code': 'onhand_sufficiency', 'status': 'blocked'},
|
||||
None,
|
||||
)
|
||||
== 'exception'
|
||||
@@ -257,7 +257,7 @@ def test_user_facing_stage_uses_position(monkeypatch):
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda t: {'current_gate_code': 'inventory_preparation'},
|
||||
lambda t: {'current_gate_code': 'onhand_preparation'},
|
||||
)
|
||||
assert ufs.user_facing_task_stage(FakeTask()) == '待上传库存'
|
||||
|
||||
@@ -315,7 +315,7 @@ def test_summary_prefers_gate_shortage_over_freeze(monkeypatch):
|
||||
FakeTask(),
|
||||
'shortage_review',
|
||||
user_mode='must_human',
|
||||
gate_code='inventory_sufficiency',
|
||||
gate_code='onhand_sufficiency',
|
||||
)
|
||||
assert '缺口' in summary['message'] or '库存' in summary['message']
|
||||
assert summary['user_mode'] == 'must_human'
|
||||
@@ -332,7 +332,7 @@ def test_notice_text_failure_maps_to_quality_issue():
|
||||
|
||||
|
||||
def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
"""关键断言:SQL CASE 在 Execution=inventory_sufficiency/blocked 时为 exception。"""
|
||||
"""关键断言:SQL CASE 在 Execution=onhand_sufficiency/blocked 时为 exception。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
@@ -345,7 +345,7 @@ def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='inventory_matching',
|
||||
stage='onhand_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
@@ -355,7 +355,7 @@ def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
execution_no='SPE-SQL-GATE-SHORT',
|
||||
task_id=int(ot.id),
|
||||
status='blocked',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
current_gate_code='onhand_sufficiency',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
@@ -474,7 +474,7 @@ def test_sql_todo_category_running_inventory_prep_is_in_progress(app):
|
||||
execution_no='SPE-SQL-RUNNING-PREP',
|
||||
task_id=int(ot.id),
|
||||
status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
current_gate_code='onhand_preparation',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
@@ -12,8 +12,8 @@ from decimal import Decimal
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryVerification,
|
||||
ShippingInventoryVerificationLine,
|
||||
ShippingOnhandVerification,
|
||||
ShippingOnhandVerificationLine,
|
||||
ShippingReservation,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import exportable_snapshot_line_ids
|
||||
@@ -24,7 +24,7 @@ from tests.test_line_closure_fulfillment import _seed_close_decision
|
||||
|
||||
def _seed_available_reservations(fixture):
|
||||
"""两行各建一条 available 预约 + 一轮 completed 核验。"""
|
||||
verification = ShippingInventoryVerification(task_id=fixture.order.id, status='completed')
|
||||
verification = ShippingOnhandVerification(task_id=fixture.order.id, status='completed')
|
||||
db.session.add(verification)
|
||||
db.session.flush()
|
||||
for index, snap_line in enumerate(fixture.snap_lines):
|
||||
@@ -35,7 +35,7 @@ def _seed_available_reservations(fixture):
|
||||
)
|
||||
db.session.add(reservation)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryVerificationLine(
|
||||
db.session.add(ShippingOnhandVerificationLine(
|
||||
verification_id=verification.id, reservation_id=reservation.id,
|
||||
required_qty=Decimal('10'), available_qty=Decimal('10'), status='available',
|
||||
))
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision,
|
||||
)
|
||||
@@ -28,9 +28,9 @@ def _seed_match_facts(fixture):
|
||||
(fixture.snap_lines[0], 'matched', '0'),
|
||||
(fixture.snap_lines[1], 'not_found', '10'),
|
||||
):
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=fixture.order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
|
||||
line_index=snap_line.position, match_result=result, inventory_status='ready',
|
||||
line_index=snap_line.position, match_result=result, onhand_status='ready',
|
||||
required_qty='10', available_qty='10' if result == 'matched' else '0',
|
||||
shortage_qty=shortage, reservation_id=snap_line.reservation_id,
|
||||
part_number=snap_line.part_number, is_current=True,
|
||||
@@ -123,9 +123,9 @@ def test_closed_status_precedence_over_ok(app):
|
||||
fixture = _seed_frozen_order()
|
||||
# 仅第 0 行有匹配事实(matched+ready)且已结案:聚合视角为单行订单。
|
||||
snap_line = fixture.snap_lines[0]
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=fixture.order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
|
||||
line_index=snap_line.position, match_result='matched', inventory_status='ready',
|
||||
line_index=snap_line.position, match_result='matched', onhand_status='ready',
|
||||
required_qty='10', available_qty='10', shortage_qty='0',
|
||||
reservation_id=snap_line.reservation_id, part_number=snap_line.part_number,
|
||||
is_current=True,
|
||||
|
||||
@@ -29,7 +29,7 @@ def test_close_decision_syncs_gates_with_closed_trigger(app, monkeypatch):
|
||||
# 冻结订单夹具默认不带执行实例,须按结案现场补一条 blocked 的最小执行。
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='EXE-CLOSE-GATE-SYNC', task_id=int(fixture.order.id),
|
||||
status='blocked', current_gate_code='inventory_sufficiency', lock_version=1,
|
||||
status='blocked', current_gate_code='onhand_sufficiency', lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
|
||||
|
||||
def test_shortage_allows_retry_preparation_not_wait():
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
resolve_line_allowed_actions,
|
||||
)
|
||||
@@ -26,14 +26,14 @@ def test_shortage_allows_retry_preparation_not_wait():
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status='shortage',
|
||||
)
|
||||
assert inv == ['retry_inventory_preparation']
|
||||
assert 'wait_inventory' not in inv
|
||||
assert inv == ['retry_onhand_preparation']
|
||||
assert 'wait_onhand' not in inv
|
||||
assert 'change_inventory_source' not in inv
|
||||
assert line == ['close_unfulfillable']
|
||||
|
||||
|
||||
def test_rpa_running_hides_inventory_actions():
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
)
|
||||
|
||||
@@ -50,7 +50,7 @@ def test_rpa_running_hides_inventory_actions():
|
||||
|
||||
|
||||
def test_match_failed_with_snapshot_allows_matching():
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
)
|
||||
|
||||
@@ -63,11 +63,11 @@ def test_match_failed_with_snapshot_allows_matching():
|
||||
user_line_status='inventory_match_failed',
|
||||
has_usable_snapshot=True,
|
||||
)
|
||||
assert inv == ['retry_inventory_preparation', 'retry_inventory_matching']
|
||||
assert inv == ['retry_onhand_preparation', 'retry_onhand_matching']
|
||||
|
||||
|
||||
def test_matched_hides_inventory_icon_actions():
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
)
|
||||
|
||||
@@ -101,12 +101,12 @@ def test_fallback_only_without_lines():
|
||||
automation={'status': 'failed'},
|
||||
)
|
||||
assert fb is not None
|
||||
assert fb['allowed_actions'] == ['retry_inventory_preparation']
|
||||
assert fb['allowed_actions'] == ['retry_onhand_preparation']
|
||||
|
||||
|
||||
def test_waiting_to_start_allows_retry_preparation():
|
||||
"""automation waiting_to_start 不得清空库存重试动作(非真正 RPA 运行中)。"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
project_user_line_status,
|
||||
)
|
||||
@@ -128,7 +128,7 @@ def test_waiting_to_start_allows_retry_preparation():
|
||||
user_line_status=user_status,
|
||||
inventory_rpa_running=False,
|
||||
)
|
||||
assert inv == ['retry_inventory_preparation']
|
||||
assert inv == ['retry_onhand_preparation']
|
||||
|
||||
|
||||
def test_fallback_hidden_while_waiting():
|
||||
@@ -155,4 +155,4 @@ def test_waiting_inventory_maps_to_inventory_fetching_stage():
|
||||
SimpleNamespace(current_step=None, export_file_path=None),
|
||||
)
|
||||
assert status == 'automating'
|
||||
assert stage == 'inventory_fetching'
|
||||
assert stage == 'onhand_fetching'
|
||||
+9
-9
@@ -3,13 +3,13 @@ tests/test_line_inventory_match_persistence.py
|
||||
|
||||
用途:锁定 disposition → match_result 映射、not_found/invalid_key 语义,
|
||||
及行级匹配事实落库契约(含料号兜底总量 part_available_qty)。
|
||||
依赖:pytest、line_inventory_match_persistence、app 夹具(persist 用例)。
|
||||
依赖:pytest、line_onhand_match_persistence、app 夹具(persist 用例)。
|
||||
逻辑:映射用例纯单元;persist 用例写库(内存测试库),不触外部集成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||
from app.services.shipping_notice.line_onhand_match_persistence import (
|
||||
map_disposition_to_match_codes,
|
||||
persist_line_inventory_match_facts,
|
||||
)
|
||||
@@ -197,10 +197,10 @@ def test_persist_updates_part_available_qty_on_existing_row(app):
|
||||
def _make_inventory_file(app, file_no: str, warehouse_id: str) -> int:
|
||||
"""构造最小可用库存快照文件,返回主键。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
|
||||
file_row = ShippingInventoryFile(
|
||||
inventory_file_no=file_no,
|
||||
file_row = FreightRpaOnhandReportFile(
|
||||
onhand_file_no=file_no,
|
||||
storage_path=f'/tmp/{file_no}.xlsx',
|
||||
source_code='DSV360_TEST',
|
||||
warehouse_id=warehouse_id,
|
||||
@@ -237,7 +237,7 @@ def test_persist_attributes_line_to_hit_file_not_anchor(app):
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
|
||||
task = _make_snapshot_task('OT-LINE-FILE-ATTR')
|
||||
anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR', 'BYAWSCMH01')
|
||||
@@ -252,10 +252,10 @@ def test_persist_attributes_line_to_hit_file_not_anchor(app):
|
||||
inventory_snapshot_id=anchor_id,
|
||||
)
|
||||
# 断言意图:行事实挂到命中文件,而不是任务级锚点文件
|
||||
assert rows[0].inventory_snapshot_id == hit_id
|
||||
assert rows[0].onhand_snapshot_id == hit_id
|
||||
assert rows[0].matched_file_no == 'SIF-TEST-HIT'
|
||||
# 断言意图:仓库身份可由命中文件直接推出(Excel 仓库列数据源)
|
||||
hit_file = db.session.get(ShippingInventoryFile, rows[0].inventory_snapshot_id)
|
||||
hit_file = db.session.get(FreightRpaOnhandReportFile, rows[0].onhand_snapshot_id)
|
||||
assert hit_file.warehouse_id == 'AWSCV'
|
||||
|
||||
|
||||
@@ -274,4 +274,4 @@ def test_persist_falls_back_to_anchor_without_line_file_no(app):
|
||||
inventory_snapshot_id=anchor_id,
|
||||
)
|
||||
# 断言意图:无命中文件身份的行回退锚点快照(历史行为兼容)
|
||||
assert rows[0].inventory_snapshot_id == anchor_id
|
||||
assert rows[0].onhand_snapshot_id == anchor_id
|
||||
+2
-2
@@ -2,13 +2,13 @@
|
||||
tests/test_line_inventory_match_projection.py
|
||||
|
||||
用途:锁定库存匹配投影契约——not_found→0、result_missing 不得转 0、动作分域。
|
||||
依赖:pytest、line_inventory_match_projection。
|
||||
依赖:pytest、line_onhand_match_projection。
|
||||
逻辑:纯单元测试,不启 Flask 全应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
from app.services.shipping_notice.line_onhand_match_projection import (
|
||||
ACTION_CLOSE,
|
||||
ACTION_RELEASE_SHORTAGE,
|
||||
ACTION_RETRY_MATCHING,
|
||||
@@ -0,0 +1,374 @@
|
||||
"""s17c2d3e4f5a6 货代 RPA 批次 S 存量枚举数据迁移契约测试。
|
||||
|
||||
用途:锁定 s17c 只改字符串、挂在 s17b 之上,且 upgrade/downgrade 按词边界往返。
|
||||
依赖:migrations/versions(_load 手法沿用 tests/test_migration_tt16_job_keys.py)、
|
||||
SQLAlchemy 内存 SQLite、alembic Operations。
|
||||
逻辑:revision 链断言 + 桩表种子旧值 → upgrade 断言新值 → downgrade 断言旧值。
|
||||
更长标识、freight_upload、shipment、收料报表事件名不得被改写。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" / "versions"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app_ctx(app):
|
||||
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
|
||||
return app
|
||||
|
||||
|
||||
def _load(revision_prefix: str):
|
||||
for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix}*.py")):
|
||||
spec = importlib.util.spec_from_file_location(path.stem, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
raise AssertionError(f"migration {revision_prefix} not found")
|
||||
|
||||
|
||||
def test_revision_chains_from_s17b():
|
||||
"""s17c 必须单头挂在 s17b 上,且不改 s17b 自己的前驱。
|
||||
|
||||
[断言意图] 枚举数据迁移是 s17b 表 rename 之后的新 revision,不能改写 s17b 文件。
|
||||
"""
|
||||
migration = _load("s17c2d3e4f5a6")
|
||||
assert migration.revision == "s17c2d3e4f5a6"
|
||||
assert migration.down_revision == "s17b1c2d3e4f5a"
|
||||
parent = _load("s17b1c2d3e4f5a")
|
||||
assert parent.revision == "s17b1c2d3e4f5a"
|
||||
assert parent.down_revision == "tt16c7d8e9f0a1b2"
|
||||
|
||||
|
||||
def test_rewrite_keeps_longer_identifiers_and_protected_families():
|
||||
"""词边界:短契约词不能吃掉更长标识,也不能碰到 freight_upload / shipment。
|
||||
|
||||
[断言意图] ensure_inventory_via_rpa、inventory_file_no、inventory_rpa_workflow、
|
||||
.py 路径保持原样;inventory_rpa_queued 与权限整词会被换掉。
|
||||
"""
|
||||
migration = _load("s17c2d3e4f5a6")
|
||||
raw = (
|
||||
"ensure_inventory_via_rpa inventory_file_no inventory_preparation_failed "
|
||||
"inventory_rpa_workflow.py retry_inventory_matching inventory_rpa_queued "
|
||||
"freight_upload_rpa shipment_ready "
|
||||
"handlers/shipping_inventory_callback_process.py "
|
||||
"shipping_receipt_report_archived"
|
||||
)
|
||||
updated = migration.rewrite_persisted_text(raw, direction="upgrade")
|
||||
assert "ensure_inventory_via_rpa" in updated
|
||||
assert "inventory_file_no" in updated
|
||||
assert "inventory_preparation_failed" in updated
|
||||
assert "inventory_rpa_workflow.py" in updated
|
||||
assert "shipping_inventory_callback_process.py" in updated
|
||||
assert "retry_onhand_matching" in updated
|
||||
assert "onhand_rpa_queued" in updated
|
||||
assert "freight_upload_rpa" in updated
|
||||
assert "shipment_ready" in updated
|
||||
assert "shipping_receipt_report_archived" in updated
|
||||
assert migration.rewrite_persisted_text(updated, direction="downgrade") == raw
|
||||
|
||||
permission = migration.rewrite_persisted_text(
|
||||
'{"shipping_inventory": true, "shipping_inventory_sources": "x"}',
|
||||
direction="upgrade",
|
||||
permission=True,
|
||||
)
|
||||
assert '"freight_rpa": true' in permission
|
||||
assert '"freight_rpa_sources": "x"' in permission
|
||||
assert '"__s17c_perm_module":true' in permission
|
||||
assert migration.rewrite_persisted_text(permission, direction="downgrade", permission=True) == (
|
||||
'{"shipping_inventory": true, "shipping_inventory_sources": "x"}'
|
||||
)
|
||||
# [断言意图] Task 5 已写入的模块键没有本迁移标记,降级不得改回 shipping_inventory。
|
||||
already = '{"freight_rpa": true}'
|
||||
assert migration.rewrite_persisted_text(already, direction="downgrade", permission=True) == already
|
||||
|
||||
|
||||
def test_enum_data_upgrade_downgrade(app_ctx):
|
||||
"""SQLite 往返:旧契约值 upgrade 后换成新词,downgrade 逐列还原,对照行不动。
|
||||
|
||||
[断言意图] 桩表使用真实列名;权限写在 users / permission_roles / app_settings;
|
||||
freight_upload 与 shipment 对照值全程不变;收料报表事件名不是 RPA 事件,不改。
|
||||
"""
|
||||
engine = sa.create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
"jobs", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("job_type", sa.String(64)),
|
||||
sa.Column("payload_json", sa.Text()),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"schedule_tasks", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("schedule_type", sa.String(32)),
|
||||
sa.Column("job_params", sa.Text()),
|
||||
sa.Column("platform_api_path", sa.String(500)),
|
||||
sa.Column("data_source_type", sa.String(32)),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"shipping_order_tasks", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("stage", sa.String(64)),
|
||||
sa.Column("current_step", sa.String(64)),
|
||||
sa.Column("step_payload_json", sa.Text()),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"shipping_task_events", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("event_type", sa.String(64)),
|
||||
sa.Column("source", sa.String(64)),
|
||||
sa.Column("detail_json", sa.Text()),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"shipping_audit_events", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("event_type", sa.String(64)),
|
||||
sa.Column("aggregate_type", sa.String(64)),
|
||||
sa.Column("aggregate_id", sa.String(128)),
|
||||
sa.Column("actor_type", sa.String(16)),
|
||||
sa.Column("action", sa.String(64)),
|
||||
sa.Column("reason_code", sa.String(128)),
|
||||
sa.Column("before_snapshot_json", sa.Text()),
|
||||
sa.Column("after_snapshot_json", sa.Text()),
|
||||
sa.Column("diff_json", sa.Text()),
|
||||
sa.Column("previous_event_hash", sa.String(64)),
|
||||
sa.Column("event_hash", sa.String(64)),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"shipping_process_gates", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("gate_code", sa.String(64)),
|
||||
sa.Column("next_action_code", sa.String(64)),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"users", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("feature_permissions", sa.Text()),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"permission_roles", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("feature_permissions", sa.Text()),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"app_settings", metadata,
|
||||
sa.Column("key", sa.String(128), primary_key=True),
|
||||
sa.Column("value", sa.Text()),
|
||||
).create(connection)
|
||||
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO jobs (id, job_type, payload_json) VALUES "
|
||||
"(1, 'shipping_inventory_callback_process', '{\"action\":\"retry_inventory_preparation\"}'), "
|
||||
"(2, 'schedule_run', '{\"stage\":\"freight_upload_rpa\"}')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO schedule_tasks (id, schedule_type, job_params, platform_api_path, data_source_type) VALUES "
|
||||
"(1, 'platform_job', '{\"options_source\":\"shipping_inventory_sources\"}', 'freight-rpa-onhand', NULL), "
|
||||
"(2, 'platform_job', '{\"options_source\":\"shipping_receipt_sources\"}', 'freight-rpa-inbound', NULL), "
|
||||
"(3, 'platform_app', '{}', '/123', 'shipping_inventory_rpa')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_order_tasks (id, stage, current_step, step_payload_json) VALUES "
|
||||
"(1, 'inventory_matching', 'step3_inventory_prepare', "
|
||||
"'{\"action\":\"upload_inventory_file\",\"inventory_file_no\":\"F1\",\"fn\":\"ensure_inventory_via_rpa\"}'), "
|
||||
"(2, 'shipment_ready', 'freight_upload_rpa', '{\"action\":\"freight_upload_rpa\"}')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_task_events (id, event_type, source, detail_json) VALUES "
|
||||
"(1, 'inventory_rpa_queued', 'rpa', '{\"event\":\"rpa_report_inventory\"}'), "
|
||||
"(2, 'shipping_receipt_report_archived', 'freight_upload', '{}')"
|
||||
))
|
||||
from app.services.shipping_notice.audit_snapshot_service import (
|
||||
build_event_hash_payload,
|
||||
compute_event_hash,
|
||||
)
|
||||
unchanged_hash = compute_event_hash(build_event_hash_payload(
|
||||
event_type="shipping_receipt_report_downloaded",
|
||||
aggregate_type="file",
|
||||
aggregate_id="2",
|
||||
action=None,
|
||||
result=None,
|
||||
reason_code=None,
|
||||
workflow_id=None,
|
||||
workflow_item_id=None,
|
||||
workflow_item_version_id=None,
|
||||
version_no=None,
|
||||
run_no=None,
|
||||
document_id=None,
|
||||
review_case_no=None,
|
||||
task_no=None,
|
||||
operation_id=None,
|
||||
request_id=None,
|
||||
actor_type="user",
|
||||
actor_id=None,
|
||||
before_snapshot=None,
|
||||
after_snapshot=None,
|
||||
diff_json=None,
|
||||
previous_event_hash=None,
|
||||
sensitivity_level=None,
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_audit_events "
|
||||
"(id, event_type, aggregate_type, aggregate_id, actor_type, event_hash) VALUES "
|
||||
"(1, 'shipping_receipt_rpa_callback_received', 'unit', '1', 'rpa', 'stale-hash'), "
|
||||
"(2, 'shipping_receipt_report_downloaded', 'file', '2', 'user', :unchanged_hash)"
|
||||
), {"unchanged_hash": unchanged_hash})
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_process_gates (id, gate_code, next_action_code) VALUES "
|
||||
"(1, 'inventory_preparation', 'poll_inventory_preparation'), "
|
||||
"(2, 'freight_upload_rpa', 'retry_freight_upload_rpa')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO users (id, feature_permissions) VALUES "
|
||||
"(1, '{\"shipping_inventory\": true, \"shipping_notice_force_create\": true}'), "
|
||||
"(2, '{\"freight_rpa\": true}')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO permission_roles (id, feature_permissions) VALUES "
|
||||
"(1, '{\"shipping_inventory\": true}')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO app_settings (key, value) VALUES "
|
||||
"('admin_modules', 'shipping_inventory shipping_inventory_sources')"
|
||||
))
|
||||
|
||||
migration = _load("s17c2d3e4f5a6")
|
||||
migration.op = operations
|
||||
|
||||
def cell(table: str, column: str, row_id, pk: str = "id"):
|
||||
return connection.execute(sa.text(
|
||||
f'SELECT "{column}" FROM "{table}" WHERE "{pk}" = :row_id'
|
||||
), {"row_id": row_id}).scalar()
|
||||
|
||||
# [STEP 1] upgrade:旧契约换成新词,对照行与更长标识不动。
|
||||
migration.upgrade()
|
||||
assert cell("jobs", "job_type", 1) == "freight_rpa_onhand_callback_process"
|
||||
assert cell("jobs", "job_type", 2) == "schedule_run"
|
||||
assert "retry_onhand_preparation" in cell("jobs", "payload_json", 1)
|
||||
assert cell("jobs", "payload_json", 2) == '{"stage":"freight_upload_rpa"}'
|
||||
assert "freight_rpa_sources" in cell("schedule_tasks", "job_params", 1)
|
||||
assert "freight_rpa_inbound_sources" in cell("schedule_tasks", "job_params", 2)
|
||||
assert cell("schedule_tasks", "platform_api_path", 1) == "freight-rpa-onhand"
|
||||
assert cell("schedule_tasks", "data_source_type", 3) == "freight-rpa-onhand"
|
||||
assert cell("schedule_tasks", "platform_api_path", 3) == "freight-rpa-onhand"
|
||||
assert cell("schedule_tasks", "schedule_type", 3) == "platform_job"
|
||||
assert cell("shipping_order_tasks", "stage", 1) == "onhand_matching"
|
||||
assert cell("shipping_order_tasks", "current_step", 1) == "step3_onhand_prepare"
|
||||
payload = cell("shipping_order_tasks", "step_payload_json", 1)
|
||||
assert "upload_onhand_file" in payload
|
||||
assert "inventory_file_no" in payload
|
||||
assert "ensure_inventory_via_rpa" in payload
|
||||
assert cell("shipping_order_tasks", "stage", 2) == "shipment_ready"
|
||||
assert cell("shipping_task_events", "event_type", 1) == "onhand_rpa_queued"
|
||||
assert "rpa_report_onhand" in cell("shipping_task_events", "detail_json", 1)
|
||||
assert cell("shipping_task_events", "event_type", 2) == "shipping_receipt_report_archived"
|
||||
assert cell("shipping_task_events", "source", 2) == "freight_upload"
|
||||
assert cell("shipping_audit_events", "event_type", 1) == "shipping_inbound_rpa_callback_received"
|
||||
assert cell("shipping_audit_events", "event_type", 2) == "shipping_receipt_report_downloaded"
|
||||
expected_hash = compute_event_hash(build_event_hash_payload(
|
||||
event_type="shipping_inbound_rpa_callback_received",
|
||||
aggregate_type="unit",
|
||||
aggregate_id="1",
|
||||
action=None,
|
||||
result=None,
|
||||
reason_code=None,
|
||||
workflow_id=None,
|
||||
workflow_item_id=None,
|
||||
workflow_item_version_id=None,
|
||||
version_no=None,
|
||||
run_no=None,
|
||||
document_id=None,
|
||||
review_case_no=None,
|
||||
task_no=None,
|
||||
operation_id=None,
|
||||
request_id=None,
|
||||
actor_type="rpa",
|
||||
actor_id=None,
|
||||
before_snapshot=None,
|
||||
after_snapshot=None,
|
||||
diff_json=None,
|
||||
previous_event_hash=None,
|
||||
sensitivity_level=None,
|
||||
))
|
||||
assert cell("shipping_audit_events", "event_hash", 1) == expected_hash
|
||||
assert cell("shipping_audit_events", "event_hash", 2) == unchanged_hash
|
||||
assert cell("shipping_process_gates", "gate_code", 1) == "onhand_preparation"
|
||||
assert cell("shipping_process_gates", "next_action_code", 1) == "poll_onhand_preparation"
|
||||
assert cell("shipping_process_gates", "gate_code", 2) == "freight_upload_rpa"
|
||||
assert cell("shipping_process_gates", "next_action_code", 2) == "retry_freight_upload_rpa"
|
||||
user_permissions = cell("users", "feature_permissions", 1)
|
||||
assert '"freight_rpa": true' in user_permissions
|
||||
assert '"shipping_notice_force_create": true' in user_permissions
|
||||
assert '"__s17c_perm_module":true' in user_permissions
|
||||
assert cell("users", "feature_permissions", 2) == '{"freight_rpa": true}'
|
||||
assert '"__s17c_perm_module":true' in cell("permission_roles", "feature_permissions", 1)
|
||||
assert cell("app_settings", "value", "admin_modules", pk="key") == (
|
||||
"shipping_inventory freight_rpa_sources"
|
||||
)
|
||||
|
||||
# [STEP 2] downgrade:新词回到旧词,对照行仍不变。
|
||||
migration.downgrade()
|
||||
assert cell("jobs", "job_type", 1) == "shipping_inventory_callback_process"
|
||||
assert cell("jobs", "payload_json", 1) == '{"action":"retry_inventory_preparation"}'
|
||||
assert cell("schedule_tasks", "job_params", 1) == '{"options_source":"shipping_inventory_sources"}'
|
||||
assert cell("schedule_tasks", "job_params", 2) == '{"options_source":"shipping_receipt_sources"}'
|
||||
assert cell("schedule_tasks", "platform_api_path", 1) == "freight-rpa-onhand"
|
||||
assert cell("schedule_tasks", "data_source_type", 3) == "shipping_inventory_rpa"
|
||||
assert cell("shipping_order_tasks", "stage", 1) == "inventory_matching"
|
||||
assert cell("shipping_order_tasks", "current_step", 1) == "step3_inventory_prepare"
|
||||
assert cell("shipping_order_tasks", "step_payload_json", 1) == (
|
||||
'{"action":"upload_inventory_file","inventory_file_no":"F1","fn":"ensure_inventory_via_rpa"}'
|
||||
)
|
||||
assert cell("shipping_order_tasks", "stage", 2) == "shipment_ready"
|
||||
assert cell("shipping_task_events", "event_type", 1) == "inventory_rpa_queued"
|
||||
assert cell("shipping_task_events", "detail_json", 1) == '{"event":"rpa_report_inventory"}'
|
||||
assert cell("shipping_audit_events", "event_type", 1) == "shipping_receipt_rpa_callback_received"
|
||||
assert cell("shipping_process_gates", "gate_code", 1) == "inventory_preparation"
|
||||
assert cell("shipping_process_gates", "next_action_code", 1) == "poll_inventory_preparation"
|
||||
assert cell("shipping_process_gates", "gate_code", 2) == "freight_upload_rpa"
|
||||
assert cell("users", "feature_permissions", 1) == (
|
||||
'{"shipping_inventory": true, "shipping_notice_force_create": true}'
|
||||
)
|
||||
assert cell("users", "feature_permissions", 2) == '{"freight_rpa": true}'
|
||||
assert cell("app_settings", "value", "admin_modules", pk="key") == (
|
||||
"shipping_inventory shipping_inventory_sources"
|
||||
)
|
||||
restored_hash = compute_event_hash(build_event_hash_payload(
|
||||
event_type="shipping_receipt_rpa_callback_received",
|
||||
aggregate_type="unit",
|
||||
aggregate_id="1",
|
||||
action=None,
|
||||
result=None,
|
||||
reason_code=None,
|
||||
workflow_id=None,
|
||||
workflow_item_id=None,
|
||||
workflow_item_version_id=None,
|
||||
version_no=None,
|
||||
run_no=None,
|
||||
document_id=None,
|
||||
review_case_no=None,
|
||||
task_no=None,
|
||||
operation_id=None,
|
||||
request_id=None,
|
||||
actor_type="rpa",
|
||||
actor_id=None,
|
||||
before_snapshot=None,
|
||||
after_snapshot=None,
|
||||
diff_json=None,
|
||||
previous_event_hash=None,
|
||||
sensitivity_level=None,
|
||||
))
|
||||
assert cell("shipping_audit_events", "event_hash", 1) == restored_hash
|
||||
@@ -0,0 +1,420 @@
|
||||
"""s17b1c2d3e4f5a 货代 RPA 批次 S 的 29 表 rename 契约测试。
|
||||
|
||||
用途:锁定批次 S 第一段迁移——29 张表 rename、列名族(inventory→onhand /
|
||||
receipt→inbound,以及 inventory_source_id→source_id 等显式对照)、
|
||||
索引/外键/唯一/检查约束名中的旧表名替换,以及 downgrade 后原样还原。
|
||||
依赖:migrations/versions(_load 手法沿用 tests/test_migration_tt16_job_keys.py)、
|
||||
SQLAlchemy 内存 SQLite、alembic Operations。
|
||||
逻辑:revision 必须单头挂在 tt16c7d8e9f0a1b2;桩表跑 upgrade → downgrade →
|
||||
upgrade。29 张以外的表(发货行、货代取消)列名不得被改写。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" / "versions"
|
||||
|
||||
# 与迁移 _TABLE_RENAMES 对照的权威 29 对(旧, 新)。测试不从迁移模块读取,避免自证。
|
||||
_TABLE_RENAMES: list[tuple[str, str]] = [
|
||||
("shipping_inventory_sources", "freight_rpa_sources"),
|
||||
("shipping_rpa_profiles", "freight_rpa_profiles"),
|
||||
("shipping_inventory_fields", "freight_rpa_onhand_fields"),
|
||||
("shipping_inventory_source_parsing_binding_audits", "freight_rpa_onhand_source_parsing_binding_audits"),
|
||||
("shipping_inventory_parsing_profiles", "freight_rpa_parsing_profiles"),
|
||||
("shipping_inventory_structure_analyses", "freight_rpa_onhand_structure_analyses"),
|
||||
("shipping_inventory_configuration_test_runs", "freight_rpa_onhand_configuration_test_runs"),
|
||||
("shipping_inventory_validation_batches", "freight_rpa_onhand_validation_batches"),
|
||||
("shipping_inventory_routing_rules", "freight_rpa_onhand_routing_rules"),
|
||||
("shipping_inventory_routing_rule_conditions", "freight_rpa_onhand_routing_rule_conditions"),
|
||||
("shipping_inventory_routing_rule_versions", "freight_rpa_onhand_routing_rule_versions"),
|
||||
("shipping_inventory_external_mappings", "freight_rpa_onhand_external_mappings"),
|
||||
("shipping_inventory_mappings", "freight_rpa_onhand_mappings"),
|
||||
("shipping_task_inventory_rpa_attempts", "freight_rpa_onhand_task_rpa_attempts"),
|
||||
("shipping_receipt_report_configs", "freight_rpa_inbound_report_configs"),
|
||||
("shipping_receipt_rpa_unit_runs", "freight_rpa_inbound_rpa_unit_runs"),
|
||||
("shipping_receipt_report_files", "freight_rpa_inbound_report_files"),
|
||||
("shipping_receipt_notification_deliveries", "freight_rpa_inbound_notification_deliveries"),
|
||||
("shipping_inventory_files", "shipping_onhand_files"),
|
||||
("shipping_inventory_candidate_sets", "shipping_onhand_candidate_sets"),
|
||||
("shipping_inventory_candidate_sources", "shipping_onhand_candidate_sources"),
|
||||
("shipping_inventory_candidate_lines", "shipping_onhand_candidate_lines"),
|
||||
("shipping_inventory_preparation_attempts", "shipping_onhand_preparation_attempts"),
|
||||
("shipping_inventory_preparation_source_attempts", "shipping_onhand_preparation_source_attempts"),
|
||||
("shipping_task_inventory_links", "shipping_task_onhand_links"),
|
||||
("shipping_temporary_inventory_sessions", "shipping_temporary_onhand_sessions"),
|
||||
("shipping_notice_line_inventory_matches", "shipping_notice_line_onhand_matches"),
|
||||
("shipping_notice_inventory_verifications", "shipping_notice_onhand_verifications"),
|
||||
("shipping_notice_inventory_verification_lines", "shipping_notice_onhand_verification_lines"),
|
||||
]
|
||||
|
||||
# PostgreSQL NAMEDATALEN-1 = 63。通知投递外键替换后超过 63,迁移截断且降级能还原。
|
||||
# 历史迁移没有单列 recipient 索引;升级补建模型短名,降级删除。
|
||||
# 验证批次索引一对一:ix_inventory_test_run_validation_batch ↔ 模型短名。
|
||||
_LONG_FK = "shipping_receipt_notification_deliveries_recipient_user_id_fkey"
|
||||
_RECIPIENT_INDEX_NEW = "ix_fr_inbound_notif_deliveries_recipient_user_id"
|
||||
_COMPOSITE_RECIPIENT_INDEX = "ix_shipping_receipt_delivery_file_recipient"
|
||||
_LONG_FK_NEW = "freight_rpa_inbound_notification_deliveries_recipient_user_id_fkey"[:63]
|
||||
_VALIDATION_INDEX = "ix_inventory_test_run_validation_batch"
|
||||
_VALIDATION_INDEX_NEW = "ix_fr_onhand_cfg_test_runs_validation_batch_id"
|
||||
|
||||
|
||||
def _load(revision_prefix: str):
|
||||
"""按 revision 前缀加载迁移模块。
|
||||
|
||||
核心逻辑:在 migrations/versions 下按文件名前缀定位唯一模块并 exec。
|
||||
|
||||
Args:
|
||||
revision_prefix: revision id 或其唯一前缀。
|
||||
|
||||
Returns:
|
||||
已执行的迁移模块。
|
||||
|
||||
Raises:
|
||||
AssertionError: 找不到对应迁移文件。
|
||||
"""
|
||||
for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix}*.py")):
|
||||
spec = importlib.util.spec_from_file_location(path.stem, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
raise AssertionError(f"migration {revision_prefix} not found")
|
||||
|
||||
|
||||
def _table_names(connection) -> set[str]:
|
||||
"""反射当前库的用户表名集合。"""
|
||||
return set(sa.inspect(connection).get_table_names())
|
||||
|
||||
|
||||
def _column_names(connection, table: str) -> set[str]:
|
||||
"""反射指定表的列名集合。"""
|
||||
return {column["name"] for column in sa.inspect(connection).get_columns(table)}
|
||||
|
||||
|
||||
def _create_stub_schema(connection) -> None:
|
||||
"""建 29 张旧表、两条 29 张以外的对照表,以及一条索引和两条外键。
|
||||
|
||||
核心逻辑:只建契约所需的最小列。sources 带唯一约束;mappings 带指向
|
||||
sources 的外键和索引;receipt 文件表带含 receipt 的列与检查约束;
|
||||
notification deliveries 带历史复合索引和超长外键名(PG 63 字节边界),
|
||||
不预建单列 recipient 索引;
|
||||
notice lines 的外键指向将被改名的 files,但其自身列名不得改。
|
||||
"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
"users", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"shipping_notice_freight_cancellations", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("freight_receipt_no", sa.String(128)),
|
||||
sa.Column("receipt_asset_id", sa.Integer()),
|
||||
).create(connection)
|
||||
|
||||
extras: dict[str, list] = {
|
||||
"shipping_inventory_sources": [
|
||||
sa.Column("source_code", sa.String(64), nullable=False),
|
||||
sa.UniqueConstraint("source_code", name="uq_shipping_inventory_sources_source_code"),
|
||||
],
|
||||
"shipping_inventory_files": [
|
||||
sa.Column("inventory_file_no", sa.String(64), nullable=False),
|
||||
],
|
||||
"shipping_inventory_external_mappings": [
|
||||
sa.Column("inventory_source_id", sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["inventory_source_id"],
|
||||
["shipping_inventory_sources.id"],
|
||||
name="fk_shipping_inventory_external_mappings_source_id",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.Index("ix_shipping_inventory_external_mappings_source_id", "inventory_source_id"),
|
||||
],
|
||||
"shipping_notice_line_inventory_matches": [
|
||||
sa.Column("inventory_source_code", sa.String(64)),
|
||||
sa.Column("inventory_status", sa.String(32)),
|
||||
],
|
||||
"shipping_receipt_report_files": [
|
||||
sa.Column("receipt_note", sa.String(32)),
|
||||
sa.CheckConstraint(
|
||||
"receipt_note IS NULL OR length(receipt_note) > 0",
|
||||
name="ck_shipping_receipt_report_files_note",
|
||||
),
|
||||
],
|
||||
"shipping_inventory_configuration_test_runs": [
|
||||
sa.Column("validation_batch_id", sa.Integer()),
|
||||
sa.Index(_VALIDATION_INDEX, "validation_batch_id"),
|
||||
],
|
||||
"shipping_receipt_notification_deliveries": [
|
||||
sa.Column("recipient_user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("report_file_id", sa.Integer()),
|
||||
sa.ForeignKeyConstraint(
|
||||
["recipient_user_id"],
|
||||
["users.id"],
|
||||
name=_LONG_FK,
|
||||
),
|
||||
sa.Index(_COMPOSITE_RECIPIENT_INDEX, "report_file_id", "recipient_user_id"),
|
||||
],
|
||||
}
|
||||
|
||||
# 被引用表先建,避免 SQLite 建外键时找不到目标。
|
||||
first = ("shipping_inventory_sources", "shipping_inventory_files")
|
||||
ordered = list(first) + [old for old, _new in _TABLE_RENAMES if old not in first]
|
||||
for old in ordered:
|
||||
args: list = [sa.Column("id", sa.Integer(), primary_key=True), *extras.get(old, ())]
|
||||
sa.Table(old, metadata, *args).create(connection)
|
||||
|
||||
sa.Table(
|
||||
"shipping_notice_lines", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("inventory_file_id", sa.Integer()),
|
||||
sa.ForeignKeyConstraint(
|
||||
["inventory_file_id"],
|
||||
["shipping_inventory_files.id"],
|
||||
name="fk_shipping_notice_lines_shipping_inventory_files",
|
||||
ondelete="SET NULL",
|
||||
),
|
||||
).create(connection)
|
||||
|
||||
|
||||
def _seed(connection) -> None:
|
||||
"""写入跨表外键可校验的最小行,确认 rename 不丢数据。"""
|
||||
connection.execute(sa.text("INSERT INTO users (id) VALUES (1)"))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_inventory_sources (id, source_code) VALUES (1, 'DBS')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_inventory_files (id, inventory_file_no) VALUES (7, 'F-7')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_inventory_external_mappings (id, inventory_source_id) VALUES (10, 1)"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_notice_line_inventory_matches "
|
||||
"(id, inventory_source_code, inventory_status) VALUES (3, 'CRANE', 'ready')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_receipt_report_files (id, receipt_note) VALUES (4, 'note')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_receipt_notification_deliveries (id, recipient_user_id) VALUES (8, 1)"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_notice_lines (id, inventory_file_id) VALUES (5, 7)"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_notice_freight_cancellations "
|
||||
"(id, freight_receipt_no, receipt_asset_id) VALUES (6, 'R1', 9)"
|
||||
))
|
||||
|
||||
|
||||
def _fk_ok(connection) -> None:
|
||||
"""断言 SQLite 外键目标在 rename 之后仍然指向现存主键。"""
|
||||
broken = connection.execute(sa.text("PRAGMA foreign_key_check")).fetchall()
|
||||
assert broken == []
|
||||
|
||||
|
||||
def _assert_baseline(connection) -> None:
|
||||
"""升级前:29 张旧表在、新表不在,代表列与对象名仍是旧词根。"""
|
||||
names = _table_names(connection)
|
||||
# [断言意图] 29 对一一存在且互不覆盖,避免漏表或新旧同名。
|
||||
assert len(_TABLE_RENAMES) == 29
|
||||
for old, new in _TABLE_RENAMES:
|
||||
assert old in names
|
||||
assert new not in names
|
||||
assert _column_names(connection, "shipping_inventory_sources") >= {"source_code"}
|
||||
assert "inventory_source_id" in _column_names(connection, "shipping_inventory_external_mappings")
|
||||
assert "inventory_file_no" in _column_names(connection, "shipping_inventory_files")
|
||||
assert {"inventory_source_code", "inventory_status"} <= _column_names(
|
||||
connection, "shipping_notice_line_inventory_matches",
|
||||
)
|
||||
assert "receipt_note" in _column_names(connection, "shipping_receipt_report_files")
|
||||
# [断言意图] 29 张以外的 inventory/receipt 列不在本次改名范围。
|
||||
assert "inventory_file_id" in _column_names(connection, "shipping_notice_lines")
|
||||
assert {"freight_receipt_no", "receipt_asset_id"} <= _column_names(
|
||||
connection, "shipping_notice_freight_cancellations",
|
||||
)
|
||||
|
||||
|
||||
def _assert_upgraded(connection) -> None:
|
||||
"""升级后:新表名、列名、索引名、外键名到位,对照表不动,行数据仍在。"""
|
||||
names = _table_names(connection)
|
||||
for old, new in _TABLE_RENAMES:
|
||||
assert new in names
|
||||
assert old not in names
|
||||
assert "shipping_notice_lines" in names
|
||||
assert "shipping_notice_freight_cancellations" in names
|
||||
|
||||
# [断言意图] 显式列对照、通用 inventory→onhand、receipt 表 receipt→inbound。
|
||||
assert "source_id" in _column_names(connection, "freight_rpa_onhand_external_mappings")
|
||||
assert "inventory_source_id" not in _column_names(connection, "freight_rpa_onhand_external_mappings")
|
||||
assert "source_code" in _column_names(connection, "freight_rpa_sources")
|
||||
assert "onhand_file_no" in _column_names(connection, "shipping_onhand_files")
|
||||
assert "inventory_file_no" not in _column_names(connection, "shipping_onhand_files")
|
||||
matches = _column_names(connection, "shipping_notice_line_onhand_matches")
|
||||
assert "source_code" in matches and "inventory_source_code" not in matches
|
||||
assert "onhand_status" in matches and "inventory_status" not in matches
|
||||
files = _column_names(connection, "freight_rpa_inbound_report_files")
|
||||
assert "inbound_note" in files and "receipt_note" not in files
|
||||
# [断言意图] 取消单与发货行不在 29 张内,receipt/inventory 列保持原名。
|
||||
assert _column_names(connection, "shipping_notice_lines") >= {"inventory_file_id"}
|
||||
assert "onhand_file_id" not in _column_names(connection, "shipping_notice_lines")
|
||||
assert {"freight_receipt_no", "receipt_asset_id"} <= _column_names(
|
||||
connection, "shipping_notice_freight_cancellations",
|
||||
)
|
||||
|
||||
inspector = sa.inspect(connection)
|
||||
indexes = inspector.get_indexes("freight_rpa_onhand_external_mappings")
|
||||
index = next(item for item in indexes if item["name"] == "ix_freight_rpa_onhand_external_mappings_source_id")
|
||||
# [断言意图] 索引名替换旧表名,索引列跟随 inventory_source_id→source_id。
|
||||
assert index["column_names"] == ["source_id"]
|
||||
assert not any("shipping_inventory_external_mappings" in item["name"] for item in indexes)
|
||||
|
||||
foreign_keys = inspector.get_foreign_keys("freight_rpa_onhand_external_mappings")
|
||||
foreign_key = next(
|
||||
item for item in foreign_keys
|
||||
if item["name"] == "fk_freight_rpa_onhand_external_mappings_source_id"
|
||||
)
|
||||
# [断言意图] 外键名替换旧表名,目标表已是新名,ON DELETE 保留。
|
||||
assert foreign_key["referred_table"] == "freight_rpa_sources"
|
||||
assert foreign_key["constrained_columns"] == ["source_id"]
|
||||
assert foreign_key["referred_columns"] == ["id"]
|
||||
assert (foreign_key.get("options") or {}).get("ondelete") == "CASCADE"
|
||||
|
||||
outside = inspector.get_foreign_keys("shipping_notice_lines")
|
||||
outside_fk = next(
|
||||
item for item in outside
|
||||
if item["name"] == "fk_shipping_notice_lines_shipping_onhand_files"
|
||||
)
|
||||
assert outside_fk["referred_table"] == "shipping_onhand_files"
|
||||
assert outside_fk["constrained_columns"] == ["inventory_file_id"]
|
||||
|
||||
uniques = inspector.get_unique_constraints("freight_rpa_sources")
|
||||
assert any(item["name"] == "uq_freight_rpa_sources_source_code" for item in uniques)
|
||||
checks = inspector.get_check_constraints("freight_rpa_inbound_report_files")
|
||||
check = next(item for item in checks if item["name"] == "ck_freight_rpa_inbound_report_files_note")
|
||||
assert "inbound_note" in check["sqltext"]
|
||||
assert "receipt_note" not in check["sqltext"]
|
||||
|
||||
delivery_indexes = inspector.get_indexes("freight_rpa_inbound_notification_deliveries")
|
||||
delivery_names = {item["name"] for item in delivery_indexes}
|
||||
recipient = next(item for item in delivery_indexes if item["name"] == _RECIPIENT_INDEX_NEW)
|
||||
# [断言意图] 历史库没有单列索引,升级补建模型短名;复合索引名保持不动。
|
||||
assert len(_RECIPIENT_INDEX_NEW) <= 63
|
||||
assert recipient["column_names"] == ["recipient_user_id"]
|
||||
assert _COMPOSITE_RECIPIENT_INDEX in delivery_names
|
||||
validation_indexes = inspector.get_indexes("freight_rpa_onhand_configuration_test_runs")
|
||||
assert len(_VALIDATION_INDEX_NEW) <= 63
|
||||
assert any(item["name"] == _VALIDATION_INDEX_NEW for item in validation_indexes)
|
||||
assert not any(item["name"] == _VALIDATION_INDEX for item in validation_indexes)
|
||||
long_fks = inspector.get_foreign_keys("freight_rpa_inbound_notification_deliveries")
|
||||
long_fk = next(item for item in long_fks if item["name"] == _LONG_FK_NEW)
|
||||
assert long_fk["referred_table"] == "users"
|
||||
assert long_fk["constrained_columns"] == ["recipient_user_id"]
|
||||
|
||||
assert connection.execute(sa.text(
|
||||
"SELECT source_code FROM freight_rpa_sources WHERE id = 1"
|
||||
)).scalar() == "DBS"
|
||||
assert connection.execute(sa.text(
|
||||
"SELECT source_id FROM freight_rpa_onhand_external_mappings WHERE id = 10"
|
||||
)).scalar() == 1
|
||||
assert connection.execute(sa.text(
|
||||
"SELECT onhand_file_no FROM shipping_onhand_files WHERE id = 7"
|
||||
)).scalar() == "F-7"
|
||||
assert connection.execute(sa.text(
|
||||
"SELECT source_code FROM shipping_notice_line_onhand_matches WHERE id = 3"
|
||||
)).scalar() == "CRANE"
|
||||
assert connection.execute(sa.text(
|
||||
"SELECT inbound_note FROM freight_rpa_inbound_report_files WHERE id = 4"
|
||||
)).scalar() == "note"
|
||||
assert connection.execute(sa.text(
|
||||
"SELECT freight_receipt_no FROM shipping_notice_freight_cancellations WHERE id = 6"
|
||||
)).scalar() == "R1"
|
||||
_fk_ok(connection)
|
||||
|
||||
|
||||
def _assert_downgraded(connection) -> None:
|
||||
"""降级后:旧表名、旧列名、旧索引/外键名与原行一起回来。"""
|
||||
_assert_baseline(connection)
|
||||
inspector = sa.inspect(connection)
|
||||
indexes = inspector.get_indexes("shipping_inventory_external_mappings")
|
||||
assert any(item["name"] == "ix_shipping_inventory_external_mappings_source_id" for item in indexes)
|
||||
foreign_keys = inspector.get_foreign_keys("shipping_inventory_external_mappings")
|
||||
foreign_key = next(
|
||||
item for item in foreign_keys
|
||||
if item["name"] == "fk_shipping_inventory_external_mappings_source_id"
|
||||
)
|
||||
assert foreign_key["referred_table"] == "shipping_inventory_sources"
|
||||
assert foreign_key["constrained_columns"] == ["inventory_source_id"]
|
||||
outside = inspector.get_foreign_keys("shipping_notice_lines")
|
||||
assert any(item["name"] == "fk_shipping_notice_lines_shipping_inventory_files" for item in outside)
|
||||
uniques = inspector.get_unique_constraints("shipping_inventory_sources")
|
||||
assert any(item["name"] == "uq_shipping_inventory_sources_source_code" for item in uniques)
|
||||
checks = inspector.get_check_constraints("shipping_receipt_report_files")
|
||||
check = next(item for item in checks if item["name"] == "ck_shipping_receipt_report_files_note")
|
||||
# [断言意图] 降级先还原约束名,再把 inbound_note 列改回 receipt_note,检查表达式必须跟着回来。
|
||||
assert "receipt_note" in check["sqltext"]
|
||||
assert "inbound_note" not in check["sqltext"]
|
||||
delivery_indexes = inspector.get_indexes("shipping_receipt_notification_deliveries")
|
||||
delivery_names = {item["name"] for item in delivery_indexes}
|
||||
# [断言意图] 补建的单列索引降级删除;复合索引仍在;验证批次索引回到唯一旧名。
|
||||
assert _RECIPIENT_INDEX_NEW not in delivery_names
|
||||
assert "ix_shipping_receipt_notification_deliveries_recipient_user_id" not in delivery_names
|
||||
assert _COMPOSITE_RECIPIENT_INDEX in delivery_names
|
||||
validation_indexes = inspector.get_indexes("shipping_inventory_configuration_test_runs")
|
||||
validation_names = {item["name"] for item in validation_indexes}
|
||||
assert validation_names == {_VALIDATION_INDEX}
|
||||
long_fks = inspector.get_foreign_keys("shipping_receipt_notification_deliveries")
|
||||
assert any(item["name"] == _LONG_FK for item in long_fks)
|
||||
assert connection.execute(sa.text(
|
||||
"SELECT source_code FROM shipping_inventory_sources WHERE id = 1"
|
||||
)).scalar() == "DBS"
|
||||
assert connection.execute(sa.text(
|
||||
"SELECT inventory_source_id FROM shipping_inventory_external_mappings WHERE id = 10"
|
||||
)).scalar() == 1
|
||||
_fk_ok(connection)
|
||||
|
||||
|
||||
def test_revision_chains_from_tt16():
|
||||
"""s17 必须单头挂接当前 head tt16c7d8e9f0a1b2。
|
||||
|
||||
[断言意图] 再挂更早的 revision 会产生双 head,flask db upgrade 无法直行。
|
||||
"""
|
||||
migration = _load("s17b1c2d3e4f5a")
|
||||
assert migration.revision == "s17b1c2d3e4f5a"
|
||||
assert migration.down_revision == "tt16c7d8e9f0a1b2"
|
||||
|
||||
|
||||
def test_sqlite_rename_roundtrip():
|
||||
"""SQLite 往返:upgrade 换 29 表与对象名,downgrade 还原,再 upgrade 仍成立。
|
||||
|
||||
[断言意图] rename_table 本身不改索引/外键名;本迁移必须改写含旧表名的对象,
|
||||
列规则只作用于这 29 张表,且数据与外键目标在两轮 upgrade 后仍然有效。
|
||||
"""
|
||||
engine = sa.create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
_create_stub_schema(connection)
|
||||
_seed(connection)
|
||||
_assert_baseline(connection)
|
||||
|
||||
migration = _load("s17b1c2d3e4f5a")
|
||||
migration.op = operations
|
||||
|
||||
migration.upgrade()
|
||||
_assert_upgraded(connection)
|
||||
|
||||
migration.downgrade()
|
||||
_assert_downgraded(connection)
|
||||
|
||||
migration.upgrade()
|
||||
_assert_upgraded(connection)
|
||||
@@ -0,0 +1,331 @@
|
||||
"""tests/test_migration_s18_phase_b_report_ownership.py
|
||||
|
||||
用途:锁定阶段 B 报表归属迁移 s18d1e2f3a4b5——新建 freight_rpa_onhand_report_configs,
|
||||
把站点行上的 report_path_json / query_parameters_json / parsing_profile_id 搬进该表,
|
||||
把启用检查约束换成只看 excel_template_id 的模板版本,并把 shipping_onhand_files
|
||||
改名为 freight_rpa_onhand_report_files;downgrade 必须全部原样还原。
|
||||
依赖:migrations/versions(_load 手法沿用 tests/test_migration_s17_batch_s_rename.py)、
|
||||
SQLAlchemy 内存 SQLite、alembic MigrationContext / Operations。
|
||||
逻辑:s18 必须单头挂 s17c2d3e4f5a6;s17b 解析方案目标名只能是 freight_rpa_parsing_profiles,
|
||||
不允许出现 freight_rpa_onhand_parsing_profiles;op fixture 桩出 s17c 之后的库状态
|
||||
(freight_rpa_sources 与 shipping_onhand_files 及其外键目标表),upgrade → downgrade
|
||||
往返校验列搬移、数据搬移、约束替换与文件表改名。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic import op as alembic_op
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" / "versions"
|
||||
|
||||
# 测试自己定义桩表与期望对象名,不从迁移模块读取,避免自证。
|
||||
_SOURCES_TABLE = "freight_rpa_sources"
|
||||
_FILES_TABLE_OLD = "shipping_onhand_files"
|
||||
_FILES_TABLE_NEW = "freight_rpa_onhand_report_files"
|
||||
# 历史上建在文件表上的两条对象名,用于逼出“对象名含旧表名则替换”的扫描路径。
|
||||
_FILES_USER_CREATED_INDEX = f"ix_{_FILES_TABLE_OLD}_user_created"
|
||||
_FILES_SIZE_CHECK = f"ck_{_FILES_TABLE_OLD}_size"
|
||||
# 站点上的旧启用约束名与表达式(c27e 创建,s17b 换到新表名词根)。
|
||||
_ENABLED_BINDINGS_CHECK = "ck_freight_rpa_sources_enabled_bindings"
|
||||
_ENABLED_BINDINGS_SQL = (
|
||||
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)"
|
||||
)
|
||||
# 迁移在 alembic.op 模块上可能调用的入口。fixture 逐个替换为本连接上的 Operations。
|
||||
_OP_METHODS = (
|
||||
"add_column",
|
||||
"alter_column",
|
||||
"batch_alter_table",
|
||||
"create_check_constraint",
|
||||
"create_foreign_key",
|
||||
"create_index",
|
||||
"create_table",
|
||||
"drop_column",
|
||||
"drop_constraint",
|
||||
"drop_index",
|
||||
"drop_table",
|
||||
"execute",
|
||||
"get_bind",
|
||||
"rename_table",
|
||||
)
|
||||
|
||||
|
||||
def _load(revision_prefix: str):
|
||||
"""按 revision 前缀加载迁移模块。
|
||||
|
||||
核心逻辑:在 migrations/versions 下按文件名前缀定位唯一模块并 exec。
|
||||
|
||||
Args:
|
||||
revision_prefix: revision id 或其唯一前缀。
|
||||
|
||||
Returns:
|
||||
已执行的迁移模块。
|
||||
|
||||
Raises:
|
||||
AssertionError: 找不到对应迁移文件。
|
||||
"""
|
||||
for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix.removesuffix('.py')}*.py")):
|
||||
spec = importlib.util.spec_from_file_location(path.stem, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
raise AssertionError(f"migration {revision_prefix} not found")
|
||||
|
||||
|
||||
def _table_names(op) -> set[str]:
|
||||
"""反射当前库的用户表名集合。
|
||||
|
||||
Args:
|
||||
op: alembic Operations 对象。
|
||||
|
||||
Returns:
|
||||
表名集合(不含 sqlite_ 内部表)。
|
||||
"""
|
||||
return {
|
||||
name for name in sa.inspect(op.get_bind()).get_table_names()
|
||||
if not name.startswith("sqlite_")
|
||||
}
|
||||
|
||||
|
||||
def _column_names(op, table: str) -> set[str]:
|
||||
"""反射指定表的列名集合。
|
||||
|
||||
Args:
|
||||
op: alembic Operations 对象。
|
||||
table: 表名。
|
||||
|
||||
Returns:
|
||||
列名集合。表不存在时抛 KeyError(测试不应走到该分支)。
|
||||
"""
|
||||
return {column["name"] for column in sa.inspect(op.get_bind()).get_columns(table)}
|
||||
|
||||
|
||||
def _check_names(op, table: str) -> set[str]:
|
||||
"""反射指定表上的检查约束名集合,用于确认约束替换生效。
|
||||
|
||||
Args:
|
||||
op: alembic Operations 对象。
|
||||
table: 表名。
|
||||
|
||||
Returns:
|
||||
检查约束名集合。
|
||||
"""
|
||||
return {item["name"] for item in sa.inspect(op.get_bind()).get_check_constraints(table)}
|
||||
|
||||
|
||||
def _index_names(op, table: str) -> set[str]:
|
||||
"""反射指定表上的索引名集合,用于确认索引名跟随表名替换。
|
||||
|
||||
Args:
|
||||
op: alembic Operations 对象。
|
||||
table: 表名。
|
||||
|
||||
Returns:
|
||||
索引名集合。
|
||||
"""
|
||||
return {item["name"] for item in sa.inspect(op.get_bind()).get_indexes(table)}
|
||||
|
||||
|
||||
def _create_stub_schema(connection) -> None:
|
||||
"""桩出 s17c 之后的库状态:站点表、在手文件表与其外键目标表。
|
||||
|
||||
核心逻辑:freight_rpa_sources 带本期要搬走的三列与旧启用检查约束;
|
||||
shipping onhand files 带解析行、快照状态,以及名字含旧表名的索引与
|
||||
检查约束,用来逼出 s18 的对象名重写扫描。其余是被引用的最小行表。
|
||||
"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
"users", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"freight_rpa_parsing_profiles", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"shipping_excel_templates", metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
_SOURCES_TABLE, metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("source_code", sa.String(64), nullable=False),
|
||||
sa.Column("enabled", sa.Boolean(), nullable=False),
|
||||
sa.Column("parsing_profile_id", sa.Integer(), nullable=True),
|
||||
sa.Column("excel_template_id", sa.Integer(), nullable=True),
|
||||
sa.Column("report_path_json", sa.JSON(), nullable=False),
|
||||
sa.Column("query_parameters_json", sa.JSON(), nullable=False),
|
||||
sa.Column("config_version", sa.Integer(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint("source_code", name="uq_freight_rpa_sources_source_code"),
|
||||
sa.CheckConstraint(_ENABLED_BINDINGS_SQL, name=_ENABLED_BINDINGS_CHECK),
|
||||
# 与生产同构:搬走的三列中 parsing_profile_id 上既有外键也有独立索引;
|
||||
# excel_template 外键与唯一约束则原样穿过列删改。
|
||||
sa.ForeignKeyConstraint(
|
||||
["parsing_profile_id"], ["freight_rpa_parsing_profiles.id"],
|
||||
name="fk_inventory_sources_parsing_profile",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["excel_template_id"], ["shipping_excel_templates.id"],
|
||||
name="fk_inventory_sources_excel_template",
|
||||
),
|
||||
sa.Index("ix_freight_rpa_sources_parsing_profile_id", "parsing_profile_id"),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
_FILES_TABLE_OLD, metadata,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("user_id", sa.Integer(), nullable=True),
|
||||
sa.Column("onhand_lines_json", sa.JSON(), nullable=True),
|
||||
sa.Column("snapshot_status", sa.String(32), nullable=True),
|
||||
sa.Column("file_size", sa.Integer(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=True),
|
||||
sa.CheckConstraint("file_size IS NULL OR file_size >= 0", name=_FILES_SIZE_CHECK),
|
||||
sa.Index(_FILES_USER_CREATED_INDEX, "user_id", "created_at"),
|
||||
).create(connection)
|
||||
|
||||
|
||||
def _seed(connection) -> None:
|
||||
"""写入一条满足旧启用检查的站点行与一条在手文件行,供搬移断言使用。"""
|
||||
connection.execute(sa.text("INSERT INTO users (id) VALUES (1)"))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO freight_rpa_parsing_profiles (id) VALUES (1)"
|
||||
))
|
||||
connection.execute(sa.text("INSERT INTO shipping_excel_templates (id) VALUES (9)"))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO freight_rpa_sources "
|
||||
"(id, source_code, enabled, parsing_profile_id, excel_template_id, "
|
||||
"report_path_json, query_parameters_json, config_version, "
|
||||
"created_at, updated_at) "
|
||||
"VALUES (1, 'DSV', 1, 1, 9, "
|
||||
"'{\"menu\": \"onhand\"}', '[{\"name\": \"wh\"}]', 3, "
|
||||
"'2026-10-18 08:00:00', '2026-10-18 08:00:00')"
|
||||
))
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_onhand_files "
|
||||
"(id, user_id, onhand_lines_json, snapshot_status, file_size) "
|
||||
"VALUES (7, 1, '[{\"sku\": \"A\"}]', 'ready', 128)"
|
||||
))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def op(monkeypatch):
|
||||
"""给迁移模块提供接线到内存 SQLite 的 alembic.op。
|
||||
|
||||
核心逻辑:建桩库并播种后,把 alembic.op 模块上的操作入口逐个替换为
|
||||
本连接上的 Operations 方法。迁移模块以 `from alembic import op` 取到
|
||||
同一个模块对象,属性查找在调用时发生,因此无需逐模块注入。
|
||||
测试结束后 monkeypatch 恢复 alembic.op,避免污染其它测试。
|
||||
"""
|
||||
engine = sa.create_engine("sqlite:///:memory:")
|
||||
with engine.connect() as connection:
|
||||
_create_stub_schema(connection)
|
||||
_seed(connection)
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
for method in _OP_METHODS:
|
||||
monkeypatch.setattr(alembic_op, method, getattr(operations, method), raising=False)
|
||||
yield operations
|
||||
|
||||
|
||||
def test_s18_revision_follows_s17c():
|
||||
migration = _load("s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py")
|
||||
assert migration.revision == "s18d1e2f3a4b5"
|
||||
assert migration.down_revision == "s17c2d3e4f5a6"
|
||||
|
||||
|
||||
def test_s17b_parsing_profile_target_is_final_name():
|
||||
s17b = _load("s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py")
|
||||
assert ("shipping_inventory_parsing_profiles", "freight_rpa_parsing_profiles") in s17b._TABLE_RENAMES
|
||||
assert "freight_rpa_onhand_parsing_profiles" not in str(s17b._TABLE_RENAMES)
|
||||
|
||||
|
||||
def test_s18_upgrade_moves_onhand_config_and_renames_files_then_downgrade_restores(op):
|
||||
# op fixture:内存 SQLite,先跑 s17b.upgrade 再跑 s17c.upgrade(或桩出 s17c 之后的两张表)。
|
||||
# 桩站点一行:source_code='DSV',report_path_json={'menu':'onhand'},
|
||||
# query_parameters_json=[{'name':'wh'}],parsing_profile_id=1,excel_template_id=9。
|
||||
# 桩 shipping_onhand_files 一行:id=7,onhand_lines_json=[{'sku':'A'}],snapshot_status='ready'。
|
||||
migration = _load("s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py")
|
||||
migration.upgrade()
|
||||
config_cols = _column_names(op, "freight_rpa_onhand_report_configs")
|
||||
assert {"source_id", "report_path_json", "query_parameters_json", "parsing_profile_id"} <= set(config_cols)
|
||||
source_cols = _column_names(op, "freight_rpa_sources")
|
||||
assert "report_path_json" not in source_cols
|
||||
assert "parsing_profile_id" not in source_cols
|
||||
assert "source_code" in source_cols
|
||||
file_cols = _column_names(op, "freight_rpa_onhand_report_files")
|
||||
assert "onhand_lines_json" in file_cols
|
||||
assert "snapshot_status" in file_cols
|
||||
row = op.get_bind().exec_driver_sql(
|
||||
"SELECT report_path_json, parsing_profile_id FROM freight_rpa_onhand_report_configs"
|
||||
).one()
|
||||
assert row.parsing_profile_id == 1
|
||||
migration.downgrade()
|
||||
assert "report_path_json" in _column_names(op, "freight_rpa_sources")
|
||||
assert "onhand_lines_json" in _column_names(op, "shipping_onhand_files")
|
||||
assert "freight_rpa_onhand_parsing_profiles" not in _table_names(op)
|
||||
|
||||
|
||||
def test_s18_downgrade_backfills_json_defaults_for_source_without_config_row(op):
|
||||
"""无配置行的站点降级时不得把 NULL 写回 NOT NULL 的两列 JSON。
|
||||
|
||||
[断言意图] upgrade 后新增的站点行在配置表中没有对应行,downgrade 的 UPDATE
|
||||
子查询返回 NULL;两列 JSON 必须 COALESCE 回填 '{}' / '[]',parsing_profile_id
|
||||
可空保持 NULL,旧启用约束(双绑定)在 enabled=false 下行必须成立。
|
||||
"""
|
||||
migration = _load("s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py")
|
||||
migration.upgrade()
|
||||
# 升级后的站点表已没有三列;直接插入一行停用站点,配置表中没有它的配置行。
|
||||
op.get_bind().exec_driver_sql(
|
||||
"INSERT INTO freight_rpa_sources "
|
||||
"(id, source_code, enabled, excel_template_id, config_version, created_at, updated_at) "
|
||||
"VALUES (2, 'LATECOMER', 0, NULL, 1, '2026-10-18 09:00:00', '2026-10-18 09:00:00')"
|
||||
)
|
||||
migration.downgrade()
|
||||
row = op.get_bind().exec_driver_sql(
|
||||
"SELECT report_path_json, query_parameters_json, parsing_profile_id "
|
||||
"FROM freight_rpa_sources WHERE id = 2"
|
||||
).one()
|
||||
assert row.report_path_json == '{}'
|
||||
assert row.query_parameters_json == '[]'
|
||||
assert row.parsing_profile_id is None
|
||||
# 有配置行的站点仍按配置行回填,不受 COALESCE 影响。
|
||||
migrated = op.get_bind().exec_driver_sql(
|
||||
"SELECT report_path_json, query_parameters_json, parsing_profile_id "
|
||||
"FROM freight_rpa_sources WHERE id = 1"
|
||||
).one()
|
||||
assert migrated.report_path_json == '{"menu": "onhand"}'
|
||||
assert migrated.query_parameters_json == '[{"name": "wh"}]'
|
||||
assert migrated.parsing_profile_id == 1
|
||||
|
||||
|
||||
def test_s18_swaps_enabled_check_and_rewrites_file_object_names(op):
|
||||
"""升级替换启用约束并重写文件表对象名,降级全部还原。
|
||||
|
||||
[断言意图] PostgreSQL CHECK 不能跨表:站点上启用约束只看 excel_template_id;
|
||||
名字含旧表名的索引/检查也必须跟到新表名词根,否则 alembic autogenerate 会漂移。
|
||||
"""
|
||||
migration = _load("s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py")
|
||||
migration.upgrade()
|
||||
assert "ck_freight_rpa_sources_enabled_template" in _check_names(op, _SOURCES_TABLE)
|
||||
assert _ENABLED_BINDINGS_CHECK not in _check_names(op, _SOURCES_TABLE)
|
||||
new_indexes = _index_names(op, _FILES_TABLE_NEW)
|
||||
assert "ix_freight_rpa_onhand_report_files_user_created" in new_indexes
|
||||
assert not any(name and _FILES_TABLE_OLD in name for name in new_indexes)
|
||||
assert "ck_freight_rpa_onhand_report_files_size" in _check_names(op, _FILES_TABLE_NEW)
|
||||
assert not any(name and _FILES_TABLE_OLD in name for name in _check_names(op, _FILES_TABLE_NEW))
|
||||
migration.downgrade()
|
||||
assert _ENABLED_BINDINGS_CHECK in _check_names(op, _SOURCES_TABLE)
|
||||
assert "ck_freight_rpa_sources_enabled_template" not in _check_names(op, _SOURCES_TABLE)
|
||||
checks = _check_names(op, _FILES_TABLE_OLD)
|
||||
assert _FILES_SIZE_CHECK in checks
|
||||
assert not any(name and "freight_rpa_onhand_report_files" in name for name in checks)
|
||||
assert _FILES_USER_CREATED_INDEX in _index_names(op, _FILES_TABLE_OLD)
|
||||
File renamed without changes.
+151
-146
@@ -13,28 +13,28 @@ from openpyxl import Workbook
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventoryValidationBatch,
|
||||
ShippingInventoryExternalMapping,
|
||||
FreightRpaOnhandConfigurationTestRun,
|
||||
FreightRpaOnhandValidationBatch,
|
||||
FreightRpaOnhandExternalMapping,
|
||||
ShippingExcelTemplate,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryField,
|
||||
ShippingRpaProfile,
|
||||
ShippingInventorySource,
|
||||
FreightRpaOnhandReportFile,
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaProfile,
|
||||
FreightRpaSource,
|
||||
)
|
||||
from app.services.admin import shipping_inventory_service
|
||||
from app.services.admin import shipping_onhand_admin_service
|
||||
from app.services.shipping_notice import (
|
||||
inventory_configuration_test,
|
||||
inventory_parsing_profile,
|
||||
inventory_structure_analysis,
|
||||
onhand_configuration_test,
|
||||
onhand_parsing_profile,
|
||||
onhand_structure_analysis,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _inventory_field_id(field_code: str) -> str:
|
||||
"""获取测试显式创建的用户库存字段 ID。"""
|
||||
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
|
||||
return str(FreightRpaOnhandField.query.filter_by(field_code=field_code).one().id)
|
||||
|
||||
|
||||
def _workbook(path: Path) -> None:
|
||||
@@ -48,18 +48,22 @@ def _workbook(path: Path) -> None:
|
||||
|
||||
def _source(code: str = 'TEST_EXPORT_SOURCE', profile_code: str = 'TEST_EXPORT_LOGIN') -> dict:
|
||||
"""创建一个保持停用的 DBS 库存站点。"""
|
||||
login = shipping_inventory_service.save_profile({
|
||||
login = shipping_onhand_admin_service.save_profile({
|
||||
'profile_code': profile_code, 'display_name': 'Test Login', 'connector_type': 'dbs',
|
||||
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
|
||||
'username': 'user', 'password': 'password', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
return shipping_inventory_service.save_source({
|
||||
# s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行,站点载荷不再平铺。
|
||||
return shipping_onhand_admin_service.save_source({
|
||||
'source_code': code, 'display_name': 'Test Export Source', 'connector_type': 'dbs',
|
||||
'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None,
|
||||
'rpa_profile_id': login['id'], 'excel_template_id': None,
|
||||
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
|
||||
'enabled': False,
|
||||
'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
||||
'query_parameters_json': [],
|
||||
'onhand_report_config': {
|
||||
'parsing_profile_id': None,
|
||||
'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
||||
'query_parameters_json': [],
|
||||
},
|
||||
}, actor_id=None)
|
||||
|
||||
|
||||
@@ -83,8 +87,8 @@ def _published_order_field() -> str:
|
||||
|
||||
def _publish_profile_from_analysis(analysis_id: int, field_id: str, *, code: str) -> dict:
|
||||
"""从测试分析创建并发布方案,模拟管理员确认解析配置的前置动作。"""
|
||||
analysis = inventory_structure_analysis.get_analysis(analysis_id)
|
||||
draft = inventory_structure_analysis.create_profile_draft(analysis_id, {
|
||||
analysis = onhand_structure_analysis.get_analysis(analysis_id)
|
||||
draft = onhand_structure_analysis.create_profile_draft(analysis_id, {
|
||||
'profile_code': code, 'display_name': code, 'sheet_name': 'Sheet', 'header_row_index': 1,
|
||||
'field_mapping': {
|
||||
_inventory_field_id('part_number'): 'Supplier Sku',
|
||||
@@ -93,15 +97,15 @@ def _publish_profile_from_analysis(analysis_id: int, field_id: str, *, code: str
|
||||
},
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}],
|
||||
}, actor_id=None)
|
||||
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
|
||||
return onhand_parsing_profile.publish(draft['id'], actor_id=None)
|
||||
|
||||
|
||||
def _complete_test_run(source: dict, tmp_path: Path) -> dict:
|
||||
"""完成一次模拟 RPA 测试导出,返回可供确认的测试运行。"""
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
started = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result_file = tmp_path / f"{started['run_no']}.xlsx"
|
||||
_workbook(result_file)
|
||||
return inventory_configuration_test.report_test_export({
|
||||
return onhand_configuration_test.report_test_export({
|
||||
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
|
||||
})
|
||||
|
||||
@@ -131,18 +135,18 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
started = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
assert started['status'] == 'awaiting_rpa'
|
||||
assert inventory_configuration_test.start_test_export(source['id'], actor_id=None)['run_no'] == started['run_no']
|
||||
assert onhand_configuration_test.start_test_export(source['id'], actor_id=None)['run_no'] == started['run_no']
|
||||
result_file = tmp_path / 'rpa-result.xlsx'
|
||||
_workbook(result_file)
|
||||
completed = inventory_configuration_test.report_test_export({
|
||||
completed = onhand_configuration_test.report_test_export({
|
||||
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
|
||||
})
|
||||
assert completed['status'] == 'completed'
|
||||
assert completed['stage'] == 'ready_for_confirmation'
|
||||
assert not ShippingInventoryFile.query.count()
|
||||
assert ShippingInventoryConfigurationTestRun.query.count() == 1
|
||||
assert not FreightRpaOnhandReportFile.query.count()
|
||||
assert FreightRpaOnhandConfigurationTestRun.query.count() == 1
|
||||
|
||||
|
||||
def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app, tmp_path):
|
||||
@@ -156,16 +160,16 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app,
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
started = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result_file = drop_dir / f"inventory_{started['run_no']}_DSV360_BYAWSPRD01.xlsx"
|
||||
_workbook(result_file)
|
||||
windows_path = rf'C:\HxopsRpaTest\data\inventory_drop\{result_file.name}'
|
||||
completed = inventory_configuration_test.report_test_export({
|
||||
completed = onhand_configuration_test.report_test_export({
|
||||
'run_no': started['run_no'], 'status': 'success', 'file_path': windows_path,
|
||||
})
|
||||
assert completed['status'] == 'completed'
|
||||
assert completed.get('error_message') in (None, '')
|
||||
assert not ShippingInventoryFile.query.count()
|
||||
assert not FreightRpaOnhandReportFile.query.count()
|
||||
|
||||
|
||||
def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
|
||||
@@ -178,17 +182,17 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend
|
||||
field_id = _published_order_field()
|
||||
analysis_path = tmp_path / 'profile-evidence.xlsx'
|
||||
_workbook(analysis_path)
|
||||
seed_run = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seeded = inventory_configuration_test.report_test_export({
|
||||
seed_run = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seeded = onhand_configuration_test.report_test_export({
|
||||
'run_no': seed_run['run_no'], 'status': 'success', 'file_path': str(analysis_path),
|
||||
})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], field_id, code='EMPTY_RESULT_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile(
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile(
|
||||
[source['id']], profile['id'], actor_id=None, reason='空结果前已确认同类报表结构', operation='direct',
|
||||
)
|
||||
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result = inventory_configuration_test.report_test_export({
|
||||
started = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result = onhand_configuration_test.report_test_export({
|
||||
'run_no': started['run_no'], 'status': 'empty', 'message': 'no inventory rows',
|
||||
})
|
||||
|
||||
@@ -196,8 +200,8 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend
|
||||
assert result['status'] == 'completed_empty'
|
||||
assert result['stage'] == 'empty_data_pending_validation'
|
||||
assert result['result']['data_validation'] == 'pending_first_non_empty_export'
|
||||
assert not ShippingInventoryFile.query.count()
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
assert not FreightRpaOnhandReportFile.query.count()
|
||||
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
|
||||
# 关键断言:空结果测试不自动启用;本例仍缺发货模板,硬门槛阻断启用。
|
||||
assert current['enabled'] is False
|
||||
assert current['activation']['missing_requirements'] == ['excel_template']
|
||||
@@ -211,8 +215,8 @@ def test_empty_configuration_export_without_published_profile_is_rejected(app):
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result = inventory_configuration_test.report_test_export({
|
||||
started = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result = onhand_configuration_test.report_test_export({
|
||||
'run_no': started['run_no'], 'status': 'empty',
|
||||
})
|
||||
|
||||
@@ -228,11 +232,11 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app,
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'bound-profile-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BOUND_PROFILE_VERIFY')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
|
||||
|
||||
verified = _complete_test_run(source, tmp_path)
|
||||
# 关键断言:当前绑定方案无需再出现在候选确认列表,测试直接写入启用所需的确认事实。
|
||||
@@ -251,17 +255,17 @@ def test_verified_current_profile_does_not_auto_enable_ready_source(app, tmp_pat
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_PROFILE')
|
||||
template = _published_template(code='AUTO_ENABLE_TEMPLATE')
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_inventory_service.save_source({
|
||||
**current, 'parsing_profile_id': profile['id'], 'excel_template_id': template.id,
|
||||
}, actor_id=None, source_id=source['id'])
|
||||
# s18 起解析绑定走配置行绑定服务,模板绑定仍走站点保存。
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
|
||||
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_onhand_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id'])
|
||||
|
||||
verified = _complete_test_run(source, tmp_path)
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
source_model = db.session.get(FreightRpaSource, source['id'])
|
||||
# 关键断言:测试只写入验证事实,站点保持停用直至管理员显式启用。
|
||||
assert verified['stage'] == 'current_profile_verified'
|
||||
assert source_model.enabled is False
|
||||
assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True
|
||||
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['ready'] is True
|
||||
|
||||
|
||||
def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path):
|
||||
@@ -273,16 +277,14 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_BLOCKED')
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_inventory_service.save_source({
|
||||
**current, 'parsing_profile_id': profile['id'], 'excel_template_id': None,
|
||||
}, actor_id=None, source_id=source['id'])
|
||||
# s18 起解析绑定走配置行绑定服务;本例不绑模板以验证模板硬门槛。
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
|
||||
|
||||
_complete_test_run(source, tmp_path)
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
source_model = db.session.get(FreightRpaSource, source['id'])
|
||||
# 关键断言:自动启用始终复用正式门禁,缺少模板不会被测试成功放行。
|
||||
assert source_model.enabled is False
|
||||
assert shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
|
||||
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
|
||||
|
||||
|
||||
def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path):
|
||||
@@ -295,18 +297,18 @@ def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path):
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_EMPTY')
|
||||
template = _published_template(code='AUTO_ENABLE_EMPTY_TEMPLATE')
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_inventory_service.save_source({
|
||||
**current, 'parsing_profile_id': profile['id'], 'excel_template_id': template.id,
|
||||
}, actor_id=None, source_id=source['id'])
|
||||
# s18 起解析绑定走配置行绑定服务,模板绑定仍走站点保存。
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct')
|
||||
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_onhand_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id'])
|
||||
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
completed = inventory_configuration_test.report_test_export({'run_no': started['run_no'], 'status': 'empty'})
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
started = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
completed = onhand_configuration_test.report_test_export({'run_no': started['run_no'], 'status': 'empty'})
|
||||
source_model = db.session.get(FreightRpaSource, source['id'])
|
||||
# 关键断言:空库存是成功查询事实;硬门槛齐备时仍保持停用,等待显式开关。
|
||||
assert completed['status'] == 'completed_empty'
|
||||
assert source_model.enabled is False
|
||||
assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True
|
||||
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['ready'] is True
|
||||
|
||||
|
||||
def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path):
|
||||
@@ -318,27 +320,27 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app,
|
||||
first = _source('BATCH_SOURCE_A', 'BATCH_LOGIN_A')
|
||||
second = _source('BATCH_SOURCE_B', 'BATCH_LOGIN_B')
|
||||
third = _source('BATCH_SOURCE_C', 'BATCH_LOGIN_C')
|
||||
second_model = db.session.get(ShippingInventorySource, second['id'])
|
||||
second_model = db.session.get(FreightRpaSource, second['id'])
|
||||
second_model.rpa_profile_id = first['rpa_profile_id']
|
||||
second_model.config_version += 1
|
||||
db.session.commit()
|
||||
# 用首站既有测试证据创建发布方案,再作为三站批量验证的受控解析定义。
|
||||
seed = inventory_configuration_test.start_test_export(first['id'], actor_id=None)
|
||||
seed = onhand_configuration_test.start_test_export(first['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'batch-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BATCH_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile(
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile(
|
||||
[first['id'], second['id'], third['id']], profile['id'], actor_id=None, reason='批量验证测试', operation='bulk',
|
||||
)
|
||||
|
||||
write_trigger.reset_mock()
|
||||
batch = inventory_configuration_test.start_batch_test_export([first['id'], second['id'], third['id']], actor_id=None)
|
||||
batch = onhand_configuration_test.start_batch_test_export([first['id'], second['id'], third['id']], actor_id=None)
|
||||
# 关键断言:两个相同 Profile 的站点合并为一个 trigger,第三站独立触发。
|
||||
assert write_trigger.call_count == 2
|
||||
assert batch['total_count'] == 3
|
||||
runs = {run['inventory_source_id']: run for run in batch['runs']}
|
||||
runs = {run['source_id']: run for run in batch['runs']}
|
||||
result_file = tmp_path / 'batch-success.xlsx'; _workbook(result_file)
|
||||
reported = inventory_configuration_test.report_batch_test_exports({
|
||||
reported = onhand_configuration_test.report_batch_test_exports({
|
||||
'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': runs[first['id']]['run_no'], 'status': 'success', 'file_path': str(result_file)},
|
||||
{'validation_run_no': runs[second['id']]['run_no'], 'status': 'skipped', 'skip_reason': 'no_inventory_data'},
|
||||
@@ -348,7 +350,7 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app,
|
||||
# 关键断言:失败站点不影响其他站点,批次仅汇总为部分失败。
|
||||
assert reported['status'] == 'partial_failed'
|
||||
assert (reported['success_count'], reported['empty_count'], reported['failed_count']) == (1, 1, 1)
|
||||
assert ShippingInventoryValidationBatch.query.get(batch['id']).status == 'partial_failed'
|
||||
assert FreightRpaOnhandValidationBatch.query.get(batch['id']).status == 'partial_failed'
|
||||
|
||||
|
||||
def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
||||
@@ -358,17 +360,17 @@ def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('RETRY_SOURCE', 'RETRY_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'retry-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RETRY_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='重试测试', operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='重试测试', operation='bulk')
|
||||
batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
run = batch['runs'][0]
|
||||
inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
onhand_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': run['run_no'], 'status': 'failed', 'error_message': 'temporary failure'},
|
||||
]})
|
||||
retried = inventory_configuration_test.retry_failed_validation_batch(batch['id'], actor_id=None)
|
||||
retried = onhand_configuration_test.retry_failed_validation_batch(batch['id'], actor_id=None)
|
||||
assert retried['retry_of_batch_id'] == batch['id']
|
||||
assert retried['total_count'] == 1
|
||||
|
||||
@@ -380,18 +382,18 @@ def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app,
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('STALE_BATCH_SOURCE', 'STALE_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'stale-batch-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='STALE_BATCH_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='过期回调测试', operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='过期回调测试', operation='bulk')
|
||||
batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
run = batch['runs'][0]
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
source_model = db.session.get(FreightRpaSource, source['id'])
|
||||
source_model.config_version += 1
|
||||
db.session.commit()
|
||||
result_file = tmp_path / 'stale-batch-result.xlsx'; _workbook(result_file)
|
||||
reported = inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
reported = onhand_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': 'UNKNOWN-RUN', 'status': 'success', 'file_path': str(result_file)},
|
||||
{'validation_run_no': run['run_no'], 'status': 'success', 'file_path': str(result_file)},
|
||||
]})
|
||||
@@ -408,19 +410,19 @@ def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('RESTORE_BATCH_SOURCE', 'RESTORE_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'restore-batch-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RESTORE_BATCH_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
# 关键断言:刷新期间读取服务端 active batch,会返回待 Worker 处理的真实运行。
|
||||
assert inventory_configuration_test.get_latest_active_validation_batch()['id'] == batch['id']
|
||||
inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
assert onhand_configuration_test.get_latest_active_validation_batch()['id'] == batch['id']
|
||||
onhand_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': batch['runs'][0]['run_no'], 'status': 'empty'},
|
||||
]})
|
||||
# 关键断言:结束后不再恢复,避免管理端反复弹出旧批次。
|
||||
assert inventory_configuration_test.get_latest_active_validation_batch() is None
|
||||
assert onhand_configuration_test.get_latest_active_validation_batch() is None
|
||||
|
||||
|
||||
def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path):
|
||||
@@ -430,25 +432,25 @@ def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path)
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('PROGRESS_BATCH_SOURCE', 'PROGRESS_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
seed_file = tmp_path / 'progress-batch-seed.xlsx'; _workbook(seed_file)
|
||||
seeded = inventory_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)})
|
||||
profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='PROGRESS_BATCH_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None)
|
||||
run = batch['runs'][0]
|
||||
|
||||
progressed = inventory_configuration_test.report_batch_test_progress({
|
||||
progressed = onhand_configuration_test.report_batch_test_progress({
|
||||
'validation_batch_id': batch['id'], 'validation_run_no': run['run_no'], 'stage': 'rpa_exporting',
|
||||
})
|
||||
# 关键断言:页面可区分尚未领取与 Worker 已实际执行,批次仍等待最终结果。
|
||||
assert (progressed['status'], progressed['stage']) == ('processing', 'rpa_exporting')
|
||||
assert inventory_configuration_test.get_validation_batch(batch['id'])['status'] == 'running'
|
||||
assert onhand_configuration_test.get_validation_batch(batch['id'])['status'] == 'running'
|
||||
|
||||
inventory_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
onhand_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [
|
||||
{'validation_run_no': run['run_no'], 'status': 'empty'},
|
||||
]})
|
||||
unchanged = inventory_configuration_test.report_batch_test_progress({
|
||||
unchanged = onhand_configuration_test.report_batch_test_progress({
|
||||
'validation_batch_id': batch['id'], 'validation_run_no': run['run_no'], 'stage': 'rpa_exporting',
|
||||
})
|
||||
# 关键断言:迟到的 progress 不得覆盖已经确认的空库存终态。
|
||||
@@ -463,17 +465,17 @@ def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
first = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
assert inventory_configuration_test.get_latest_test_run(source['id'])['run_no'] == first['run_no']
|
||||
first = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
assert onhand_configuration_test.get_latest_test_run(source['id'])['run_no'] == first['run_no']
|
||||
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_inventory_service.save_source({**current, 'display_name': 'Changed before callback'}, actor_id=None, source_id=source['id'])
|
||||
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_onhand_admin_service.save_source({**current, 'display_name': 'Changed before callback'}, actor_id=None, source_id=source['id'])
|
||||
|
||||
# 关键断言:旧运行不再属于当前配置,重新测试必须创建新运行而不是误复用。
|
||||
assert inventory_configuration_test.get_latest_test_run(source['id']) is None
|
||||
second = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
assert onhand_configuration_test.get_latest_test_run(source['id']) is None
|
||||
second = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
assert second['run_no'] != first['run_no']
|
||||
assert inventory_configuration_test.get_latest_test_run(source['id'])['run_no'] == second['run_no']
|
||||
assert onhand_configuration_test.get_latest_test_run(source['id'])['run_no'] == second['run_no']
|
||||
|
||||
|
||||
def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
@@ -485,12 +487,12 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one()
|
||||
started = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
run = FreightRpaOnhandConfigurationTestRun.query.filter_by(run_no=started['run_no']).one()
|
||||
run.created_at = datetime.utcnow() - timedelta(seconds=2)
|
||||
db.session.commit()
|
||||
|
||||
recovered = inventory_configuration_test.get_latest_test_run(source['id'])
|
||||
recovered = onhand_configuration_test.get_latest_test_run(source['id'])
|
||||
# 关键断言:超时是明确失败终态,客户端无需自行推断或继续轮询。
|
||||
assert recovered['status'] == 'failed'
|
||||
assert recovered['stage'] == 'failed'
|
||||
@@ -498,12 +500,12 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
|
||||
result_file = tmp_path / 'late-rpa-result.xlsx'
|
||||
_workbook(result_file)
|
||||
late_callback = inventory_configuration_test.report_test_export({
|
||||
late_callback = onhand_configuration_test.report_test_export({
|
||||
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
|
||||
})
|
||||
# 关键断言:超时后的迟到回调不能将失败任务重新写成完成,也不能生成结构分析证据。
|
||||
assert late_callback['status'] == 'failed'
|
||||
assert ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one().analysis_id is None
|
||||
assert FreightRpaOnhandConfigurationTestRun.query.filter_by(run_no=started['run_no']).one().analysis_id is None
|
||||
|
||||
|
||||
def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
|
||||
@@ -515,21 +517,21 @@ def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, t
|
||||
):
|
||||
first = _source('TIMEOUT_QUEUE_A', 'TIMEOUT_QUEUE_LOGIN')
|
||||
second = _source('TIMEOUT_QUEUE_B', 'TIMEOUT_QUEUE_LOGIN_B')
|
||||
second_model = db.session.get(ShippingInventorySource, second['id'])
|
||||
second_model = db.session.get(FreightRpaSource, second['id'])
|
||||
second_model.rpa_profile_id = first['rpa_profile_id']
|
||||
second_model.config_version += 1
|
||||
db.session.commit()
|
||||
seed = _complete_test_run(first, tmp_path)
|
||||
profile = _publish_profile_from_analysis(seed['analysis_id'], _published_order_field(), code='TIMEOUT_QUEUE_PROFILE')
|
||||
shipping_inventory_service.bind_source_parsing_profile([first['id'], second['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = inventory_configuration_test.start_batch_test_export([first['id'], second['id']], actor_id=None)
|
||||
queued_run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=second['id']).one()
|
||||
shipping_onhand_admin_service.bind_source_parsing_profile([first['id'], second['id']], profile['id'], actor_id=None, operation='bulk')
|
||||
batch = onhand_configuration_test.start_batch_test_export([first['id'], second['id']], actor_id=None)
|
||||
queued_run = FreightRpaOnhandConfigurationTestRun.query.filter_by(source_id=second['id']).one()
|
||||
queued_run.created_at = datetime.utcnow() - timedelta(seconds=15)
|
||||
db.session.commit()
|
||||
|
||||
recovered = inventory_configuration_test.get_validation_batch(batch['id'])
|
||||
recovered = onhand_configuration_test.get_validation_batch(batch['id'])
|
||||
# 关键断言:第二站可等待同组第一站完成,20 秒总窗口内不应被单站 10 秒误判。
|
||||
assert next(run for run in recovered['runs'] if run['inventory_source_id'] == second['id'])['status'] == 'awaiting_rpa'
|
||||
assert next(run for run in recovered['runs'] if run['source_id'] == second['id'])['status'] == 'awaiting_rpa'
|
||||
|
||||
|
||||
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
|
||||
@@ -543,16 +545,17 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_CONFIRMED')
|
||||
|
||||
confirmed = inventory_configuration_test.confirm_test_profile(
|
||||
confirmed = onhand_configuration_test.confirm_test_profile(
|
||||
source['id'], completed['run_no'], profile['id'], actor_id=None,
|
||||
)
|
||||
|
||||
assert confirmed['parsing_profile_id'] == profile['id']
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
assert source_model.parsing_profile_id == profile['id']
|
||||
assert 'configuration_test' not in shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements']
|
||||
source_model = db.session.get(FreightRpaSource, source['id'])
|
||||
# s18 起解析绑定归 onhand_report_config 配置行,站点行不再有 parsing_profile_id。
|
||||
assert source_model.onhand_report_config.parsing_profile_id == profile['id']
|
||||
assert 'configuration_test' not in shipping_onhand_admin_service.get_source_activation_status(source_model)['missing_requirements']
|
||||
# 关键断言:外部仓库映射只在调拨前校验,不应出现在站点启用阻断清单。
|
||||
assert shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
|
||||
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template']
|
||||
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='TEST_ACTIVATION', display_name='Activation Template', version=1, status='published',
|
||||
@@ -567,10 +570,10 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
|
||||
db.session.flush()
|
||||
source_model.excel_template_id = template.id
|
||||
db.session.commit()
|
||||
assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True
|
||||
assert shipping_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True
|
||||
assert shipping_onhand_admin_service.get_source_activation_status(source_model)['ready'] is True
|
||||
assert shipping_onhand_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True
|
||||
assert 'configuration_test' not in {
|
||||
item['code'] for item in shipping_inventory_service.get_source_activation_status(source_model)['checks']
|
||||
item['code'] for item in shipping_onhand_admin_service.get_source_activation_status(source_model)['checks']
|
||||
}
|
||||
|
||||
|
||||
@@ -584,26 +587,26 @@ def test_rpa_profile_change_does_not_block_activation_hard_gates(app, tmp_path):
|
||||
source = _source()
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='PROFILE_STALE')
|
||||
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
|
||||
onhand_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
|
||||
template = _published_template(code='PROFILE_STALE_TEMPLATE')
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
source_model = db.session.get(FreightRpaSource, source['id'])
|
||||
source_model.excel_template_id = template.id
|
||||
db.session.commit()
|
||||
|
||||
rpa_profile = db.session.get(ShippingRpaProfile, source['rpa_profile_id'])
|
||||
shipping_inventory_service.save_profile({
|
||||
rpa_profile = db.session.get(FreightRpaProfile, source['rpa_profile_id'])
|
||||
shipping_onhand_admin_service.save_profile({
|
||||
'profile_code': rpa_profile.profile_code, 'display_name': rpa_profile.display_name,
|
||||
'connector_type': rpa_profile.connector_type, 'login_url': rpa_profile.login_url,
|
||||
'login_config_json': rpa_profile.login_config_json, 'enabled': True,
|
||||
'username': 'updated-user', 'password': 'updated-password',
|
||||
}, actor_id=None, profile_id=rpa_profile.id)
|
||||
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
status = shipping_inventory_service.get_source_activation_status(source_model)
|
||||
source_model = db.session.get(FreightRpaSource, source['id'])
|
||||
status = shipping_onhand_admin_service.get_source_activation_status(source_model)
|
||||
# 关键断言:连接变更不再把测试导出塞进启用门禁;硬门槛齐备即可启用。
|
||||
assert 'configuration_test' not in {item['code'] for item in status['checks']}
|
||||
assert status['ready'] is True
|
||||
assert shipping_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True
|
||||
assert shipping_onhand_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True
|
||||
|
||||
|
||||
def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path):
|
||||
@@ -617,14 +620,15 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_STALE')
|
||||
|
||||
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_inventory_service.save_source({**current, 'display_name': 'Changed after test'}, actor_id=None, source_id=source['id'])
|
||||
current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id'])
|
||||
shipping_onhand_admin_service.save_source({**current, 'display_name': 'Changed after test'}, actor_id=None, source_id=source['id'])
|
||||
with pytest.raises(ConflictError) as stale:
|
||||
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
|
||||
assert stale.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE'
|
||||
onhand_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
|
||||
assert stale.value.code == 'SHIPPING.ONHAND_CONFIGURATION_TEST_STALE'
|
||||
|
||||
source_model = db.session.get(ShippingInventorySource, source['id'])
|
||||
source_model.parsing_profile_id = profile['id']
|
||||
source_model = db.session.get(FreightRpaSource, source['id'])
|
||||
# s18 起解析绑定写配置行;_source() 已建配置行,直接改绑定即可。
|
||||
source_model.onhand_report_config.parsing_profile_id = profile['id']
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='TEST_ENABLED', display_name='Test Enabled', version=1, status='published',
|
||||
storage_bucket='test', storage_key='test.xlsx', original_filename='test.xlsx',
|
||||
@@ -636,8 +640,8 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
|
||||
source_model.enabled = True
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as enabled:
|
||||
inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
assert enabled.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID'
|
||||
onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
assert enabled.value.code == 'SHIPPING.ONHAND_CONFIGURATION_TEST_INVALID'
|
||||
|
||||
|
||||
def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
|
||||
@@ -648,17 +652,17 @@ def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
failed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result = inventory_configuration_test.report_test_export({
|
||||
failed = onhand_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result = onhand_configuration_test.report_test_export({
|
||||
'run_no': failed['run_no'], 'status': 'failed', 'error_message': 'RPA login failed',
|
||||
})
|
||||
assert result['status'] == 'failed'
|
||||
assert not ShippingInventoryFile.query.count()
|
||||
assert not FreightRpaOnhandReportFile.query.count()
|
||||
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
field_id = _published_order_field()
|
||||
_publish_profile_from_analysis(completed['analysis_id'], field_id, code='TEST_MATCHED')
|
||||
unrelated = inventory_parsing_profile.save_draft({
|
||||
unrelated = onhand_parsing_profile.save_draft({
|
||||
'profile_code': 'TEST_UNRELATED', 'display_name': 'Unrelated', 'file_format': 'xlsx',
|
||||
'sample_analysis_id': completed['analysis_id'],
|
||||
'definition': {
|
||||
@@ -671,8 +675,9 @@ def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}],
|
||||
},
|
||||
}, actor_id=None)
|
||||
unrelated = inventory_parsing_profile.publish(unrelated['id'], actor_id=None)
|
||||
unrelated = onhand_parsing_profile.publish(unrelated['id'], actor_id=None)
|
||||
with pytest.raises(ValidationError) as rejected:
|
||||
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], unrelated['id'], actor_id=None)
|
||||
assert rejected.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID'
|
||||
assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None
|
||||
onhand_configuration_test.confirm_test_profile(source['id'], completed['run_no'], unrelated['id'], actor_id=None)
|
||||
assert rejected.value.code == 'SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID'
|
||||
# s18 起绑定归配置行;被拒后配置行必须保持未绑定。
|
||||
assert db.session.get(FreightRpaSource, source['id']).onhand_report_config.parsing_profile_id is None
|
||||
+8
-8
@@ -4,10 +4,10 @@ tests/test_inventory_download_name.py
|
||||
用途:锁定 build_inventory_download_name 的下载展示名规范化契约——
|
||||
复用企微压缩包短名规则({seq}_{source}_{warehouse})并附加 exported_at
|
||||
数据截止时间点;worker 原始登记名不受影响。
|
||||
依赖:models.ShippingInventoryFile、inventory_file_store.build_inventory_download_name。
|
||||
依赖:models.FreightRpaOnhandReportFile、onhand_file_store.build_inventory_download_name。
|
||||
逻辑:pure_unit;长名规范化、规范名幂等、exported_at → rpa_run_no → mtime 回退链、
|
||||
warehouse 连续重复段去重(AWSDU_AWSDU → AWSDU)、无 seq 前缀省略、
|
||||
source/warehouse/时间点任一缺失时保持原名(禁止凭空造名)、空名回退 inventory_file_no。
|
||||
source/warehouse/时间点任一缺失时保持原名(禁止凭空造名)、空名回退 onhand_file_no。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,8 +17,8 @@ from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
build_inventory_download_name,
|
||||
)
|
||||
|
||||
@@ -27,10 +27,10 @@ pytestmark = pytest.mark.pure_unit
|
||||
_WORKER_LONG_NAME = '006_inventory_RUN2026101423006F54E_DSV360_AWSDU_AWSDU_20261014231148.xlsx'
|
||||
|
||||
|
||||
def _inv_file(**overrides) -> ShippingInventoryFile:
|
||||
def _inv_file(**overrides) -> FreightRpaOnhandReportFile:
|
||||
"""构造不落库的快照行;默认字段对齐 prod 4510042199 批次的真实登记值。"""
|
||||
defaults = dict(
|
||||
inventory_file_no='INV-20261014-0001',
|
||||
onhand_file_no='INV-20261014-0001',
|
||||
source_file_name=_WORKER_LONG_NAME,
|
||||
source_code='DSV360',
|
||||
warehouse_id='AWSDU',
|
||||
@@ -39,7 +39,7 @@ def _inv_file(**overrides) -> ShippingInventoryFile:
|
||||
rpa_run_no='RUN2026101423006F54E',
|
||||
)
|
||||
defaults.update(overrides)
|
||||
return ShippingInventoryFile(**defaults)
|
||||
return FreightRpaOnhandReportFile(**defaults)
|
||||
|
||||
|
||||
def test_worker_long_name_normalized_with_exported_at():
|
||||
@@ -113,7 +113,7 @@ def test_insufficient_info_keeps_original_name():
|
||||
|
||||
|
||||
def test_empty_source_file_name_falls_back_to_file_no():
|
||||
"""空登记名回退 inventory_file_no + 小写后缀(既有行为不变)。"""
|
||||
"""空登记名回退 onhand_file_no + 小写后缀(既有行为不变)。"""
|
||||
name = build_inventory_download_name(
|
||||
_inv_file(source_file_name=None), source_file_name=None,
|
||||
)
|
||||
+2
-2
@@ -2,11 +2,11 @@
|
||||
tests/test_inventory_empty_snapshot.py
|
||||
|
||||
用途:验证 RPA 零库存结果仅形成审计快照,绝不作为可匹配库存复用。
|
||||
依赖:inventory_snapshot_store、ShippingInventoryFile、Flask 测试应用。
|
||||
依赖:onhand_snapshot_store、FreightRpaOnhandReportFile、Flask 测试应用。
|
||||
逻辑:二期空结果由 Worker/回调写入 empty 快照;查询 ready 快照的运行链路必须忽略它。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
from app.services.shipping_notice.onhand_snapshot_store import (
|
||||
create_empty_rpa_inventory_snapshot,
|
||||
find_latest_ready_snapshot,
|
||||
)
|
||||
+16
-16
@@ -1,6 +1,6 @@
|
||||
"""
|
||||
用途:验证库存字段目录零预置、用户字段维护和引用保护。
|
||||
依赖:inventory_field_catalog、库存字段 ORM 与统一测试应用上下文。
|
||||
依赖:onhand_field_catalog、库存字段 ORM 与统一测试应用上下文。
|
||||
逻辑:目录初始为空;用户字段未引用时可删除,引用后用途和数据格式受保护。
|
||||
"""
|
||||
|
||||
@@ -8,61 +8,61 @@ import pytest
|
||||
|
||||
from app.core.errors import ConflictError
|
||||
from app import db
|
||||
from app.models import ShippingInventoryField
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
from app.services.shipping_notice import inventory_field_catalog
|
||||
from app.models import FreightRpaOnhandField
|
||||
from app.models import FreightRpaParsingProfile
|
||||
from app.services.shipping_notice import onhand_field_catalog
|
||||
|
||||
|
||||
def test_catalog_is_empty_until_user_creates_fields(app):
|
||||
"""新环境不得由迁移或服务自动创建任何具体库存字段。"""
|
||||
with app.app_context():
|
||||
ShippingInventoryField.query.delete()
|
||||
FreightRpaOnhandField.query.delete()
|
||||
db.session.commit()
|
||||
assert inventory_field_catalog.list_fields() == []
|
||||
assert onhand_field_catalog.list_fields() == []
|
||||
|
||||
|
||||
def test_extension_field_can_be_created_updated_and_deleted(app):
|
||||
"""未被下游配置引用的扩展字段可完整维护,不需要再改 Python 白名单。"""
|
||||
with app.app_context():
|
||||
created = inventory_field_catalog.create_field({
|
||||
created = onhand_field_catalog.create_field({
|
||||
'display_name': '原产国', 'description': '货品原产地国家或地区。',
|
||||
'value_type': 'text', 'usage_type': 'general', 'sort_order': 200,
|
||||
}, actor_id=None)
|
||||
updated = inventory_field_catalog.update_field(created['id'], {
|
||||
updated = onhand_field_catalog.update_field(created['id'], {
|
||||
'display_name': '原产国家', 'description': '货品原产地国家或地区。',
|
||||
'value_type': 'text', 'usage_type': 'general', 'sort_order': 210,
|
||||
}, actor_id=None)
|
||||
assert updated['display_name'] == '原产国家'
|
||||
assert updated['sort_order'] == 210
|
||||
assert inventory_field_catalog.delete_field(created['id']) == {'action': 'deleted'}
|
||||
assert db.session.get(ShippingInventoryField, created['id']) is None
|
||||
assert onhand_field_catalog.delete_field(created['id']) == {'action': 'deleted'}
|
||||
assert db.session.get(FreightRpaOnhandField, created['id']) is None
|
||||
|
||||
|
||||
def test_extension_field_referenced_by_parsing_profile_cannot_be_deleted_or_retired(app):
|
||||
"""解析方案已引用用户字段时,目录服务阻止删除、停用和改变能力用途。"""
|
||||
with app.app_context():
|
||||
extension = ShippingInventoryField(
|
||||
extension = FreightRpaOnhandField(
|
||||
field_code='batch_no', display_name='库存批号', value_type='text',
|
||||
usage_type='general', status='active', sort_order=100,
|
||||
)
|
||||
db.session.add(extension)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryParsingProfile(
|
||||
db.session.add(FreightRpaParsingProfile(
|
||||
profile_code='REFERENCE_FIELD', display_name='Reference field', version=1,
|
||||
status='draft', file_format='xlsx',
|
||||
definition_json={'field_mapping': {str(extension.id): 'Batch No'}, 'match_keys': []},
|
||||
))
|
||||
db.session.commit()
|
||||
for operation, code in (
|
||||
(inventory_field_catalog.delete_field, 'SHIPPING.INVENTORY_FIELD_DELETE_BLOCKED'),
|
||||
(inventory_field_catalog.retire_field, 'SHIPPING.INVENTORY_FIELD_RETIRE_BLOCKED'),
|
||||
(onhand_field_catalog.delete_field, 'SHIPPING.ONHAND_FIELD_DELETE_BLOCKED'),
|
||||
(onhand_field_catalog.retire_field, 'SHIPPING.ONHAND_FIELD_RETIRE_BLOCKED'),
|
||||
):
|
||||
with pytest.raises(ConflictError) as error:
|
||||
operation(extension.id)
|
||||
assert error.value.code == code
|
||||
with pytest.raises(ConflictError) as update_error:
|
||||
inventory_field_catalog.update_field(extension.id, {
|
||||
onhand_field_catalog.update_field(extension.id, {
|
||||
'display_name': '库存批号', 'description': '',
|
||||
'value_type': 'decimal', 'usage_type': 'inventory_quantity', 'sort_order': 100,
|
||||
}, actor_id=None)
|
||||
assert update_error.value.code == 'SHIPPING.INVENTORY_FIELD_IMMUTABLE'
|
||||
assert update_error.value.code == 'SHIPPING.ONHAND_FIELD_IMMUTABLE'
|
||||
+29
-29
@@ -1,6 +1,6 @@
|
||||
"""
|
||||
用途:验证可复用库存解析 Profile 的版本、共享绑定和订单字段匹配键门禁。
|
||||
依赖:inventory_parsing_profile、shipping_inventory_service、订单 Schema 服务。
|
||||
依赖:onhand_parsing_profile、shipping_onhand_admin_service、订单 Schema 服务。
|
||||
逻辑:发布一个 Profile 后绑定多个 Source;新版本并存且旧绑定稳定,非法字段、退役引用或非发布绑定被拒绝。
|
||||
"""
|
||||
|
||||
@@ -8,16 +8,16 @@ from cryptography.fernet import Fernet
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.admin import shipping_inventory_service
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
from app.services.admin import shipping_onhand_admin_service
|
||||
from app.services.shipping_notice import onhand_parsing_profile
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app import db
|
||||
from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryStructureAnalysis
|
||||
from app.models import ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaOnhandStructureAnalysis
|
||||
|
||||
|
||||
def _inventory_mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]:
|
||||
"""以库存字段目录 ID 构造解析映射,禁止测试继续模拟旧字段编码配置。"""
|
||||
rows = {item.field_code: item for item in ShippingInventoryField.query.filter_by(status='active').all()}
|
||||
rows = {item.field_code: item for item in FreightRpaOnhandField.query.filter_by(status='active').all()}
|
||||
return {
|
||||
str(rows['part_number'].id): part,
|
||||
str(rows['reservation_id'].id): reservation,
|
||||
@@ -27,12 +27,12 @@ def _inventory_mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reserv
|
||||
|
||||
def _part_number_field_id() -> str:
|
||||
"""返回内部料号目录 ID,作为订单明细匹配键的库存端引用。"""
|
||||
return str(ShippingInventoryField.query.filter_by(field_code='part_number').one().id)
|
||||
return str(FreightRpaOnhandField.query.filter_by(field_code='part_number').one().id)
|
||||
|
||||
|
||||
def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_format: str = 'xlsx') -> int:
|
||||
"""构造最小化样本结构证据,使 Profile 测试遵循生产环境的表头绑定门禁。"""
|
||||
item = ShippingInventoryStructureAnalysis(
|
||||
item = FreightRpaOnhandStructureAnalysis(
|
||||
source_kind='sample_upload', source_file_name='sample.xlsx', storage_path=None,
|
||||
file_checksum='a' * 64, file_format=file_format, analysis_status='ready',
|
||||
structure_json={'candidates': [{
|
||||
@@ -57,7 +57,7 @@ def _published_profile() -> dict:
|
||||
order_schema_service.publish(
|
||||
schema_draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
|
||||
)
|
||||
draft = inventory_parsing_profile.save_draft({
|
||||
draft = onhand_parsing_profile.save_draft({
|
||||
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common', 'file_format': 'xlsx',
|
||||
'sample_analysis_id': _sample_evidence(headers=['Supplier Sku', 'Reservation ID', 'Qty Available']),
|
||||
'definition': {
|
||||
@@ -66,7 +66,7 @@ def _published_profile() -> dict:
|
||||
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
|
||||
},
|
||||
}, actor_id=None)
|
||||
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
|
||||
return onhand_parsing_profile.publish(draft['id'], actor_id=None)
|
||||
|
||||
|
||||
def _schema_field_config(field_id: str) -> dict:
|
||||
@@ -117,17 +117,17 @@ def test_published_parsing_profile_can_be_shared_by_sources(app):
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
parsing = _published_profile()
|
||||
login = shipping_inventory_service.save_profile({
|
||||
login = shipping_onhand_admin_service.save_profile({
|
||||
'profile_code': 'DBS_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs',
|
||||
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
|
||||
'username': 'u', 'password': 'p', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
first = shipping_inventory_service.save_source(_source(login['id'], parsing['id'], 'DUB'), actor_id=None)
|
||||
second = shipping_inventory_service.save_source(_source(login['id'], parsing['id'], 'RTM'), actor_id=None)
|
||||
first = shipping_onhand_admin_service.save_source(_source(login['id'], parsing['id'], 'DUB'), actor_id=None)
|
||||
second = shipping_onhand_admin_service.save_source(_source(login['id'], parsing['id'], 'RTM'), actor_id=None)
|
||||
|
||||
assert first['parsing_profile_id'] == parsing['id']
|
||||
assert second['parsing_profile_id'] == parsing['id']
|
||||
assert inventory_parsing_profile.list_profiles()[0]['source_count'] == 2
|
||||
assert onhand_parsing_profile.list_profiles()[0]['source_count'] == 2
|
||||
|
||||
|
||||
def test_source_rejects_draft_parsing_profile(app):
|
||||
@@ -136,7 +136,7 @@ def test_source_rejects_draft_parsing_profile(app):
|
||||
with app.app_context():
|
||||
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
|
||||
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
draft = inventory_parsing_profile.save_draft({
|
||||
draft = onhand_parsing_profile.save_draft({
|
||||
'profile_code': 'DRAFT_ONLY', 'display_name': 'Draft', 'definition': {
|
||||
'sheet_name': None, 'header_row_index': 1,
|
||||
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
|
||||
@@ -144,14 +144,14 @@ def test_source_rejects_draft_parsing_profile(app):
|
||||
},
|
||||
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
|
||||
}, actor_id=None)
|
||||
login = shipping_inventory_service.save_profile({
|
||||
login = shipping_onhand_admin_service.save_profile({
|
||||
'profile_code': 'LOGIN', 'display_name': 'Login', 'connector_type': 'dbs',
|
||||
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
|
||||
'username': 'u', 'password': 'p', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.save_source(_source(login['id'], draft['id'], 'DUB'), actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED'
|
||||
shipping_onhand_admin_service.save_source(_source(login['id'], draft['id'], 'DUB'), actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'
|
||||
|
||||
|
||||
def test_csv_parsing_profile_rejects_worksheet_configuration(app):
|
||||
@@ -162,7 +162,7 @@ def test_csv_parsing_profile_rejects_worksheet_configuration(app):
|
||||
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
|
||||
}, actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_parsing_profile.save_draft({
|
||||
onhand_parsing_profile.save_draft({
|
||||
'profile_code': 'CSV_SHEET', 'display_name': 'CSV Sheet', 'file_format': 'csv',
|
||||
'definition': {
|
||||
'sheet_name': 'Inventory', 'header_row_index': 1,
|
||||
@@ -170,7 +170,7 @@ def test_csv_parsing_profile_rejects_worksheet_configuration(app):
|
||||
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
|
||||
},
|
||||
}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_new_published_version_does_not_retire_bound_version(app):
|
||||
@@ -179,7 +179,7 @@ def test_new_published_version_does_not_retire_bound_version(app):
|
||||
with app.app_context():
|
||||
first = _published_profile()
|
||||
field_id = order_schema_service.get_state()['fields'][0]['id']
|
||||
second_draft = inventory_parsing_profile.save_draft({
|
||||
second_draft = onhand_parsing_profile.save_draft({
|
||||
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx',
|
||||
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
|
||||
'definition': {
|
||||
@@ -188,9 +188,9 @@ def test_new_published_version_does_not_retire_bound_version(app):
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_field_id()}],
|
||||
},
|
||||
}, actor_id=None)
|
||||
second = inventory_parsing_profile.publish(second_draft['id'], actor_id=None)
|
||||
second = onhand_parsing_profile.publish(second_draft['id'], actor_id=None)
|
||||
assert first['id'] != second['id']
|
||||
assert {item['status'] for item in inventory_parsing_profile.list_profiles()} == {'published'}
|
||||
assert {item['status'] for item in onhand_parsing_profile.list_profiles()} == {'published'}
|
||||
|
||||
|
||||
def test_referenced_published_profile_cannot_be_retired(app):
|
||||
@@ -198,15 +198,15 @@ def test_referenced_published_profile_cannot_be_retired(app):
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
parsing = _published_profile()
|
||||
login = shipping_inventory_service.save_profile({
|
||||
login = shipping_onhand_admin_service.save_profile({
|
||||
'profile_code': 'RETIRE_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs',
|
||||
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
|
||||
'username': 'u', 'password': 'p', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
shipping_inventory_service.save_source(_source(login['id'], parsing['id'], 'RETIRE'), actor_id=None)
|
||||
shipping_onhand_admin_service.save_source(_source(login['id'], parsing['id'], 'RETIRE'), actor_id=None)
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
inventory_parsing_profile.retire(parsing['id'])
|
||||
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED'
|
||||
onhand_parsing_profile.retire(parsing['id'])
|
||||
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED'
|
||||
|
||||
|
||||
def test_parsing_profile_publish_rejects_field_removed_from_current_schema(app):
|
||||
@@ -222,7 +222,7 @@ def test_parsing_profile_publish_rejects_field_removed_from_current_schema(app):
|
||||
order_schema_service.publish(
|
||||
first['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
|
||||
)
|
||||
profile = inventory_parsing_profile.save_draft({
|
||||
profile = onhand_parsing_profile.save_draft({
|
||||
'profile_code': 'STALE_FIELD', 'display_name': 'Stale Field',
|
||||
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
|
||||
'definition': {
|
||||
@@ -232,5 +232,5 @@ def test_parsing_profile_publish_rejects_field_removed_from_current_schema(app):
|
||||
},
|
||||
}, actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_parsing_profile.publish(profile['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID'
|
||||
onhand_parsing_profile.publish(profile['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID'
|
||||
+20
-20
@@ -1,6 +1,6 @@
|
||||
"""inventory 只读轮询失败语义(P1)单测。
|
||||
|
||||
锁定契约:poll_inventory_preparation 查询到 RPA 失败事实(含超时扫描收口的 failed
|
||||
锁定契约:poll_onhand_preparation 查询到 RPA 失败事实(含超时扫描收口的 failed
|
||||
Attempt)时——
|
||||
1. 只读路径返回可重试失败语义 status='failed'(executor 映射为 blocked_retryable),
|
||||
而非 needs_human 伪装的人工阻断;
|
||||
@@ -8,7 +8,7 @@ Attempt)时——
|
||||
3. 全链路不新建任何 RPA Attempt(轮询零写入)。
|
||||
|
||||
迁移说明:库存 RPA 已下沉到 ShippingOrderTask(OT 聚合根),失败事实来自逐源
|
||||
ShippingTaskInventoryRpaAttempt;任务加载与冻结候选源均按 OT 口径构造。
|
||||
FreightRpaOnhandTaskAttempt;任务加载与冻结候选源均按 OT 口径构造。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,11 +19,11 @@ from app import db
|
||||
from app.models import (
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
FreightRpaOnhandTaskAttempt,
|
||||
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.onhand_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 (
|
||||
@@ -35,7 +35,7 @@ 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(
|
||||
db.session.add(FreightRpaOnhandTaskAttempt(
|
||||
task_no=task_no,
|
||||
source_code=source_code,
|
||||
attempt_no=1,
|
||||
@@ -51,7 +51,7 @@ def _seed_failed_rpa_attempt(task_no: str, source_code: str = 'DSV360_AWSDU') ->
|
||||
|
||||
|
||||
def _rpa_attempt_count(task_no: str) -> int:
|
||||
return ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=task_no).count()
|
||||
return FreightRpaOnhandTaskAttempt.query.filter_by(task_no=task_no).count()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
@@ -84,43 +84,43 @@ def test_readonly_poll_failure_returns_failed_not_needs_human(app, monkeypatch,
|
||||
|
||||
# 仅隔离外部边界门禁(客户/冲突/Reservation/源校验),被测链路保持真实。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.task_execution_block_reason',
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.task_execution_block_reason',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.customer_gate_tool_response',
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.customer_gate_tool_response',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.field_conflict_gate_response',
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.field_conflict_gate_response',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.task_reservation_gate_issues',
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.task_reservation_gate_issues',
|
||||
lambda _task: [],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.assert_inventory_source_gate',
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.assert_inventory_source_gate',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.task_rpa_inventory_source',
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.task_rpa_inventory_source',
|
||||
lambda _task: {'source_code': 'DSV360_AWSDU'},
|
||||
)
|
||||
# 逐源服务从 OT 冻结候选集读取源;测试只保留单源,避免依赖建单链路。
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service,
|
||||
'task_frozen_inventory_source_codes',
|
||||
'task_frozen_onhand_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU'],
|
||||
)
|
||||
# 本用例只锁定失败语义,隔离任务投影与 Tool 响应组装,避免 OT 缺失
|
||||
# 快照/订单字段时被投影逻辑干扰。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.serialize_task_for_tool',
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.serialize_task_for_tool',
|
||||
lambda _task: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.tool_response',
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.tool_response',
|
||||
lambda **kwargs: kwargs,
|
||||
)
|
||||
|
||||
@@ -154,7 +154,7 @@ def test_poll_failure_closes_gate_as_blocked_retryable(app, monkeypatch):
|
||||
)
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_source_routing',
|
||||
through_gate_code='onhand_source_routing',
|
||||
reason='test_poll_failure_semantics',
|
||||
)
|
||||
_seed_failed_rpa_attempt(task.task_no)
|
||||
@@ -169,18 +169,18 @@ def test_poll_failure_closes_gate_as_blocked_retryable(app, monkeypatch):
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
'app.services.shipping_notice.onhand_workflow.ensure_onhand',
|
||||
_failed_poll,
|
||||
)
|
||||
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
gate_code='onhand_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': {}},
|
||||
input_snapshot={'action_code': 'poll_onhand_preparation', 'payload': {}},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
@@ -190,7 +190,7 @@ def test_poll_failure_closes_gate_as_blocked_retryable(app, monkeypatch):
|
||||
# 这比把 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.next_action_code == 'retry_onhand_preparation'
|
||||
assert gate.blocking_reason_code == 'inventory_source_routing_required'
|
||||
|
||||
# 断言 2:Attempt 收口为失败(blocked_retryable 不属于成功族)
|
||||
+12
-12
@@ -1,7 +1,7 @@
|
||||
"""inventory 只读轮询(A1)单测。
|
||||
|
||||
覆盖 ensure_all_required_sources_prepared 的 allow_auto_retry 开关:
|
||||
1. allow_auto_retry=False(poll_inventory_preparation 查询路径):
|
||||
1. allow_auto_retry=False(poll_onhand_preparation 查询路径):
|
||||
RPA Attempt failed / 从未触发 → 只上报 failed,禁止自动新建 Attempt/Trigger。
|
||||
2. allow_auto_retry=False + queued → 仍视为 pending(轮询语义保持)。
|
||||
3. failed/exhausted Attempt 只能由显式 retry_rpa 创建下一 Attempt;
|
||||
@@ -13,13 +13,13 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
from app.models import ShippingNotice, FreightRpaOnhandTaskAttempt
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
|
||||
|
||||
def _seed_attempt(task_no: str, *, status: str, attempt_no: int = 1) -> ShippingTaskInventoryRpaAttempt:
|
||||
def _seed_attempt(task_no: str, *, status: str, attempt_no: int = 1) -> FreightRpaOnhandTaskAttempt:
|
||||
"""在测试库写入一条真实逐源 Attempt,供 _latest_attempt / FOR UPDATE 复检读取。"""
|
||||
att = ShippingTaskInventoryRpaAttempt(
|
||||
att = FreightRpaOnhandTaskAttempt(
|
||||
task_no=task_no,
|
||||
source_code='SRC_A',
|
||||
attempt_no=attempt_no,
|
||||
@@ -48,7 +48,7 @@ def poll_task(app):
|
||||
def _patch_common(monkeypatch, *, snapshot_ready=False):
|
||||
"""统一 monkeypatch:单候选源 + 快照未就绪;Attempt 走真实表。"""
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A']
|
||||
per_source_rpa_service, 'task_frozen_onhand_source_codes', lambda task: ['SRC_A']
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: snapshot_ready
|
||||
@@ -75,7 +75,7 @@ def test_poll_read_only_reports_failed_without_new_attempt(monkeypatch, app, pol
|
||||
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
|
||||
assert FreightRpaOnhandTaskAttempt.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):
|
||||
@@ -93,7 +93,7 @@ def test_poll_read_only_keeps_pending_for_active_attempt(monkeypatch, app, poll_
|
||||
|
||||
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
|
||||
assert FreightRpaOnhandTaskAttempt.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):
|
||||
@@ -109,7 +109,7 @@ def test_poll_read_only_reports_failed_when_never_attempted(monkeypatch, app, po
|
||||
)
|
||||
|
||||
assert result.failed_source_codes == ['SRC_A']
|
||||
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 0
|
||||
assert FreightRpaOnhandTaskAttempt.query.filter_by(task_no=poll_task.task_no).count() == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status', ['failed', 'exhausted'])
|
||||
@@ -126,7 +126,7 @@ def test_auto_does_not_retry_terminal_attempt(monkeypatch, app, poll_task, statu
|
||||
|
||||
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
|
||||
assert FreightRpaOnhandTaskAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
|
||||
|
||||
|
||||
def test_explicit_retry_rpa_creates_next_attempt(monkeypatch, app, poll_task):
|
||||
@@ -135,7 +135,7 @@ def test_explicit_retry_rpa_creates_next_attempt(monkeypatch, app, poll_task):
|
||||
说明:最新 Attempt 用 monkeypatch 提供(SQLite 会忽略 PG 部分唯一索引的 where 条件,
|
||||
真实行 + 新 queued 行在测试库会误撞全量唯一索引;生产 PostgreSQL 无此问题)。"""
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A']
|
||||
per_source_rpa_service, 'task_frozen_onhand_source_codes', lambda task: ['SRC_A']
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False
|
||||
@@ -149,7 +149,7 @@ def test_explicit_retry_rpa_creates_next_attempt(monkeypatch, app, poll_task):
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
|
||||
'app.services.shipping_notice.onhand_source_rules.task_rpa_inventory_source',
|
||||
lambda task: {'source_code': 'SRC_A'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -160,7 +160,7 @@ def test_explicit_retry_rpa_creates_next_attempt(monkeypatch, app, poll_task):
|
||||
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()
|
||||
attempts = FreightRpaOnhandTaskAttempt.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
|
||||
+12
-12
@@ -13,14 +13,14 @@ from io import BytesIO
|
||||
from openpyxl import Workbook
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.services.shipping_notice import inventory_parsing_profile, inventory_structure_analysis
|
||||
from app.services.shipping_notice import onhand_parsing_profile, onhand_structure_analysis
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.models import ShippingInventoryField
|
||||
from app.models import FreightRpaOnhandField
|
||||
|
||||
|
||||
def _part_number_inventory_field_id() -> str:
|
||||
"""返回测试用户创建的匹配字段 ID。"""
|
||||
return str(ShippingInventoryField.query.filter_by(field_code='part_number').one().id)
|
||||
return str(FreightRpaOnhandField.query.filter_by(field_code='part_number').one().id)
|
||||
|
||||
|
||||
def _upload(*, qty: int, extra_column: bool = False) -> FileStorage:
|
||||
@@ -58,17 +58,17 @@ def _field_id() -> str:
|
||||
|
||||
def _published_profile(field_id: str) -> dict:
|
||||
"""通过一次真实分析创建并发布含结构指纹的库存文件解析方案。"""
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=9), actor_id=None)
|
||||
draft = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
analysis = onhand_structure_analysis.create_sample_upload(_upload(qty=9), actor_id=None)
|
||||
draft = onhand_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'SHARED_INVENTORY', 'display_name': '共享库存文件', 'sheet_name': 'Sheet', 'header_row_index': 1,
|
||||
'field_mapping': {
|
||||
_part_number_inventory_field_id(): 'Supplier Sku',
|
||||
str(ShippingInventoryField.query.filter_by(field_code='reservation_id').one().id): 'Reservation ID',
|
||||
str(ShippingInventoryField.query.filter_by(field_code='available_qty').one().id): 'Qty Available',
|
||||
str(FreightRpaOnhandField.query.filter_by(field_code='reservation_id').one().id): 'Reservation ID',
|
||||
str(FreightRpaOnhandField.query.filter_by(field_code='available_qty').one().id): 'Qty Available',
|
||||
},
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_inventory_field_id()}],
|
||||
}, actor_id=None)
|
||||
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
|
||||
return onhand_parsing_profile.publish(draft['id'], actor_id=None)
|
||||
|
||||
|
||||
def test_same_structure_with_different_data_recommends_exact_profile(app, tmp_path):
|
||||
@@ -76,7 +76,7 @@ def test_same_structure_with_different_data_recommends_exact_profile(app, tmp_pa
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
profile = _published_profile(_field_id())
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=999), actor_id=None)
|
||||
analysis = onhand_structure_analysis.create_sample_upload(_upload(qty=999), actor_id=None)
|
||||
result = analysis['match_result']
|
||||
assert result['status'] == 'exact'
|
||||
assert result['candidates'][0]['profile_id'] == profile['id']
|
||||
@@ -87,7 +87,7 @@ def test_added_non_critical_column_recommends_compatible_profile(app, tmp_path):
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
profile = _published_profile(_field_id())
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=12, extra_column=True), actor_id=None)
|
||||
analysis = onhand_structure_analysis.create_sample_upload(_upload(qty=12, extra_column=True), actor_id=None)
|
||||
candidate = analysis['match_result']['candidates'][0]
|
||||
assert analysis['match_result']['status'] == 'compatible'
|
||||
assert candidate['profile_id'] == profile['id']
|
||||
@@ -99,7 +99,7 @@ def test_adopting_recommendation_does_not_bind_inventory_source(app, tmp_path):
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
profile = _published_profile(_field_id())
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=10), actor_id=None)
|
||||
adopted = inventory_structure_analysis.adopt_published_profile(analysis['id'], profile['id'])
|
||||
analysis = onhand_structure_analysis.create_sample_upload(_upload(qty=10), actor_id=None)
|
||||
adopted = onhand_structure_analysis.adopt_published_profile(analysis['id'], profile['id'])
|
||||
assert adopted['match_result']['adopted_profile_id'] == profile['id']
|
||||
assert profile['source_count'] == 0
|
||||
File renamed without changes.
+4
-4
@@ -11,8 +11,8 @@ from datetime import datetime, timedelta
|
||||
from sqlalchemy import event
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.shipping_notice.onhand_snapshot_store import (
|
||||
expire_snapshot,
|
||||
find_latest_ready_snapshot,
|
||||
)
|
||||
@@ -22,8 +22,8 @@ def _seed_snapshot(*, inventory_file_no: str, source_code: str, warehouse_id: st
|
||||
"""写入一个 ready 且文件真实存在(freshness 通过)的快照行。"""
|
||||
path = tmp_path / f'{inventory_file_no}.xlsx'
|
||||
path.write_bytes(b'placeholder')
|
||||
row = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
row = FreightRpaOnhandReportFile(
|
||||
onhand_file_no=inventory_file_no,
|
||||
storage_path=str(path),
|
||||
source_code=source_code,
|
||||
warehouse_id=warehouse_id,
|
||||
+10
-10
@@ -2,7 +2,7 @@
|
||||
tests/test_inventory_source_gate_notice_task.py
|
||||
|
||||
用途:锁定「库存源稳定门禁 / 库存身份对 ShippingNotice 的归一」契约。
|
||||
依赖:pytest、inventory_source_gate、inventory_candidate_projection、app 夹具(内存测试库)。
|
||||
依赖:pytest、onhand_source_gate、onhand_candidate_projection、app 夹具(内存测试库)。
|
||||
逻辑:货代上传入口按 business_no 加载 Notice,而候选集事实挂在 OT 上;门禁必须沿
|
||||
order_task_id 归一读取。历史缺陷:Notice 缺 active_inventory_candidate_set_id
|
||||
字段导致 is_inventory_source_stable(Notice) 恒 False,RPA 上传被
|
||||
@@ -16,9 +16,9 @@ def _make_frozen_task_with_notice(task_no: str):
|
||||
"""构造带冻结候选集(单源 CRANE)的 OT 及其已绑定 Notice。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingOnhandCandidateLine,
|
||||
ShippingOnhandCandidateSet,
|
||||
ShippingOnhandCandidateSource,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
@@ -27,7 +27,7 @@ def _make_frozen_task_with_notice(task_no: str):
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
candidate_set = ShippingOnhandCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=1,
|
||||
lifecycle_status='frozen',
|
||||
@@ -36,13 +36,13 @@ def _make_frozen_task_with_notice(task_no: str):
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
db.session.add(ShippingOnhandCandidateSource(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
source_code='CRANE',
|
||||
candidate_order=1,
|
||||
candidate_origin='rule',
|
||||
))
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
db.session.add(ShippingOnhandCandidateLine(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
line_no=1,
|
||||
part_number='PN-1',
|
||||
@@ -65,7 +65,7 @@ def _make_frozen_task_with_notice(task_no: str):
|
||||
|
||||
def _patch_source_lookup(monkeypatch):
|
||||
"""注入启用的 CRANE 源配置(inventory_match 动态仓),免建 RPA Profile。"""
|
||||
from app.services.shipping_notice import inventory_source_gate as gate_mod
|
||||
from app.services.shipping_notice import onhand_source_gate as gate_mod
|
||||
|
||||
def _source(code):
|
||||
if str(code).upper() != 'CRANE':
|
||||
@@ -86,7 +86,7 @@ def test_inventory_source_stable_resolves_notice_to_order_task(app, monkeypatch)
|
||||
"""门禁对 Notice 必须沿 order_task_id 读取冻结候选集,判定与 OT 一致。"""
|
||||
_patch_source_lookup(monkeypatch)
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
from app.services.shipping_notice.onhand_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
task_inventory_identity,
|
||||
)
|
||||
@@ -108,7 +108,7 @@ def test_inventory_source_stable_fail_closed_without_order_task(app, monkeypatch
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
from app.services.shipping_notice.onhand_source_gate import is_inventory_source_stable
|
||||
|
||||
orphan = ShippingNotice(
|
||||
task_no='SN-ORPHAN-NOTICE',
|
||||
+40
-40
@@ -2,7 +2,7 @@
|
||||
tests/test_inventory_structure_analysis.py
|
||||
|
||||
用途:验证库存样本的后端结构分析、真实表头约束和解析方案草稿创建。
|
||||
依赖:openpyxl、inventory_structure_analysis、订单字段 Schema 服务。
|
||||
依赖:openpyxl、onhand_structure_analysis、订单字段 Schema 服务。
|
||||
逻辑:管理端上传样本后必须由后端决定工作表和来源栏位;草稿创建只能引用分析出的真实栏位。
|
||||
"""
|
||||
|
||||
@@ -17,14 +17,14 @@ import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.extensions import db
|
||||
from app.services.shipping_notice import inventory_structure_analysis
|
||||
from app.services.shipping_notice import onhand_structure_analysis
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis
|
||||
from app.models import FreightRpaOnhandField, FreightRpaParsingProfile, FreightRpaOnhandStructureAnalysis
|
||||
|
||||
|
||||
def _field_id(field_code: str) -> str:
|
||||
"""返回测试显式创建的用户库存字段 ID。"""
|
||||
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
|
||||
return str(FreightRpaOnhandField.query.filter_by(field_code=field_code).one().id)
|
||||
|
||||
|
||||
def _mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]:
|
||||
@@ -79,7 +79,7 @@ def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_p
|
||||
"""上传样本必须定位真实库存表头,只持久化脱敏样例并清理完整工作簿。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
result = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
result = onhand_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
assert result['file_format'] == 'xlsx'
|
||||
assert result['structure']['selected_sheet_name'] == 'Inventory'
|
||||
assert result['structure']['selected_header_row_index'] == 3
|
||||
@@ -90,7 +90,7 @@ def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_p
|
||||
assert qty['inferred_type'] == 'number'
|
||||
assert qty['sample_values'] == ['9', '11']
|
||||
assert result['sample_rows'][0] == ['P***1', '10***51', 9, 'A***U', '00***74']
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, result['id'])
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, result['id'])
|
||||
assert analysis is not None
|
||||
assert analysis.storage_path is None
|
||||
assert analysis.sample_rows_json == result['sample_rows']
|
||||
@@ -112,7 +112,7 @@ def test_sample_analysis_prefers_populated_detail_sheet_over_same_score_summary(
|
||||
inventory.append(['PART-001', 'RSV-001', 7])
|
||||
workbook.save(stream)
|
||||
stream.seek(0)
|
||||
result = inventory_structure_analysis.create_sample_upload(
|
||||
result = onhand_structure_analysis.create_sample_upload(
|
||||
FileStorage(stream=stream, filename='multi-sheet.xlsx'), actor_id=None,
|
||||
)
|
||||
assert result['structure']['selected_sheet_name'] == 'Inventory'
|
||||
@@ -126,7 +126,7 @@ def test_sample_analysis_reads_legacy_xls(app, tmp_path):
|
||||
template = Path(__file__).resolve().parents[1] / 'templates' / 'maintenance_record_history_template.xls'
|
||||
with app.app_context():
|
||||
upload = FileStorage(stream=BytesIO(template.read_bytes()), filename='legacy-inventory.xls')
|
||||
result = inventory_structure_analysis.create_sample_upload(upload, actor_id=None)
|
||||
result = onhand_structure_analysis.create_sample_upload(upload, actor_id=None)
|
||||
|
||||
assert result['file_format'] == 'xls'
|
||||
assert result['structure']['selected_headers']
|
||||
@@ -137,15 +137,15 @@ def test_profile_draft_rejects_source_header_not_present_in_analysis(app, tmp_pa
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
field_id = _published_part_number()
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
analysis = onhand_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
onhand_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'INVALID_HEADERS', 'display_name': 'Invalid',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': _mapping(part='Made Up'),
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
||||
}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID'
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID'
|
||||
|
||||
|
||||
def test_profile_draft_rejects_duplicate_source_header(app, tmp_path):
|
||||
@@ -160,17 +160,17 @@ def test_profile_draft_rejects_duplicate_source_header(app, tmp_path):
|
||||
sheet.append(['PN-1', 'PN-OTHER', '1000140351', 9])
|
||||
workbook.save(stream)
|
||||
stream.seek(0)
|
||||
analysis = inventory_structure_analysis.create_sample_upload(
|
||||
analysis = onhand_structure_analysis.create_sample_upload(
|
||||
FileStorage(stream=stream, filename='duplicate.xlsx'), actor_id=None,
|
||||
)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
onhand_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'DUPLICATE_HEADERS', 'display_name': 'Duplicate',
|
||||
'sheet_name': 'Sheet', 'header_row_index': 1,
|
||||
'field_mapping': _mapping(),
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
||||
}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID'
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID'
|
||||
|
||||
|
||||
def test_profile_draft_uses_analysis_header_selection(app, tmp_path):
|
||||
@@ -178,8 +178,8 @@ def test_profile_draft_uses_analysis_header_selection(app, tmp_path):
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
field_id = _published_part_number()
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
analysis = onhand_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = onhand_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'AWS_INVENTORY', 'display_name': 'AWS 库存文件',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': _mapping(),
|
||||
@@ -188,7 +188,7 @@ def test_profile_draft_uses_analysis_header_selection(app, tmp_path):
|
||||
assert profile['status'] == 'draft'
|
||||
assert profile['definition']['sheet_name'] == 'Inventory'
|
||||
assert profile['definition']['field_mapping'][_field_id('part_number')] == 'Supplier Sku'
|
||||
saved = db.session.get(ShippingInventoryParsingProfile, profile['id'])
|
||||
saved = db.session.get(FreightRpaParsingProfile, profile['id'])
|
||||
assert saved is not None
|
||||
assert saved.sample_analysis_id == analysis['id']
|
||||
|
||||
@@ -198,26 +198,26 @@ def test_profile_sample_replacement_requires_confirmation_and_keeps_audit_histor
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
field_id = _published_part_number()
|
||||
first = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = inventory_structure_analysis.create_profile_draft(first['id'], {
|
||||
first = onhand_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = onhand_structure_analysis.create_profile_draft(first['id'], {
|
||||
'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': _mapping(),
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
||||
}, actor_id=None)
|
||||
second = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
preview = inventory_structure_analysis.preview_profile_sample_replacement(profile['id'], second['id'])
|
||||
second = onhand_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
preview = onhand_structure_analysis.preview_profile_sample_replacement(profile['id'], second['id'])
|
||||
assert preview['can_confirm'] is True
|
||||
assert preview['difference']['missing_mapped_headers'] == []
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_structure_analysis.create_profile_draft(second['id'], {
|
||||
onhand_structure_analysis.create_profile_draft(second['id'], {
|
||||
'profile_id': profile['id'], 'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': _mapping(),
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
||||
}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED'
|
||||
updated = inventory_structure_analysis.create_profile_draft(second['id'], {
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED'
|
||||
updated = onhand_structure_analysis.create_profile_draft(second['id'], {
|
||||
'profile_id': profile['id'], 'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': _mapping(),
|
||||
@@ -234,8 +234,8 @@ def test_profile_sample_replacement_rejects_file_format_change(app, tmp_path):
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
field_id = _published_part_number()
|
||||
first = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = inventory_structure_analysis.create_profile_draft(first['id'], {
|
||||
first = onhand_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = onhand_structure_analysis.create_profile_draft(first['id'], {
|
||||
'profile_code': 'FORMAT_REPLACEMENT', 'display_name': 'Format replacement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': _mapping(),
|
||||
@@ -245,32 +245,32 @@ def test_profile_sample_replacement_rejects_file_format_change(app, tmp_path):
|
||||
stream=BytesIO(b'Supplier Sku,Reservation ID,Qty Available\nPN-001,R-1,1\n'),
|
||||
filename='replacement.csv',
|
||||
)
|
||||
csv_analysis = inventory_structure_analysis.create_sample_upload(csv_upload, actor_id=None)
|
||||
csv_analysis = onhand_structure_analysis.create_sample_upload(csv_upload, actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_structure_analysis.create_profile_draft(csv_analysis['id'], {
|
||||
onhand_structure_analysis.create_profile_draft(csv_analysis['id'], {
|
||||
'profile_id': profile['id'], 'profile_code': 'FORMAT_REPLACEMENT', 'display_name': 'Format replacement',
|
||||
'header_row_index': 1, 'field_mapping': _mapping(),
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
||||
'confirm_sample_replacement': True,
|
||||
}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_profile_draft_requires_persisted_sample_evidence(app):
|
||||
"""绕过样本分析直接保存草稿时必须被拒绝,避免来源表头脱离审计依据。"""
|
||||
with app.app_context():
|
||||
field_id = _published_part_number()
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
from app.services.shipping_notice import onhand_parsing_profile
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_parsing_profile.save_draft({
|
||||
onhand_parsing_profile.save_draft({
|
||||
'profile_code': 'NO_EVIDENCE', 'display_name': 'No evidence', 'file_format': 'xlsx',
|
||||
'definition': {
|
||||
'sheet_name': 'Inventory', 'header_row_index': 1, 'field_mapping': _mapping(),
|
||||
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
||||
},
|
||||
}, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED'
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED'
|
||||
|
||||
|
||||
def test_sample_analysis_rejects_invalid_file(app, tmp_path):
|
||||
@@ -279,17 +279,17 @@ def test_sample_analysis_rejects_invalid_file(app, tmp_path):
|
||||
with app.app_context():
|
||||
upload = FileStorage(stream=BytesIO(b'not a workbook'), filename='invalid.xlsx')
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_structure_analysis.create_sample_upload(upload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID'
|
||||
onhand_structure_analysis.create_sample_upload(upload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID'
|
||||
|
||||
|
||||
def test_profile_draft_purpose_passthrough_creates_inbound_profile(app, tmp_path):
|
||||
"""purpose='inbound' 必须透传到解析规则:入站草稿不依赖库存字段目录与匹配键。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
analysis = onhand_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
# 关键断言:inbound 映射直接用定死领域字段码作键,不需要订单匹配键。
|
||||
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
profile = onhand_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'MOVE_STD', 'display_name': '入站解析标准', 'purpose': 'inbound',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
|
||||
@@ -303,12 +303,12 @@ def test_profile_draft_purpose_passthrough_creates_inbound_profile(app, tmp_path
|
||||
|
||||
def test_publish_inbound_profile_skips_order_match_key_contract(app, tmp_path):
|
||||
"""发布 inbound 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。"""
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
from app.services.shipping_notice import onhand_parsing_profile
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
analysis = onhand_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = onhand_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'MOVE_PUB', 'display_name': '入站解析发布', 'purpose': 'inbound',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
|
||||
@@ -316,7 +316,7 @@ def test_publish_inbound_profile_skips_order_match_key_contract(app, tmp_path):
|
||||
'match_keys': None,
|
||||
}, actor_id=None)
|
||||
# 关键断言:inbound 草稿必须能直接发布(有样本证据即可),match_keys 为空是合法契约。
|
||||
published = inventory_parsing_profile.publish(profile['id'], actor_id=None)
|
||||
published = onhand_parsing_profile.publish(profile['id'], actor_id=None)
|
||||
assert published['status'] == 'published'
|
||||
assert published['checksum']
|
||||
assert published['definition']['match_keys'] == []
|
||||
+37
-26
@@ -10,13 +10,13 @@ from openpyxl import Workbook
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryFile,
|
||||
ShippingInventoryParsingProfile, ShippingInventorySource, ShippingRpaProfile,
|
||||
ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaOnhandReportFile,
|
||||
FreightRpaOnhandReportConfig, FreightRpaParsingProfile, FreightRpaSource, FreightRpaProfile,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
|
||||
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path
|
||||
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition
|
||||
from app.services.shipping_notice.onhand_file_store import parse_inventory_snapshot_file
|
||||
from app.services.shipping_notice.onhand_structure_analysis import _analyse_path
|
||||
from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure
|
||||
from app.services.shipping_notice.onhand_structure_fingerprint import exact_fingerprint, structure_definition
|
||||
|
||||
|
||||
def _workbook(path: Path, headers: list[str]) -> None:
|
||||
@@ -47,15 +47,15 @@ def _multi_sheet_workbook(path: Path) -> None:
|
||||
workbook.save(path)
|
||||
|
||||
|
||||
def _source_with_profile(path: Path) -> ShippingInventorySource:
|
||||
def _source_with_profile(path: Path) -> FreightRpaSource:
|
||||
"""从基准文件建立已启用站点和已发布方案,模拟完成全部启用前校验后的状态。"""
|
||||
structure, _suggested, _summary, _warnings = _analyse_path(path, '.xlsx')
|
||||
definition = structure_definition(
|
||||
file_format='xlsx', sheet_name='Sheet', header_row_index=1,
|
||||
headers=structure['selected_headers'],
|
||||
)
|
||||
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.filter_by(status='active').all()}
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
inventory_fields = {item.field_code: str(item.id) for item in FreightRpaOnhandField.query.filter_by(status='active').all()}
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code='DRIFT_PROFILE', display_name='Drift Profile', version=1, status='published', file_format='xlsx',
|
||||
definition_json={'sheet_name': 'Sheet', 'header_row_index': 1, 'field_mapping': {
|
||||
inventory_fields['part_number']: 'Supplier Sku', inventory_fields['reservation_id']: 'Reservation ID',
|
||||
@@ -63,7 +63,7 @@ def _source_with_profile(path: Path) -> ShippingInventorySource:
|
||||
}, 'match_keys': []}, structure_definition_json=definition,
|
||||
exact_structure_fingerprint=exact_fingerprint(definition), checksum='1' * 64,
|
||||
)
|
||||
rpa = ShippingRpaProfile(
|
||||
rpa = FreightRpaProfile(
|
||||
profile_code='DRIFT_LOGIN', display_name='Drift Login', connector_type='dbs',
|
||||
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
|
||||
)
|
||||
@@ -73,12 +73,17 @@ def _source_with_profile(path: Path) -> ShippingInventorySource:
|
||||
definition_json={'mappings': [{'source_kind': 'inventory_field', 'source_key': 'part_number'}]},
|
||||
definition_checksum='2' * 64,
|
||||
)
|
||||
source = ShippingInventorySource(
|
||||
source = FreightRpaSource(
|
||||
source_code='DRIFT_SOURCE', display_name='Drift Source', connector_type='dbs', rpa_profile=rpa,
|
||||
parsing_profile=profile, excel_template=template, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
||||
query_parameters_json=[], enabled=True,
|
||||
excel_template=template, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
|
||||
enabled=True,
|
||||
)
|
||||
# s18 起报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载。
|
||||
db.session.add(FreightRpaOnhandReportConfig(
|
||||
source=source, parsing_profile=profile,
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
||||
query_parameters_json=[],
|
||||
))
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
return source
|
||||
@@ -112,7 +117,7 @@ def test_production_structure_blocks_core_column_drift(app, tmp_path):
|
||||
|
||||
with pytest.raises(ConflictError) as blocked:
|
||||
validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=drifted)
|
||||
assert blocked.value.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED'
|
||||
assert blocked.value.code == 'SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED'
|
||||
|
||||
|
||||
def test_production_structure_uses_configured_worksheet_not_best_guess(app, tmp_path):
|
||||
@@ -121,16 +126,18 @@ def test_production_structure_uses_configured_worksheet_not_best_guess(app, tmp_
|
||||
baseline = tmp_path / 'baseline.xlsx'
|
||||
_workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available'])
|
||||
source = _source_with_profile(baseline)
|
||||
source.parsing_profile.definition_json = {
|
||||
**source.parsing_profile.definition_json,
|
||||
# s18 起解析方案绑定挂在配置行上,测试直接改绑定方案的定义。
|
||||
profile = source.onhand_report_config.parsing_profile
|
||||
profile.definition_json = {
|
||||
**profile.definition_json,
|
||||
'sheet_name': 'Inventory',
|
||||
}
|
||||
source.parsing_profile.structure_definition_json = structure_definition(
|
||||
profile.structure_definition_json = structure_definition(
|
||||
file_format='xlsx', sheet_name='Inventory', header_row_index=1,
|
||||
headers=['Supplier Sku', 'Reservation ID', 'Qty Available'],
|
||||
)
|
||||
source.parsing_profile.exact_structure_fingerprint = exact_fingerprint(
|
||||
source.parsing_profile.structure_definition_json,
|
||||
profile.exact_structure_fingerprint = exact_fingerprint(
|
||||
profile.structure_definition_json,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
@@ -146,8 +153,8 @@ def test_snapshot_reread_uses_published_profile_not_header_guess(app, tmp_path):
|
||||
path = tmp_path / 'configured-only.xlsx'
|
||||
_workbook(path, ['Custom Part', 'Custom Reservation', 'Custom Quantity'])
|
||||
source = _source_with_profile(path)
|
||||
fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
||||
source.parsing_profile.definition_json = {
|
||||
fields = {item.field_code: str(item.id) for item in FreightRpaOnhandField.query.all()}
|
||||
source.onhand_report_config.parsing_profile.definition_json = {
|
||||
'sheet_name': 'Sheet', 'header_row_index': 1,
|
||||
'field_mapping': {
|
||||
fields['part_number']: 'Custom Part',
|
||||
@@ -156,18 +163,22 @@ def test_snapshot_reread_uses_published_profile_not_header_guess(app, tmp_path):
|
||||
},
|
||||
'match_keys': [],
|
||||
}
|
||||
snapshot = ShippingInventoryFile(
|
||||
inventory_file_no='INV-REREAD-001', storage_path=str(path), source_code=source.source_code,
|
||||
warehouse_id='DUB', snapshot_status='ready', inventory_lines_json=None,
|
||||
snapshot = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='INV-REREAD-001', storage_path=str(path), source_code=source.source_code,
|
||||
warehouse_id='DUB', snapshot_status='ready', onhand_lines_json=None,
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.commit()
|
||||
|
||||
lines, meta = parse_inventory_snapshot_file(snapshot)
|
||||
# 关键断言:值必须来自绑定方案的字段映射(字段 ID 键),而不是表头猜测;
|
||||
# 正式快照同时镜像 canonical 字段码键(onhand_snapshot._normalize_inventory_row 的既定契约)。
|
||||
assert lines == [{
|
||||
fields['part_number']: 'PN-CUSTOM',
|
||||
fields['reservation_id']: '1000140999',
|
||||
fields['available_qty']: 7.0,
|
||||
'part_number': 'PN-CUSTOM',
|
||||
'reservation_id': '1000140999',
|
||||
'available_qty': 7.0,
|
||||
}]
|
||||
assert 'part_number' not in lines[0]
|
||||
assert str(meta['mapping_source']).startswith('parsing_profile:DRIFT_PROFILE:v1')
|
||||
@@ -1,11 +1,11 @@
|
||||
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验 + 迁移往返)。
|
||||
|
||||
用途:验证 inventory_parsing_profile._validate_definition(purpose=...) 分支——
|
||||
用途:验证 onhand_parsing_profile._validate_definition(purpose=...) 分支——
|
||||
inbound 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
|
||||
不查库存字段目录、无 match_keys);onhand/outbound 维持既有库存字段目录 + match_keys
|
||||
校验(outbound 出站文件结构就位,暂无运行时消费方)。并用 app fixture 校验模型
|
||||
purpose 列默认 'onhand'、CHECK 约束三元枚举,以及 tt15 迁移 SQLite 真实往返。
|
||||
依赖:inventory_parsing_profile._validate_definition / save_draft(纯 + app SQLite)、
|
||||
依赖:onhand_parsing_profile._validate_definition / save_draft(纯 + app SQLite)、
|
||||
migrations/versions/tt15(batch_alter_table 改枚举)、app_ctx(根 conftest app
|
||||
fixture 上下文别名)。
|
||||
逻辑:_required_movement_field_ids 纯函数校验;模型列默认值/约束经 app fixture 校验;
|
||||
@@ -23,7 +23,7 @@ from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.inventory_parsing_profile import _validate_definition, save_draft
|
||||
from app.services.shipping_notice.onhand_parsing_profile import _validate_definition, save_draft
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
@@ -82,12 +82,12 @@ def test_inbound_definition_rejects_unknown_field():
|
||||
|
||||
|
||||
def test_purpose_enum_values():
|
||||
"""模型 purpose 列:default/server_default 均为 'onhand',CHECK 枚举恰为三元新枚举。"""
|
||||
from app.models.shipping_inventory_config import ShippingInventoryParsingProfile
|
||||
col = ShippingInventoryParsingProfile.__table__.columns["purpose"]
|
||||
"""模型 purpose 列:default/server_default 均为 'onhand',CHECK 名为批次 S 新约束,枚举恰为三元。"""
|
||||
from app.models.freight_rpa_config import FreightRpaParsingProfile
|
||||
col = FreightRpaParsingProfile.__table__.columns["purpose"]
|
||||
assert col.default.arg == "onhand" and col.server_default.arg == "onhand"
|
||||
check = next(c for c in ShippingInventoryParsingProfile.__table__.constraints
|
||||
if getattr(c, "name", "") == "ck_shipping_inventory_parsing_profiles_purpose")
|
||||
check = next(c for c in FreightRpaParsingProfile.__table__.constraints
|
||||
if getattr(c, "name", "") == "ck_freight_rpa_parsing_profiles_purpose")
|
||||
sql = str(getattr(check, "sqltext", check))
|
||||
for value in ("onhand", "inbound", "outbound"):
|
||||
assert value in sql
|
||||
@@ -98,9 +98,9 @@ def test_purpose_enum_values():
|
||||
def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_format: str = 'xlsx') -> int:
|
||||
"""构造最小化样本结构证据,使 save_draft 遵循生产环境的表头绑定门禁。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryStructureAnalysis
|
||||
from app.models import FreightRpaOnhandStructureAnalysis
|
||||
|
||||
item = ShippingInventoryStructureAnalysis(
|
||||
item = FreightRpaOnhandStructureAnalysis(
|
||||
source_kind='sample_upload', source_file_name='sample.xlsx', storage_path=None,
|
||||
file_checksum='c' * 64, file_format=file_format, analysis_status='ready',
|
||||
structure_json={'candidates': [{
|
||||
@@ -116,9 +116,9 @@ def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_
|
||||
|
||||
def _catalog_mapping() -> dict[str, str]:
|
||||
"""以库存字段目录 ID 构造 onhand/outbound 用解析映射(目录分支端点)。"""
|
||||
from app.models import ShippingInventoryField
|
||||
from app.models import FreightRpaOnhandField
|
||||
|
||||
rows = {item.field_code: item for item in ShippingInventoryField.query.filter_by(status='active').all()}
|
||||
rows = {item.field_code: item for item in FreightRpaOnhandField.query.filter_by(status='active').all()}
|
||||
return {
|
||||
str(rows['part_number'].id): 'Supplier Sku',
|
||||
str(rows['reservation_id'].id): 'Reservation ID',
|
||||
@@ -127,7 +127,7 @@ def _catalog_mapping() -> dict[str, str]:
|
||||
|
||||
|
||||
def test_draft_accepts_outbound_and_rejects_legacy(app_ctx):
|
||||
"""save_draft purpose='outbound' 通过校验;purpose='movement' 报 SHIPPING.INVENTORY_PARSING_PROFILE_INVALID。"""
|
||||
"""save_draft purpose='outbound' 通过校验;purpose='movement' 报 SHIPPING.ONHAND_PARSING_PROFILE_INVALID。"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderField
|
||||
|
||||
@@ -155,14 +155,14 @@ def test_draft_accepts_outbound_and_rejects_legacy(app_ctx):
|
||||
'definition': {'header_row_index': 1, 'field_mapping': _catalog_mapping(), 'match_keys': []},
|
||||
}, actor_id=None)
|
||||
# 关键断言:旧枚举 movement 已从白名单移除,fail-closed 报统一错误码。
|
||||
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
|
||||
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_model_purpose_column_defaults_to_onhand(app):
|
||||
"""模型 purpose 列默认 'onhand'(存量 inventory 行由 tt15 数据迁移回填)。"""
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
from app.models import FreightRpaParsingProfile
|
||||
|
||||
existing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first()
|
||||
existing = FreightRpaParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first()
|
||||
assert existing is not None and existing.purpose == 'onhand'
|
||||
|
||||
|
||||
|
||||
@@ -16,16 +16,16 @@ import pytest
|
||||
|
||||
def test_persist_without_snapshot_forbids_ready_not_found(app):
|
||||
"""BE-5:无 snapshot 时不得写入 ready/not_found。"""
|
||||
from app.services.shipping_notice import line_inventory_match_persistence as svc
|
||||
from app.services.shipping_notice import line_onhand_match_persistence as svc
|
||||
|
||||
task = SimpleNamespace(id=1, inventory_snapshot_id=None)
|
||||
task = SimpleNamespace(id=1, onhand_snapshot_id=None)
|
||||
added = []
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(svc, 'resolve_review_case_for_task', return_value=None),
|
||||
patch.object(svc, '_draft_line_keys_by_index', return_value={0: 'L1'}),
|
||||
patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(svc.ShippingNoticeLineOnhandMatch, 'query') as match_q,
|
||||
patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
patch.object(svc.db.session, 'flush'),
|
||||
):
|
||||
@@ -52,15 +52,15 @@ def test_persist_without_snapshot_forbids_ready_not_found(app):
|
||||
|
||||
assert len(added) == 1
|
||||
assert added[0].match_result == 'result_missing'
|
||||
assert added[0].inventory_status == 'unavailable'
|
||||
assert added[0].onhand_status == 'unavailable'
|
||||
assert added[0].available_qty is None
|
||||
|
||||
|
||||
def test_persist_prefers_formal_draft_line_key_over_matcher_temporary_key(app):
|
||||
"""匹配器 line-1 不得覆盖 Case 草稿 machine-1 的正式明细身份。"""
|
||||
from app.services.shipping_notice import line_inventory_match_persistence as svc
|
||||
from app.services.shipping_notice import line_onhand_match_persistence as svc
|
||||
|
||||
task = SimpleNamespace(id=1, inventory_snapshot_id=7)
|
||||
task = SimpleNamespace(id=1, onhand_snapshot_id=7)
|
||||
added = []
|
||||
|
||||
with app.app_context():
|
||||
@@ -69,7 +69,7 @@ def test_persist_prefers_formal_draft_line_key_over_matcher_temporary_key(app):
|
||||
patch.object(svc, '_draft_line_keys_by_index', return_value={0: 'machine-1'}),
|
||||
patch.object(svc, 'get_active_candidate_set', return_value=None),
|
||||
patch.object(svc, 'get_active_candidate_lines', return_value=[]),
|
||||
patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(svc.ShippingNoticeLineOnhandMatch, 'query') as match_q,
|
||||
patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
patch.object(svc.db.session, 'flush'),
|
||||
):
|
||||
@@ -101,19 +101,19 @@ def test_persist_prefers_formal_draft_line_key_over_matcher_temporary_key(app):
|
||||
|
||||
def test_persist_derives_line_file_number_from_snapshot_when_matcher_omits_it(app):
|
||||
"""行级匹配结果漏带文件号时,持久化必须从已绑定快照补齐下载证据。"""
|
||||
from app.services.shipping_notice import line_inventory_match_persistence as svc
|
||||
from app.services.shipping_notice import line_onhand_match_persistence as svc
|
||||
|
||||
task = SimpleNamespace(id=1, inventory_snapshot_id=7)
|
||||
task = SimpleNamespace(id=1, onhand_snapshot_id=7)
|
||||
added = []
|
||||
snapshot = SimpleNamespace(inventory_file_no='SIF-SNAPSHOT-7')
|
||||
snapshot = SimpleNamespace(onhand_file_no='SIF-SNAPSHOT-7')
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(svc, 'resolve_review_case_for_task', return_value=None),
|
||||
patch.object(svc, 'get_active_candidate_set', return_value=None),
|
||||
patch.object(svc, 'get_active_candidate_lines', return_value=[]),
|
||||
patch.object(svc, 'ShippingInventoryFile') as file_model,
|
||||
patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(svc, 'FreightRpaOnhandReportFile') as file_model,
|
||||
patch.object(svc.ShippingNoticeLineOnhandMatch, 'query') as match_q,
|
||||
patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
patch.object(svc.db.session, 'flush'),
|
||||
):
|
||||
@@ -142,7 +142,7 @@ def test_persist_derives_line_file_number_from_snapshot_when_matcher_omits_it(ap
|
||||
|
||||
def test_unit_participates_in_match_key():
|
||||
"""BE-6:同料号预约单但单位不同不得命中。"""
|
||||
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
|
||||
from app.services.shipping_notice.stp_line_onhand_match import match_order_lines_across_candidates
|
||||
|
||||
out = match_order_lines_across_candidates(
|
||||
order_lines=[{
|
||||
@@ -184,7 +184,7 @@ def test_unit_participates_in_match_key():
|
||||
|
||||
def test_reservation_part_match_without_unit_aggregates_fourteen_rows():
|
||||
"""库存 Profile 未配置单位时,Reservation+料号命中 14 行并汇总为 14。"""
|
||||
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
|
||||
from app.services.shipping_notice.stp_line_onhand_match import match_order_lines_across_candidates
|
||||
|
||||
inventory = [
|
||||
{
|
||||
@@ -255,7 +255,7 @@ def test_compensation_runner_noops_when_flag_disabled(app, monkeypatch):
|
||||
|
||||
|
||||
def test_mark_auto_fulfill_failed_sets_fact_columns(app):
|
||||
"""BE-7:失败写入匹配事实独立列,不新建 wait_inventory。"""
|
||||
"""BE-7:失败写入匹配事实独立列,不新建 wait_onhand。"""
|
||||
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
|
||||
|
||||
case = SimpleNamespace(id=1, case_no='RC-1', confirmed_task_id=9)
|
||||
@@ -271,7 +271,7 @@ def test_mark_auto_fulfill_failed_sets_fact_columns(app):
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(coord.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(coord.ShippingNoticeLineOnhandMatch, 'query') as match_q,
|
||||
patch.object(coord.ShippingOrderReviewLineDecision, 'query') as dec_q,
|
||||
patch.object(coord.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
):
|
||||
|
||||
@@ -48,7 +48,7 @@ def test_released_shortage_line_is_eligible_for_post_ot_wave():
|
||||
'is_shortage': True,
|
||||
'required_qty': '3',
|
||||
'available_qty': '0',
|
||||
'decision': {'decision_code': 'release_inventory_shortage'},
|
||||
'decision': {'decision_code': 'release_onhand_shortage'},
|
||||
})
|
||||
|
||||
assert str(required) == '3'
|
||||
@@ -65,7 +65,7 @@ def test_list_eligible_post_ot_lines_keeps_released_shortage_only():
|
||||
'line_key': 'released', 'line_status': 'released_shortage',
|
||||
'inventory_status': 'ready', 'match_result': 'matched', 'is_shortage': True,
|
||||
'required_qty': '3', 'available_qty': '0',
|
||||
'decision': {'decision_code': 'release_inventory_shortage'},
|
||||
'decision': {'decision_code': 'release_onhand_shortage'},
|
||||
},
|
||||
{
|
||||
'line_key': 'unreleased', 'line_status': 'pending_decision',
|
||||
@@ -220,7 +220,7 @@ def test_create_post_ot_wave_param_conflict_raises_409(app):
|
||||
|
||||
|
||||
def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app):
|
||||
"""整波失败必须 rollback,且失败标记不得创建 wait_inventory 半成品。"""
|
||||
"""整波失败必须 rollback,且失败标记不得创建 wait_onhand 半成品。"""
|
||||
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
|
||||
|
||||
case = SimpleNamespace(id=3, case_no='RC-FAIL', confirmed_task_id=8)
|
||||
@@ -286,7 +286,7 @@ def test_coordinate_auto_fulfill_requires_manual_selection_for_multiple_lines(ap
|
||||
|
||||
|
||||
def test_mark_auto_fulfill_failed_does_not_create_wait_inventory(app):
|
||||
"""无活动决定时只写匹配事实 detail,不新建 wait_inventory 决定。"""
|
||||
"""无活动决定时只写匹配事实 detail,不新建 wait_onhand 决定。"""
|
||||
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
|
||||
|
||||
case = SimpleNamespace(id=4, case_no='RC-2', confirmed_task_id=12)
|
||||
@@ -295,7 +295,7 @@ def test_mark_auto_fulfill_failed_does_not_create_wait_inventory(app):
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(coord.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(coord.ShippingNoticeLineOnhandMatch, 'query') as match_q,
|
||||
patch.object(coord.ShippingOrderReviewLineDecision, 'query') as dec_q,
|
||||
patch.object(coord.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
):
|
||||
|
||||
@@ -9,7 +9,7 @@ tests/test_review_line_fulfillment_shortage_projection.py
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewDraft
|
||||
from app.models import ShippingNoticeLineOnhandMatch, ShippingOrderReviewCase, ShippingOrderReviewDraft
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
project_review_case_line_decisions,
|
||||
)
|
||||
@@ -21,9 +21,9 @@ def test_line_fulfillment_has_shortage_with_match_facts(app):
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
# 短缺事实:第 0 行 not_found、缺 10。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=fixture.order.id, snapshot_line_id=fixture.snap_lines[0].id,
|
||||
line_no=1, line_index=0, match_result='not_found', inventory_status='ready',
|
||||
line_no=1, line_index=0, match_result='not_found', onhand_status='ready',
|
||||
required_qty='10', available_qty='0', shortage_qty='10',
|
||||
reservation_id='RSV-1', part_number='D4-A08AR12000002-', is_current=True,
|
||||
))
|
||||
|
||||
@@ -89,16 +89,18 @@ def test_migrate_legacy_full_path_platform_api_path():
|
||||
assert migrated["data_source_type"] is None
|
||||
|
||||
|
||||
def test_migrate_legacy_shipping_inventory_rpa():
|
||||
"""旧 shipping_inventory_rpa 语义应迁移为 platform_job。"""
|
||||
migrated = migrate_legacy_schedule_payload({
|
||||
def test_migrate_legacy_shipping_inventory_rpa_is_not_a_runtime_alias():
|
||||
"""历史 data_source 整值不再由运行期拼接或别名表改写,交给 s17c。"""
|
||||
raw = {
|
||||
"schedule_type": "platform_app",
|
||||
"data_source_type": "shipping_inventory_rpa",
|
||||
"platform_api_path": "/123",
|
||||
})
|
||||
assert migrated["schedule_type"] == "platform_job"
|
||||
assert migrated["platform_api_path"] == "freight-rpa-onhand"
|
||||
assert migrated["data_source_type"] is None
|
||||
}
|
||||
migrated = migrate_legacy_schedule_payload(raw)
|
||||
# 关键断言:运行期不再识别该历史键,避免用字符串拼接绕过 grep 门禁。
|
||||
assert migrated["data_source_type"] == "shipping_inventory_rpa"
|
||||
assert migrated["platform_api_path"] == "/123"
|
||||
assert "shipping_inventory_rpa" not in str(migrate_legacy_schedule_payload.__code__.co_consts)
|
||||
|
||||
|
||||
def test_migrate_legacy_faq_hot_aggregate():
|
||||
@@ -215,7 +217,7 @@ def test_get_platform_jobs_api(client, admin_jwt_headers):
|
||||
assert all("label" in item for item in body)
|
||||
# 内置 job 应返回稳定 i18n key,供前端 $t(label_key) 渲染
|
||||
by_key = {item["key"]: item for item in body}
|
||||
assert by_key["freight-rpa-onhand"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
|
||||
assert by_key["freight-rpa-onhand"]["label_key"] == "admin.schedule.form.platformJobFreightRpaOnhand"
|
||||
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
|
||||
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
|
||||
assert by_key["accounting-voucher-po-print"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherPoPrint"
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.services.schedule.job_params import (
|
||||
|
||||
def _enabled_source_code() -> str:
|
||||
"""读取测试数据库的首个启用库存源,避免测试依赖已废弃 YAML 的固定编码。"""
|
||||
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
|
||||
from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources
|
||||
|
||||
sources = list_database_inventory_sources()
|
||||
assert sources, 'expected at least one enabled inventory source'
|
||||
@@ -65,7 +65,7 @@ def test_platform_task_definitions_returns_params_schema(client, admin_jwt_heade
|
||||
assert rpa['category'] == 'shipping'
|
||||
schema_keys = {f['key']: f for f in rpa['params_schema']}
|
||||
assert schema_keys['source_codes']['type'] == 'multi_select'
|
||||
assert schema_keys['source_codes']['options_source'] == 'shipping_inventory_sources'
|
||||
assert schema_keys['source_codes']['options_source'] == 'freight_rpa_sources'
|
||||
assert rpa['defaults'] == {'source_codes': []}
|
||||
# FAQ 热点聚合:select 应用字段
|
||||
faq = by_type['faq-aggregate-hot']
|
||||
@@ -79,7 +79,7 @@ def test_platform_task_definitions_returns_params_schema(client, admin_jwt_heade
|
||||
def test_platform_task_options_shipping_sources(client, admin_jwt_headers, app):
|
||||
"""options 接口应返回库存源统一 label/value 结构。"""
|
||||
res = client.get(
|
||||
'/api/admin/platform-tasks/options?source=shipping_inventory_sources',
|
||||
'/api/admin/platform-tasks/options?source=freight_rpa_sources',
|
||||
headers=admin_jwt_headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
@@ -365,7 +365,7 @@ def test_faq_job_prefers_job_params_over_dify_agent_id(app):
|
||||
|
||||
def test_shipping_rpa_filter_prefers_job_params(app):
|
||||
"""货代 RPA 应优先按 job_params.source_codes 筛选库存源。"""
|
||||
from app.services.schedule.freight_onhand_rpa_job import _filter_sources
|
||||
from app.services.schedule.freight_rpa_onhand_job import _filter_sources
|
||||
|
||||
with app.app_context():
|
||||
source_code = _enabled_source_code()
|
||||
|
||||
@@ -15,7 +15,7 @@ from unittest.mock import patch
|
||||
from app import db
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingOnhandCandidateSet,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
@@ -34,7 +34,7 @@ def _task_with_candidate(*, complete_order: bool = True) -> ShippingOrderTask:
|
||||
task = ShippingOrderTask(task_no='OT-APX-P0-3-001', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
candidate = ShippingInventoryCandidateSet(
|
||||
candidate = ShippingOnhandCandidateSet(
|
||||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='a' * 64,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
@@ -50,7 +50,7 @@ def _task_with_candidate(*, complete_order: bool = True) -> ShippingOrderTask:
|
||||
def test_formal_start_gate_is_derived_from_persisted_task_facts(app):
|
||||
"""无解析、未冻结、候选未冻结与候选冻结必须分别停在对应正式 Gate。"""
|
||||
task = _task_with_candidate(complete_order=False)
|
||||
candidate = ShippingInventoryCandidateSet.query.filter_by(task_id=task.id).one()
|
||||
candidate = ShippingOnhandCandidateSet.query.filter_by(task_id=task.id).one()
|
||||
|
||||
assert determine_formal_start_gate(task, candidate_set=candidate) == 'document_materialization'
|
||||
|
||||
@@ -59,10 +59,10 @@ def test_formal_start_gate_is_derived_from_persisted_task_facts(app):
|
||||
|
||||
task.order_snapshot_id = 201
|
||||
candidate.lifecycle_status = 'draft'
|
||||
assert determine_formal_start_gate(task, candidate_set=candidate) == 'inventory_source_routing'
|
||||
assert determine_formal_start_gate(task, candidate_set=candidate) == 'onhand_source_routing'
|
||||
|
||||
candidate.lifecycle_status = 'frozen'
|
||||
assert determine_formal_start_gate(task, candidate_set=candidate) == 'inventory_preparation'
|
||||
assert determine_formal_start_gate(task, candidate_set=candidate) == 'onhand_preparation'
|
||||
|
||||
|
||||
def test_submit_creates_formal_execution_for_task_without_case(app):
|
||||
@@ -102,7 +102,7 @@ def test_formal_execution_queues_one_gate_attempt_job(app):
|
||||
formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=formal,
|
||||
through_gate_code='inventory_source_routing',
|
||||
through_gate_code='onhand_source_routing',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
task.active_process_execution_id = formal.id
|
||||
@@ -126,14 +126,14 @@ def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app):
|
||||
task = _task_with_candidate()
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=903, task_id=int(task.id))
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
execution_id=int(execution.id), gate_code='onhand_preparation',
|
||||
).one()
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'inventory_rpa_timeout'
|
||||
gate.next_action_code = 'upload_inventory_file'
|
||||
gate.blocking_reason_code = 'onhand_rpa_timeout'
|
||||
gate.next_action_code = 'upload_onhand_file'
|
||||
execution.status = 'blocked'
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
execution.primary_next_action_code = 'upload_inventory_file'
|
||||
execution.current_gate_code = 'onhand_preparation'
|
||||
execution.primary_next_action_code = 'upload_onhand_file'
|
||||
execution.responsible_party = 'worker'
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
@@ -145,7 +145,7 @@ def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app):
|
||||
result = submit_auto_progress(task=task, trigger='callback_recovery')
|
||||
|
||||
assert result['status'] == 'waiting_human'
|
||||
assert result['gate_code'] == 'inventory_preparation'
|
||||
assert result['gate_code'] == 'onhand_preparation'
|
||||
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0
|
||||
|
||||
|
||||
@@ -159,11 +159,11 @@ def test_submit_does_not_redispatch_after_failed_worker_attempt(app):
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=904, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_source_routing',
|
||||
through_gate_code='onhand_source_routing',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
execution_id=int(execution.id), gate_code='onhand_preparation',
|
||||
).one()
|
||||
# Worker 已真实执行并失败:failed Attempt 持有非空 job_id
|
||||
failed_job = Job(
|
||||
@@ -183,10 +183,10 @@ def test_submit_does_not_redispatch_after_failed_worker_attempt(app):
|
||||
job_id=int(failed_job.id),
|
||||
))
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
gate.next_action_code = 'retry_onhand_preparation'
|
||||
execution.status = 'blocked'
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
execution.primary_next_action_code = 'retry_inventory_preparation'
|
||||
execution.current_gate_code = 'onhand_preparation'
|
||||
execution.primary_next_action_code = 'retry_onhand_preparation'
|
||||
execution.responsible_party = 'worker'
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
@@ -195,10 +195,10 @@ def test_submit_does_not_redispatch_after_failed_worker_attempt(app):
|
||||
with patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
):
|
||||
result = submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded')
|
||||
result = submit_auto_progress(task=task, trigger='onhand_rpa_callback_succeeded')
|
||||
|
||||
assert result['status'] == 'waiting_human'
|
||||
assert result['gate_code'] == 'inventory_preparation'
|
||||
assert result['gate_code'] == 'onhand_preparation'
|
||||
# 没有新的 ProcessGate Job 被创建(仅存量失败 Job)
|
||||
assert Job.query.filter(
|
||||
Job.job_type == 'shipping_process_gate',
|
||||
@@ -209,7 +209,7 @@ def test_submit_does_not_redispatch_after_failed_worker_attempt(app):
|
||||
|
||||
|
||||
def test_explicit_retry_rpa_overrides_waiting_external_poll(app) -> None:
|
||||
"""waiting_external + 残留 poll 时,显式 retry_rpa 必须改入队 retry_inventory_preparation。
|
||||
"""waiting_external + 残留 poll 时,显式 retry_rpa 必须改入队 retry_onhand_preparation。
|
||||
|
||||
回归背景:行级改源 / 强制获取库存调用 run_task_auto_progress(inventory_mode=retry_rpa)
|
||||
后,submit_auto_progress 只改 Execution 指针、不改 Gate.next_action_code,继续入队
|
||||
@@ -219,18 +219,18 @@ def test_explicit_retry_rpa_overrides_waiting_external_poll(app) -> None:
|
||||
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',
|
||||
through_gate_code='onhand_source_routing',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
execution_id=int(execution.id), gate_code='onhand_preparation',
|
||||
).one()
|
||||
gate.status = 'waiting_external'
|
||||
gate.blocking_reason_code = 'inventory_rpa_export_failed'
|
||||
gate.next_action_code = 'poll_inventory_preparation'
|
||||
gate.blocking_reason_code = 'onhand_rpa_export_failed'
|
||||
gate.next_action_code = 'poll_onhand_preparation'
|
||||
execution.status = 'waiting_external'
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
execution.primary_next_action_code = 'poll_inventory_preparation'
|
||||
execution.current_gate_code = 'onhand_preparation'
|
||||
execution.primary_next_action_code = 'poll_onhand_preparation'
|
||||
execution.responsible_party = 'worker'
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
@@ -244,7 +244,7 @@ def test_explicit_retry_rpa_overrides_waiting_external_poll(app) -> None:
|
||||
result = submit_auto_progress(
|
||||
task=task,
|
||||
trigger='manual_override_source',
|
||||
resume_gate_code='inventory_preparation',
|
||||
resume_gate_code='onhand_preparation',
|
||||
inventory_mode='retry_rpa',
|
||||
commit=True,
|
||||
)
|
||||
@@ -260,7 +260,7 @@ def test_explicit_retry_rpa_overrides_waiting_external_poll(app) -> None:
|
||||
.first()
|
||||
)
|
||||
assert queued is not None
|
||||
assert (queued.input_snapshot_json or {}).get('action_code') == 'retry_inventory_preparation'
|
||||
assert (queued.input_snapshot_json or {}).get('action_code') == 'retry_onhand_preparation'
|
||||
assert ((queued.input_snapshot_json or {}).get('payload') or {}).get('inventory_mode') == 'retry_rpa'
|
||||
|
||||
|
||||
@@ -306,10 +306,10 @@ def test_derived_fulfillment_status_uses_line_match_facts_for_order_task():
|
||||
|
||||
task = SimpleNamespace(id=1)
|
||||
with patch(
|
||||
'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task',
|
||||
'app.services.shipping_notice.onhand_file_store.inventory_matches_complete_for_task',
|
||||
return_value=True,
|
||||
), patch(
|
||||
'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage',
|
||||
'app.services.shipping_notice.onhand_file_store.current_inventory_matches_have_shortage',
|
||||
return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
|
||||
@@ -332,7 +332,7 @@ def test_auto_retry_blocked_only_for_non_user_trigger():
|
||||
|
||||
核心逻辑:has_failed_worker_attempt 守卫本意是防止自动/后台 trigger 无限重试,
|
||||
用户显式重试(user_retry/user_manual)或带 resume_gate_code 的显式定向推进
|
||||
(如匹配工具 tool_api_match_inventory_line + resume_gate_code='inventory_matching')
|
||||
(如匹配工具 tool_api_match_inventory_line + resume_gate_code='onhand_matching')
|
||||
应绕过,否则点"重新匹配库存"报"无待处理 Gate"。
|
||||
"""
|
||||
from app.services.shipping_notice.auto_progress_controller import _auto_retry_blocked
|
||||
@@ -346,8 +346,8 @@ def test_auto_retry_blocked_only_for_non_user_trigger():
|
||||
assert _auto_retry_blocked('auto', False) is False
|
||||
# 匹配工具 trigger 非 user_retry,但带 resume_gate_code(显式定向重匹配)→ 放行
|
||||
assert _auto_retry_blocked('tool_api_match_inventory_line', True) is True
|
||||
assert _auto_retry_blocked('tool_api_match_inventory_line', True, resume_gate_code='inventory_matching') is False
|
||||
assert _auto_retry_blocked('auto', True, resume_gate_code='inventory_matching') is False
|
||||
assert _auto_retry_blocked('tool_api_match_inventory_line', True, resume_gate_code='onhand_matching') is False
|
||||
assert _auto_retry_blocked('auto', True, resume_gate_code='onhand_matching') is False
|
||||
|
||||
|
||||
def test_retry_inventory_matching_fulfillable_passes():
|
||||
@@ -370,7 +370,7 @@ def test_retry_inventory_matching_fulfillable_passes():
|
||||
task_id = 1
|
||||
|
||||
class _Gate:
|
||||
gate_code = 'inventory_matching'
|
||||
gate_code = 'onhand_matching'
|
||||
|
||||
class _OT:
|
||||
query = MagicMock(get=MagicMock(return_value=_Task()))
|
||||
@@ -381,7 +381,7 @@ def test_retry_inventory_matching_fulfillable_passes():
|
||||
patch('app.services.shipping_notice.process_gate_executor.ShippingOrderTask', _OT), \
|
||||
patch('app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', return_value=True), \
|
||||
patch('app.services.shipping_notice.fulfillment_workflow.match_completed', return_value=True), \
|
||||
patch('app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', return_value={}):
|
||||
patch('app.services.shipping_notice.line_onhand_match_projection.load_current_match_facts_by_task', return_value={}):
|
||||
result = ex._handle_retry_inventory_matching(execution=_Execution(), gate=_Gate(), payload={'actor_user_id': 1})
|
||||
assert result['outcome'] == 'passed'
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ def test_qualification_and_workflow_node_audit_events_are_frozen() -> None:
|
||||
def test_chat_process_gate_event_mapping() -> None:
|
||||
"""retry → retried;人工动作 → taken_over;skip → skipped。"""
|
||||
assert _chat_process_gate_event_type(
|
||||
action_code='retry_inventory_matching',
|
||||
action_code='retry_onhand_matching',
|
||||
trigger_type='user_retry',
|
||||
) == 'chat_process_gate_retried'
|
||||
assert _chat_process_gate_event_type(
|
||||
|
||||
@@ -86,8 +86,8 @@ def test_pending_customer_blocks_every_downstream_entry(app):
|
||||
task, _notice, _customer, _user = _seed_task()
|
||||
operations = [
|
||||
'auto_progress',
|
||||
'ensure_inventory',
|
||||
'upload_inventory_file',
|
||||
'ensure_onhand',
|
||||
'upload_onhand_file',
|
||||
'ensure_inventory_via_rpa',
|
||||
'match_inventory',
|
||||
'generate_excel',
|
||||
|
||||
@@ -23,7 +23,7 @@ from app.models import (
|
||||
ShippingOrderTask,
|
||||
ShippingExportArtifact,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
FreightRpaParsingProfile,
|
||||
)
|
||||
from app.services.shipping_notice.done_line_report import (
|
||||
DONE_REPORT_HEADERS,
|
||||
@@ -44,7 +44,7 @@ def _seed_report_fixture(db, *, owner: int):
|
||||
storage_bucket='test', storage_key='done.xlsx', original_filename='done.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code='DONELINE', display_name='DoneLine', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
|
||||
@@ -77,8 +77,8 @@ def test_message_zh_for_reason_and_rpa_meta():
|
||||
from app.services.shipping_notice.process_gate_contract import owning_gate_for_reason
|
||||
|
||||
assert message_zh_for_reason('business_table_empty')
|
||||
assert message_zh_for_reason('inventory_rpa_exhausted')
|
||||
assert owning_gate_for_reason('inventory_rpa_exhausted') == 'inventory_preparation'
|
||||
assert message_zh_for_reason('onhand_rpa_exhausted')
|
||||
assert owning_gate_for_reason('onhand_rpa_exhausted') == 'onhand_preparation'
|
||||
assert owning_gate_for_reason('upload_rpa_failed') == 'freight_upload_rpa'
|
||||
assert message_zh_for_reason('totally_unknown_xyz') is None
|
||||
|
||||
@@ -122,8 +122,8 @@ def test_inventory_preparation_reason_code_from_pending(app):
|
||||
# [STEP 1] RPA 排队/耗尽由 pending_human_reason 细分(不能退化为 preparation_failed)
|
||||
queued = _pending_task('OT-QUEUED', PH_RPA_PENDING)
|
||||
exhausted = _pending_task('OT-EXHAUSTED', PH_RPA_EXHAUSTED)
|
||||
assert inventory_preparation_reason_code(queued) == 'inventory_rpa_queued'
|
||||
assert inventory_preparation_reason_code(exhausted) == 'inventory_rpa_exhausted'
|
||||
assert inventory_preparation_reason_code(queued) == 'onhand_rpa_queued'
|
||||
assert inventory_preparation_reason_code(exhausted) == 'onhand_rpa_exhausted'
|
||||
|
||||
# [STEP 2] 空列表 = 已落文件但无有效行 → 生产按活动库存行数判定为空;
|
||||
# None = 尚未生成库存文件 → 由 inv_unavail 语义命中 inventory_file_missing。
|
||||
@@ -242,7 +242,7 @@ def test_layer_c_emitted_includes_profile_and_excel_template():
|
||||
def test_emitted_subsets_for_attachment_prep_excel_close():
|
||||
"""附件/准备/Excel/关闭已接线子集须非空且文案可解析。"""
|
||||
assert 'attachment_size_exceeded' in ATTACHMENT_REASON_CODES_EMITTED
|
||||
assert 'inventory_rpa_exhausted' in INVENTORY_PREP_REASON_CODES_EMITTED
|
||||
assert 'onhand_rpa_exhausted' in INVENTORY_PREP_REASON_CODES_EMITTED
|
||||
assert 'excel_not_ready' in EXCEL_UPLOAD_REASON_CODES_EMITTED
|
||||
assert 'task_cancelled_by_user' in TASK_CLOSE_REASON_CODES_EMITTED
|
||||
assert message_zh_for_reason('task_voided_for_correction')
|
||||
@@ -345,20 +345,20 @@ def test_audit_reason_code_mapping_for_rpa_and_notice_replace():
|
||||
"""
|
||||
任务事件双写审计须能映射到可解释性稳定码。
|
||||
|
||||
核心逻辑:inventory_rpa_failed 按 error 细分;notice_replaced → attachment_replaced。
|
||||
核心逻辑:onhand_rpa_failed 按 error 细分;notice_replaced → attachment_replaced。
|
||||
"""
|
||||
from app.services.shipping_notice.tool_common import _audit_reason_code_for_task_event
|
||||
|
||||
assert _audit_reason_code_for_task_event('inventory_rpa_exhausted', {}) == 'inventory_rpa_exhausted'
|
||||
assert _audit_reason_code_for_task_event('onhand_rpa_exhausted', {}) == 'onhand_rpa_exhausted'
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'inventory_rpa_failed', {'error': 'login timeout'},
|
||||
) == 'inventory_rpa_timeout'
|
||||
'onhand_rpa_failed', {'error': 'login timeout'},
|
||||
) == 'onhand_rpa_timeout'
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'inventory_rpa_failed', {'error': 'Crane scheduled report not ready for download within 300000ms'},
|
||||
) == 'inventory_rpa_timeout'
|
||||
'onhand_rpa_failed', {'error': 'Crane scheduled report not ready for download within 300000ms'},
|
||||
) == 'onhand_rpa_timeout'
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'inventory_rpa_failed', {'error': 'auth rejected'},
|
||||
) == 'inventory_rpa_login_failed'
|
||||
'onhand_rpa_failed', {'error': 'auth rejected'},
|
||||
) == 'onhand_rpa_login_failed'
|
||||
assert _audit_reason_code_for_task_event('notice_replaced', {}) == 'attachment_replaced'
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'notice_replace_extract_failed', {},
|
||||
@@ -424,11 +424,12 @@ def test_inventory_all_sources_disabled_blocks_as_unavailable(app):
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingInventorySource,
|
||||
ShippingRpaProfile,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaOnhandRoutingRule,
|
||||
FreightRpaOnhandRoutingRuleCondition,
|
||||
FreightRpaSource,
|
||||
FreightRpaProfile,
|
||||
)
|
||||
from app.services.shipping_notice.order_build_eligibility_service import (
|
||||
project_line_inventory_candidates,
|
||||
@@ -445,11 +446,11 @@ def test_inventory_all_sources_disabled_blocks_as_unavailable(app):
|
||||
}
|
||||
|
||||
# [STEP 1] 创建未启用库存源 + 命中该源的规则
|
||||
profile = ShippingRpaProfile(
|
||||
profile = FreightRpaProfile(
|
||||
profile_code='RPA_AWSSG', display_name='AWSSG', connector_type='dbs',
|
||||
login_url='https://test.invalid/awssg', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
parsing = FreightRpaParsingProfile(
|
||||
profile_code='PARSE_AWSSG', display_name='AWSSG Parse', version=1,
|
||||
status='published', file_format='xlsx', definition_json={'match_keys': []},
|
||||
)
|
||||
@@ -459,20 +460,24 @@ def test_inventory_all_sources_disabled_blocks_as_unavailable(app):
|
||||
storage_key='test/awssg.xlsx', original_filename='t.xlsx',
|
||||
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
|
||||
)
|
||||
source = ShippingInventorySource(
|
||||
source = FreightRpaSource(
|
||||
source_code='DSV360_AWSSG', display_name='AWSSG',
|
||||
connector_type='dbs', rpa_profile=profile, parsing_profile=parsing,
|
||||
connector_type='dbs', rpa_profile=profile,
|
||||
excel_template=template, warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='SIN', report_path_json={'program_group': 'Bison'},
|
||||
query_parameters_json=[], enabled=False,
|
||||
fixed_warehouse_id='SIN', enabled=False,
|
||||
)
|
||||
# s18 起解析绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行。
|
||||
db.session.add(FreightRpaOnhandReportConfig(
|
||||
source=source, parsing_profile=parsing,
|
||||
report_path_json={'program_group': 'Bison'}, query_parameters_json=[],
|
||||
))
|
||||
db.session.add_all([profile, parsing, template, source])
|
||||
db.session.add(ShippingInventoryRoutingRule(
|
||||
db.session.add(FreightRpaOnhandRoutingRule(
|
||||
rule_code='ROUTE_HINT_AWSSG', rule_name='ROUTE_HINT_AWSSG',
|
||||
scope='line', priority=100, match_mode='all', status='published',
|
||||
action_type='add_source_candidates',
|
||||
action_payload_json={'source_codes': ['DSV360_AWSSG']}, version=1,
|
||||
conditions=[ShippingInventoryRoutingRuleCondition(
|
||||
conditions=[FreightRpaOnhandRoutingRuleCondition(
|
||||
condition_group=1, source_kind='order_field',
|
||||
order_field_id=field_ids['reservation_id'],
|
||||
operator='prefix', expected_value_json='3', sequence=1,
|
||||
|
||||
@@ -12,11 +12,11 @@ def test_order_task_status_does_not_query_formal_notice(monkeypatch) -> None:
|
||||
|
||||
# 履约状态必须来自当前行级 Match/File 事实,而不是 OT 旧投影字段。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task',
|
||||
'app.services.shipping_notice.onhand_file_store.inventory_matches_complete_for_task',
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage',
|
||||
'app.services.shipping_notice.onhand_file_store.current_inventory_matches_have_shortage',
|
||||
lambda _task: False,
|
||||
)
|
||||
|
||||
|
||||
@@ -17,11 +17,11 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
|
||||
ShippingExcelTemplate, FreightRpaOnhandReportConfig, FreightRpaParsingProfile, FreightRpaSource, ShippingOrderExtraction,
|
||||
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, ShippingOrderTask,
|
||||
ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink,
|
||||
ShippingCustomer, FreightRpaOnhandField, FreightRpaOnhandReportFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, FreightRpaProfile, ShippingNotice, ShippingOrderTask,
|
||||
ShippingNoticeLineOnhandMatch, ShippingTaskOnhandLink,
|
||||
)
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice.export import (
|
||||
@@ -34,7 +34,7 @@ from app.services.shipping_notice.export import (
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
|
||||
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
active_inventory_lines_for_task,
|
||||
replace_task_inventory_link,
|
||||
resolve_inventory_lines_for_execution,
|
||||
@@ -53,7 +53,7 @@ def _lookup_standard_fields(*codes: str) -> dict[str, ShippingOrderField]:
|
||||
|
||||
def _inventory_field_id(field_code: str) -> str:
|
||||
"""返回库存字段目录 ID,使模板测试覆盖当前发布契约。"""
|
||||
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
|
||||
return str(FreightRpaOnhandField.query.filter_by(field_code=field_code).one().id)
|
||||
|
||||
|
||||
def test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fact():
|
||||
@@ -141,7 +141,7 @@ def _freeze_export_snapshot(
|
||||
|
||||
|
||||
def _materialize_export_notice(
|
||||
*, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: ShippingInventoryFile,
|
||||
*, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: FreightRpaOnhandReportFile,
|
||||
source_code: str, notice_no: str,
|
||||
) -> ShippingNotice:
|
||||
"""从 OT 的冻结快照构造正式 Notice、NoticeLine、匹配事实与活动库存链接。
|
||||
@@ -166,10 +166,10 @@ def _materialize_export_notice(
|
||||
},
|
||||
)
|
||||
for line in snapshot.lines:
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no,
|
||||
match_result='matched', inventory_status='ready',
|
||||
inventory_snapshot_id=inventory_file.id, inventory_source_code=source_code,
|
||||
match_result='matched', onhand_status='ready',
|
||||
onhand_snapshot_id=inventory_file.id, source_code=source_code,
|
||||
is_current=True, detail_json={},
|
||||
))
|
||||
db.session.flush()
|
||||
@@ -231,9 +231,9 @@ def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cac
|
||||
"""业务执行必须使用活动库存 Link,忽略请求库存。"""
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(task_no='OT-INVENTORY-SOURCE', user_id=1)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'),
|
||||
inventory_lines_json=[{'part_number': 'ACTIVE'}], line_count=1,
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'),
|
||||
onhand_lines_json=[{'part_number': 'ACTIVE'}], line_count=1,
|
||||
share_mode='task_only', snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, inventory_file])
|
||||
@@ -268,9 +268,9 @@ def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp
|
||||
storage_path = tmp_path / 'stale.xlsx'
|
||||
storage_path.write_bytes(b'stale-source')
|
||||
task = ShippingOrderTask(task_no='OT-INVENTORY-NO-REPARSE', user_id=1)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path),
|
||||
inventory_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}],
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path),
|
||||
onhand_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}],
|
||||
line_count=1, share_mode='task_only', snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, inventory_file])
|
||||
@@ -284,7 +284,7 @@ def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp
|
||||
return ([{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-STALE'}], {})
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.parse_inventory_snapshot_file', stale_reparse,
|
||||
'app.services.shipping_notice.onhand_file_store.parse_inventory_snapshot_file', stale_reparse,
|
||||
)
|
||||
|
||||
assert active_inventory_lines_for_task(task) == [
|
||||
@@ -358,23 +358,28 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
parsing = FreightRpaParsingProfile(
|
||||
profile_code='COMMON_INV', display_name='Common Inventory', version=1, status='published',
|
||||
file_format='xlsx', definition_json={
|
||||
'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'},
|
||||
'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}],
|
||||
}, checksum='p' * 64,
|
||||
)
|
||||
login = ShippingRpaProfile(
|
||||
login = FreightRpaProfile(
|
||||
profile_code='LOGIN', display_name='Login', connector_type='dbs', login_url='https://invalid',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add_all([parsing, login])
|
||||
db.session.flush()
|
||||
source = ShippingInventorySource(
|
||||
source = FreightRpaSource(
|
||||
source_code='DUB', display_name='Dublin', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB',
|
||||
)
|
||||
# s18 起解析绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行,随站点级联入库。
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=source, parsing_profile_id=parsing.id,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
ot = ShippingOrderTask(task_no='OT-EXPORT-1', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(ot)
|
||||
@@ -403,10 +408,10 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
db.session.add(confirmed_customer)
|
||||
db.session.flush()
|
||||
confirm_test_customer_resolution(ot, customer=confirmed_customer, extraction=extraction)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-EXPORT-1', user_id=None,
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-EXPORT-1', user_id=None,
|
||||
source_file_name='inventory.xlsx', storage_path=str(tmp_path / 'inventory.xlsx'),
|
||||
inventory_lines_json=[{
|
||||
onhand_lines_json=[{
|
||||
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
|
||||
}],
|
||||
line_count=1, share_mode='task_only', warehouse_id='DUB', source_code='DUB', snapshot_status='ready',
|
||||
@@ -536,23 +541,28 @@ def test_two_sources_can_share_one_published_excel_template(app, tmp_path):
|
||||
]},
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
parsing = FreightRpaParsingProfile(
|
||||
profile_code='SHARED_INV', display_name='Shared Inventory', version=1, status='published',
|
||||
file_format='xlsx', definition_json={}, checksum='p' * 64,
|
||||
)
|
||||
login = ShippingRpaProfile(
|
||||
login = FreightRpaProfile(
|
||||
profile_code='SHARED_LOGIN', display_name='Shared Login', connector_type='dbs',
|
||||
login_url='https://invalid', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add_all([parsing, login])
|
||||
db.session.flush()
|
||||
for code in ('DUB', 'RTM'):
|
||||
db.session.add(ShippingInventorySource(
|
||||
shared_source = FreightRpaSource(
|
||||
source_code=code, display_name=code, connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'],
|
||||
excel_template_id=published['id'],
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id=code,
|
||||
)
|
||||
# s18 起解析绑定/报表路径/查询条件归配置行,随站点级联入库。
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=shared_source, parsing_profile_id=parsing.id,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
)
|
||||
db.session.add(shared_source)
|
||||
db.session.commit()
|
||||
|
||||
template = db.session.get(ShippingExcelTemplate, published['id'])
|
||||
@@ -571,17 +581,17 @@ def test_disabled_source_still_blocks_template_retirement(app):
|
||||
}]},
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
login = ShippingRpaProfile(
|
||||
login = FreightRpaProfile(
|
||||
profile_code='DISABLED_REF', display_name='Disabled Ref', connector_type='dbs',
|
||||
login_url='https://invalid', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add(login)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventorySource(
|
||||
# s18 起站点行不再承载报表路径/查询条件;停用站点退役守卫只读模板绑定。
|
||||
db.session.add(FreightRpaSource(
|
||||
source_code='DISABLED_REF', display_name='Disabled Ref', connector_type='dbs', enabled=False,
|
||||
rpa_profile_id=login.id, excel_template_id=published['id'],
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -611,20 +621,26 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
|
||||
]},
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
parsing = FreightRpaParsingProfile(
|
||||
profile_code='KEYED', display_name='Keyed', version=1, status='published', file_format='xlsx',
|
||||
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
|
||||
)
|
||||
login = ShippingRpaProfile(
|
||||
login = FreightRpaProfile(
|
||||
profile_code='KEYED', display_name='Keyed', connector_type='dbs', login_url='https://invalid',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add_all([parsing, login]); db.session.flush()
|
||||
db.session.add(ShippingInventorySource(
|
||||
keyed_source = FreightRpaSource(
|
||||
source_code='KEYED', display_name='Keyed', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB',
|
||||
)
|
||||
# s18 起解析绑定/报表路径/查询条件归配置行,随站点级联入库。
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=keyed_source, parsing_profile_id=parsing.id,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
db.session.add(keyed_source)
|
||||
customer = ShippingCustomer(standard_name='键控匹配客户', short_code='KEY', status='active')
|
||||
db.session.add(customer); db.session.flush()
|
||||
ot = ShippingOrderTask(task_no='OT-KEYED', user_id=1, status='ready', current_step='customer_review')
|
||||
@@ -646,10 +662,10 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
|
||||
value_text=value, decision_id=decision.id,
|
||||
))
|
||||
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-KEYED', user_id=None, source_file_name='keyed.xlsx',
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-KEYED', user_id=None, source_file_name='keyed.xlsx',
|
||||
storage_path=str(tmp_path / 'keyed.xlsx'),
|
||||
inventory_lines_json=[
|
||||
onhand_lines_json=[
|
||||
{_inventory_field_id('part_number'): 'PN-B', _inventory_field_id('odm_id'): 'ODM-B'},
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-A'},
|
||||
],
|
||||
@@ -800,20 +816,26 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
|
||||
]},
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
parsing = FreightRpaParsingProfile(
|
||||
profile_code='AMBIGUOUS', display_name='Ambiguous', version=1, status='published', file_format='xlsx',
|
||||
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
|
||||
)
|
||||
login = ShippingRpaProfile(
|
||||
login = FreightRpaProfile(
|
||||
profile_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', login_url='https://invalid',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add_all([parsing, login]); db.session.flush()
|
||||
db.session.add(ShippingInventorySource(
|
||||
ambiguous_source = FreightRpaSource(
|
||||
source_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB',
|
||||
)
|
||||
# s18 起解析绑定/报表路径/查询条件归配置行,随站点级联入库。
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=ambiguous_source, parsing_profile_id=parsing.id,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
db.session.add(ambiguous_source)
|
||||
customer = ShippingCustomer(standard_name='模糊匹配客户', short_code='AMB', status='active')
|
||||
db.session.add(customer); db.session.flush()
|
||||
ot = ShippingOrderTask(task_no='OT-AMBIGUOUS', user_id=1, status='ready', current_step='customer_review')
|
||||
@@ -834,10 +856,10 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
|
||||
value_text='PN-A', decision_id=decision.id,
|
||||
))
|
||||
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
|
||||
ambiguous_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-AMBIGUOUS', user_id=None, source_file_name='ambiguous.xlsx',
|
||||
ambiguous_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-AMBIGUOUS', user_id=None, source_file_name='ambiguous.xlsx',
|
||||
storage_path=str(tmp_path / 'ambiguous.xlsx'),
|
||||
inventory_lines_json=[
|
||||
onhand_lines_json=[
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-1'},
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-2'},
|
||||
],
|
||||
@@ -859,10 +881,10 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
|
||||
export_root = tmp_path / 'shipping' / 'exports'
|
||||
assert not export_root.exists() or not list(export_root.rglob('*.xlsx'))
|
||||
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-ACTIVE-FIXED', user_id=None,
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-ACTIVE-FIXED', user_id=None,
|
||||
source_file_name='fixed.xlsx', storage_path=str(tmp_path / 'fixed.xlsx'),
|
||||
inventory_lines_json=[
|
||||
onhand_lines_json=[
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'},
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'},
|
||||
],
|
||||
@@ -873,8 +895,8 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
|
||||
db.session.flush()
|
||||
replace_task_inventory_link(task, inventory_file, role='owner')
|
||||
# 切换活动库存后,行级匹配事实须指向新快照;导出只读取活动 Link。
|
||||
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=ot.id, is_current=True).all():
|
||||
match.inventory_snapshot_id = inventory_file.id
|
||||
for match in ShippingNoticeLineOnhandMatch.query.filter_by(task_id=ot.id, is_current=True).all():
|
||||
match.onhand_snapshot_id = inventory_file.id
|
||||
db.session.flush()
|
||||
|
||||
path, _filename_value, artifact = generate_shipment_excel(task)
|
||||
@@ -926,20 +948,26 @@ def _build_multi_odm_notice(
|
||||
]},
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
parsing = FreightRpaParsingProfile(
|
||||
profile_code='ODMSCOPE', display_name='OdmScope', version=1, status='published', file_format='xlsx',
|
||||
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
|
||||
)
|
||||
login = ShippingRpaProfile(
|
||||
login = FreightRpaProfile(
|
||||
profile_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', login_url='https://invalid',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add_all([parsing, login]); db.session.flush()
|
||||
db.session.add(ShippingInventorySource(
|
||||
odm_source = FreightRpaSource(
|
||||
source_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB',
|
||||
)
|
||||
# s18 起解析绑定/报表路径/查询条件归配置行,随站点级联入库。
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=odm_source, parsing_profile_id=parsing.id,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
db.session.add(odm_source)
|
||||
customer = ShippingCustomer(
|
||||
standard_name='ODM范围客户', short_code='ODMSC', status='active',
|
||||
odm_ids=list(customer_odm_ids) if customer_odm_ids is not None else None,
|
||||
@@ -971,10 +999,10 @@ def _build_multi_odm_notice(
|
||||
for spec in specs:
|
||||
for odm in spec['odm_values']:
|
||||
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
|
||||
storage_path=str(tmp_path / 'odm-scope.xlsx'),
|
||||
inventory_lines_json=inventory_rows,
|
||||
onhand_lines_json=inventory_rows,
|
||||
line_count=len(inventory_rows), share_mode='task_only', warehouse_id='DUB', source_code='ODMSCOPE',
|
||||
snapshot_status='ready',
|
||||
)
|
||||
@@ -988,7 +1016,7 @@ def _build_multi_odm_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
|
||||
)
|
||||
if choice_odm is not None:
|
||||
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
|
||||
for match in ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
|
||||
match.chosen_odm_id = choice_odm
|
||||
db.session.flush()
|
||||
return notice, customer
|
||||
@@ -1095,7 +1123,7 @@ def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
|
||||
result = set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-2')
|
||||
|
||||
assert result['odm_id'] == 'ODM-2'
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
matches = ShippingNoticeLineOnhandMatch.query.filter_by(
|
||||
task_id=int(task.order_task_id), is_current=True,
|
||||
).all()
|
||||
assert matches and {m.chosen_odm_id for m in matches} == {'ODM-2'}
|
||||
@@ -1134,7 +1162,7 @@ def test_notice_odm_choice_syncs_same_snapshot_file_lines(app, tmp_path):
|
||||
|
||||
# [断言] 同步范围=同一快照文件:两行当前匹配行写同一选择。
|
||||
assert result['synced_line_count'] == 2
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
matches = ShippingNoticeLineOnhandMatch.query.filter_by(
|
||||
task_id=int(task.order_task_id), is_current=True,
|
||||
).all()
|
||||
assert len(matches) == 2
|
||||
|
||||
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
ShippingOrderReviewEvent,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES
|
||||
@@ -181,13 +181,13 @@ def test_inventory_invalidation_writes_formal_edit_audit_chain(app):
|
||||
)
|
||||
_link_order_task(task, stage='excel_generating')
|
||||
# 前置:任务已在行级匹配为 matched(否则 before 快照不存在“被失效”的匹配状态)。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=int(task.id),
|
||||
snapshot_line_id=1,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
onhand_status='ready',
|
||||
required_qty='10',
|
||||
available_qty='10',
|
||||
shortage_qty='0',
|
||||
|
||||
@@ -10,11 +10,11 @@ from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
FreightRpaOnhandReportFile,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskOnhandLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
complete_gate_attempt,
|
||||
@@ -34,18 +34,18 @@ def test_gate_audit_failure_does_not_rollback_complete_outcome(app, monkeypatch)
|
||||
if gate.sequence_no < 13:
|
||||
gate.status = 'passed'
|
||||
prep = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
execution_id=int(execution.id), gate_code='onhand_preparation',
|
||||
).one()
|
||||
prep.status = 'queued'
|
||||
db.session.flush()
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code='inventory_preparation',
|
||||
gate_code='onhand_preparation',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
idempotency_key='audit-isolate-prep',
|
||||
input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}},
|
||||
input_snapshot={'action_code': 'retry_onhand_preparation', 'payload': {}},
|
||||
)
|
||||
assert attempt is not None
|
||||
attempt.status = 'running'
|
||||
@@ -80,19 +80,19 @@ def test_sync_ready_inventory_keeps_matching_pending_without_rows(app):
|
||||
task = ShippingOrderTask(task_no='OT-MATCH-PENDING', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
inv = ShippingInventoryFile(
|
||||
inventory_file_no='INV-MATCH-PENDING',
|
||||
inv = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='INV-MATCH-PENDING',
|
||||
storage_path='test/inv.xlsx',
|
||||
source_file_name='inv.xlsx',
|
||||
snapshot_status='ready',
|
||||
line_count=1,
|
||||
inventory_lines_json=[{'part_number': 'PN-1', 'qty': 1}],
|
||||
onhand_lines_json=[{'part_number': 'PN-1', 'qty': 1}],
|
||||
mapping_confirmed=True,
|
||||
)
|
||||
db.session.add(inv)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=int(task.id), inventory_file_id=int(inv.id), is_active=True,
|
||||
db.session.add(ShippingTaskOnhandLink(
|
||||
task_id=int(task.id), onhand_file_id=int(inv.id), is_active=True,
|
||||
))
|
||||
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
|
||||
# 前置 Gate 已通过;匹配尚未执行。清掉活动 Attempt,避免 sync 因 BUSY 早退。
|
||||
@@ -102,7 +102,7 @@ def test_sync_ready_inventory_keeps_matching_pending_without_rows(app):
|
||||
).all():
|
||||
attempt.status = 'superseded'
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all():
|
||||
if gate.gate_code == 'inventory_matching':
|
||||
if gate.gate_code == 'onhand_matching':
|
||||
gate.status = 'pending'
|
||||
gate.next_action_code = None
|
||||
gate.blocking_reason_code = None
|
||||
@@ -115,7 +115,7 @@ def test_sync_ready_inventory_keeps_matching_pending_without_rows(app):
|
||||
db.session.commit()
|
||||
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_matching',
|
||||
execution_id=int(execution.id), gate_code='onhand_matching',
|
||||
).one()
|
||||
# pending=尚未入队;queued=已由 auto-progress 入队待跑。二者都不是「匹配失败」。
|
||||
assert matching.status in {'pending', 'queued', 'running'}
|
||||
|
||||
@@ -124,10 +124,10 @@ def test_inventory_main_gates_are_existing_and_ordered():
|
||||
"""
|
||||
assert len(INVENTORY_MAIN_GATES) == 4
|
||||
assert INVENTORY_MAIN_GATES == (
|
||||
'inventory_source_routing',
|
||||
'onhand_source_routing',
|
||||
'order_freeze_readiness',
|
||||
'inventory_preparation',
|
||||
'inventory_matching',
|
||||
'onhand_preparation',
|
||||
'onhand_matching',
|
||||
)
|
||||
for gate_code in INVENTORY_MAIN_GATES:
|
||||
assert gate_code in PROCESS_GATE_STATUSES or gate_code in (
|
||||
@@ -200,7 +200,7 @@ def test_convenience_lookup_functions_sanity():
|
||||
assert user_mode_for_blocking_reason(None) is None
|
||||
assert user_mode_for_blocking_reason('') is None
|
||||
assert user_mode_for_blocking_reason('no_inventory_source_candidates') == 'needs_human'
|
||||
assert user_mode_for_blocking_reason('inventory_rpa_timeout') == 'retryable_tech'
|
||||
assert user_mode_for_blocking_reason('onhand_rpa_timeout') == 'retryable_tech'
|
||||
assert user_mode_for_blocking_reason('unknown_code_xyz') is None
|
||||
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ from types import SimpleNamespace
|
||||
from app import db
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingOnhandCandidateSet,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
@@ -37,7 +37,7 @@ def _task_with_candidate(*, task_no: str = 'OT-ORCH-SEP-001') -> ShippingOrderTa
|
||||
task = ShippingOrderTask(task_no=task_no, user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
candidate = ShippingInventoryCandidateSet(
|
||||
candidate = ShippingOnhandCandidateSet(
|
||||
task_id=task.id,
|
||||
set_version=1,
|
||||
lifecycle_status='frozen',
|
||||
@@ -62,11 +62,11 @@ def _patch_fulfillable_inventory(monkeypatch) -> None:
|
||||
source_query_json={},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
|
||||
'app.services.shipping_notice.onhand_file_store.active_inventory_file_for_task',
|
||||
lambda _task: inv_file,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.active_inventory_lines_for_task',
|
||||
'app.services.shipping_notice.onhand_file_store.active_inventory_lines_for_task',
|
||||
lambda _task: [{'reservation_id': 'R1', 'part_number': 'P1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -137,7 +137,7 @@ def test_try_auto_chain_gate_path_does_not_call_generate_or_upload(app, monkeypa
|
||||
|
||||
|
||||
def test_match_handler_fulfillable_does_not_call_generate_excel(app, monkeypatch) -> None:
|
||||
"""inventory_matching Handler 成功履约时不得调用 generate_excel。"""
|
||||
"""onhand_matching Handler 成功履约时不得调用 generate_excel。"""
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching
|
||||
|
||||
with app.app_context():
|
||||
@@ -148,7 +148,7 @@ def test_match_handler_fulfillable_does_not_call_generate_excel(app, monkeypatch
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=9201, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_field_mapping',
|
||||
through_gate_code='onhand_field_mapping',
|
||||
reason='test_orch_sep',
|
||||
)
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
@@ -168,13 +168,13 @@ def test_match_handler_fulfillable_does_not_call_generate_excel(app, monkeypatch
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
|
||||
'app.services.shipping_notice.line_onhand_match_projection.load_current_match_facts_by_task',
|
||||
lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}},
|
||||
)
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='inventory_matching',
|
||||
gate_code='onhand_matching',
|
||||
).one()
|
||||
result = _handle_retry_inventory_matching(
|
||||
execution=execution,
|
||||
@@ -208,7 +208,7 @@ def test_match_pass_enqueues_artifact_generation_attempt(app, monkeypatch) -> No
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=9202, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_field_mapping',
|
||||
through_gate_code='onhand_field_mapping',
|
||||
reason='test_orch_sep_enqueue',
|
||||
)
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
@@ -222,24 +222,24 @@ def test_match_pass_enqueues_artifact_generation_attempt(app, monkeypatch) -> No
|
||||
|
||||
matching_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='inventory_matching',
|
||||
gate_code='onhand_matching',
|
||||
).one()
|
||||
if matching_gate.status != 'passed':
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code='inventory_matching',
|
||||
gate_code='onhand_matching',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
idempotency_key=f'test-orch-sep-match:{execution.id}',
|
||||
expected_gate_version=int(matching_gate.evaluation_version),
|
||||
input_snapshot={'action_code': 'retry_inventory_matching', 'payload': {}},
|
||||
input_snapshot={'action_code': 'retry_onhand_matching', 'payload': {}},
|
||||
)
|
||||
assert attempt is not None
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
outcome='passed',
|
||||
output_snapshot={'action_code': 'retry_inventory_matching'},
|
||||
output_snapshot={'action_code': 'retry_onhand_matching'},
|
||||
effective_result_json={'match_status': 'fulfillable'},
|
||||
)
|
||||
|
||||
@@ -277,7 +277,7 @@ def test_happy_path_generate_excel_only_in_artifact_attempt(app, monkeypatch) ->
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=9203, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_field_mapping',
|
||||
through_gate_code='onhand_field_mapping',
|
||||
reason='test_orch_sep_e2e',
|
||||
)
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
@@ -312,13 +312,13 @@ def test_happy_path_generate_excel_only_in_artifact_attempt(app, monkeypatch) ->
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
|
||||
'app.services.shipping_notice.line_onhand_match_projection.load_current_match_facts_by_task',
|
||||
lambda _task_id: {1: {'shortage_qty': '0', 'available_qty': '3'}},
|
||||
)
|
||||
|
||||
matching_gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='inventory_matching',
|
||||
gate_code='onhand_matching',
|
||||
).one()
|
||||
match_result = _handle_retry_inventory_matching(
|
||||
execution=execution,
|
||||
|
||||
@@ -17,7 +17,7 @@ pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
|
||||
"""行级重抓必须把该行 source_codes 交给 ensure_inventory,并收窄失效范围。"""
|
||||
"""行级重抓必须把该行 source_codes 交给 ensure_onhand,并收窄失效范围。"""
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
|
||||
|
||||
task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-LINE-SCOPE')
|
||||
@@ -38,15 +38,15 @@ def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
|
||||
lambda _task: SimpleNamespace(id=77),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
'app.services.shipping_notice.onhand_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: candidate_set,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines',
|
||||
'app.services.shipping_notice.onhand_candidate_projection.get_active_candidate_lines',
|
||||
lambda _task: [line],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources',
|
||||
'app.services.shipping_notice.onhand_candidate_projection.get_active_candidate_sources',
|
||||
lambda _task: sources,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -58,7 +58,7 @@ def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
|
||||
} if line_scope_key not in (None, '') else None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
|
||||
'app.services.shipping_notice.onhand_recovery_service.create_inventory_preparation_round',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -66,7 +66,7 @@ def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
|
||||
lambda **kwargs: invalidate_calls.append(dict(kwargs)) or {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
'app.services.shipping_notice.onhand_workflow.ensure_onhand',
|
||||
lambda payload: captured.append(dict(payload)) or {'status': 'running', 'data': {'rpa': {}}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -84,9 +84,9 @@ def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
|
||||
|
||||
_handle_retry_inventory_preparation(
|
||||
execution=SimpleNamespace(task_id=1, id=21, candidate_set_id=None),
|
||||
gate=SimpleNamespace(gate_code='inventory_preparation'),
|
||||
gate=SimpleNamespace(gate_code='onhand_preparation'),
|
||||
payload={
|
||||
'action_code': 'retry_inventory_preparation',
|
||||
'action_code': 'retry_onhand_preparation',
|
||||
'actor_user_id': 5,
|
||||
'snapshot_line_id': 1001,
|
||||
},
|
||||
@@ -145,14 +145,14 @@ def test_inventory_matching_line_scope_uses_match_inventory_line(monkeypatch):
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
|
||||
'app.services.shipping_notice.line_onhand_match_projection.load_current_match_facts_by_task',
|
||||
lambda _task_id: {},
|
||||
)
|
||||
|
||||
result = _handle_retry_inventory_matching(
|
||||
execution=SimpleNamespace(task_id=1, id=21),
|
||||
gate=SimpleNamespace(gate_code='inventory_matching'),
|
||||
payload={'action_code': 'retry_inventory_matching', 'snapshot_line_id': 1002, 'actor_user_id': 5},
|
||||
gate=SimpleNamespace(gate_code='onhand_matching'),
|
||||
payload={'action_code': 'retry_onhand_matching', 'snapshot_line_id': 1002, 'actor_user_id': 5},
|
||||
)
|
||||
|
||||
assert match_calls and match_calls[0]['line_no'] == 3
|
||||
@@ -165,20 +165,20 @@ def test_line_scoped_invalidation_skips_noticed_lines_and_artifacts(monkeypatch)
|
||||
from app.services.shipping_notice import recovery_invalidation_service as svc
|
||||
|
||||
link_a = SimpleNamespace(
|
||||
id=11, inventory_file_id=101, matched_source_code='WH_A',
|
||||
id=11, onhand_file_id=101, matched_source_code='WH_A',
|
||||
is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
|
||||
)
|
||||
link_b = SimpleNamespace(
|
||||
id=12, inventory_file_id=102, matched_source_code='WH_B',
|
||||
id=12, onhand_file_id=102, matched_source_code='WH_B',
|
||||
is_active=True, invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
|
||||
)
|
||||
match_open = SimpleNamespace(
|
||||
id=21, snapshot_line_id=1001, inventory_source_code='WH_A',
|
||||
id=21, snapshot_line_id=1001, source_code='WH_A',
|
||||
allowed_source_codes_snapshot=['WH_A'], is_current=True,
|
||||
invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
|
||||
)
|
||||
match_noticed = SimpleNamespace(
|
||||
id=22, snapshot_line_id=1002, inventory_source_code='WH_A',
|
||||
id=22, snapshot_line_id=1002, source_code='WH_A',
|
||||
allowed_source_codes_snapshot=['WH_A'], is_current=True,
|
||||
invalidated_at=None, invalidated_by_attempt_id=None, invalidation_reason=None,
|
||||
)
|
||||
@@ -200,25 +200,25 @@ def test_line_scoped_invalidation_skips_noticed_lines_and_artifacts(monkeypatch)
|
||||
return self
|
||||
|
||||
monkeypatch.setattr(svc, '_noticed_snapshot_line_ids', lambda _task_id: {1002})
|
||||
monkeypatch.setattr(svc, 'invalidate_downstream_gates', lambda **_: ['inventory_matching'])
|
||||
monkeypatch.setattr(svc, 'invalidate_downstream_gates', lambda **_: ['onhand_matching'])
|
||||
monkeypatch.setattr(svc.db.session, 'get', lambda *_a, **_k: SimpleNamespace(id=1))
|
||||
monkeypatch.setattr(svc.db.session, 'flush', lambda: None)
|
||||
# 纯单测不启 Flask:替换模块内模型符号,避免触碰 Flask-SQLAlchemy query 描述符。
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingTaskOnhandLink',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([link_a, link_b]))),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'ShippingNoticeLineInventoryMatch',
|
||||
'ShippingNoticeLineOnhandMatch',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **kw: _Query([match_open, match_noticed]))),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'ShippingInventoryMapping',
|
||||
'FreightRpaOnhandMapping',
|
||||
SimpleNamespace(
|
||||
inventory_file_id=SimpleNamespace(in_=lambda _ids: True),
|
||||
onhand_file_id=SimpleNamespace(in_=lambda _ids: True),
|
||||
status='active',
|
||||
query=SimpleNamespace(filter=lambda *_a, **_k: _Query([])),
|
||||
),
|
||||
@@ -235,7 +235,7 @@ def test_line_scoped_invalidation_skips_noticed_lines_and_artifacts(monkeypatch)
|
||||
|
||||
result = svc.invalidate_inventory_downstream(
|
||||
execution=SimpleNamespace(task_id=1),
|
||||
action_code='retry_inventory_preparation',
|
||||
action_code='retry_onhand_preparation',
|
||||
attempt_id=9,
|
||||
source_codes=['WH_A'],
|
||||
snapshot_line_id=1001,
|
||||
|
||||
@@ -2,21 +2,21 @@
|
||||
tests/test_shipping_line_source_ambiguity.py
|
||||
|
||||
用途:锁定多候选库存源「数据自证 + 歧义兜底」契约(设计 D4/D5,2026-08-29)。
|
||||
依赖:stp_line_inventory_match.match_order_lines_across_candidates。
|
||||
依赖:stp_line_onhand_match.match_order_lines_across_candidates。
|
||||
逻辑:同一行命中多源必须 multi_file_conflict 阻断并携带候选源列表(禁止静默选源);
|
||||
唯一源命中按行反写 源/可用量/缺口。既有能力以测试固化,防止后续回归。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
from app.services.shipping_notice.stp_line_onhand_match import (
|
||||
match_order_lines_across_candidates,
|
||||
)
|
||||
|
||||
|
||||
def test_same_reservation_across_two_sources_marks_conflict_with_candidates():
|
||||
"""[断言] 同一预约单在两个源都有库存:该行 multi_file_conflict 阻断并带候选源列表,
|
||||
resolved source 必须为空(选源交由人工 override_line_inventory_source)。"""
|
||||
resolved source 必须为空(选源交由人工 override_line_onhand_source)。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
order_lines=[{'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5'}],
|
||||
inventory_lines=[
|
||||
@@ -66,7 +66,7 @@ def test_unique_source_hit_writes_back_source_qty_and_shortage():
|
||||
|
||||
def test_disambiguation_via_pinned_allowed_sources_resolves_conflict():
|
||||
"""[断言] 人工选源后(行 allowed_source_codes 钉住单一源):原冲突行在钉住源内正常匹配,
|
||||
这是 override_line_inventory_source 行级重匹配的数据前提。"""
|
||||
这是 override_line_onhand_source 行级重匹配的数据前提。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
order_lines=[{
|
||||
'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5',
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.models import (
|
||||
ShippingOrderTask,
|
||||
ShippingExportArtifact,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
FreightRpaParsingProfile,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderExtraction,
|
||||
@@ -63,7 +63,7 @@ def test_count_my_todos_reports_stage_counts_and_done_breakdown(app):
|
||||
storage_bucket='test', storage_key='stage.xlsx', original_filename='stage.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code='STAGE', display_name='Stage', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
)
|
||||
from app.services.shipping_notice.shipping_notice_creation_service import (
|
||||
create_shipping_notice_after_inventory_gate,
|
||||
@@ -37,9 +37,9 @@ def _seed_customer(snapshot):
|
||||
|
||||
def _seed_match_row(order, snap_line, *, match_result='matched', shortage='0'):
|
||||
"""给冻结行补一条当前匹配事实(matched+ready 表示门禁可过)。"""
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
|
||||
line_index=snap_line.position, match_result=match_result, inventory_status='ready',
|
||||
line_index=snap_line.position, match_result=match_result, onhand_status='ready',
|
||||
required_qty='10', available_qty='10', shortage_qty=shortage,
|
||||
reservation_id=snap_line.reservation_id, part_number=snap_line.part_number,
|
||||
is_current=True,
|
||||
@@ -96,5 +96,5 @@ def test_whole_order_notice_rejected_when_all_lines_closed(app):
|
||||
# 断言:结案剔除后目标行集为空,整单调用走门禁未通过分支(与 match_completed 口径一致)。
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
create_shipping_notice_after_inventory_gate(fixture.order)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_GATE_NOT_PASSED'
|
||||
assert 'SHIPPING.INVENTORY_GATE_NOT_PASSED' in repr(exc_info.value)
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_GATE_NOT_PASSED'
|
||||
assert 'SHIPPING.ONHAND_GATE_NOT_PASSED' in repr(exc_info.value)
|
||||
@@ -5,13 +5,13 @@ from pathlib import Path
|
||||
from openpyxl import Workbook
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.inventory_snapshot import (
|
||||
from app.services.shipping_notice.onhand_snapshot import (
|
||||
parse_inventory_excel_with_meta,
|
||||
parse_inventory_rows,
|
||||
parse_inventory_text,
|
||||
read_inventory_schema_preview,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
|
||||
from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping
|
||||
from app.services.shipping_notice.match import match_notice_lines
|
||||
|
||||
|
||||
@@ -191,7 +191,7 @@ def test_parse_inventory_excel_uses_preview_header_row_index(app, tmp_path):
|
||||
def test_inventory_parser_uses_configured_worksheet_and_rejects_missing_sheet(tmp_path):
|
||||
"""多 Sheet 库存文件必须读取 Profile 指定工作表,错误名称不得静默回退 active sheet。"""
|
||||
from openpyxl import Workbook
|
||||
from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel_with_meta
|
||||
from app.services.shipping_notice.onhand_snapshot import parse_inventory_excel_with_meta
|
||||
|
||||
path = tmp_path / 'multi-sheet.xlsx'
|
||||
workbook = Workbook()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_shipping_notice_inventory_rpa_archive.py
|
||||
|
||||
用途:库存 RPA 原始库存 ZIP 归档、summary 可见性与 admin API 路由单测。
|
||||
依赖:freight_onhand_rpa_archive、api/schedule/runs、query_service、freight_onhand_rpa_finalize。
|
||||
依赖:freight_rpa_onhand_archive、api/schedule/runs、query_service、freight_rpa_onhand_finalize。
|
||||
逻辑:finalize 预生成 ZIP;列表只读 summary;下载 send_file 归档路径。
|
||||
"""
|
||||
|
||||
@@ -20,13 +20,13 @@ import pytest
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import ScheduleRun, ShippingInventoryFile, User
|
||||
from app.models import ScheduleRun, FreightRpaOnhandReportFile, User
|
||||
from app.services.schedule.query_service import serialize_run
|
||||
from app.services.schedule.scheduler_service import (
|
||||
_build_schedule_run_wecom_description,
|
||||
_build_schedule_run_wecom_jump_params,
|
||||
)
|
||||
from app.services.schedule.freight_onhand_rpa_archive import (
|
||||
from app.services.schedule.freight_rpa_onhand_archive import (
|
||||
inventory_raw_zip_available_from_summary,
|
||||
inventory_raw_zip_download_name,
|
||||
inventory_rpa_attachment_stem,
|
||||
@@ -96,8 +96,8 @@ def _attach_inventory_file(
|
||||
warehouse_id: str = "WH1",
|
||||
) -> None:
|
||||
db.session.add(
|
||||
ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
FreightRpaOnhandReportFile(
|
||||
onhand_file_no=inventory_file_no,
|
||||
storage_path=str(storage_path),
|
||||
source_file_name="inventory.xlsx",
|
||||
source_code=source_code,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_shipping_notice_inventory_schedule.py
|
||||
|
||||
用途:货代库存 RPA 排程 executor、defer/finalize 契约与 source 过滤单测。
|
||||
依赖:ScheduleTask/ScheduleRun、freight_onhand_rpa_job、freight_onhand_rpa_finalize。
|
||||
依赖:ScheduleTask/ScheduleRun、freight_rpa_onhand_job、freight_rpa_onhand_finalize。
|
||||
逻辑:覆盖 trigger 写入、awaiting 终态、回调 finalize、超时回收。
|
||||
"""
|
||||
|
||||
@@ -14,7 +14,7 @@ import pytest
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig, User
|
||||
from app.services.schedule.scheduler_service import run_task_now
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import (
|
||||
from app.services.schedule.freight_rpa_onhand_finalize import (
|
||||
_build_finalize_details,
|
||||
_compute_run_status,
|
||||
is_awaiting_rpa_schedule_run,
|
||||
@@ -22,9 +22,9 @@ from app.services.schedule.freight_onhand_rpa_finalize import (
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
)
|
||||
from app.services.schedule import reload_config, resolve_schedule_header
|
||||
from app.services.schedule.freight_onhand_rpa_job import (
|
||||
from app.services.schedule.freight_rpa_onhand_job import (
|
||||
_filter_sources,
|
||||
run_shipping_inventory_rpa_schedule,
|
||||
run_freight_rpa_onhand_schedule,
|
||||
)
|
||||
from tests.conftest import v2_inventory_batch_payload
|
||||
|
||||
@@ -37,17 +37,17 @@ def _freeze_schedule_batch_callback_contract(monkeypatch):
|
||||
解耦到同步 process_rpa_report_inventory_batch(由异步 worker job 调用);单测保持
|
||||
同步断言,因此把旧入口重新指向同步处理函数。
|
||||
"""
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
from app.services.shipping_notice import onhand_rpa_workflow
|
||||
import sys
|
||||
|
||||
def _wrapped(payload):
|
||||
return inventory_rpa_workflow.process_rpa_report_inventory_batch(
|
||||
return onhand_rpa_workflow.process_rpa_report_inventory_batch(
|
||||
v2_inventory_batch_payload(payload)
|
||||
)
|
||||
|
||||
monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped)
|
||||
monkeypatch.setattr(onhand_rpa_workflow, 'rpa_report_inventory_batch', _wrapped)
|
||||
monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped)
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory_batch
|
||||
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
total, success, failed, skipped, details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
|
||||
total, success, failed, skipped, details, errors, logs = run_freight_rpa_onhand_schedule(task, run)
|
||||
assert total >= 1
|
||||
assert success == 0
|
||||
assert failed == 0
|
||||
@@ -195,7 +195,7 @@ def test_recover_all_stale_awaiting_on_startup(app):
|
||||
status="running",
|
||||
started_at=datetime.utcnow() - timedelta(seconds=1200),
|
||||
response_summary_json={"awaiting_rpa": True},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -254,7 +254,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
|
||||
raise RuntimeError("excel exploded")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.freight_onhand_rpa_finalize.export_schedule_result_excel",
|
||||
"app.services.schedule.freight_rpa_onhand_finalize.export_schedule_result_excel",
|
||||
_excel_boom,
|
||||
)
|
||||
|
||||
@@ -278,7 +278,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
|
||||
"display_name": "ATL01",
|
||||
}],
|
||||
},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -319,7 +319,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
|
||||
raise RuntimeError("finalize exploded")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.freight_onhand_rpa_finalize._build_finalize_details",
|
||||
"app.services.schedule.freight_rpa_onhand_finalize._build_finalize_details",
|
||||
_boom,
|
||||
)
|
||||
|
||||
@@ -343,7 +343,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
|
||||
"display_name": "ATL01",
|
||||
}],
|
||||
},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -399,7 +399,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
|
||||
"display_name": "ATL01",
|
||||
}],
|
||||
},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -442,7 +442,7 @@ def test_recover_stale_awaiting_rpa_schedule_run(app):
|
||||
status="running",
|
||||
started_at=datetime.utcnow() - timedelta(seconds=1200),
|
||||
response_summary_json={"awaiting_rpa": True},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -541,7 +541,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
|
||||
{"source_code": "DSV360_AWSAMS", "warehouse_id": "RTM", "display_name": "AMS"},
|
||||
],
|
||||
},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -590,7 +590,7 @@ def test_finalize_inventory_rpa_schedule_run_with_skipped_callback(app):
|
||||
"display_name": "ATL01",
|
||||
}],
|
||||
},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -713,7 +713,7 @@ def test_schedule_batch_rejects_mismatched_run_no(app, tmp_path):
|
||||
started_at=datetime.utcnow(),
|
||||
total_count=1,
|
||||
response_summary_json={"awaiting_rpa": True, "pending_details": []},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -733,7 +733,7 @@ def test_schedule_batch_rejects_mismatched_run_no(app, tmp_path):
|
||||
|
||||
def test_scheduled_batch_progress_updates_run_counts(app):
|
||||
"""定时 batch 进度回调应实时回写排程 run 的累计笔数。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import report_inventory_batch_progress
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -747,7 +747,7 @@ def test_scheduled_batch_progress_updates_run_counts(app):
|
||||
started_at=datetime.utcnow(),
|
||||
total_count=2,
|
||||
response_summary_json={"awaiting_rpa": True, "pending_details": []},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -775,7 +775,7 @@ def test_scheduled_batch_progress_updates_run_counts(app):
|
||||
|
||||
def test_scheduled_batch_progress_rejects_mismatched_run_no(app):
|
||||
"""进度回调 run_no 与排程 run 不一致时必须拒绝,且不改变 run 计数。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import report_inventory_batch_progress
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -789,7 +789,7 @@ def test_scheduled_batch_progress_rejects_mismatched_run_no(app):
|
||||
started_at=datetime.utcnow(),
|
||||
total_count=1,
|
||||
response_summary_json={"awaiting_rpa": True, "pending_details": []},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -812,7 +812,7 @@ def test_scheduled_batch_progress_rejects_mismatched_run_no(app):
|
||||
|
||||
def test_scheduled_batch_progress_noop_after_finalized(app):
|
||||
"""run 已终态(不再 awaiting)时进度回调应为 no-op,不修改计数。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import report_inventory_batch_progress
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -849,7 +849,7 @@ def test_scheduled_batch_progress_noop_after_finalized(app):
|
||||
|
||||
def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
|
||||
"""定时 batch 成功项缺少 Warehouse 时必须拒绝,不能仅凭 Source 入库。"""
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
@@ -859,7 +859,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
|
||||
with app.app_context():
|
||||
before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
|
||||
before = FreightRpaOnhandReportFile.query.filter_by(snapshot_status="ready").count()
|
||||
result = rpa_report_inventory_batch({
|
||||
"run_no": "RUN-MISSING-WAREHOUSE",
|
||||
"trigger_type": "scheduled",
|
||||
@@ -869,7 +869,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
|
||||
"file_path": str(sample),
|
||||
}],
|
||||
})
|
||||
after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
|
||||
after = FreightRpaOnhandReportFile.query.filter_by(snapshot_status="ready").count()
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert result["failed_count"] == 1
|
||||
@@ -879,7 +879,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
|
||||
|
||||
def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkeypatch):
|
||||
"""finalize 失败重试同一回调时不得重复创建 ready 快照。"""
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
@@ -892,7 +892,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
raise RuntimeError("finalize exploded")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.freight_onhand_rpa_finalize._build_finalize_details",
|
||||
"app.services.schedule.freight_rpa_onhand_finalize._build_finalize_details",
|
||||
_boom,
|
||||
)
|
||||
|
||||
@@ -909,7 +909,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
started_at=datetime.utcnow(),
|
||||
total_count=1,
|
||||
response_summary_json={"awaiting_rpa": True, "pending_details": []},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -926,7 +926,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
}
|
||||
first = rpa_report_inventory_batch(payload)
|
||||
second = rpa_report_inventory_batch(payload)
|
||||
count = ShippingInventoryFile.query.filter_by(
|
||||
count = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no=run.run_no,
|
||||
source_code="DSV360_AWSDU",
|
||||
warehouse_id="AWSDU",
|
||||
@@ -941,8 +941,8 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
|
||||
def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, monkeypatch):
|
||||
"""finalize 首次失败、重试成功后应归档 callback 原文件。"""
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.services.schedule import freight_onhand_rpa_finalize as finalize_mod
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.schedule import freight_rpa_onhand_finalize as finalize_mod
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
@@ -985,7 +985,7 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon
|
||||
started_at=datetime.utcnow(),
|
||||
total_count=1,
|
||||
response_summary_json={"awaiting_rpa": True, "pending_details": []},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
@@ -1009,7 +1009,7 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon
|
||||
assert second["data"]["created"][0].get("reused_existing_snapshot") is True
|
||||
assert not sample.is_file()
|
||||
assert list(processed_dir.glob("retry_move.xlsx"))
|
||||
assert ShippingInventoryFile.query.filter_by(
|
||||
assert FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no=run.run_no,
|
||||
snapshot_status="ready",
|
||||
).count() == 1
|
||||
@@ -14,7 +14,7 @@ from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingUploadAttempt,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
FreightRpaParsingProfile,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderExtraction,
|
||||
@@ -145,7 +145,7 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
|
||||
storage_bucket='test', storage_key='page-filter.xlsx', original_filename='page-filter.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code='PAGE_FILTER', display_name='Page filter', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
@@ -376,7 +376,7 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app):
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLine, ShippingNoticeLineOnhandMatch,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import serialize_task_summary
|
||||
@@ -420,13 +420,13 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app):
|
||||
notice_id=second.id, snapshot_line_id=second_snapshot_line.id, position=1, line_no=1,
|
||||
part_number='PART-SECOND', reservation_id='RES-2', required_qty='8', field_values_json={},
|
||||
),
|
||||
ShippingNoticeLineInventoryMatch(
|
||||
ShippingNoticeLineOnhandMatch(
|
||||
task_id=first_task.id, snapshot_line_id=first_snapshot_line.id, line_no=1,
|
||||
match_result='matched', inventory_status='ready', available_qty='20', shortage_qty='0', is_current=True,
|
||||
match_result='matched', onhand_status='ready', available_qty='20', shortage_qty='0', is_current=True,
|
||||
),
|
||||
ShippingNoticeLineInventoryMatch(
|
||||
ShippingNoticeLineOnhandMatch(
|
||||
task_id=second_task.id, snapshot_line_id=second_snapshot_line.id, line_no=1,
|
||||
match_result='matched', inventory_status='ready', available_qty='9', shortage_qty='0', is_current=True,
|
||||
match_result='matched', onhand_status='ready', available_qty='9', shortage_qty='0', is_current=True,
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
@@ -551,7 +551,7 @@ def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app):
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExportArtifact, ShippingExcelTemplate, ShippingInventoryParsingProfile,
|
||||
ShippingExportArtifact, ShippingExcelTemplate, FreightRpaParsingProfile,
|
||||
ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice import query_service
|
||||
@@ -563,7 +563,7 @@ def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app):
|
||||
storage_key='test/template.xlsx', original_filename='template.xlsx', file_checksum='a' * 64,
|
||||
definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code='MODE', display_name='Mode', version=1, status='published', file_format='xlsx',
|
||||
definition_json={},
|
||||
)
|
||||
@@ -719,7 +719,7 @@ def test_list_my_todos_and_count_buckets(app):
|
||||
storage_bucket='test', storage_key='todo.xlsx', original_filename='todo.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code='TODO', display_name='Todo', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
@@ -1139,7 +1139,7 @@ def test_todo_category_sql_matches_formal_notice_facts(app):
|
||||
template_code='LW', display_name='LW', version=1, status='published', storage_bucket='test',
|
||||
storage_key='lw.xlsx', original_filename='lw.xlsx', file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code='LW', display_name='LW', version=1, status='published', file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='LW', display_name='LW')
|
||||
@@ -1211,7 +1211,7 @@ def test_count_my_todos_running_gate_is_processing_and_not_double_counted(app):
|
||||
execution_no="SPE-RUN-ONCE",
|
||||
task_id=int(order_task.id),
|
||||
status="active",
|
||||
current_gate_code="inventory_preparation",
|
||||
current_gate_code="onhand_preparation",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch):
|
||||
"""batch 开启时单票按需应写 inventory_export_batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config.pop("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", None)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
app.config.pop("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED", None)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED", "true")
|
||||
|
||||
source = {
|
||||
"source_code": "DSV360_AWSDU",
|
||||
@@ -57,12 +57,12 @@ def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path):
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED"] = False
|
||||
|
||||
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
|
||||
with app.app_context(), pytest.raises(ValidationError, match="v2") as exc_info:
|
||||
write_inventory_export_trigger_for_task("SN-LEGACY-1", source)
|
||||
assert exc_info.value.code == "SHIPPING.INVENTORY_RPA_V2_REQUIRED"
|
||||
assert exc_info.value.code == "SHIPPING.ONHAND_RPA_V2_REQUIRED"
|
||||
assert not list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json"))
|
||||
|
||||
|
||||
@@ -94,7 +94,7 @@ def test_batch_trigger_writes_explicit_v2_callback_identity(app, tmp_path):
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED"] = True
|
||||
source = {
|
||||
"source_code": "DBS",
|
||||
"connector_type": "dbs",
|
||||
|
||||
@@ -15,7 +15,7 @@ import pytest
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryParsingProfile,
|
||||
FreightRpaParsingProfile,
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
@@ -520,7 +520,7 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
storage_bucket="test", storage_key="test/stp.xlsx", original_filename="stp.xlsx",
|
||||
file_checksum="a" * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code="STP_PF", display_name="STP profile", version=1, status="published",
|
||||
file_format="xlsx", definition_json={},
|
||||
)
|
||||
|
||||
@@ -17,10 +17,10 @@ from app.models import (
|
||||
ChatLog,
|
||||
ChatSession,
|
||||
ShippingCustomer,
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaOnhandRoutingRule,
|
||||
FreightRpaOnhandReportFile,
|
||||
FreightRpaOnhandRoutingRuleCondition,
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
@@ -33,7 +33,7 @@ from app.models import (
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskOnhandLink,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.match import match_notice_lines
|
||||
@@ -495,7 +495,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
db.session.add(
|
||||
ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type="inventory_rpa_triggered",
|
||||
event_type="onhand_rpa_triggered",
|
||||
detail_json={"attempt": 1},
|
||||
created_at=datetime.utcnow() - timedelta(seconds=5),
|
||||
)
|
||||
@@ -509,9 +509,9 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
assert result["status"] == "needs_human"
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert task.pending_human_reason == PH_RPA_EXHAUSTED
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_exhausted").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="onhand_rpa_failed").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="onhand_rpa_triggered").count() == 1
|
||||
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="onhand_rpa_exhausted").count() == 1
|
||||
assert len(list(trigger.glob("inventory_export_*.json"))) == 0
|
||||
|
||||
|
||||
|
||||
@@ -13,8 +13,8 @@ tests/test_shipping_notice_ui_state.py
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine, ShippingInventoryCandidateSet, ShippingInventoryCandidateSource,
|
||||
ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
|
||||
ShippingOnhandCandidateLine, ShippingOnhandCandidateSet, ShippingOnhandCandidateSource,
|
||||
ShippingNotice, ShippingNoticeLine, ShippingNoticeLineOnhandMatch,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, User,
|
||||
)
|
||||
from app.services.shipping_notice.constants import (
|
||||
@@ -102,7 +102,7 @@ def test_unified_action_shape_contains_gate_version_fields():
|
||||
"lock_version": 7,
|
||||
"current_gate": {"evaluation_version": 3},
|
||||
"primary_action": {
|
||||
"code": "retry_inventory_matching",
|
||||
"code": "retry_onhand_matching",
|
||||
"label": "重新匹配",
|
||||
"dispatch": "mutation",
|
||||
},
|
||||
@@ -300,7 +300,7 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
|
||||
execution.current_gate_code = 'inventory_matching'
|
||||
execution.current_gate_code = 'onhand_matching'
|
||||
db.session.flush()
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
@@ -382,11 +382,11 @@ def test_build_task_ui_state_queries_process_gate_once(app, monkeypatch) -> None
|
||||
def _fake_gate(_task):
|
||||
calls['n'] += 1
|
||||
return {
|
||||
'current_gate_code': 'inventory_sufficiency',
|
||||
'current_gate_code': 'onhand_sufficiency',
|
||||
'status': 'blocked',
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_blocking_gate': {
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
'gate_code': 'onhand_sufficiency',
|
||||
'status': 'blocked_manual',
|
||||
},
|
||||
'primary_action': None,
|
||||
@@ -555,18 +555,18 @@ def test_stp_facts_candidates_frozen_projected(app) -> None:
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
candidate_set = ShippingOnhandCandidateSet(
|
||||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='a' * 64,
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingInventoryCandidateSource(
|
||||
ShippingOnhandCandidateSource(
|
||||
candidate_set_id=candidate_set.id, source_code=code, candidate_order=index,
|
||||
)
|
||||
for index, code in enumerate(['DBS_DUB', 'DBS_RTM'], start=1)
|
||||
])
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
db.session.add(ShippingOnhandCandidateLine(
|
||||
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DBS_DUB', 'DBS_RTM'],
|
||||
))
|
||||
task.active_inventory_candidate_set_id = candidate_set.id
|
||||
@@ -585,7 +585,7 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-UI-STP-LINES', user_id=user.id, stage='inventory_matching',
|
||||
task_no='OT-UI-STP-LINES', user_id=user.id, stage='onhand_matching',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -602,11 +602,11 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
|
||||
match_result='matched', inventory_status='ready', required_qty='10', available_qty='10',
|
||||
match_result='matched', onhand_status='ready', required_qty='10', available_qty='10',
|
||||
matched_qty='10', shortage_qty='0', reservation_id='3000092917', part_number='PN-1',
|
||||
inventory_source_code='DBS_DUB', matched_file_no='INV-1', is_current=True,
|
||||
source_code='DBS_DUB', matched_file_no='INV-1', is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -651,7 +651,7 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||||
user = User(username='ui-structured-match', email='ui-structured-match@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(task_no='OT-UI-STRUCTURED-MATCH', user_id=user.id, stage='inventory_matching')
|
||||
task = ShippingOrderTask(task_no='OT-UI-STRUCTURED-MATCH', user_id=user.id, stage='onhand_matching')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
@@ -667,20 +667,20 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
onhand_status="ready",
|
||||
required_qty="10",
|
||||
available_qty="7",
|
||||
matched_qty="7",
|
||||
shortage_qty="3",
|
||||
reservation_id="RSV-1",
|
||||
part_number="PN-1",
|
||||
inventory_source_code="DBS_DUB",
|
||||
source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -703,22 +703,22 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||||
# §1.5 明细按钮:短缺 → close_unfulfillable / release_inventory_shortage + retry 两动作。
|
||||
assert line["is_shortage"] is True
|
||||
assert line["user_line_status"] == "shortage"
|
||||
assert set(line["line_allowed_actions"]) == {"close_unfulfillable", "release_inventory_shortage"}
|
||||
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
|
||||
assert set(line["line_allowed_actions"]) == {"close_unfulfillable", "release_onhand_shortage"}
|
||||
assert "retry_onhand_preparation" in line["inventory_allowed_actions"]
|
||||
|
||||
|
||||
def test_stage_context_hides_inventory_actions_while_rpa_running(app) -> None:
|
||||
"""库存 RPA queued/running 时,工作台 preparation 行不得下发重试 RPA 动作。
|
||||
|
||||
与 Case 投影同源:inventory_rpa_is_running 在行循环外算一次;运行中 actions 为空。
|
||||
与 Case 投影同源:onhand_rpa_is_running 在行循环外算一次;运行中 actions 为空。
|
||||
"""
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
from app.models import FreightRpaOnhandTaskAttempt
|
||||
|
||||
with app.app_context():
|
||||
user = User(username='ui-rpa-running', email='ui-rpa-running@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(task_no='OT-UI-RPA-RUNNING', user_id=user.id, stage='inventory_matching')
|
||||
task = ShippingOrderTask(task_no='OT-UI-RPA-RUNNING', user_id=user.id, stage='onhand_matching')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
@@ -734,23 +734,23 @@ def test_stage_context_hides_inventory_actions_while_rpa_running(app) -> None:
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
onhand_status='ready',
|
||||
required_qty='10',
|
||||
available_qty='7',
|
||||
matched_qty='7',
|
||||
shortage_qty='3',
|
||||
reservation_id='RSV-RPA',
|
||||
part_number='PN-RPA',
|
||||
inventory_source_code='DBS_DUB',
|
||||
source_code='DBS_DUB',
|
||||
is_current=True,
|
||||
))
|
||||
db.session.add(ShippingTaskInventoryRpaAttempt(
|
||||
db.session.add(FreightRpaOnhandTaskAttempt(
|
||||
task_no=task.task_no,
|
||||
source_code='DBS_DUB',
|
||||
attempt_no=1,
|
||||
@@ -769,7 +769,7 @@ def test_stage_context_hides_inventory_actions_while_rpa_running(app) -> None:
|
||||
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monkeypatch) -> None:
|
||||
"""行级 source_conflict 与候选源只读 Match;Excel 未生成时下发 source_options。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.list_database_inventory_sources',
|
||||
'app.services.shipping_notice.onhand_source_repository.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [
|
||||
{'source_code': 'src_a', 'display_name': 'Source A'},
|
||||
{'source_code': 'SRC_B', 'display_name': ''},
|
||||
@@ -779,7 +779,7 @@ def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monke
|
||||
user = User(username='ui-source-ambiguity', email='ui-source-ambiguity@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(task_no='OT-UI-SOURCE-AMBIG', user_id=user.id, stage='inventory_matching')
|
||||
task = ShippingOrderTask(task_no='OT-UI-SOURCE-AMBIG', user_id=user.id, stage='onhand_matching')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
@@ -792,9 +792,9 @@ def test_stage_context_preparation_projects_source_ambiguity_and_lock(app, monke
|
||||
line = ShippingOrderSnapshotLine(snapshot_id=snapshot.id, position=0, line_no=1, field_values_json={})
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||||
match_result='source_conflict', inventory_status='source_conflict',
|
||||
match_result='source_conflict', onhand_status='source_conflict',
|
||||
allowed_source_codes_snapshot=['SRC_A', 'SRC_B'], is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -820,15 +820,15 @@ def test_stage_context_projects_selected_source_without_backfilling_match_source
|
||||
part_number='PN-SEL',
|
||||
qty='2',
|
||||
)
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
candidate_set = ShippingOnhandCandidateSet(
|
||||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='b' * 64,
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
db.session.add(ShippingOnhandCandidateSource(
|
||||
candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1,
|
||||
))
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
db.session.add(ShippingOnhandCandidateLine(
|
||||
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'],
|
||||
))
|
||||
task.active_inventory_candidate_set_id = candidate_set.id
|
||||
@@ -858,23 +858,23 @@ def test_stage_context_notice_resolves_ot_match_and_selected_source(app) -> None
|
||||
part_number='PN-NOTICE',
|
||||
qty='3',
|
||||
)
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
candidate_set = ShippingOnhandCandidateSet(
|
||||
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='c' * 64,
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
db.session.add(ShippingOnhandCandidateSource(
|
||||
candidate_set_id=candidate_set.id, source_code='DSV360_AWSSG', candidate_order=1,
|
||||
))
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
db.session.add(ShippingOnhandCandidateLine(
|
||||
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DSV360_AWSSG'],
|
||||
))
|
||||
task.active_inventory_candidate_set_id = candidate_set.id
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||||
match_result='matched', inventory_status='ready', required_qty='3', available_qty='3',
|
||||
match_result='matched', onhand_status='ready', required_qty='3', available_qty='3',
|
||||
matched_qty='3', shortage_qty='0', reservation_id='RSV-NOTICE', part_number='PN-NOTICE',
|
||||
inventory_source_code='DSV360_AWSSG', matched_file_no='INV-NOTICE', is_current=True,
|
||||
source_code='DSV360_AWSSG', matched_file_no='INV-NOTICE', is_current=True,
|
||||
))
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-UI-NOTICE-RESOLVE',
|
||||
@@ -934,12 +934,12 @@ def test_preparation_lines_carry_part_available_qty(app) -> None:
|
||||
qty="8",
|
||||
)
|
||||
# 行 Match 事实:required '8'、part_available_qty='9'(允许源内、忽略预约号与单位的料号总可用量)。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||||
match_result="matched", inventory_status="ready", required_qty="8",
|
||||
match_result="matched", onhand_status="ready", required_qty="8",
|
||||
available_qty="9", matched_qty="9", shortage_qty="0", part_available_qty="9",
|
||||
reservation_id="RSV-PART-AVAIL", part_number="PN-PART-AVAIL",
|
||||
inventory_source_code="DBS_DUB", is_current=True,
|
||||
source_code="DBS_DUB", is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -951,8 +951,8 @@ def test_preparation_lines_carry_part_available_qty(app) -> None:
|
||||
|
||||
def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None:
|
||||
"""库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。"""
|
||||
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingTaskOnhandLink
|
||||
from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download
|
||||
|
||||
with app.app_context():
|
||||
inventory_path = tmp_path / "task-inventory.xlsx"
|
||||
@@ -960,8 +960,8 @@ def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_pat
|
||||
task = ShippingOrderTask(
|
||||
task_no="OT-UI-INVENTORY-DOWNLOAD", user_id=1, source_type="direct_pdf",
|
||||
)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no="SIF-UI-DOWNLOAD",
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no="SIF-UI-DOWNLOAD",
|
||||
storage_path=str(inventory_path),
|
||||
source_file_name="task-inventory.xlsx",
|
||||
snapshot_status="ready",
|
||||
@@ -972,9 +972,9 @@ def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_pat
|
||||
# 未建立 task link 时不得因为文件存在而放行下载。
|
||||
assert resolve_task_inventory_download(task) is None
|
||||
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
db.session.add(ShippingTaskOnhandLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inventory_file.id,
|
||||
onhand_file_id=inventory_file.id,
|
||||
is_active=True,
|
||||
access_mode="readonly",
|
||||
))
|
||||
@@ -988,7 +988,7 @@ def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_pat
|
||||
|
||||
def test_workspace_inventory_download_requires_owned_active_file(app, client, tmp_path) -> None:
|
||||
"""库存下载路由只能返回当前用户任务的 active link 文件,不能泄漏其他任务或无关联文件。"""
|
||||
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingTaskOnhandLink
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username='inventory-download-owner', email='inventory-download-owner@example.com')
|
||||
@@ -999,17 +999,17 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm
|
||||
inventory_path.write_bytes(b'inventory-download-content')
|
||||
task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='direct_pdf')
|
||||
no_file_task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='direct_pdf')
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-DOWNLOAD-API',
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-INVENTORY-DOWNLOAD-API',
|
||||
storage_path=str(inventory_path),
|
||||
source_file_name='inventory-download.xlsx',
|
||||
snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, no_file_task, inventory_file])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
db.session.add(ShippingTaskOnhandLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inventory_file.id,
|
||||
onhand_file_id=inventory_file.id,
|
||||
is_active=True,
|
||||
access_mode='readonly',
|
||||
))
|
||||
@@ -1026,14 +1026,14 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm
|
||||
# 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。
|
||||
missing = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers)
|
||||
assert missing.status_code == 404
|
||||
assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND'
|
||||
assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_ONHAND_FILE_NOT_FOUND'
|
||||
forbidden = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers)
|
||||
assert forbidden.status_code == 404
|
||||
|
||||
|
||||
def test_workspace_line_inventory_download_requires_current_line_reference(app, client, tmp_path) -> None:
|
||||
"""行内下载只能读取当前匹配事实引用的库存文件,不能按文件号探测同任务其他来源。"""
|
||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username='line-inventory-download-owner', email='line-inventory-download-owner@example.com')
|
||||
@@ -1046,20 +1046,20 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app,
|
||||
task, snapshot_line = _frozen_task_with_line(
|
||||
task_no='OT-LINE-INVENTORY-DOWNLOAD', user_id=owner.id,
|
||||
)
|
||||
allowed_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path),
|
||||
allowed_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path),
|
||||
source_file_name='crane.xlsx', source_code='CRANE', snapshot_status='ready',
|
||||
)
|
||||
denied_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-LINE-DBS', storage_path=str(denied_path),
|
||||
denied_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-LINE-DBS', storage_path=str(denied_path),
|
||||
source_file_name='dbs.xlsx', source_code='DBS', snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, allowed_file, denied_file])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
|
||||
inventory_snapshot_id=allowed_file.id, matched_file_no=allowed_file.inventory_file_no,
|
||||
inventory_source_code='CRANE', match_result='not_found', inventory_status='ready', is_current=True,
|
||||
onhand_snapshot_id=allowed_file.id, matched_file_no=allowed_file.onhand_file_no,
|
||||
source_code='CRANE', match_result='not_found', onhand_status='ready', is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
|
||||
@@ -1088,19 +1088,19 @@ def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app)
|
||||
part_number="PN-LEGACY",
|
||||
qty="10",
|
||||
)
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
onhand_status="ready",
|
||||
required_qty="10",
|
||||
available_qty="8",
|
||||
shortage_qty="2",
|
||||
reservation_id="RSV-LEGACY",
|
||||
part_number="PN-LEGACY",
|
||||
inventory_source_code="DBS_DUB",
|
||||
source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -1125,19 +1125,19 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch
|
||||
part_number="PN-DETAIL",
|
||||
qty="2",
|
||||
)
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
onhand_status="ready",
|
||||
required_qty="2",
|
||||
available_qty="2",
|
||||
shortage_qty="0",
|
||||
reservation_id="RSV-DETAIL",
|
||||
part_number="PN-DETAIL",
|
||||
inventory_source_code="DBS_DUB",
|
||||
source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -1160,9 +1160,9 @@ def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
|
||||
task, snapshot_line = _frozen_task_with_line(
|
||||
task_no="OT-UI-STP-MULTI", reservation_id="RSV-MULTI", part_number="PN-MULTI", qty="1",
|
||||
)
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
|
||||
match_result='source_conflict', inventory_status='source_conflict',
|
||||
match_result='source_conflict', onhand_status='source_conflict',
|
||||
allowed_source_codes_snapshot=['DBS_DUB', 'DBS_RTM'], is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -1233,7 +1233,7 @@ def test_stage_context_line_actions_without_match_rows(app) -> None:
|
||||
"""正式 OT 无匹配行时,preparation.lines 仍须下发明细库存重试动作。
|
||||
|
||||
断言:has_formal_ot 不得用 current_match_rows 判定;无 match 时 fact 兜底 preparing,
|
||||
inventory_allowed_actions 含 retry_inventory_preparation。
|
||||
inventory_allowed_actions 含 retry_onhand_preparation。
|
||||
"""
|
||||
with app.app_context():
|
||||
user = User(username='ui-no-match-actions', email='ui-no-match-actions@example.com')
|
||||
@@ -1253,7 +1253,7 @@ def test_stage_context_line_actions_without_match_rows(app) -> None:
|
||||
assert len(preparation["lines"]) == 1
|
||||
line = preparation["lines"][0]
|
||||
# 关键断言:无 Match 行时明细仍可点「重试库存准备」,不得因 has_formal_ot=False 空动作。
|
||||
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
|
||||
assert "retry_onhand_preparation" in line["inventory_allowed_actions"]
|
||||
assert "close_unfulfillable" in line["line_allowed_actions"]
|
||||
|
||||
|
||||
@@ -1286,15 +1286,15 @@ def test_stage_context_preparation_projects_shortage_release_template_fields(app
|
||||
"""短缺行必须按库存源发货模板投影人工补录字段,禁止 fail-closed 空列表。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaSource,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
location = ShippingInventoryField.query.filter_by(field_code='location').one()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
location = FreightRpaOnhandField.query.filter_by(field_code='location').one()
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
template = db.session.get(ShippingExcelTemplate, int(source.excel_template_id))
|
||||
assert template is not None
|
||||
template.definition_json = {
|
||||
@@ -1325,7 +1325,7 @@ def test_stage_context_preparation_projects_shortage_release_template_fields(app
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-UI-RELEASE-FIELDS',
|
||||
user_id=user.id,
|
||||
stage='inventory_matching',
|
||||
stage='onhand_matching',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -1351,21 +1351,21 @@ def test_stage_context_preparation_projects_shortage_release_template_fields(app
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
# 无库存快照时模板库存字段全部人工补录;源码必须能解析到 published 发货模板。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result='not_found',
|
||||
inventory_status='ready',
|
||||
onhand_status='ready',
|
||||
required_qty='10',
|
||||
available_qty='0',
|
||||
matched_qty='0',
|
||||
shortage_qty='10',
|
||||
reservation_id='RSV-RELEASE',
|
||||
part_number='PN-RELEASE',
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
inventory_snapshot_id=None,
|
||||
source_code='DSV360_AWSDU',
|
||||
onhand_snapshot_id=None,
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
+5
-5
@@ -2,7 +2,7 @@
|
||||
tests/test_shipping_inventory_candidate_routing.py
|
||||
|
||||
用途:验证 field_id→值 路由路径与冻结 Snapshot 路由路径结果一致,并断言 can_build 语义。
|
||||
依赖:inventory_routing_engine、订单 Schema service、库存路由模型。
|
||||
依赖:onhand_routing_engine、订单 Schema service、库存路由模型。
|
||||
逻辑:同一组字段值分别走 Snapshot 与 field_values 评估器,对比 status/source_codes;
|
||||
覆盖 ambiguous 多候选可建单与 unresolved/conflicted 不可建单分支。
|
||||
"""
|
||||
@@ -13,11 +13,11 @@ from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
|
||||
FreightRpaOnhandRoutingRule, FreightRpaOnhandRoutingRuleCondition, ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_routing_engine import (
|
||||
from app.services.shipping_notice.onhand_routing_engine import (
|
||||
evaluate_inventory_source_rules,
|
||||
evaluate_inventory_source_rules_for_field_values,
|
||||
)
|
||||
@@ -124,11 +124,11 @@ def _task_with_line_values(
|
||||
|
||||
def _rule(*, code: str, priority: int, sources: list[str], conditions: list[tuple[str, str, object]], action_type: str = 'add_source_candidates'):
|
||||
"""构造已发布行级路由规则。"""
|
||||
return ShippingInventoryRoutingRule(
|
||||
return FreightRpaOnhandRoutingRule(
|
||||
rule_code=code, rule_name=code, scope='line', priority=priority, match_mode='all',
|
||||
status='published', action_type=action_type, action_payload_json={'source_codes': sources}, version=1,
|
||||
conditions=[
|
||||
ShippingInventoryRoutingRuleCondition(
|
||||
FreightRpaOnhandRoutingRuleCondition(
|
||||
condition_group=1, source_kind='order_field', order_field_id=field_id,
|
||||
operator=operator, expected_value_json=expected, sequence=index,
|
||||
)
|
||||
+71
-50
@@ -2,7 +2,7 @@
|
||||
tests/test_shipping_inventory_configuration.py
|
||||
|
||||
用途:验证库存源主数据、外部系统映射约束和 RPA 凭据加密的阶段一契约。
|
||||
依赖:Flask app/db、库存配置模型、freight_rpa.common.credential_crypto、inventory_source_repository。
|
||||
依赖:Flask app/db、库存配置模型、freight_rpa.common.credential_crypto、onhand_source_repository。
|
||||
逻辑:阶段二前锁定最小数据安全与关系约束,避免错误配置进入路由或 RPA 执行链路。
|
||||
"""
|
||||
|
||||
@@ -15,23 +15,23 @@ from sqlalchemy.exc import IntegrityError
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryExternalMapping, ShippingInventoryFile,
|
||||
ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
|
||||
ShippingExcelTemplate, FreightRpaOnhandExternalMapping, FreightRpaOnhandReportFile,
|
||||
FreightRpaOnhandField, FreightRpaOnhandReportConfig, FreightRpaParsingProfile, FreightRpaSource,
|
||||
ShippingCustomer, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask, ShippingRpaProfile,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask, FreightRpaProfile,
|
||||
)
|
||||
from app.services.freight_rpa.common.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.onhand_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.onhand_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:
|
||||
def _profile(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> FreightRpaProfile:
|
||||
"""构造最小可持久化 RPA Profile,避免测试包含明文真实凭据。"""
|
||||
return ShippingRpaProfile(
|
||||
return FreightRpaProfile(
|
||||
profile_code=code,
|
||||
display_name=code,
|
||||
connector_type=connector_type,
|
||||
@@ -40,9 +40,9 @@ def _profile(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> ShippingRp
|
||||
)
|
||||
|
||||
|
||||
def _source(profile: ShippingRpaProfile, *, code: str = 'DBS_DUB', mode: str = 'fixed') -> ShippingInventorySource:
|
||||
def _source(profile: FreightRpaProfile, *, code: str = 'DBS_DUB', mode: str = 'fixed') -> FreightRpaSource:
|
||||
"""构造固定或动态 Warehouse 的库存源,供约束测试复用。"""
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
parsing = FreightRpaParsingProfile(
|
||||
profile_code=f'{code}_PARSING', display_name=f'{code} Parsing', version=1,
|
||||
status='published', file_format='xlsx', definition_json={'match_keys': []},
|
||||
)
|
||||
@@ -52,16 +52,22 @@ def _source(profile: ShippingRpaProfile, *, code: str = 'DBS_DUB', mode: str = '
|
||||
storage_key=f'test/{code}-export.xlsx', original_filename='template.xlsx',
|
||||
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
|
||||
)
|
||||
return ShippingInventorySource(
|
||||
source = FreightRpaSource(
|
||||
source_code=code,
|
||||
display_name=code,
|
||||
connector_type=profile.connector_type,
|
||||
rpa_profile=profile,
|
||||
parsing_profile=parsing,
|
||||
excel_template=template,
|
||||
warehouse_resolution_mode=mode,
|
||||
fixed_warehouse_id='DUB' if mode == 'fixed' else None,
|
||||
)
|
||||
# s18 起解析方案绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行;
|
||||
# 经关系级联随站点一并入库,调用方只需 add(source)。
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=source, parsing_profile=parsing,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
return source
|
||||
|
||||
|
||||
def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
|
||||
@@ -153,7 +159,7 @@ def test_source_profile_connector_types_must_match(app):
|
||||
"""Source 绑定不同 Driver 的 Profile 必须被服务层拒绝。"""
|
||||
with app.app_context(), pytest.raises(ValidationError) as exc_info:
|
||||
validate_source_profile(_source(_profile(connector_type='dbs')), _profile(code='CRANE_01', connector_type='crane'))
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH'
|
||||
assert exc_info.value.code == 'SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH'
|
||||
|
||||
|
||||
def test_dynamic_source_disallows_fixed_warehouse_in_database(app):
|
||||
@@ -173,8 +179,8 @@ def test_external_mapping_allows_topgp_organization_code_to_be_null(app):
|
||||
with app.app_context():
|
||||
profile = _profile()
|
||||
source = _source(profile)
|
||||
mapping = ShippingInventoryExternalMapping(
|
||||
inventory_source=source,
|
||||
mapping = FreightRpaOnhandExternalMapping(
|
||||
source=source,
|
||||
freight_warehouse_id='DUB',
|
||||
external_system_code='TOPGP',
|
||||
external_organization_code=None,
|
||||
@@ -209,11 +215,12 @@ def test_database_source_snapshot_uses_source_business_report_configuration(app)
|
||||
profile = _profile()
|
||||
profile.login_config_json = {'auth_mode': 'password'}
|
||||
source = _source(profile)
|
||||
source.report_path_json = {
|
||||
# s18 起报表路径/查询条件写在站点的 onhand_report_config 配置行上。
|
||||
source.onhand_report_config.report_path_json = {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inventory', 'report_name': 'Source Report',
|
||||
}
|
||||
source.query_parameters_json = [
|
||||
source.onhand_report_config.query_parameters_json = [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
|
||||
]
|
||||
db.session.add(source)
|
||||
@@ -248,12 +255,12 @@ def test_external_mapping_prefers_exact_warehouse_then_source_default(app):
|
||||
with app.app_context():
|
||||
profile = _profile(code='CRANE_EU', connector_type='crane')
|
||||
source = _source(profile, code='CRANE', mode='inventory_match')
|
||||
exact = ShippingInventoryExternalMapping(
|
||||
inventory_source=source, freight_warehouse_id='FRA', external_system_code='TOPGP',
|
||||
exact = FreightRpaOnhandExternalMapping(
|
||||
source=source, freight_warehouse_id='FRA', external_system_code='TOPGP',
|
||||
external_warehouse_code='FRA01', external_warehouse_name='Frankfurt',
|
||||
)
|
||||
fallback = ShippingInventoryExternalMapping(
|
||||
inventory_source=source, freight_warehouse_id=None, external_system_code='TOPGP',
|
||||
fallback = FreightRpaOnhandExternalMapping(
|
||||
source=source, freight_warehouse_id=None, external_system_code='TOPGP',
|
||||
external_warehouse_code='CRANE_DEFAULT', external_warehouse_name='Crane Default',
|
||||
)
|
||||
db.session.add_all([exact, fallback])
|
||||
@@ -266,21 +273,28 @@ 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.onhand_snapshot_store import link_snapshot_to_task
|
||||
|
||||
with app.app_context():
|
||||
base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = ShippingRpaProfile(
|
||||
base_source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = FreightRpaProfile(
|
||||
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'},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
# s18 起解析方案绑定挂在 base_source 的 onhand_report_config 配置行上。
|
||||
base_profile = base_source.onhand_report_config.parsing_profile
|
||||
crane_source = FreightRpaSource(
|
||||
source_code='CRANE', display_name='Crane', connector_type='crane',
|
||||
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
|
||||
rpa_profile=crane_profile,
|
||||
excel_template=base_source.excel_template,
|
||||
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
|
||||
report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
enabled=True,
|
||||
)
|
||||
# Crane 站点复用同一解析方案;报表路径/查询条件归配置行且 Crane 恒为空。
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=crane_source, parsing_profile=base_profile,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-DYNAMIC-WH', user_id=1, source_type='direct_pdf', status='ready',
|
||||
@@ -298,21 +312,21 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
|
||||
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 = dict(base_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
|
||||
base_profile.definition_json = definition
|
||||
db.session.commit()
|
||||
|
||||
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
||||
inventory_fields = {item.field_code: str(item.id) for item in FreightRpaOnhandField.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',
|
||||
snapshot = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-DYNAMIC-WH', storage_path=str(path), snapshot_status='ready',
|
||||
source_code='CRANE', warehouse_id=None, share_mode='warehouse_pool',
|
||||
inventory_lines_json=[
|
||||
onhand_lines_json=[
|
||||
{
|
||||
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
|
||||
inventory_fields['warehouse_id']: 'FRA', inventory_fields['available_qty']: 1,
|
||||
@@ -332,21 +346,28 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
|
||||
|
||||
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.onhand_snapshot_store import link_snapshot_to_task
|
||||
|
||||
with app.app_context():
|
||||
base_source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = ShippingRpaProfile(
|
||||
base_source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = FreightRpaProfile(
|
||||
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'},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
# s18 起解析方案绑定挂在 base_source 的 onhand_report_config 配置行上。
|
||||
base_profile = base_source.onhand_report_config.parsing_profile
|
||||
crane_source = FreightRpaSource(
|
||||
source_code='CRANE_AMBIG', display_name='Crane Ambiguous', connector_type='crane',
|
||||
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
|
||||
rpa_profile=crane_profile,
|
||||
excel_template=base_source.excel_template,
|
||||
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None,
|
||||
report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
enabled=True,
|
||||
)
|
||||
# Crane 站点复用同一解析方案;报表路径/查询条件归配置行且 Crane 恒为空。
|
||||
FreightRpaOnhandReportConfig(
|
||||
source=crane_source, parsing_profile=base_profile,
|
||||
report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-DYNAMIC-AMBIG', user_id=1, source_type='direct_pdf', status='ready',
|
||||
@@ -364,21 +385,21 @@ def test_dynamic_source_rejects_ambiguous_warehouse_for_same_order_key(app, tmp_
|
||||
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 = dict(base_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
|
||||
base_profile.definition_json = definition
|
||||
db.session.commit()
|
||||
|
||||
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
||||
inventory_fields = {item.field_code: str(item.id) for item in FreightRpaOnhandField.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',
|
||||
snapshot = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-DYNAMIC-AMBIG', storage_path=str(path), snapshot_status='ready',
|
||||
source_code='CRANE_AMBIG', warehouse_id=None, share_mode='warehouse_pool',
|
||||
inventory_lines_json=[
|
||||
onhand_lines_json=[
|
||||
{
|
||||
inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1',
|
||||
inventory_fields['warehouse_id']: 'FRA', inventory_fields['available_qty']: 1,
|
||||
@@ -397,12 +418,12 @@ def test_dynamic_source_rejects_ambiguous_warehouse_for_same_order_key(app, tmp_
|
||||
def test_dynamic_snapshot_is_idempotent_per_rpa_run(app, tmp_path):
|
||||
"""同一 RPA run 的动态多仓文件只能入库一次,避免回调重放产生重复快照。"""
|
||||
with app.app_context():
|
||||
first = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-DYNAMIC-IDEMPOTENT-1', storage_path=str(tmp_path / 'first.xlsx'),
|
||||
first = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-DYNAMIC-IDEMPOTENT-1', storage_path=str(tmp_path / 'first.xlsx'),
|
||||
snapshot_status='ready', source_code='CRANE', warehouse_id=None, rpa_run_no='RUN-DYNAMIC-1',
|
||||
)
|
||||
second = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-DYNAMIC-IDEMPOTENT-2', storage_path=str(tmp_path / 'second.xlsx'),
|
||||
second = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-DYNAMIC-IDEMPOTENT-2', storage_path=str(tmp_path / 'second.xlsx'),
|
||||
snapshot_status='ready', source_code='CRANE', warehouse_id=None, rpa_run_no='RUN-DYNAMIC-1',
|
||||
)
|
||||
db.session.add(first)
|
||||
File renamed without changes.
+16
-16
@@ -2,7 +2,7 @@
|
||||
tests/test_shipping_inventory_link_ot_owner.py
|
||||
|
||||
用途:锁定库存 Link 挂在正式 OT 上;传入 ShippingNotice 时仍须解析到该 OT 的 active link。
|
||||
依赖:pytest、inventory_file_store.active_inventory_file_for_task / resolve_inventory_lines_for_execution。
|
||||
依赖:pytest、onhand_file_store.active_inventory_file_for_task / resolve_inventory_lines_for_execution。
|
||||
逻辑:复现「Notice.id ≠ OT.id → Excel 导出读到 0 行库存」回归。
|
||||
"""
|
||||
|
||||
@@ -10,12 +10,12 @@ from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
FreightRpaOnhandReportFile,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskOnhandLink,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
from app.services.shipping_notice.onhand_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
resolve_inventory_lines_for_execution,
|
||||
)
|
||||
@@ -36,12 +36,12 @@ def test_active_inventory_file_for_notice_uses_order_task_link(app, tmp_path) ->
|
||||
db.session.flush()
|
||||
|
||||
ot = ShippingOrderTask(task_no='OT-INV-LINK-OWNER', user_id=1, source_type='direct_pdf')
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INV-LINK-OWNER',
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-INV-LINK-OWNER',
|
||||
storage_path=str(inventory_path),
|
||||
source_file_name='ot-owned-inventory.xlsx',
|
||||
snapshot_status='ready',
|
||||
inventory_lines_json=[
|
||||
onhand_lines_json=[
|
||||
{'reservation_id': '3000112934', 'part_number': 'D4-A08AR12000001'},
|
||||
],
|
||||
line_count=1,
|
||||
@@ -59,9 +59,9 @@ def test_active_inventory_file_for_notice_uses_order_task_link(app, tmp_path) ->
|
||||
db.session.flush()
|
||||
assert int(notice.id) != int(ot.id)
|
||||
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
db.session.add(ShippingTaskOnhandLink(
|
||||
task_id=int(ot.id),
|
||||
inventory_file_id=int(inventory_file.id),
|
||||
onhand_file_id=int(inventory_file.id),
|
||||
is_active=True,
|
||||
access_mode='readonly',
|
||||
))
|
||||
@@ -92,12 +92,12 @@ def test_resolve_inventory_lines_for_notice_reads_owner_ot_frozen_candidates(app
|
||||
db.session.flush()
|
||||
|
||||
ot = ShippingOrderTask(task_no='OT-INV-NOTICE-CAND', user_id=1, source_type='direct_pdf')
|
||||
link_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INV-NOTICE-CAND-LINK',
|
||||
link_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-INV-NOTICE-CAND-LINK',
|
||||
storage_path='unused://notice-cand-link.xlsx',
|
||||
source_file_name='link-only.xlsx',
|
||||
snapshot_status='ready',
|
||||
inventory_lines_json=[{'part_number': 'ONLY_LINK_ROW'}],
|
||||
onhand_lines_json=[{'part_number': 'ONLY_LINK_ROW'}],
|
||||
line_count=1,
|
||||
)
|
||||
db.session.add_all([ot, link_file])
|
||||
@@ -113,9 +113,9 @@ def test_resolve_inventory_lines_for_notice_reads_owner_ot_frozen_candidates(app
|
||||
db.session.flush()
|
||||
assert int(notice.id) != int(ot.id)
|
||||
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
db.session.add(ShippingTaskOnhandLink(
|
||||
task_id=int(ot.id),
|
||||
inventory_file_id=int(link_file.id),
|
||||
onhand_file_id=int(link_file.id),
|
||||
is_active=True,
|
||||
access_mode='readonly',
|
||||
))
|
||||
@@ -123,7 +123,7 @@ def test_resolve_inventory_lines_for_notice_reads_owner_ot_frozen_candidates(app
|
||||
|
||||
# 冻结候选事实只挂在 OT 上;Notice 自身查不到任何冻结源。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
'app.services.shipping_notice.stp_onhand_freeze.task_frozen_onhand_source_codes',
|
||||
lambda task: ['SRC_A', 'SRC_B'] if isinstance(task, ShippingOrderTask) else [],
|
||||
)
|
||||
prepared_with = []
|
||||
@@ -139,7 +139,7 @@ def test_resolve_inventory_lines_for_notice_reads_owner_ot_frozen_candidates(app
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
|
||||
'app.services.shipping_notice.stp_line_onhand_match.prepare_candidate_onhand_lines',
|
||||
_fake_prepare,
|
||||
)
|
||||
|
||||
+5
-5
@@ -3,14 +3,14 @@
|
||||
逻辑:通过最小模型级约束检查和服务分支合同,禁止跨任务失效。
|
||||
"""
|
||||
|
||||
from app.models import ShippingInventoryMapping
|
||||
from app.models import FreightRpaOnhandMapping
|
||||
|
||||
|
||||
def test_mapping_status_contract_allows_invalidation_without_delete():
|
||||
"""Mapping 失效必须保留记录,状态使用正式 invalidated 枚举。"""
|
||||
allowed = next(
|
||||
constraint.sqltext.text
|
||||
for constraint in ShippingInventoryMapping.__table__.constraints
|
||||
for constraint in FreightRpaOnhandMapping.__table__.constraints
|
||||
if getattr(constraint, 'name', '') == 'ck_shipping_inventory_mapping_status'
|
||||
)
|
||||
assert 'invalidated' in allowed
|
||||
@@ -20,11 +20,11 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
|
||||
"""候选版本切换后,旧 Artifact 不可下载,未终态上传 Attempt 不得继续使用。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile,
|
||||
ShippingExcelTemplate, ShippingExportArtifact, FreightRpaParsingProfile,
|
||||
ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask, ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import _invalidate_task_candidate_outputs
|
||||
from app.services.shipping_notice.onhand_candidate_freeze_service import _invalidate_task_candidate_outputs
|
||||
|
||||
task = ShippingOrderTask(task_no='OT-CANDIDATE-INVALIDATE-1', user_id=1)
|
||||
notice = ShippingNotice(task_no='SN-CANDIDATE-INVALIDATE-1')
|
||||
@@ -33,7 +33,7 @@ def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
|
||||
status='published', storage_bucket='test', storage_key='template.xlsx',
|
||||
original_filename='template.xlsx', file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile = FreightRpaParsingProfile(
|
||||
profile_code='CANDIDATE-INVALIDATE', display_name='Candidate invalidate', version=1,
|
||||
status='published', file_format='xlsx', definition_json={},
|
||||
)
|
||||
+2
-2
@@ -7,8 +7,8 @@
|
||||
from datetime import datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint
|
||||
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
|
||||
from app.services.shipping_notice.onhand_combination_fingerprint import build_inventory_combination_fingerprint
|
||||
from app.services.shipping_notice.onhand_snapshot_reuse_policy import check_inventory_snapshot_reusable
|
||||
|
||||
|
||||
def test_snapshot_reuse_requires_ready_identity_and_versions():
|
||||
+6
-6
@@ -2,7 +2,7 @@
|
||||
tests/test_shipping_inventory_routing_engine.py
|
||||
|
||||
用途:验证库存源路由只消费冻结订单 Snapshot 中的已裁决字段值。
|
||||
依赖:订单 Schema service、库存路由模型、inventory_routing_engine。
|
||||
依赖:订单 Schema service、库存路由模型、onhand_routing_engine。
|
||||
逻辑:测试以稳定 field_id 创建冻结行事实,确认库存源线索优先于预定单号兜底且不会读取可变解析投影。
|
||||
"""
|
||||
|
||||
@@ -10,11 +10,11 @@ from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
|
||||
FreightRpaOnhandRoutingRule, FreightRpaOnhandRoutingRuleCondition, ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_routing_engine import (
|
||||
from app.services.shipping_notice.onhand_routing_engine import (
|
||||
evaluate_inventory_source_rules,
|
||||
evaluate_inventory_source_rules_for_field_values,
|
||||
)
|
||||
@@ -121,11 +121,11 @@ def _task_with_line_values(
|
||||
|
||||
def _rule(*, code: str, priority: int, sources: list[str], conditions: list[tuple[str, str, object]]):
|
||||
"""构造已发布的行级订单字段规则;禁止使用 system_fact 路径。"""
|
||||
return ShippingInventoryRoutingRule(
|
||||
return FreightRpaOnhandRoutingRule(
|
||||
rule_code=code, rule_name=code, scope='line', priority=priority, match_mode='all',
|
||||
status='published', action_type='add_source_candidates', action_payload_json={'source_codes': sources}, version=1,
|
||||
conditions=[
|
||||
ShippingInventoryRoutingRuleCondition(
|
||||
FreightRpaOnhandRoutingRuleCondition(
|
||||
condition_group=1, source_kind='order_field', order_field_id=field_id,
|
||||
operator=operator, expected_value_json=expected, sequence=index,
|
||||
)
|
||||
@@ -222,7 +222,7 @@ def test_five_digit_reservation_rule_can_route_to_crane(app):
|
||||
def _hint_sources(monkeypatch, codes):
|
||||
"""隔离线索解析的启用源清单(引擎自 list_database_inventory_sources 读取)。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_routing_engine.list_database_inventory_sources',
|
||||
'app.services.shipping_notice.onhand_routing_engine.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [{'source_code': code} for code in codes],
|
||||
)
|
||||
|
||||
+3
-3
@@ -2,7 +2,7 @@
|
||||
tests/test_shipping_inventory_source_adjudication.py
|
||||
|
||||
用途:锁定库存源裁决不得在 unresolved/空候选时兜底全部启用源,并采纳行级 ambiguous。
|
||||
依赖:inventory_source_rules、inventory_routing_engine、pytest monkeypatch。
|
||||
依赖:onhand_source_rules、onhand_routing_engine、pytest monkeypatch。
|
||||
逻辑:用可控引擎结果复现 OT-C68 类缺陷——行级 PREFIX 多候选被丢弃后膨胀为全源。
|
||||
"""
|
||||
|
||||
@@ -10,8 +10,8 @@ from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.inventory_routing_engine import InventoryRoutingResult
|
||||
from app.services.shipping_notice import inventory_source_rules as rules
|
||||
from app.services.shipping_notice.onhand_routing_engine import InventoryRoutingResult
|
||||
from app.services.shipping_notice import onhand_source_rules as rules
|
||||
|
||||
|
||||
def _source(code: str) -> dict:
|
||||
Loaded 100 of 453 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user