Merge branch 'dev' into order-delivery-reply
# Conflicts: # .env.shared # backend/app/api/chat.py # backend/app/core/config/settings.py # backend/app/models/user.py # backend/app/services/admin/permission_service.py # docs/demand.md # frontend/src/app/router/routes/workspace.routes.ts # frontend/src/features/admin/modules/users/components/UserFormModal.vue # frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts # frontend/src/features/admin/types/user.types.ts # frontend/src/features/auth/stores/auth.store.ts # frontend/src/features/user/views/UserProfilePage.vue # frontend/src/locales/en/admin.json # frontend/src/locales/en/errors.json # frontend/src/locales/th/admin.json # frontend/src/locales/th/errors.json # frontend/src/locales/zh-CN/admin.json # frontend/src/locales/zh-CN/errors.json # frontend/src/locales/zh-TW/admin.json # frontend/src/locales/zh-TW/errors.json # frontend/src/shared/utils/auth.ts
This commit is contained in:
commit
616034a4cd
541 files changed
+43805
-14767
No files matched your search
+29
-18
@@ -85,8 +85,8 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
return
|
||||
app = request.getfixturevalue("app")
|
||||
tmp_path = request.getfixturevalue("tmp_path")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
|
||||
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
|
||||
)
|
||||
if request.node.get_closest_marker("auto_rpa"):
|
||||
@@ -108,9 +108,9 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||||
app.config["ENV_NAME"] = "dev"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
|
||||
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
@@ -686,7 +686,12 @@ def client(app):
|
||||
|
||||
@pytest.fixture
|
||||
def dbs_ready_file() -> dict:
|
||||
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。"""
|
||||
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。
|
||||
|
||||
rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date),
|
||||
与真实仓库 movement_file_repository 产出一致(B5 接线后 run_precheck 按
|
||||
parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。
|
||||
"""
|
||||
return {
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
@@ -696,22 +701,25 @@ def dbs_ready_file() -> dict:
|
||||
"checksum": "d" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 10, "invoice_no": "INV-001", "material_no": "MAT-001",
|
||||
{"sheet": "Receipt", "row_no": 10, "doc_no": "INV-001", "material_code": "MAT-001",
|
||||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "500", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 11, "invoice_no": "INV-001", "material_no": "MAT-001",
|
||||
"movement_date": "2026-08-05", "quantity": "500", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 11, "doc_no": "INV-001", "material_code": "MAT-001",
|
||||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "700", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 20, "invoice_no": "INV-002", "material_no": "MAT-002",
|
||||
"movement_date": "2026-08-05", "quantity": "700", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 20, "doc_no": "INV-002", "material_code": "MAT-002",
|
||||
"material_name": "控制器组件", "specification": "标准型 / 48V",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "1200", "source_code": "DBS-AWSBI"},
|
||||
"movement_date": "2026-08-05", "quantity": "1200", "source_code": "DBS-AWSBI"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def crane_ready_file() -> dict:
|
||||
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。"""
|
||||
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。
|
||||
|
||||
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
|
||||
"""
|
||||
return {
|
||||
"source_code": "CRANE-SZ",
|
||||
"business_date": "2026-08-06",
|
||||
@@ -721,16 +729,19 @@ def crane_ready_file() -> dict:
|
||||
"checksum": "c" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Inbound", "row_no": 5, "invoice_no": "INV-008", "material_no": "MAT-200",
|
||||
{"sheet": "Inbound", "row_no": 5, "doc_no": "INV-008", "material_code": "MAT-200",
|
||||
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "600", "source_code": "CRANE-SZ"},
|
||||
"movement_date": "2026-08-05", "quantity": "600", "source_code": "CRANE-SZ"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def same_day_receipt_file() -> dict:
|
||||
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。"""
|
||||
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。
|
||||
|
||||
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
|
||||
"""
|
||||
return {
|
||||
"source_code": "DBS-AWSSG",
|
||||
"business_date": "2026-08-06",
|
||||
@@ -740,9 +751,9 @@ def same_day_receipt_file() -> dict:
|
||||
"checksum": "s" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 3, "invoice_no": "INV-041", "material_no": "MAT-041",
|
||||
{"sheet": "Receipt", "row_no": 3, "doc_no": "INV-041", "material_code": "MAT-041",
|
||||
"material_name": "连接器组件", "specification": "C 型",
|
||||
"receipt_date": "2026-08-06", "receipt_quantity": "400", "source_code": "DBS-AWSSG"},
|
||||
"movement_date": "2026-08-06", "quantity": "400", "source_code": "DBS-AWSSG"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,42 @@ from app.jobs.context import JobContext
|
||||
from app.jobs.handlers.schedule_run import run_schedule
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.queue_service import enqueue_due_schedule_runs, enqueue_manual_schedule_run
|
||||
from app.services.schedule.queue_service import (
|
||||
enqueue_due_schedule_runs,
|
||||
enqueue_manual_schedule_run,
|
||||
prepare_schedule_queue,
|
||||
)
|
||||
|
||||
|
||||
def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycle(app, monkeypatch):
|
||||
"""关键断言:调拨来源等待回调 Job 的超时回收每轮领取都执行,不只在 worker 启动时扫一次。
|
||||
|
||||
[STEP 1] 用计数桩替换 receipt_callback_bridge.recover_stale_waiting_source_jobs(queue_service
|
||||
在函数体内延迟 import,桩生效)并复位 _worker_initialized,隔离模块级启动标记。
|
||||
[STEP 2] 连续两轮调用真实 prepare_schedule_queue(空库下其余恢复均为 no-op)。
|
||||
[STEP 3] 第二轮后计数必须为 2:若回收仍挂在启动一次性分支,第二次调用不会触发,计数停留 1。
|
||||
"""
|
||||
from app.services.in_transit_transfer import receipt_callback_bridge
|
||||
from app.services.schedule import queue_service
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat_alert
|
||||
|
||||
calls: list[int] = []
|
||||
|
||||
def _fake_recover() -> int:
|
||||
calls.append(1)
|
||||
return 0
|
||||
|
||||
def _fake_heartbeat(**_kwargs):
|
||||
return {"skipped": True, "reason": "test_stub"}
|
||||
|
||||
monkeypatch.setattr(receipt_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
|
||||
monkeypatch.setattr(rpa_worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
|
||||
monkeypatch.setattr(queue_service, "_worker_initialized", False)
|
||||
|
||||
assert prepare_schedule_queue() == 0
|
||||
assert len(calls) == 1 # 第一轮:启动 + 每轮维护都应触发回收
|
||||
assert prepare_schedule_queue() == 0
|
||||
assert len(calls) == 2 # 第二轮:回收仍须执行(修复前停留 1,此处为核心回归断言)
|
||||
|
||||
|
||||
def _create_task(*, due: bool = False, platform_api_path: str | None = None, name: str = "schedule queue test") -> ScheduleTask:
|
||||
|
||||
@@ -158,7 +158,7 @@ def _published_route_field_id() -> str:
|
||||
|
||||
def test_profile_credentials_are_not_returned(app):
|
||||
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
assert payload['password_configured'] is True
|
||||
@@ -169,7 +169,7 @@ def test_profile_credentials_are_not_returned(app):
|
||||
|
||||
def test_profile_rejects_page_operation_configuration(app):
|
||||
"""货代登录连接不得保存报表路径、selector 或下载策略,防止连接越界成为业务配置源。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = _profile_data()
|
||||
payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}}
|
||||
@@ -180,7 +180,7 @@ def test_profile_rejects_page_operation_configuration(app):
|
||||
|
||||
def test_multiple_dbs_profiles_bind_independent_sources(app):
|
||||
"""同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
@@ -192,7 +192,7 @@ def test_multiple_dbs_profiles_bind_independent_sources(app):
|
||||
|
||||
def test_source_rejects_profile_connector_mismatch(app):
|
||||
"""库存源不能绑定不同 Driver 的 Profile。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
@@ -202,7 +202,7 @@ def test_source_rejects_profile_connector_mismatch(app):
|
||||
|
||||
def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
|
||||
"""禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
payload = _source_data(login['id'], code='DRAFT_SOURCE')
|
||||
@@ -227,7 +227,7 @@ def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
|
||||
|
||||
def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
|
||||
"""普通保存只能保留停用站点;独立启用动作必须返回尚未完成的测试步骤。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
payload = _source_data(login['id'], code='ACTIVATION_SOURCE')
|
||||
@@ -250,7 +250,7 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
|
||||
|
||||
def test_activation_status_exposes_structured_checks_without_duplicate_test_blocks(app):
|
||||
"""未测试站点应显示后续验证步骤,但只由测试门禁阻断,避免管理员面对重复待办。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
payload = {
|
||||
@@ -279,7 +279,7 @@ def test_activation_status_exposes_structured_checks_without_duplicate_test_bloc
|
||||
|
||||
def test_enabled_source_rejects_disabled_rpa_profile(app):
|
||||
"""启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(
|
||||
{**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None,
|
||||
@@ -291,7 +291,7 @@ def test_enabled_source_rejects_disabled_rpa_profile(app):
|
||||
|
||||
def test_dbs_source_persists_report_path_parameters_and_aliases(app):
|
||||
"""数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
@@ -303,11 +303,11 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app):
|
||||
|
||||
def test_source_rejects_driver_selector_in_business_parameters(app):
|
||||
"""业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
payload = _source_data(profile['id'])
|
||||
payload['query_parameters_json'][0]['selector_env'] = 'SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
|
||||
payload['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'
|
||||
@@ -315,7 +315,7 @@ def test_source_rejects_driver_selector_in_business_parameters(app):
|
||||
|
||||
def test_crane_source_rejects_dbs_report_path(app):
|
||||
"""动态仓 Crane 库存源不得误填 DBS 四级报表路径。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
payload = _source_data(profile['id'], code='CRANE', connector_type='crane')
|
||||
@@ -328,7 +328,7 @@ def test_crane_source_rejects_dbs_report_path(app):
|
||||
|
||||
def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app):
|
||||
"""停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE')
|
||||
@@ -357,7 +357,7 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a
|
||||
|
||||
def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app):
|
||||
"""批量绑定必须先全量预检;已启用站点阻断时其余站点不能部分写入。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED')
|
||||
@@ -380,7 +380,7 @@ def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app):
|
||||
|
||||
def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app):
|
||||
"""直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE')
|
||||
@@ -407,7 +407,7 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app
|
||||
|
||||
def test_published_rule_cannot_be_mutated_in_place(app):
|
||||
"""发布规则必须依靠新版本演进,避免改写历史任务依据。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
@@ -469,7 +469,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
|
||||
|
||||
def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
|
||||
"""未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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'])
|
||||
@@ -500,7 +500,7 @@ def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
|
||||
|
||||
def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
|
||||
"""发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
@@ -535,7 +535,7 @@ def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
|
||||
|
||||
def test_active_default_external_mapping_is_unique_per_source(app):
|
||||
"""同一库存源只能有一条启用的默认外部系统映射。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
@@ -550,7 +550,7 @@ def test_active_default_external_mapping_is_unique_per_source(app):
|
||||
|
||||
def test_external_mapping_normalizes_freight_warehouse_identity(app):
|
||||
"""配置端小写货代仓应与库存行大写 Warehouse 使用同一精确映射身份。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
@@ -564,7 +564,7 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app):
|
||||
|
||||
def test_upload_config_change_does_not_bump_rpa_profile_version(app):
|
||||
"""连接级上传配置(upload_config_json)变更不递增 config_version。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
base_version = profile['config_version']
|
||||
|
||||
@@ -13,6 +13,7 @@ import pytest
|
||||
from openpyxl import Workbook
|
||||
|
||||
from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows
|
||||
from app.services.in_transit_transfer.file_parser import parse_movement_rows
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
@@ -44,7 +45,7 @@ def _movement_xlsx_bytes() -> bytes:
|
||||
|
||||
|
||||
def test_extract_movement_rows_maps_columns_to_domain_fields():
|
||||
"""表头别名被映射为定死领域字段 code 的行字段。"""
|
||||
"""表头别名被映射为定死领域字段 code 的行字段,并携带真实溯源 sheet/row_no。"""
|
||||
rows = _extract_movement_rows(
|
||||
_movement_xlsx_bytes(),
|
||||
field_mapping=MOVEMENT_MAPPING,
|
||||
@@ -59,6 +60,17 @@ def test_extract_movement_rows_maps_columns_to_domain_fields():
|
||||
assert str(first['movement_date']) == '2026-08-05'
|
||||
second = rows[1]
|
||||
assert second['quantity'] == 300
|
||||
# [断言意图] 溯源字段必须指向真实电子表格位置:sheet=实际工作表标题,
|
||||
# row_no=工作表 1-based 行号(表头第 1 行 → 数据行在第 2/3 行)。
|
||||
assert first['sheet'] == 'Movement'
|
||||
assert second['sheet'] == 'Movement'
|
||||
assert first['row_no'] == 2
|
||||
assert second['row_no'] == 3
|
||||
# [断言意图] 仓库产出直连解析器:含溯源字段的行必须通过 parse_movement_rows
|
||||
# 行校验(不出现 missing_sheet_or_row_no 整链阻断),证据行号透传到解析行。
|
||||
parsed = parse_movement_rows(source_code='DBS-AWSBI', rows=rows)
|
||||
assert [row.row_no for row in parsed] == [2, 3]
|
||||
assert [row.invoice_no for row in parsed] == ['MOV-001', 'MOV-001']
|
||||
|
||||
|
||||
def test_extract_movement_rows_skips_missing_alias_columns():
|
||||
@@ -79,3 +91,6 @@ def test_extract_movement_rows_skips_missing_alias_columns():
|
||||
assert rows[0]['doc_no'] == 'MOV-9'
|
||||
assert rows[0]['quantity'] == 120
|
||||
assert 'movement_date' not in rows[0]
|
||||
# 部分映射下溯源字段仍在:sheet/row_no 不依赖业务列是否齐全。
|
||||
assert rows[0]['sheet'] == 'S'
|
||||
assert rows[0]['row_no'] == 2
|
||||
@@ -13,6 +13,7 @@ import pytest
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpAdapter
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
create_precheck,
|
||||
restore_precheck,
|
||||
@@ -162,3 +163,26 @@ def test_route_not_resolved_marks_source_failed(dbs_ready_file):
|
||||
by_source = {stage.source_code: stage for stage in result.sources}
|
||||
assert by_source["DBS-AWSBI"].stage == "failed"
|
||||
assert by_source["CRANE-SZ"].stage == "waiting_rpa_callback" # 无文件 → 等待,不阻断
|
||||
|
||||
|
||||
def test_run_precheck_consumes_movement_field_rows(app):
|
||||
"""run_precheck 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。"""
|
||||
# [断言意图] 真实仓库 rows 以 doc_no/material_code/quantity/movement_date 为键;
|
||||
# 预检应正确产出 executable 明细而非 ReceiptFileSchemaError
|
||||
# 注:sheet/row_no 为解析校验必带的溯源字段(与 parse_movement_rows 契约一致,同校验)。
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [{
|
||||
"sheet": "Movement", "row_no": 1,
|
||||
"doc_no": "INV-1", "material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(erp_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_inventory("INV-1", 5) # FakeERP 按 invoice_no 键维护账面库存
|
||||
result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
item = next(i for i in result.items if i.invoice_no == "INV-1")
|
||||
assert item.result == "executable"
|
||||
@@ -0,0 +1,55 @@
|
||||
"""收料回调桥与超时回收测试。
|
||||
|
||||
用途:验证收料回调终态能推进调拨 waiting_rpa_callback 来源任务(Task 6),
|
||||
以及超时未回调的任务被回收为 failed(Task 8)。
|
||||
依赖:app(SQLite)fixture、TransferSourceJob/TransferRun 工厂、回调桥函数。
|
||||
逻辑:成功带文件 → file_ready;失败/空数据 → failed 带错误码;桥内异常不外抛。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import TransferSourceJob, TransferRun
|
||||
from app.services.in_transit_transfer.receipt_callback_bridge import (
|
||||
advance_source_job_from_receipt_callback,
|
||||
)
|
||||
|
||||
|
||||
def _make_waiting_job(run_no: str, source_code: str = "DSV360_AWSDU") -> TransferSourceJob:
|
||||
"""造一个处于 waiting_rpa_callback 的来源任务(status/trigger_type 必须取冻结枚举值)。"""
|
||||
run = TransferRun(run_no=run_no, business_date="2026-09-17", status="preparing_files", trigger_type="manual")
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
job = TransferSourceJob(run_id=run.id, source_code=source_code, status="waiting_rpa_callback")
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
return job
|
||||
|
||||
|
||||
def test_success_callback_advances_job_to_file_ready(app):
|
||||
"""成功回调(含文件号/sha256)应把最新等待任务推进为 file_ready。"""
|
||||
job = _make_waiting_job("RUN-BRIDGE-1")
|
||||
advanced = advance_source_job_from_receipt_callback(
|
||||
source_code=job.source_code, file_no="42", file_sha256="abc", callback_ok=True,
|
||||
)
|
||||
assert advanced is not None and advanced.status == "file_ready"
|
||||
assert advanced.file_no == "42" and advanced.file_sha256 == "abc"
|
||||
assert advanced.finished_at is not None
|
||||
|
||||
|
||||
def test_recover_stale_waiting_source_jobs(app):
|
||||
"""超过收料回调超时的等待任务回收为 failed;新任务不动。"""
|
||||
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
|
||||
|
||||
stale = _make_waiting_job("RUN-BRIDGE-STALE-1", "DSV360_AWSDU")
|
||||
stale.updated_at = datetime.utcnow() - timedelta(seconds=3600)
|
||||
fresh = _make_waiting_job("RUN-BRIDGE-STALE-2", "DSV360_AWSSG")
|
||||
assert fresh.updated_at > datetime.utcnow() - timedelta(seconds=60)
|
||||
recovered = recover_stale_waiting_source_jobs()
|
||||
db.session.expire_all()
|
||||
assert recovered == 1
|
||||
assert db.session.get(TransferSourceJob, stale.id).status == "failed"
|
||||
assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_RECEIPT_CALLBACK_TIMEOUT"
|
||||
assert db.session.get(TransferSourceJob, fresh.id).status == "waiting_rpa_callback"
|
||||
@@ -1,7 +1,8 @@
|
||||
"""真实收料 RPA 触发服务测试。
|
||||
|
||||
用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者;
|
||||
配置/来源/触发目录缺失时 fail-closed(ok=False)。
|
||||
触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
|
||||
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、
|
||||
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
|
||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。
|
||||
@@ -21,9 +22,9 @@ def receipt_source():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
assert source is not None
|
||||
config = ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
inventory_source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
query_parameters_json=[], warehouse_ids_json=[],
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
|
||||
)
|
||||
from app import db
|
||||
|
||||
@@ -50,6 +51,8 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
|
||||
assert result['callback_id']
|
||||
assert result['trigger_path'].endswith('.json')
|
||||
assert calls['units'][0]['source_code'] == 'DSV360_AWSDU'
|
||||
# 关键断言:按需触发取 Warehouse 条件的第一个仓作为拆分维度。
|
||||
assert calls['units'][0]['warehouse_id'] == 'AWSDU'
|
||||
assert calls['units'][0]['credential_envelope']
|
||||
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
|
||||
@@ -70,3 +73,56 @@ def test_trigger_receipt_rpa_missing_config_fails_closed(app):
|
||||
"""来源启用但无收料配置 → ok=False。"""
|
||||
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
|
||||
assert result['ok'] is False
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
|
||||
"""触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
# [断言意图] writer 收到的载荷必须携带真实 unit.id——
|
||||
# 单元行先 flush 拿 id,再序列化进 trigger,回调才能按 callback_id 找到单元。
|
||||
captured["units"] = units
|
||||
return "trigger.json"
|
||||
|
||||
outcome = trigger_receipt_rpa(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17",
|
||||
reason="transfer_retry_receipt", writer=fake_writer,
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
|
||||
assert unit.status == "awaiting_rpa"
|
||||
assert unit.schedule_run_id == 0 # 调拨触发无排程 run,沿用 0 占位约定
|
||||
assert captured["units"][0]["unit_run_id"] == unit.id
|
||||
assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id
|
||||
|
||||
|
||||
def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""deps 默认触发器必须真写 trigger 文件,不得只查配置就返回 ok=True(B1 断线根因)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
# [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
outcome = trigger_receipt_rpa(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17",
|
||||
reason="transfer_retry_receipt", 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()
|
||||
assert unit.status == "failed"
|
||||
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
|
||||
@@ -0,0 +1,384 @@
|
||||
"""
|
||||
backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py
|
||||
|
||||
用途:验证客户识别三级命中(canonical 等值 > 完整包含 > 截断包含)与受控自动确认边界。
|
||||
依赖:内存数据库、customer_normalization、identity_resolution.resolver、
|
||||
customer_auto_resolution、customer_shadow_resolution。
|
||||
逻辑:以 QCH/Quanta 真实差异形态(标点变体、c/o 截断、折行块整段提取、家族前缀、
|
||||
跨行 vs 单行证据)构造分支,断言影子候选层级、状态语义,以及自动确认只放行
|
||||
「等值唯一」与「完整包含唯一且证据授权」,截断建议永不自动确认。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_auto_resolution import resolve_auto_customer_decision
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
IDENTITY_MATCH_CONTAINMENT_STRONG,
|
||||
IDENTITY_MATCH_CONTAINMENT_WEAK,
|
||||
IDENTITY_MATCH_EQUALITY,
|
||||
canonical_identity_key,
|
||||
classify_identity_containment,
|
||||
normalize_identity_evidence_value,
|
||||
)
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
from app.services.shipping_notice.identity_resolution import resolve_candidate_identity
|
||||
|
||||
FIELD_ID = 'fid-ship-to-customer'
|
||||
RULE_SET_DEF_ID = 'def-ship-to-customer'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestCanonicalIdentityKey:
|
||||
"""canonical 键:标点/空白/大小写不敏感,中文保留。"""
|
||||
|
||||
def test_punctuation_whitespace_case_insensitive(self):
|
||||
# 关键断言:QCH 注册值与 PDF 打印值的标点/空格差异不再分裂等值命中。
|
||||
assert canonical_identity_key('QCH, INC., A NEVADA CORPORATION') == canonical_identity_key(
|
||||
'qch inc a nevada corporation',
|
||||
)
|
||||
|
||||
def test_keeps_cjk_word_chars(self):
|
||||
# 关键断言:中文客户名不被剔除,仍可参与等值比较。
|
||||
assert canonical_identity_key('英業達股份有限公司桃科廠') == '英業達股份有限公司桃科廠'
|
||||
assert canonical_identity_key('Inventec 英業達') == 'inventec英業達'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestNormalizeIdentityEvidenceValue:
|
||||
"""识别证据统一归一化:三处调用点同源,兜底分支折叠内部空白。"""
|
||||
|
||||
def test_fallback_collapses_newlines(self):
|
||||
# 关键断言:多行提取值折叠换行后可与单行注册证据等值(修复换行不对称缺陷)。
|
||||
assert normalize_identity_evidence_value('QUANTA MFG,\n1 WALDENBOOKS DR.') == 'QUANTA MFG, 1 WALDENBOOKS DR.'
|
||||
|
||||
def test_name_normalizer_strips_punctuation(self):
|
||||
assert normalize_identity_evidence_value('Hyve, Solutions', normalizer_key='name') == 'HYVESOLUTIONS'
|
||||
|
||||
def test_email_branch_keeps_semantic_chars(self):
|
||||
assert normalize_identity_evidence_value('A@B.COM', option_key='from_email') == 'a@b.com'
|
||||
|
||||
def test_blank_returns_none(self):
|
||||
assert normalize_identity_evidence_value(' ') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestClassifyIdentityContainment:
|
||||
"""双向包含分级:强=指纹完整出现;弱=提取值疑似截断;邮箱/域名不参与。"""
|
||||
|
||||
EVIDENCE = 'QCH INC., A NEVADA CORPORATION C/O QUANTA'
|
||||
|
||||
def test_strong_when_fingerprint_fully_inside_runtime(self):
|
||||
# 关键断言:折行块整段进入字段值时,完整指纹命中判强包含(可受控自动确认)。
|
||||
assert classify_identity_containment(
|
||||
'QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC', self.EVIDENCE,
|
||||
) == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_weak_when_runtime_is_truncation(self):
|
||||
# 关键断言:截断方向只判弱命中——剩余部分未经验证,禁止自动确认。
|
||||
assert classify_identity_containment(
|
||||
'QCH, INC., A NEVADA CORPORATION c/o', self.EVIDENCE,
|
||||
) == IDENTITY_MATCH_CONTAINMENT_WEAK
|
||||
|
||||
def test_fragment_below_minimum_chars_rejected(self):
|
||||
# 关键断言:'c/o'→'CO' 这类短碎片不得产生包含噪声。
|
||||
assert classify_identity_containment('c/o', self.EVIDENCE) is None
|
||||
|
||||
def test_email_domain_never_contained(self):
|
||||
assert classify_identity_containment('ops@corp.com', 'ops@corp', option_key='from_email') is None
|
||||
|
||||
def test_unrelated_values_rejected(self):
|
||||
assert classify_identity_containment('HYVE SOLUTIONS CORPORATION', self.EVIDENCE) is None
|
||||
|
||||
|
||||
def _build_identity_world(*, runtime_value: str, evidences: list[dict]):
|
||||
"""
|
||||
构建最小识别世界:发布规则集 + 单 Header 字段抽取链 + 客户/证据主数据。
|
||||
|
||||
Args:
|
||||
runtime_value: 已裁决 Header 字段值(模拟 PDF 提取结果)。
|
||||
evidences: 注册证据列表,每项含 customer_name/short_code/normalized_value,
|
||||
可选 auto(默认 True,对应 auto_match_allowed)。
|
||||
Returns:
|
||||
(candidate, intake) 供 resolve_candidate_identity / 影子刷新使用。
|
||||
"""
|
||||
user = User(username='tier-user', email='tier@example.com', role='user')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', lock_version=1, checksum='1' * 64,
|
||||
definition_json={'fields': [{
|
||||
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'display_name': 'Ship To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'trim',
|
||||
}]},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
definition_json = {
|
||||
'order_schema': {'id': version.id, 'version': version.version, 'checksum': version.checksum},
|
||||
'definitions': [{
|
||||
'id': RULE_SET_DEF_ID, 'definition_code': 'ship_to_customer_rule',
|
||||
'display_name': 'Ship To Customer', 'evidence_label': 'Ship To',
|
||||
'target_type': 'customer', 'context_field_id': FIELD_ID,
|
||||
'default_weight': 100, 'max_automation': 'conditional', 'status': 'active',
|
||||
'field_config': {
|
||||
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'scope': 'header',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
'context_source': {'provider': 'order_field', 'option_key': None},
|
||||
'available_for_customer_identity': True,
|
||||
},
|
||||
}],
|
||||
}
|
||||
db.session.add(ShippingIdentityRuleSet(version=1, status='published', definition_json=definition_json, checksum='c' * 64))
|
||||
db.session.add(ShippingIdentityDefinition(
|
||||
id=RULE_SET_DEF_ID, definition_code='ship_to_customer_rule', target_type='customer',
|
||||
context_field_id=FIELD_ID, default_weight=100, max_automation='conditional', status='active',
|
||||
))
|
||||
intake = ShippingOrderIntake(intake_no='INT-TIER', asset_id=1, user_id=user.id, parser_version='test')
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
intake_id=intake.id, schema_version_id=version.id, input_snapshot_hash='h' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, field_id=FIELD_ID, decision_status='accepted', decided_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, field_id=FIELD_ID, decision_id=decision.id, value_text=runtime_value,
|
||||
))
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-TIER', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key='tier-test', candidate_status='accepted', order_extraction_id=extraction.id,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
for index, spec in enumerate(evidences, start=1):
|
||||
customer = ShippingCustomer(
|
||||
standard_name=spec['customer_name'], short_code=spec['short_code'], status='active',
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingIdentityEvidence(
|
||||
definition_id=RULE_SET_DEF_ID, customer_id=customer.id,
|
||||
raw_value=spec['normalized_value'], normalized_value=spec['normalized_value'],
|
||||
status='approved', auto_match_allowed=spec.get('auto', True),
|
||||
))
|
||||
db.session.commit()
|
||||
return candidate, intake
|
||||
|
||||
|
||||
class TestResolverTierMatching:
|
||||
"""影子识别三级命中与状态语义(resolve_candidate_identity)。"""
|
||||
|
||||
def test_punctuation_variant_hits_equality_tier(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:'QCH,' vs 'QCH' 标点差异经 canonical 等值命中,不再是 unmatched。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
|
||||
def test_truncated_runtime_becomes_weak_suggestion(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:c/o 截断形态产出唯一弱命中候选(unique_candidate 仅表示展示层唯一),
|
||||
# match_kind=containment_weak,交由人工确认。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_WEAK
|
||||
|
||||
def test_wrapped_block_hits_strong_containment(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:折行块整段提取时完整指纹出现,判强包含。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_family_prefix_stays_ambiguous(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:家族共享前缀同时包含命中 QCG/TW 两个站点客户 → ambiguous,不取首条。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='Quanta Computer Inc.',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'QUANTA QCG', 'short_code': 'QCG',
|
||||
'normalized_value': 'QUANTA COMPUTER INC. DE 2470.58.340',
|
||||
},
|
||||
{
|
||||
'customer_name': 'QUANTA TW', 'short_code': 'TWQ',
|
||||
'normalized_value': 'QUANTA COMPUTER INC. HQ PLANT',
|
||||
},
|
||||
],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'ambiguous'
|
||||
assert {item['match_kind'] for item in result['customer_matches']} == {IDENTITY_MATCH_CONTAINMENT_WEAK}
|
||||
|
||||
def test_equality_beats_containment_in_order(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:等值候选排在包含候选之前,且顶层唯一时状态为 unique_candidate。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
|
||||
'normalized_value': 'WISTRON CORPORATION',
|
||||
},
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
|
||||
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
},
|
||||
],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
names = {item['standard_name']: item for item in result['customer_matches']}
|
||||
# 关键断言:等值候选排第一,强包含候选次之;强层级唯一 → unique_candidate。
|
||||
assert result['customer_matches'][0]['standard_name'] == 'WIWYNN CZ BRNO'
|
||||
assert names['WIWYNN CZ BRNO']['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
assert names['WIWYNN CZ']['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_multiline_runtime_matches_single_line_evidence(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:运行侧换行折叠修复后,跨行提取值可与单行注册证据等值命中。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='Quanta Manufacturing Nashville, LLC,\n1 Waldenbooks Dr.',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QUANTA MANUFACTURING NASHVILLE, LLC, 1 WALDENBOOKS DR.',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
|
||||
|
||||
class TestAutoConfirmDecision:
|
||||
"""自动确认分级裁决(resolve_auto_customer_decision)。"""
|
||||
|
||||
def _shadow(self, candidate):
|
||||
return refresh_candidate_shadow_resolution(candidate)
|
||||
|
||||
def test_equality_unique_confirms_strong(self, app):
|
||||
with app.app_context():
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_strong_match'
|
||||
assert decision['customer_id'] is not None
|
||||
|
||||
def test_containment_strong_unique_confirms_with_match_kind(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:指纹完整出现的唯一包含命中且证据授权 → unique_containment_match,
|
||||
# 审计证据带 match_kind=containment_strong 溯源。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_containment_match'
|
||||
assert decision['customer_id'] is not None
|
||||
assert decision['evidence'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_truncation_only_never_confirms(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:截断形态(本单 7911678818.PDF)永不自动确认,保持 unmatched 交人工。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unmatched'
|
||||
assert decision['customer_id'] is None
|
||||
|
||||
def test_unauthorized_evidence_never_confirms(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:auto_match_allowed=False 的证据即使等值唯一也不自动确认。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION', 'auto': False,
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unmatched'
|
||||
assert decision['customer_id'] is None
|
||||
|
||||
def test_equality_precedes_containment(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:等值命中存在时包含命中不参与裁决,等值客户唯一即确认。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
|
||||
'normalized_value': 'WISTRON CORPORATION',
|
||||
},
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
|
||||
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
},
|
||||
],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_strong_match'
|
||||
customers = {c.id: c.standard_name for c in ShippingCustomer.query.all()}
|
||||
assert customers[decision['customer_id']] == 'WIWYNN CZ BRNO'
|
||||
@@ -235,6 +235,180 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
|
||||
assert bundle['user_status'] == 'waiting_human'
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [BR] blocking_reason 资格快照回退:
|
||||
# automation 无具体原因码时,回退到草稿校验快照(validation_result_json)
|
||||
# 中首要 blocking issue 的冻结 explainability 透传(code/message/next_action),
|
||||
# 让批次中心与工作台展示具体原因,而非「当前步骤需要人工处理」兜底。
|
||||
# ============================================================
|
||||
|
||||
def _validation_snapshot_with_issues(issues: list[dict]) -> dict:
|
||||
"""构造与 order_build_eligibility 持久化结构一致的 validation 快照。"""
|
||||
return {'can_build': False, 'can_auto_create': False, 'issues': issues}
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_falls_back_to_primary_validation_issue_when_automation_lacks_reason():
|
||||
"""[BR-1] automation 无具体原因码时,blocking_reason 必须回退到首要 blocking issue。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
'message': '客户尚未确认',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
# 断言意图:透传冻结契约的事实三元组,前端据此展示「客户尚未确认 / 确认客户」
|
||||
assert reason['code'] == 'customer_unresolved'
|
||||
assert reason['message'] == '客户尚未确认'
|
||||
assert reason['next_action'] == 'confirm_customer'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_validation_fallback_skips_degraded_and_non_blocking_issues():
|
||||
"""[BR-2] 降级码(unknown_business_failure)与非 blocking issue 不进入回退。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
# 仅阻断自动建单,不属用户阻断
|
||||
{
|
||||
'code': 'candidate_qualification_blocked',
|
||||
'severity': 'auto_create_blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'llm_path_cannot_auto_freeze',
|
||||
'message': '智能识别结果尚未通过自动建单资格检查',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
# 契约降级码:不透传给用户
|
||||
{
|
||||
'code': 'weird_new_issue',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'unknown_business_failure',
|
||||
'message': '业务处理失败,请凭请求编号联系管理员',
|
||||
'next_action': '',
|
||||
},
|
||||
},
|
||||
# 首个可用 blocking issue
|
||||
{
|
||||
'code': 'required_field_missing',
|
||||
'severity': 'blocking',
|
||||
'field_code': 'reservation_id',
|
||||
'explainability': {
|
||||
'reason_code': 'required_field_missing',
|
||||
'message': '缺少创建订单所需字段',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'required_field_missing'
|
||||
assert reason['next_action'] == 'open_order_review'
|
||||
assert reason['details'].get('field_code') == 'reservation_id'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_keeps_mapped_automation_reason_over_validation_fallback(monkeypatch):
|
||||
"""[BR-3] automation 已有映射的具体原因码时不回退,避免覆盖更精确的裁决。"""
|
||||
from app.services.shipping_notice import reconciliation_projector
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
monkeypatch.setattr(
|
||||
reconciliation_projector,
|
||||
'project_case_automation_status',
|
||||
lambda case, *, validation, post_confirm: {
|
||||
'status': 'manual_fallback',
|
||||
'retryable': False,
|
||||
'reason_code': 'duplicate_decision_required',
|
||||
},
|
||||
)
|
||||
bundle = reconciliation_projector.project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'duplicate_decision_required'
|
||||
assert reason.get('message') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_without_usable_issues_keeps_legacy_blocking_reason():
|
||||
"""[BR-4] 快照无可用 issue 时保持既有兜底行为(不得抛错、不得造原因)。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation={'can_build': True, 'can_auto_create': True, 'issues': []},
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert isinstance(reason, dict)
|
||||
assert reason.get('message') is None
|
||||
assert reason.get('next_action') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_unmapped_automation_reason_uses_existing_generic_i18n_key():
|
||||
"""[BR-5] 未映射原因码的 fail-closed 兜底必须指向前端真实存在的键。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_blocking_reason,
|
||||
)
|
||||
|
||||
reason = project_case_blocking_reason({
|
||||
'status': 'manual_fallback',
|
||||
'reason_code': 'totally_new_unmapped_code',
|
||||
})
|
||||
|
||||
assert reason['code'] == 'totally_new_unmapped_code'
|
||||
# 此前指向不存在的 shipping.review.blocked_generic,任何未映射码都会双重落空
|
||||
assert reason['i18n_key'] == 'chat.shippingProcessing.reasonCode.unknown'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task():
|
||||
"""字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。"""
|
||||
|
||||
@@ -29,15 +29,16 @@ def _create_users() -> None:
|
||||
|
||||
|
||||
def _dbs_payload() -> dict:
|
||||
"""构造 DBS 收料配置;日期未出现表示保持系统页面默认 NULL。"""
|
||||
"""构造 DBS 收料配置;Warehouse 条件即逐仓拆分维度,日期未出现表示保持系统页面默认 NULL。"""
|
||||
return {
|
||||
'enabled': True,
|
||||
'report_path_json': {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
|
||||
},
|
||||
'warehouse_ids_json': ['AWSDU', 'AWSDU-02'],
|
||||
'query_parameters_json': [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}],
|
||||
'query_parameters_json': [
|
||||
{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['AWSDU', 'AWSDU-02'], 'required': False, 'select_all': False},
|
||||
{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +66,9 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
)
|
||||
assert response.status_code == 200
|
||||
config = parse_api_data(response.get_json())
|
||||
assert config['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
# 关键断言:Warehouse 条件原样保存,作为逐仓拆分维度的唯一持久化位置。
|
||||
warehouse_condition = next(item for item in config['query_parameters_json'] if item['name'] == 'Warehouse')
|
||||
assert warehouse_condition['values'] == ['AWSDU', 'AWSDU-02']
|
||||
assert config['report_path_json']['report_group'] == 'Inbound'
|
||||
|
||||
with app.app_context():
|
||||
@@ -78,7 +81,7 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
|
||||
).one()
|
||||
assert audit.before_snapshot_json is None
|
||||
assert audit.after_snapshot_json['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
assert audit.after_snapshot_json['query_parameters_json'][0]['values'] == ['AWSDU', 'AWSDU-02']
|
||||
|
||||
|
||||
def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, client):
|
||||
@@ -120,9 +123,40 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
# 关键断言:Warehouse 条件即逐仓拆分维度——缺失、重复、空值都必须拒绝。
|
||||
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',
|
||||
json=missing_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
duplicate_warehouse = _dbs_payload()
|
||||
duplicate_warehouse['query_parameters_json'] = [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU-02'], 'required': False, 'select_all': False},
|
||||
]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=duplicate_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
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',
|
||||
json=empty_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
invalid_crane = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Other Report'},
|
||||
'warehouse_ids_json': ['NOT-ALLOWED'], 'query_parameters_json': [],
|
||||
'report_path_json': {'report_name': 'Other Report'},
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
@@ -153,7 +187,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
crane_id = crane_source.id
|
||||
|
||||
default_query = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Inbound Details'}, 'warehouse_ids_json': [],
|
||||
'report_path_json': {'report_name': 'Inbound Details'},
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
|
||||
@@ -19,7 +19,7 @@ def test_agent_type_catalog_contains_three_seed_types():
|
||||
"""Catalog 应包含 generic、shipping_notice、file_check 等注册类型(含后续扩展)。"""
|
||||
assert {
|
||||
'generic', 'shipping_notice', 'file_check',
|
||||
'procurement_contract_review', 'in_transit_transfer',
|
||||
'procurement_contract_review', 'in_transit_transfer', 'contract_payment', 'voucher_check',
|
||||
} <= set(AGENT_TYPE_CATALOG.keys())
|
||||
|
||||
|
||||
@@ -28,12 +28,14 @@ def test_list_type_catalog_includes_agent_code_and_label():
|
||||
catalog = list_type_catalog()
|
||||
assert len(catalog) >= 5
|
||||
codes = {entry['agent_code'] for entry in catalog}
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer'} <= codes
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer', 'contract_payment', 'voucher_check'} <= codes
|
||||
labels = {entry['label'] for entry in catalog}
|
||||
assert '通用问答 / 知识库' in labels
|
||||
assert '在途仓自动调拨' in labels
|
||||
assert '货代发货通知' in labels
|
||||
assert '文件检核' in labels
|
||||
assert '合同付款预警' in labels
|
||||
assert '立账凭证' in labels
|
||||
|
||||
|
||||
def test_get_catalog_entry_returns_runtime_handler_for_hybrid_types():
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_agent_registry_contract_payment.py
|
||||
|
||||
用途:验证 contract_payment 已注册为 builtin Chat Agent 类型。
|
||||
依赖:catalog_loader / catalog_bindings / handlers.bootstrap。
|
||||
逻辑:只读断言 Catalog 声明与 Handler 绑定;不创建 Flask 应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.agent_registry import catalog_bindings
|
||||
from app.services.agent_registry.catalog_loader import build_agent_type_catalog, get_catalog_entry
|
||||
from app.services.agent_registry.handlers.base import AgentHandler
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
|
||||
def test_contract_payment_type_in_catalog():
|
||||
"""catalog 必须包含 contract_payment,默认 builtin + task_chat。"""
|
||||
entry = get_catalog_entry('contract_payment')
|
||||
assert entry is not None
|
||||
assert entry.get('label') == '合同付款预警'
|
||||
assert entry.get('runtime_provider_default') == 'builtin'
|
||||
assert entry.get('conversation_mode_default') == 'task_chat'
|
||||
assert entry.get('runtime_handler') == 'contract_payment'
|
||||
|
||||
|
||||
def test_contract_payment_bound_to_runtime_handler():
|
||||
"""catalog_bindings 必须把 contract_payment 绑定到同名 HANDLER_REGISTRY key。"""
|
||||
assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['contract_payment'] == 'contract_payment'
|
||||
|
||||
|
||||
def test_contract_payment_handler_registered():
|
||||
"""bootstrap 加载后 HANDLER_REGISTRY 包含 ContractPaymentHandler。"""
|
||||
reset_handlers_for_tests()
|
||||
load_handlers()
|
||||
handler = HANDLER_REGISTRY.get('contract_payment')
|
||||
assert handler is not None
|
||||
assert isinstance(handler, AgentHandler)
|
||||
assert handler.handler_key == 'contract_payment'
|
||||
reset_handlers_for_tests()
|
||||
|
||||
|
||||
def test_contract_payment_present_in_full_catalog():
|
||||
"""完整 catalog 与既有类型共存。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
assert 'contract_payment' in catalog
|
||||
assert 'shipping_notice' in catalog
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_agent_registry_voucher_check.py
|
||||
|
||||
用途:验证 voucher_check 已注册为 builtin Chat Agent 类型。
|
||||
依赖:catalog_loader / catalog_bindings / handlers.bootstrap。
|
||||
逻辑:只读断言 Catalog 声明与 Handler 绑定;不创建 Flask 应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.agent_registry import catalog_bindings
|
||||
from app.services.agent_registry.catalog_loader import build_agent_type_catalog, get_catalog_entry
|
||||
from app.services.agent_registry.handlers.base import AgentHandler
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
|
||||
def test_voucher_check_type_in_catalog():
|
||||
"""catalog 必须包含 voucher_check,默认 builtin + task_chat。"""
|
||||
entry = get_catalog_entry('voucher_check')
|
||||
assert entry is not None
|
||||
assert entry.get('label') == '立账凭证'
|
||||
assert entry.get('runtime_provider_default') == 'builtin'
|
||||
assert entry.get('conversation_mode_default') == 'task_chat'
|
||||
assert entry.get('runtime_handler') == 'voucher_check'
|
||||
|
||||
|
||||
def test_voucher_check_bound_to_runtime_handler():
|
||||
"""catalog_bindings 必须把 voucher_check 绑定到同名 HANDLER_REGISTRY key。"""
|
||||
assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['voucher_check'] == 'voucher_check'
|
||||
|
||||
|
||||
def test_voucher_check_handler_registered():
|
||||
"""bootstrap 加载后 HANDLER_REGISTRY 包含 VoucherCheckHandler。"""
|
||||
reset_handlers_for_tests()
|
||||
load_handlers()
|
||||
handler = HANDLER_REGISTRY.get('voucher_check')
|
||||
assert handler is not None
|
||||
assert isinstance(handler, AgentHandler)
|
||||
assert handler.handler_key == 'voucher_check'
|
||||
reset_handlers_for_tests()
|
||||
|
||||
|
||||
def test_voucher_check_present_in_full_catalog():
|
||||
"""完整 catalog 与既有类型共存。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
assert 'voucher_check' in catalog
|
||||
assert 'contract_payment' in catalog
|
||||
@@ -104,7 +104,7 @@ def test_try_fast_route_hr_leave_when_route_declared(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -136,11 +136,11 @@ def test_try_fast_route_text2sql_for_erp_kb(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.text2sql.Text2SQLService.stream_chat',
|
||||
'app.services.integrations.text2sql.Text2SQLService.stream_chat',
|
||||
classmethod(lambda cls, *args, **kwargs: iter(['data: {"event":"message"}\n\n'])),
|
||||
)
|
||||
|
||||
@@ -172,7 +172,7 @@ def test_try_fast_route_returns_none_for_generic_query(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
|
||||
@@ -200,7 +200,7 @@ def test_try_fast_route_plm_skips_when_attachments_present(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: True),
|
||||
)
|
||||
|
||||
@@ -227,7 +227,7 @@ def test_try_fast_route_skips_hr_when_route_not_declared(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
|
||||
@@ -254,7 +254,7 @@ def test_try_fast_route_skips_text2sql_without_route(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
"""
|
||||
backend/tests/test_chat_user_attachments.py
|
||||
|
||||
用途:验证聊天附件快照的后端白名单清洗与归属安全合并。
|
||||
依赖:chat API 附件辅助函数、pytest monkeypatch。
|
||||
逻辑:覆盖敏感字段过滤、数量/大小边界、无 ChatLog ID 不写入和有效终态合并。
|
||||
用途:验证聊天附件快照的后端白名单清洗、超限显式失败与归属安全合并。
|
||||
依赖:chat API 附件辅助函数、pytest、ValidationError。
|
||||
逻辑:覆盖敏感字段过滤、数量上限显式失败、无效项丢弃、无 ChatLog ID 不写入和有效终态合并。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api.chat import (
|
||||
CHAT_USER_ATTACHMENT_LIMIT,
|
||||
_merge_user_attachments_from_terminal_event,
|
||||
_normalize_user_attachments,
|
||||
)
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
def test_normalize_user_attachments_keeps_only_display_whitelist():
|
||||
@@ -34,7 +37,7 @@ def test_normalize_user_attachments_keeps_only_display_whitelist():
|
||||
}]
|
||||
|
||||
|
||||
def test_normalize_user_attachments_limits_items_and_drops_invalid_values():
|
||||
def test_normalize_user_attachments_keeps_all_items_at_limit():
|
||||
valid = {
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
@@ -42,16 +45,66 @@ def test_normalize_user_attachments_limits_items_and_drops_invalid_values():
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}
|
||||
items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 5)]
|
||||
items[0] = {**valid, 'type': 'executable'}
|
||||
items[1] = {**valid, 'source': 'unknown'}
|
||||
items[2] = {**valid, 'size': -1, 'extension': '../pdf'}
|
||||
|
||||
items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(CHAT_USER_ATTACHMENT_LIMIT)]
|
||||
normalized = _normalize_user_attachments(items)
|
||||
assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT
|
||||
assert normalized[0]['name'] == 'file-0.pdf'
|
||||
assert normalized[-1]['name'] == f'file-{CHAT_USER_ATTACHMENT_LIMIT - 1}.pdf'
|
||||
|
||||
assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT - 2
|
||||
assert 'size' not in normalized[0]
|
||||
assert 'extension' not in normalized[0]
|
||||
|
||||
def test_normalize_user_attachments_keeps_more_than_legacy_twenty():
|
||||
valid = {
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}
|
||||
items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(21)]
|
||||
normalized = _normalize_user_attachments(items)
|
||||
assert len(normalized) == 21
|
||||
|
||||
|
||||
def test_normalize_user_attachments_raises_when_over_limit():
|
||||
valid = {
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}
|
||||
items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 1)]
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_normalize_user_attachments(items)
|
||||
err = exc_info.value
|
||||
assert err.code == 'CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED'
|
||||
assert err.details.get('limit') == CHAT_USER_ATTACHMENT_LIMIT
|
||||
assert err.details.get('count') == CHAT_USER_ATTACHMENT_LIMIT + 1
|
||||
|
||||
|
||||
def test_normalize_user_attachments_drops_invalid_values_without_truncating_valid_tail():
|
||||
valid = {
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}
|
||||
items = [
|
||||
{**valid, 'type': 'executable'},
|
||||
{**valid, 'source': 'unknown'},
|
||||
]
|
||||
# 旧 [:20] 会在处理完前 20 项后丢弃尾部合法项;无 slice 后应保留 tail。
|
||||
items.extend({**valid, 'type': 'executable'} for _ in range(18))
|
||||
items.append({**valid, 'name': 'kept-tail.pdf'})
|
||||
normalized = _normalize_user_attachments(items)
|
||||
assert normalized == [{
|
||||
'name': 'kept-tail.pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
'extension': 'pdf',
|
||||
'size': 1,
|
||||
}]
|
||||
|
||||
|
||||
def test_merge_user_attachments_requires_terminal_chat_log_id(monkeypatch):
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_ledger_focus.py
|
||||
|
||||
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
||||
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、待补充、本月应付合同后核对计数与 focus 筛选。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、进行中、本月应付合同后核对计数与 focus 筛选。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,12 +11,12 @@ from __future__ import annotations
|
||||
from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.models import Agent, ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.services.contract_payment.ledger_focus import ledger_focus_counts
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户。"""
|
||||
"""创建已授予合同付款预警 Agent 的落库用户。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
@@ -26,9 +26,22 @@ def _create_user(*, username: str) -> User:
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if not agent:
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
@@ -76,7 +89,8 @@ def _seed_focus_contracts() -> None:
|
||||
_add_node(due, due=today.replace(day=14))
|
||||
overdue = _add_contract(contract_no='HT-FOCUS-OVERDUE')
|
||||
_add_node(overdue, due=date(2026, 8, 20))
|
||||
_add_contract(contract_no='HT-FOCUS-NEEDS')
|
||||
active = _add_contract(contract_no='HT-FOCUS-ACTIVE')
|
||||
_add_node(active, due=date(2026, 11, 1))
|
||||
month = _add_contract(contract_no='HT-FOCUS-MONTH')
|
||||
_add_node(month, due=date(2026, 9, 28))
|
||||
db.session.commit()
|
||||
@@ -87,10 +101,10 @@ def test_ledger_focus_counts_by_contract(app):
|
||||
with app.app_context():
|
||||
_seed_focus_contracts()
|
||||
counts = ledger_focus_counts(session=db.session, today=date(2026, 9, 10))
|
||||
# 关键断言:即将到期 1、逾期 1、待补充 1、本月应付为 9/14 与 9/28 两份。
|
||||
# 关键断言:即将到期 1、逾期 1、进行中 2(11/1 与 9/28)、本月应付为 9/14 与 9/28 两份。
|
||||
assert counts['due'] == 1
|
||||
assert counts['overdue'] == 1
|
||||
assert counts['needs_completion'] == 1
|
||||
assert counts['active'] == 2
|
||||
assert counts['due_this_month'] == 2
|
||||
|
||||
|
||||
@@ -106,12 +120,19 @@ def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
|
||||
|
||||
headers = _auth_headers(user)
|
||||
overdue = client.get('/api/contract-payment/contracts?focus=overdue', headers=headers)
|
||||
active = client.get('/api/contract-payment/contracts?focus=active', headers=headers)
|
||||
summary = client.get('/api/contract-payment/contracts/summary', headers=headers)
|
||||
empty = client.get('/api/contract-payment/contracts?focus=overdue&keyword=NO-SUCH', headers=headers)
|
||||
# 关键断言:逾期卡只筛出逾期合同;汇总仍看全量台账。
|
||||
# 关键断言:逾期卡只筛出逾期合同;进行中含未到期的 11/1 与本月 9/28;汇总仍看全量台账。
|
||||
assert overdue.status_code == 200
|
||||
data = overdue.get_json()['data']
|
||||
assert data['total'] == 1
|
||||
assert data['items'][0]['contract_no'] == 'HT-FOCUS-OVERDUE'
|
||||
assert {item['contract_no'] for item in active.get_json()['data']['items']} == {
|
||||
'HT-FOCUS-ACTIVE',
|
||||
'HT-FOCUS-MONTH',
|
||||
}
|
||||
assert summary.get_json()['data']['overdue'] == 1
|
||||
assert summary.get_json()['data']['active'] == 2
|
||||
assert 'needs_completion' not in summary.get_json()['data']
|
||||
assert empty.get_json()['data']['total'] == 0
|
||||
@@ -1,19 +1,19 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_list.py
|
||||
|
||||
用途:验收合同付款台账列表的 keyword 筛选,尤其是按供应商名称模糊匹配。
|
||||
依赖:Flask test client、ContractPaymentContract、用户功能权限。
|
||||
逻辑:构造两份已解析合同,确认供应商片段只命中对应行,且合同号/采购单号检索仍可用。
|
||||
用途:验收合同付款台账列表的 keyword 与申请人筛选。
|
||||
依赖:Flask test client、ContractPaymentContract、Agent 授权。
|
||||
逻辑:构造两份已解析合同,确认供应商/申请人只命中对应行,且合同号/采购单号检索仍可用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, User
|
||||
from app.models import Agent, ContractPaymentContract, User
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户,供列表接口走 legacy header 认证。"""
|
||||
"""创建已授予合同付款预警 Agent 的落库用户,供列表接口走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
@@ -23,9 +23,22 @@ def _create_user(*, username: str) -> User:
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if not agent:
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
@@ -42,7 +55,7 @@ def _auth_headers(user: User) -> dict[str, str]:
|
||||
|
||||
|
||||
def _seed_parsed_contracts() -> None:
|
||||
"""写入两份已进入台账的合同,供应商名称可区分。"""
|
||||
"""写入两份已进入台账的合同,供应商和申请人都可区分。"""
|
||||
db.session.add_all(
|
||||
[
|
||||
ContractPaymentContract(
|
||||
@@ -50,6 +63,7 @@ def _seed_parsed_contracts() -> None:
|
||||
workflow_no='5203-2609020001',
|
||||
purchase_order_no='5203-2609020001',
|
||||
supplier_name='诺亘(上海)工业自动化有限公司',
|
||||
applicant_name='李采购',
|
||||
parse_status='parsed',
|
||||
status='active',
|
||||
),
|
||||
@@ -58,6 +72,7 @@ def _seed_parsed_contracts() -> None:
|
||||
workflow_no='5203-2608270005',
|
||||
purchase_order_no='5203-2608270005',
|
||||
supplier_name='无锡市质谨机电科技有限公司',
|
||||
applicant_name='王申请',
|
||||
parse_status='parsed',
|
||||
status='active',
|
||||
),
|
||||
@@ -96,3 +111,17 @@ def test_list_contracts_keyword_still_matches_contract_and_po(client, app):
|
||||
assert by_po.get_json()['data']['items'][0]['purchase_order_no'] == '5203-2608270005'
|
||||
assert by_contract.get_json()['data']['total'] == 1
|
||||
assert by_contract.get_json()['data']['items'][0]['contract_no'] == 'HT-20260903-30622-0'
|
||||
|
||||
|
||||
def test_list_contracts_filters_by_applicant(client, app):
|
||||
"""关键词命中申请人姓名时只返回对应合同。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username='cp_list_applicant')
|
||||
_seed_parsed_contracts()
|
||||
|
||||
headers = _auth_headers(user)
|
||||
res = client.get('/api/contract-payment/contracts?keyword=李采', headers=headers)
|
||||
# 关键断言:申请人模糊匹配生效,不误伤其他申请人。
|
||||
assert res.get_json()['data']['total'] == 1
|
||||
assert res.get_json()['data']['items'][0]['applicant_name'] == '李采购'
|
||||
assert res.get_json()['data']['items'][0]['contract_no'] == 'HT-20260903-30622-0'
|
||||
@@ -1,31 +1,19 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_permissions.py
|
||||
|
||||
用途:验收合同付款预警专项权限 `contract_payment.access` 的角色默认值、显式覆盖与 API 拦截。
|
||||
依赖:User 功能权限、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账,但不能触发同步/扫描/发送;关闭 admin 覆盖后同样 403。
|
||||
用途:验收合同付款预警改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 无需绑定即可查询;普通用户默认 403;授予 contract_payment Agent 后可查询台账,
|
||||
但不能触发同步/扫描/发送。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _make_memory_user(*, role: str, overrides: dict | None = None) -> User:
|
||||
"""构造带功能权限覆盖的内存用户(不落库,仅测 has_feature_permission)。"""
|
||||
user = User(username=f'cp-{role}', role=role)
|
||||
if overrides is not None:
|
||||
user.feature_permissions = overrides
|
||||
return user
|
||||
|
||||
|
||||
def _create_user(
|
||||
*,
|
||||
username: str,
|
||||
role: str = 'user',
|
||||
feature_permissions: dict | None = None,
|
||||
) -> User:
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
"""创建落库用户,供 contract-payment API 走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
@@ -36,11 +24,39 @@ def _create_user(
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions(feature_permissions)
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def _ensure_contract_payment_agent() -> Agent:
|
||||
"""确保存在启用中的合同付款预警 Agent,供授权绑定。"""
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if agent:
|
||||
return agent
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(agent)
|
||||
return agent
|
||||
|
||||
|
||||
def _grant_contract_payment_agent(user: User) -> User:
|
||||
"""把合同付款预警 Agent 授权给指定用户并重新取出,避免会话分离后丢失关系。"""
|
||||
agent = _ensure_contract_payment_agent()
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
@@ -62,49 +78,16 @@ def _json_error(response) -> dict:
|
||||
return body['error']
|
||||
|
||||
|
||||
def test_admin_default_has_contract_payment_access(app):
|
||||
"""admin 角色默认具备 contract_payment.access;普通用户默认无。"""
|
||||
with app.app_context():
|
||||
admin = _make_memory_user(role='admin')
|
||||
user = _make_memory_user(role='user')
|
||||
# 关键断言:不新建角色,仅功能键裁剪工作台访问。
|
||||
assert admin.can_access_contract_payment() is True
|
||||
assert user.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_explicit_grant_and_revoke_contract_payment_access(app):
|
||||
"""普通用户可被显式授予;admin 可被显式关闭。"""
|
||||
with app.app_context():
|
||||
granted = _make_memory_user(role='user', overrides={'contract_payment.access': True})
|
||||
revoked_admin = _make_memory_user(role='admin', overrides={'contract_payment.access': False})
|
||||
# 关键断言:显式覆盖优先于角色默认。
|
||||
assert granted.can_access_contract_payment() is True
|
||||
assert revoked_admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_set_feature_permissions_persists_contract_payment_override(app):
|
||||
"""用户表单保存时只持久化与角色默认值不同的 contract_payment.access。"""
|
||||
with app.app_context():
|
||||
user = User(username='cp-override', role='user')
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
# 关键断言:未知键被忽略,已知覆盖项写入 JSON。
|
||||
assert user.feature_permissions == {'contract_payment.access': True}
|
||||
assert user.can_access_contract_payment() is True
|
||||
|
||||
admin = User(username='cp-admin-override', role='admin')
|
||||
admin.set_feature_permissions({'contract_payment.access': False})
|
||||
assert admin.feature_permissions == {'contract_payment.access': False}
|
||||
assert admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_contract_payment_api_forbids_user_without_access(client, app):
|
||||
"""无权限用户查询台账或触发同步均返回 CONTRACT_PAYMENT.FORBIDDEN。"""
|
||||
def test_contract_payment_api_forbids_user_without_agent(client, app):
|
||||
"""未授予 Agent 的普通用户查询台账或触发同步均返回 CONTRACT_PAYMENT.FORBIDDEN。"""
|
||||
with app.app_context():
|
||||
ordinary = _create_user(username='cp_api_denied')
|
||||
_ensure_contract_payment_agent()
|
||||
db.session.expunge(ordinary)
|
||||
|
||||
headers = _auth_headers(ordinary)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:登录不足够,专项权限缺失必须 403。
|
||||
# 关键断言:登录不足够,Agent 授权缺失必须 403。
|
||||
assert list_res.status_code == 403
|
||||
assert _json_error(list_res)['code'] == 'CONTRACT_PAYMENT.FORBIDDEN'
|
||||
|
||||
@@ -114,29 +97,36 @@ def test_contract_payment_api_forbids_user_without_access(client, app):
|
||||
|
||||
|
||||
def test_contract_payment_api_allows_granted_user(client, app):
|
||||
"""显式授予后普通用户可以查询台账。"""
|
||||
"""授予 contract_payment Agent 后普通用户可以查询台账。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_granted',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
granted = _grant_contract_payment_agent(_create_user(username='cp_api_granted'))
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:授予后不再 403,返回标准成功 envelope。
|
||||
# 关键断言:Agent 授权后不再 403,返回标准成功 envelope。
|
||||
assert list_res.status_code == 200
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
|
||||
|
||||
def test_contract_payment_api_allows_admin_without_agent_binding(client, app):
|
||||
"""平台 admin 即使未绑定该 Agent 也可查询台账。"""
|
||||
with app.app_context():
|
||||
admin = _create_user(username='cp_api_admin', role='admin')
|
||||
_ensure_contract_payment_agent()
|
||||
db.session.expunge(admin)
|
||||
|
||||
headers = _auth_headers(admin)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
assert list_res.status_code == 200
|
||||
assert list_res.get_json().get('success') is True
|
||||
|
||||
|
||||
def test_contract_payment_jobs_require_admin(client, app):
|
||||
"""已授权的普通用户可查台账,但不能触发同步、扫描或周汇总发送。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_jobs_denied',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
granted = _grant_contract_payment_agent(_create_user(username='cp_api_jobs_denied'))
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
# 关键断言:访问权不等于操作权,手动任务仅管理员。
|
||||
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
|
||||
|
||||
def _load_navigation():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_navigation.py"
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "crane_navigation.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_navigation_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
|
||||
|
||||
def _load_export():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_report_export.py"
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "crane_report_export.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_report_export_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -47,7 +47,7 @@ def test_fill_parameters_skips_warehouse(monkeypatch):
|
||||
select_or_fill=_fake_select,
|
||||
)
|
||||
|
||||
assert calls == [("SHIPPING_NOTICE_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
|
||||
assert calls == [("FREIGHT_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
|
||||
|
||||
|
||||
def test_build_schedule_description_uses_short_uuid_hex(monkeypatch):
|
||||
@@ -73,7 +73,7 @@ def test_build_schedule_description_hex_len_env():
|
||||
text = module._build_schedule_description(
|
||||
{"source_code": "CRANE_TZR2"},
|
||||
None,
|
||||
env=lambda name, default="": "16" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
|
||||
env=lambda name, default="": "16" if name == "FREIGHT_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
|
||||
)
|
||||
assert len(text) == 16
|
||||
|
||||
@@ -148,7 +148,7 @@ def test_should_run_report_before_schedule_uses_driver_environment_only():
|
||||
assert (
|
||||
module._should_run_report_before_schedule(
|
||||
{"navigation": {}},
|
||||
env=lambda name, default="": "false" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default,
|
||||
env=lambda name, default="": "false" if name == "FREIGHT_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default,
|
||||
)
|
||||
is False
|
||||
)
|
||||
@@ -444,7 +444,7 @@ def test_resolve_download_mode_uses_driver_environment_only():
|
||||
"""下载模式只能由 Driver 环境变量决定。"""
|
||||
module = _load_export()
|
||||
assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report"
|
||||
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
|
||||
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "FREIGHT_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
|
||||
|
||||
|
||||
def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch):
|
||||
@@ -596,3 +596,34 @@ def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_p
|
||||
download_dir=str(tmp_path),
|
||||
)
|
||||
assert fallback_called["value"] is False
|
||||
|
||||
|
||||
def test_row_matches_scheduled_report_normalizes_name_form(monkeypatch):
|
||||
"""行名 InboundDetails.xlsx 与期望名 Inbound Details 应规范化后相等(收料轮询 not found 根因)。"""
|
||||
module = _load_export()
|
||||
texts = ["InboundDetails.xlsx", "2026/9/18 22:02:53", "accf9483fabe", "Download"]
|
||||
|
||||
class _Cell:
|
||||
def __init__(self, text):
|
||||
self._text = text
|
||||
|
||||
def inner_text(self, timeout=None):
|
||||
return self._text
|
||||
|
||||
cells = MagicMock()
|
||||
cells.count.return_value = len(texts)
|
||||
cells.nth.side_effect = lambda i: _Cell(texts[i])
|
||||
row = MagicMock()
|
||||
row.locator.return_value = cells
|
||||
row.is_visible.return_value = True
|
||||
|
||||
assert module._row_matches_scheduled_report(
|
||||
row, description="accf9483fabe", expected_report_name="Inbound Details"
|
||||
) is True
|
||||
# [断言意图] 描述不一致时不得匹配(唯一性由 UUID 保证)
|
||||
assert module._row_matches_scheduled_report(
|
||||
row, description="other", expected_report_name="Inbound Details"
|
||||
) is False
|
||||
assert module._row_matches_scheduled_report(
|
||||
row, description="accf9483fabe", expected_report_name="OnHandDetails.xlsx"
|
||||
) is False
|
||||
@@ -8,7 +8,7 @@ from unittest.mock import MagicMock
|
||||
|
||||
|
||||
def _load_crane_session():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_session.py"
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "crane_session.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_session_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -108,15 +108,15 @@ def test_maybe_auto_login_crane_fills_username_password_and_clicks_sign_in(monke
|
||||
module.maybe_auto_login_crane(
|
||||
page,
|
||||
env=lambda name, default="": {
|
||||
"SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME": "crane-user",
|
||||
"SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD": "crane-pass",
|
||||
"FREIGHT_RPA_WORKER_CRANE_USERNAME": "crane-user",
|
||||
"FREIGHT_RPA_WORKER_CRANE_PASSWORD": "crane-pass",
|
||||
}.get(name, default),
|
||||
browser_timeout_ms=5_000,
|
||||
)
|
||||
|
||||
assert calls == [
|
||||
("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"),
|
||||
("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"),
|
||||
("FREIGHT_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"),
|
||||
("FREIGHT_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"),
|
||||
]
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
|
||||
|
||||
locator = module._find_crane_sign_in_button(
|
||||
page,
|
||||
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
|
||||
selector_env="FREIGHT_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=3_000,
|
||||
)
|
||||
@@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
|
||||
|
||||
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
|
||||
"""batch 内 session 有效时不应重复 goto + login。"""
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
|
||||
assert spec and spec.loader
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -7,7 +7,7 @@ import pytest
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent, ChatLog, User
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -13,7 +13,7 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.services.file_check import FileCheckService
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ def _mock_stream_response(monkeypatch, *, status_code: int = 200, lines: list[by
|
||||
calls["count"] += 1
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
|
||||
return calls
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ def test_workflow_streaming_503_retries_then_success(monkeypatch):
|
||||
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
|
||||
|
||||
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||
|
||||
@@ -199,7 +199,7 @@ def test_workflow_streaming_401_does_not_retry(monkeypatch):
|
||||
resp.status_code = 401
|
||||
raise requests.HTTPError(response=resp)
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
|
||||
|
||||
with pytest.raises(requests.HTTPError):
|
||||
DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||
@@ -353,7 +353,7 @@ def test_dedupe_exact_doubled_text_fixes_historical_records():
|
||||
def test_chat_stream_error_event_keeps_persisted_chat_log_id(app, monkeypatch):
|
||||
"""连接超时的 error SSE 必须携带持久化主键,供领域 Handler 回写失败状态。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.dify.requests.post",
|
||||
"app.services.integrations.dify.requests.post",
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(requests.exceptions.ConnectTimeout("connect timed out")),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -402,7 +402,7 @@ def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeyp
|
||||
yield _sse_lines({"event": "message", "answer": "partial answer"})[0]
|
||||
raise requests.exceptions.ReadTimeout("read timed out")
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
|
||||
monkeypatch.setattr(
|
||||
DifyService,
|
||||
"_persist_stream_chat_record",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""scripts/rpa/dsv_report_parameters.py 单元测试。"""
|
||||
"""scripts/freight_rpa/dsv_report_parameters.py 单元测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,7 +7,7 @@ from pathlib import Path
|
||||
|
||||
|
||||
def _load_module():
|
||||
path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_parameters.py"
|
||||
path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_parameters.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_parameters_test", path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -43,7 +43,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
|
||||
|
||||
module.fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"Owner",
|
||||
"CADU-0000000100",
|
||||
env=lambda name, default="": default,
|
||||
@@ -104,7 +104,7 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue():
|
||||
|
||||
module.fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"BYAWSATL01",
|
||||
env=lambda name, default="": default,
|
||||
@@ -290,7 +290,7 @@ def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value():
|
||||
|
||||
module.fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"RTM",
|
||||
env=lambda name, default="": default,
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
"""
|
||||
tests/test_effective_order_view.py
|
||||
|
||||
用途:验证「冻结快照 + 冻结后人工修正」的有效订单值视图。
|
||||
依赖:pytest、effective_order_view、task_order_field_editor、订单 Schema/快照模型。
|
||||
逻辑:覆盖行级修正对位叠加、快照不可变、整行替换后的保守跳过与 Notice 行事实投影。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.effective_order_view import (
|
||||
effective_line_facts_for_notice,
|
||||
effective_order_field_values,
|
||||
)
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
from app.services.shipping_notice.task_order_field_editor import (
|
||||
replace_current_line_field_value,
|
||||
replace_current_line_fields,
|
||||
)
|
||||
|
||||
|
||||
def _seed_frozen_order():
|
||||
"""最小冻结订单夹具:OT + accepted Extraction(两行三字段)+ 冻结快照。"""
|
||||
user = User(username='eff-view-user', email='eff-view@test.local', role='user', status='active')
|
||||
db.session.add(user)
|
||||
schema = ShippingOrderSchema(schema_code='EFFVIEW', display_name='EffView')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published',
|
||||
definition_json={'fields': [
|
||||
{'field_id': 'f-part', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'field_category': 'order_line', 'sequence': 1, 'enabled': True},
|
||||
{'field_id': 'f-rsv', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'field_category': 'order_line', 'sequence': 2, 'enabled': True},
|
||||
{'field_id': 'f-qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'field_category': 'order_line', 'sequence': 3, 'enabled': True},
|
||||
]},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
order = ShippingOrderTask(task_no='OT-EFFVIEW-1', source_type='direct_pdf', user_id=user.id)
|
||||
db.session.add(order)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=order.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
rule_versions_json={'fulfillment_rule': {'required_field_ids': {
|
||||
'part_number': 'f-part', 'reservation_id': 'f-rsv', 'qty': 'f-qty',
|
||||
}}},
|
||||
header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
snap_lines = []
|
||||
for position, part in enumerate(('D4-A08AR12000002-', 'D4-B07BR07000001')):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for field_id, value in (('f-part', part), ('f-rsv', f'RSV-{position + 1}'), ('f-qty', '10')):
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_id,
|
||||
decision_status='accepted', resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_id=decision.id,
|
||||
value_text=str(value), value_json=value,
|
||||
))
|
||||
snap_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=position, line_no=position + 1,
|
||||
part_number=part, reservation_id=f'RSV-{position + 1}', qty=Decimal('10'),
|
||||
field_values_json={'f-part': part, 'f-rsv': f'RSV-{position + 1}', 'f-qty': '10'},
|
||||
)
|
||||
db.session.add(snap_line)
|
||||
db.session.flush()
|
||||
snap_lines.append(snap_line)
|
||||
order.current_order_extraction_id = extraction.id
|
||||
order.order_snapshot_id = snapshot.id
|
||||
db.session.flush()
|
||||
return SimpleNamespace(user=user, order=order, extraction=extraction, snapshot=snapshot, snap_lines=snap_lines)
|
||||
|
||||
|
||||
def test_edited_part_number_flows_into_effective_values(app):
|
||||
"""冻结后人工修正料号,有效视图必须返回修正值(匹配/Excel 的读取口径)。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
_header, lines = effective_order_field_values(fixture.order)
|
||||
# 断言:第 0 行为修正值、第 1 行保持冻结值,证明对位叠加只影响被改行。
|
||||
assert lines[0]['f-part'] == 'D4-A08AR12000002'
|
||||
assert lines[1]['f-part'] == 'D4-B07BR07000001'
|
||||
|
||||
|
||||
def test_snapshot_stays_frozen_after_edit(app):
|
||||
"""有效视图不得回写快照:冻结事实仍是审计锚点。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
# 断言:快照强类型列与 field_values_json 均保持冻结原值。
|
||||
assert fixture.snap_lines[0].part_number == 'D4-A08AR12000002-'
|
||||
assert fixture.snap_lines[0].field_values_json['f-part'] == 'D4-A08AR12000002-'
|
||||
|
||||
|
||||
def test_line_set_replacement_skips_line_overlay(app):
|
||||
"""整行替换后 position 不再可比:行级叠加保守跳过,返回冻结行值。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
# 注:替换行不带 qty——本测试只验证行集替换守卫;decimal 经整行替换路径的可持久化
|
||||
# 已由 test_line_set_replacement_with_decimal_persists_without_json_error 单独覆盖。
|
||||
replace_current_line_fields(task=fixture.order, lines=[
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': 'RSV-1'},
|
||||
])
|
||||
_header, lines = effective_order_field_values(fixture.order)
|
||||
# 断言:行级叠加被守卫跳过(行集维度属后续特性),值仍来自冻结快照两行原样。
|
||||
assert [row['f-part'] for row in lines] == ['D4-A08AR12000002-', 'D4-B07BR07000001']
|
||||
|
||||
|
||||
def test_effective_line_facts_for_notice(app):
|
||||
"""Notice 行物化事实按冻结规则映射强类型键并携带修正值。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
facts = effective_line_facts_for_notice(fixture.order)
|
||||
first = facts[int(fixture.snap_lines[0].id)]
|
||||
# 断言:料号为修正值,数量被安全转为 Decimal,字段值字典完整。
|
||||
assert first['part_number'] == 'D4-A08AR12000002'
|
||||
assert first['reservation_id'] == 'RSV-1'
|
||||
assert first['qty'] == Decimal('10')
|
||||
assert first['field_values']['f-rsv'] == 'RSV-1'
|
||||
|
||||
|
||||
def test_decimal_edit_persists_without_json_error(app):
|
||||
"""数量(decimal 字段)人工编辑必须可持久化:value_json 存字符串、value_decimal 存 Decimal。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='qty', value='12.5',
|
||||
)
|
||||
rows = [
|
||||
item for item in ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=fixture.extraction.id,
|
||||
).all()
|
||||
if item.value_json is not None
|
||||
]
|
||||
# 夹具两行均预置了 f-qty FieldValue(未编辑行 value_json='10'),须限定被编辑的第 0 行再断言。
|
||||
edited_line = ShippingOrderLine.query.filter_by(
|
||||
extraction_id=fixture.extraction.id, position=0,
|
||||
).one()
|
||||
qty_rows = [item for item in rows if item.field_id == 'f-qty' and item.line_id == edited_line.id]
|
||||
# 断言:JSON 列存规范字符串(与机器路径 _json_value 对齐),类型列保留 Decimal。
|
||||
assert qty_rows, 'qty FieldValue 必须存在'
|
||||
assert all(item.value_json == '12.5' for item in qty_rows)
|
||||
assert any(item.value_decimal == Decimal('12.5') for item in qty_rows)
|
||||
|
||||
|
||||
def test_line_set_replacement_with_decimal_persists_without_json_error(app):
|
||||
"""整行替换带 decimal 字段必须同样可持久化:新当前 Extraction 的 qty JSON 列存字符串、类型列存 Decimal。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_fields(task=fixture.order, lines=[
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': 'RSV-1', 'qty': '12.5'},
|
||||
])
|
||||
rows = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=fixture.order.current_order_extraction_id,
|
||||
field_id='f-qty',
|
||||
).all()
|
||||
line_qty_rows = [item for item in rows if item.line_id is not None]
|
||||
# 断言:整行替换路径的 Decision/FieldValue 均经 _json_value 落库且不得抛序列化错误。
|
||||
assert line_qty_rows, '替换行集的 qty FieldValue 必须存在'
|
||||
assert all(item.value_json == '12.5' for item in line_qty_rows)
|
||||
assert all(item.value_decimal == Decimal('12.5') for item in line_qty_rows)
|
||||
|
||||
|
||||
def test_matching_purpose_values_use_effective_view(app):
|
||||
"""库存匹配用途投影必须读到修正后的料号(修复改值不进匹配的断层)。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-EFFVIEW-1', source_type='manual', user_id=fixture.user.id,
|
||||
order_task_id=fixture.order.id,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
purpose_values = task_line_purpose_values(notice)
|
||||
# 断言:第 0 行用途值为修正料号,第 1 行保持冻结值。
|
||||
assert purpose_values[0]['part_number'] == 'D4-A08AR12000002'
|
||||
assert purpose_values[1]['part_number'] == 'D4-B07BR07000001'
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
依赖:正文补充解析器与合并服务。
|
||||
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威;关联优先 PO+料号,
|
||||
其次 PO+预约号,歧义稳定进入复核。
|
||||
其次 PO+预约号;无同 PO 时仅 PO 缺失行可料号兜底;错 PO 禁止补充。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,7 +23,7 @@ SCHEMA = {'fields': [
|
||||
{'field_id': 'qty', 'field_code': 'qty'},
|
||||
{
|
||||
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'aliases': ['Reservation ID', 'External reservation ID', 'Reservation Number'],
|
||||
'aliases': ['Reservation ID', 'External reservation ID', 'Reservation Number', 'IR#'],
|
||||
},
|
||||
{'field_id': 'allocation', 'field_code': 'allocation_id'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']},
|
||||
@@ -213,7 +213,12 @@ def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review():
|
||||
)[0]
|
||||
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == 'PDF-33873'
|
||||
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
|
||||
assert any(
|
||||
item.get('severity') == 'blocking'
|
||||
and item.get('reason') == 'supplement_field_conflict'
|
||||
and item.get('field') == 'reservation_id'
|
||||
for item in merged['conflicts']
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -337,12 +342,12 @@ def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_
|
||||
order['lines'][0]['fields'][0]['observations'][0]['value'] = value
|
||||
supplement = {'document_id': 44, 'rows': [{
|
||||
'po_number': '4518738152', mail_field: value,
|
||||
'reservation_id': f'30000{index}', 'evidence': {},
|
||||
'reservation_id': f'300000000{index}', 'evidence': {},
|
||||
}]}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == f'30000{index}'
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == f'300000000{index}'
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
@@ -447,17 +452,13 @@ def test_email_supplement_po_fallback_requires_one_reservation():
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in result['conflicts'])
|
||||
|
||||
|
||||
def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
"""邮件 PO 与 PDF 不一致时,唯一完全匹配 MPN 仍可保守补齐预约号。"""
|
||||
def test_email_supplement_unique_mpn_fallback_rejects_mistyped_email_po():
|
||||
"""邮件 PO 有值且与 PDF 不一致时禁止 mpn_fallback,哪怕料号唯一命中。"""
|
||||
order = _order()
|
||||
order['header_fields'][0]['observations'][0]['value'] = '4518838152'
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
@@ -472,10 +473,121 @@ def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
|
||||
assert not any(item['field_id'] == 'reservation' for item in result['lines'][0]['fields'])
|
||||
assert result.get('_hxops_email_supplement_relation') is None
|
||||
|
||||
|
||||
def test_email_supplement_mpn_fallback_when_po_absent_and_part_unique():
|
||||
"""PO 列缺失时,唯一料号命中仍可保守补齐预约号与库存源线索。"""
|
||||
order = _order()
|
||||
result = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577',
|
||||
'inventory_source_hint': 'DBS SIN',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '2000484577'
|
||||
assert _value(result['lines'][0]['fields'], 'source') == 'DBS SIN'
|
||||
assert result['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_single_line_po_absent_still_requires_part_match():
|
||||
"""双边各一行且 PO 缺失时仍须料号对上;对不上不得广播预约号。"""
|
||||
order = _order()
|
||||
result = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'part_number': 'OTHER-PART-0001',
|
||||
'reservation_id': '2000484577',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert not any(item['field_id'] == 'reservation' for item in result['lines'][0]['fields'])
|
||||
assert result.get('_hxops_email_supplement_relation') is None
|
||||
|
||||
|
||||
def test_email_supplement_po_absent_unique_reservation_per_part_merges_rows():
|
||||
"""多行 PO 缺失时按料号唯一预约号逐行补充;同料号多预约则歧义。"""
|
||||
order = {
|
||||
'_hxops_intake_id': 1,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': '4518738152'}]}],
|
||||
'lines': [
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000002'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 1}]},
|
||||
]},
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 2}]},
|
||||
]},
|
||||
],
|
||||
'conflicts': [],
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': '2000484577', 'evidence': {}},
|
||||
{'part_number': 'D4-A08AR12000003', 'reservation_id': '2000484578', 'evidence': {}},
|
||||
]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert merged['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == '2000484577'
|
||||
assert _value(merged['lines'][1]['fields'], 'reservation') == '2000484578'
|
||||
|
||||
ambiguous = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': '2000484577', 'evidence': {}},
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': '2000484579', 'evidence': {}},
|
||||
{'part_number': 'D4-A08AR12000003', 'reservation_id': '2000484578', 'evidence': {}},
|
||||
]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in ambiguous['conflicts'])
|
||||
assert not any(item['field_id'] == 'reservation' for item in ambiguous['lines'][0]['fields'])
|
||||
assert not any(item['field_id'] == 'reservation' for item in ambiguous['lines'][1]['fields'])
|
||||
|
||||
|
||||
def test_email_supplement_normalizes_reservation_short_numeric_suffix_on_merge():
|
||||
"""同 PO 命中后,IR# 形态 35354-1 写入订单行时归一为 35354。"""
|
||||
result = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'customer_po_number': '4518738152',
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '35354-1',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '35354'
|
||||
assert result['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_html_ir_hash_suffix_survives_parse_and_merge():
|
||||
"""解析 IR#=35354-1 不得因非法形态丢列,合并后预约号为 35354。"""
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='i' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>IR#</th></tr>
|
||||
<tr><td>4518738152</td><td>D4-A08AR12000002</td><td>35354-1</td></tr></table>'''],
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
assert supplement['rows'][0]['reservation_id'] == '35354'
|
||||
assert 'email_supplement_field_invalid' not in supplement.get('issues', [])
|
||||
merged = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {**supplement, 'document_id': 44}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == '35354'
|
||||
|
||||
|
||||
def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_body_text():
|
||||
"""Outlook 展平的纵向表头可恢复补充行,尾部邮件正文不会被误当数据。"""
|
||||
supplement = parse_email_allocation_text(
|
||||
@@ -508,6 +620,43 @@ def test_email_supplement_requires_frozen_schema_alias_for_order_headers():
|
||||
assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']}
|
||||
|
||||
|
||||
def test_email_supplement_parses_without_po_when_mpn_and_reservation_present():
|
||||
"""无 PO 表头但有 MPN + External reservation ID 时仍须产出补充行(本单回归)。"""
|
||||
html = '''<table><tr>
|
||||
<th>MPN</th><th>Source type</th><th>External reservation ID</th>
|
||||
</tr><tr>
|
||||
<td>D4-A08AR12000002</td><td>VMI-SIN</td><td>3000092917</td>
|
||||
</tr></table>'''
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='j' * 64, html_tables=[html], schema_definition=SCHEMA,
|
||||
)
|
||||
assert len(supplement['rows']) == 1
|
||||
assert supplement['rows'][0]['part_number'] == 'D4-A08AR12000002'
|
||||
assert supplement['rows'][0]['reservation_id'] == '3000092917'
|
||||
assert supplement['rows'][0]['inventory_source_hint'] == 'VMI-SIN'
|
||||
assert 'email_supplement_po_header_missing' in supplement['issues']
|
||||
merged = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {**supplement, 'document_id': 44}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == '3000092917'
|
||||
assert _value(merged['lines'][0]['fields'], 'source') == 'VMI-SIN'
|
||||
assert merged['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_still_skips_table_without_po_or_part_or_reservation():
|
||||
"""无 PO 且无料号/预约号可映射列时仍整表跳过,避免无身份噪声行。"""
|
||||
result = parse_email_allocation_tables(
|
||||
content_hash='k' * 64,
|
||||
schema_definition=SCHEMA,
|
||||
html_tables=['''<table><tr><th>Location ID</th><th>Supplier code</th></tr>
|
||||
<tr><td>941.76</td><td>0000000100</td></tr></table>'''],
|
||||
)
|
||||
assert result['rows'] == []
|
||||
assert 'email_supplement_po_header_missing' in result['issues']
|
||||
|
||||
|
||||
def test_email_supplement_inventec_po_date_two_digit_year_keeps_source_location():
|
||||
"""Inventec 分配表 PO Date=12-Jun-26 时仍须保留 Source Location / 预约号。
|
||||
|
||||
|
||||
@@ -297,7 +297,10 @@ def test_file_check_tool_accepts_any_valid_task(app, client, monkeypatch):
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
@@ -382,7 +385,10 @@ def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkey
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -619,7 +625,10 @@ def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
@@ -1224,18 +1233,13 @@ def test_file_check_tool_excel_download_uses_signed_token(app, client):
|
||||
|
||||
|
||||
def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
|
||||
started_threads = []
|
||||
enqueued = []
|
||||
|
||||
class _Thread:
|
||||
def __init__(self, *, target, daemon, name):
|
||||
self.target = target
|
||||
self.daemon = daemon
|
||||
self.name = name
|
||||
def _enqueue(*args, **kwargs):
|
||||
enqueued.append({"args": args, "kwargs": kwargs})
|
||||
return 1
|
||||
|
||||
def start(self):
|
||||
started_threads.append(self.name)
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -1254,7 +1258,7 @@ def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeyp
|
||||
assert data['ok'] is True
|
||||
assert data['run']['task_id'] == task_id
|
||||
assert data['run']['status'] == 'running'
|
||||
assert started_threads == [f"file-check-run-{data['run']['run_id']}"]
|
||||
assert enqueued and enqueued[0]['kwargs'].get('domain') == 'file_check'
|
||||
|
||||
|
||||
def test_serialize_file_judgement_reads_file_key():
|
||||
@@ -1816,7 +1820,10 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -1860,7 +1867,7 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
|
||||
) == run_id
|
||||
|
||||
chat_log_id = None
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
data={'conversation_id': 'sess-registry-001'},
|
||||
@@ -1998,7 +2005,10 @@ def _stub_file_check_thread(monkeypatch):
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
|
||||
def _file_check_agent_proxy(task_id: int):
|
||||
@@ -2049,7 +2059,7 @@ def test_chat_tool_runs_tool_first_then_chat_log(app, client, monkeypatch):
|
||||
assert res.status_code == 200
|
||||
run_id = res.get_json()['run']['run_id']
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
@@ -2094,7 +2104,7 @@ def test_chat_tool_runs_chat_log_first_then_tool(app, client, monkeypatch):
|
||||
admin_id = admin.id
|
||||
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
@@ -2219,7 +2229,7 @@ def test_chat_tool_runs_same_message_does_not_cross_runs(app, client, monkeypatc
|
||||
run_b = res_b.get_json()['run']['run_id']
|
||||
assert run_b == run_a
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
result_b = DifyService._persist_stream_chat_record(
|
||||
@@ -2279,7 +2289,7 @@ def test_chat_tool_runs_without_turn_id_same_message_skips_ambiguous_bind(app, c
|
||||
from app.models import ChatToolRun
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
|
||||
@@ -30,6 +30,67 @@ def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch)
|
||||
assert ShippingInventoryFile.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
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.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-receipt-rpa', 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={})
|
||||
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()
|
||||
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
|
||||
db.session.add(job); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.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)
|
||||
# [断言意图] 桥接发生:收料归档后调拨任务状态推进 file_ready,file_no 为归档文件 id
|
||||
db.session.expire_all()
|
||||
advanced = db.session.get(TransferSourceJob, job.id)
|
||||
assert advanced.status == "file_ready"
|
||||
assert advanced.file_no == str(result["file_id"])
|
||||
|
||||
|
||||
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
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.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-receipt-rpa', 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={})
|
||||
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()
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
|
||||
|
||||
result = ingest_receipt_callback(payload)
|
||||
assert result['status'] == 'failed'
|
||||
# [断言意图] 推进必须已落库而非仅 flush:rollback 丢弃会话内未提交变更,
|
||||
# 只有真正 commit 过的推进才能在 expire_all 后被新查询读到。
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
advanced = db.session.get(TransferSourceJob, job.id)
|
||||
assert advanced.status == 'failed'
|
||||
assert advanced.error_code == 'RPA_TEST_FAIL'
|
||||
|
||||
|
||||
def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
|
||||
"""Callback cannot read arbitrary local xlsx files outside the receipt-only drop root."""
|
||||
from app.core.errors import ValidationError
|
||||
@@ -38,7 +99,7 @@ def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
|
||||
with app.app_context():
|
||||
allowed_root = tmp_path / 'receipt-drop'
|
||||
allowed_root.mkdir()
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
|
||||
outside = tmp_path / 'outside.xlsx'
|
||||
outside.write_bytes(b'not-a-real-xlsx')
|
||||
|
||||
|
||||
@@ -19,9 +19,9 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch
|
||||
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,
|
||||
)
|
||||
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, enabled=True, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, warehouse_ids_json=['A', 'B']),])
|
||||
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, query_parameters_json=[{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['A', 'B'], 'required': False, 'select_all': False}]),])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, enabled=True, report_path_json={'report_name': 'Inbound Details'}, warehouse_ids_json=[]))
|
||||
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[]))
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', job_params={'source_codes': [dbs.source_code, crane.source_code]})
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-1', schedule_task_id=task.id, status='running')
|
||||
@@ -45,10 +45,12 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch
|
||||
}
|
||||
assert dbs_unit['report_path_json']['report_name'] == 'Receipt Detail'
|
||||
assert dbs_unit['warehouse_id'] == 'A'
|
||||
# 关键断言:单元快照必须剥离 Warehouse 条件,Worker 才能按 warehouse_id 自动追加不重复。
|
||||
assert all(item['name'] != 'Warehouse' for item in dbs_unit['query_parameters_json'])
|
||||
|
||||
|
||||
def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
"""动态排程选项只暴露库存站点已启用且收料配置也启用的站点。"""
|
||||
"""动态排程选项只暴露库存站点已启用且已配置收料的站点。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
@@ -56,9 +58,9 @@ def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
inventory_source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'},
|
||||
warehouse_ids_json=['A'],
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['A'], 'required': False, 'select_all': False}],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -74,7 +76,7 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.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-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
@@ -98,7 +100,7 @@ def test_receipt_trigger_is_published_atomically(app, tmp_path):
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
|
||||
written = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'receipt:atomic'}])
|
||||
|
||||
assert written is not None
|
||||
|
||||
@@ -7,18 +7,18 @@ from pathlib import Path
|
||||
|
||||
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
|
||||
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
|
||||
assert 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR' in text
|
||||
assert 'shipping_receipt_rpa.v1' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-batch-ready' in text
|
||||
assert 'freight_rpa_worker' not in text
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
|
||||
assert 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
|
||||
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
receipt_driver = (root / 'receipt' / 'receipt_crane_export.py').read_text(encoding='utf-8')
|
||||
crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8')
|
||||
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver
|
||||
@@ -27,7 +27,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
module_path = root / 'receipt' / 'receipt_crane_export.py'
|
||||
sys.path.insert(0, str(root))
|
||||
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path)
|
||||
@@ -41,3 +41,59 @@ def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
assert module._inbound_details_entry_url('https://wms-portal.craneww.com/') == (
|
||||
'https://wms-portal.craneww.com/#/inbound-details-query'
|
||||
)
|
||||
|
||||
|
||||
def test_receipt_worker_uses_common_trigger_consumer():
|
||||
"""收料 Worker 必须复用公共 claim/归档原语,不再自建目录搬移实现。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'claim_trigger' in text
|
||||
assert 'archive_trigger' in text
|
||||
assert "path.replace(claimed)" not in text # 领取逻辑收敛到公共模块
|
||||
|
||||
|
||||
def test_receipt_worker_logs_full_lifecycle_and_banner():
|
||||
"""收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'configure_file_logging' in text
|
||||
assert 'maybe_rotate_open_log' in text
|
||||
assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段
|
||||
assert '[receipt-unit] success' in text # 成功单元留痕(此前成功路径零输出)
|
||||
assert '[receipt-unit] failed' in text
|
||||
assert '[receipt-trigger] claimed' in text and '[receipt-trigger] archived' in text
|
||||
|
||||
|
||||
def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
|
||||
"""收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
|
||||
|
||||
|
||||
def test_receipt_register_script_mirrors_inventory_with_distinct_identity():
|
||||
"""收料计划任务注册脚本与库存同构(AtLogOn+Interactive+headless),任务名独立可同机并存。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
receipt = (root / 'receipt' / 'register_receipt_worker_tasks.ps1').read_text(encoding='utf-8')
|
||||
inventory = (root / 'inventory' / 'register_inventory_worker_tasks.ps1').read_text(encoding='utf-8')
|
||||
# [断言意图] 任务名赋值行必须指向 Receipt;docstring 允许提及库存任务名(并排设计说明),功能段不得引用
|
||||
assert '$TestTask = "HXOPS Receipt RPA Worker TEST"' in receipt
|
||||
assert '$ProdTask = "HXOPS Receipt RPA Worker PROD"' in receipt
|
||||
assert 'HXOPS Inventory RPA Worker TEST' in inventory and 'HXOPS Receipt RPA Worker' not in inventory
|
||||
# [断言意图] 动作必须指向收料启动脚本,且不得把库存启动脚本带进收料注册
|
||||
assert 'start_receipt_worker.ps1' in receipt and 'start_inventory_worker.ps1' not in receipt
|
||||
# [断言意图] 形状约束与库存同款:AtLogOn + Interactive + headless + 隐藏控制台
|
||||
assert 'AtLogOn' in receipt and 'Interactive' in receipt and 'Headless' in receipt and 'WindowStyle Hidden' in receipt
|
||||
|
||||
|
||||
def test_receipt_worker_supports_opt_in_session_reuse():
|
||||
"""收料 Worker 支持可选跨批次会话复用:ps1 注入开关,worker 按 env 切换持久/一次性 Profile。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
# [断言意图] 开关经 env 读取(默认 false 保持一次性 Profile 行为不变)
|
||||
assert "env('FREIGHT_RPA_WORKER_SESSION_REUSE', 'false')" in text
|
||||
# [断言意图] 复用模式使用持久 receipt_session 目录,且该目录不做批次后删除(跨批次复用登录态)
|
||||
assert "profile_root / 'receipt_session'" in text
|
||||
assert 'not reuse_session' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
|
||||
# [断言意图] 启动脚本提供 -SessionReuse 开关并注入对应 env
|
||||
assert '[switch]$SessionReuse' in ps1
|
||||
assert 'FREIGHT_RPA_WORKER_SESSION_REUSE' in ps1
|
||||
@@ -10,7 +10,7 @@ from pathlib import Path
|
||||
|
||||
|
||||
def _load_freight_rpa_heartbeat_module():
|
||||
rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "rpa"
|
||||
rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa"
|
||||
if str(rpa_dir) not in sys.path:
|
||||
sys.path.insert(0, str(rpa_dir))
|
||||
module_path = rpa_dir / "common" / "rpa_heartbeat.py"
|
||||
@@ -24,7 +24,7 @@ def _load_freight_rpa_heartbeat_module():
|
||||
def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
payload = module.build_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\inventory_drop",
|
||||
@@ -35,15 +35,15 @@ def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
|
||||
|
||||
def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
)
|
||||
assert module._resolve_shared_scope_id() == ""
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
r"C:\mount\hxops-rpa-test-data\inventory_triggers",
|
||||
)
|
||||
assert module._resolve_shared_scope_id() == "hxops-rpa-test-data"
|
||||
@@ -54,7 +54,7 @@ def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
|
||||
|
||||
trigger_dir = tmp_path / "inventory_triggers"
|
||||
trigger_dir.mkdir()
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01")
|
||||
|
||||
sentinel = trigger_dir / ".hxops_rpa_shared_mount"
|
||||
@@ -78,7 +78,7 @@ def test_maybe_send_heartbeat_does_not_block_trigger_loop_when_http_stalls(tmp_p
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(module, "post_heartbeat", stalled_post)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "15")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS", "15")
|
||||
started = time.monotonic()
|
||||
sent_at = module.maybe_send_heartbeat(
|
||||
trigger_dir=tmp_path,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""scripts/rpa/freight_rpa_worker.py tests.
|
||||
"""scripts/freight_rpa/freight_rpa_worker.py tests.
|
||||
|
||||
覆盖货代 RPA worker 对真实库存导出 trigger JSON 的消费路径:
|
||||
1. 读取 inventory_export_SN-20260629-2EDADC77.json。
|
||||
@@ -15,6 +15,7 @@ import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -27,7 +28,7 @@ def _repo_root() -> Path:
|
||||
|
||||
|
||||
def _load_freight_rpa_worker():
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
@@ -162,7 +163,7 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
|
||||
"inventory_sources": [source],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -216,7 +217,7 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_
|
||||
"inventory_sources": [source],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -300,7 +301,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
}],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -359,7 +360,7 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
|
||||
}],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -432,11 +433,11 @@ def test_env_strips_wrapping_quotes(monkeypatch):
|
||||
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", '"user@example.com"')
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "'secret-pass'")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", '"user@example.com"')
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "'secret-pass'")
|
||||
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "user@example.com"
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "secret-pass"
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "user@example.com"
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "secret-pass"
|
||||
|
||||
|
||||
def test_worker_accepts_business_connector_without_site_id():
|
||||
@@ -511,7 +512,7 @@ def test_dsv_sso_blank_transition_refreshes_once_before_portal_wait(monkeypatch)
|
||||
clock['value'] += 3.0
|
||||
return clock['value']
|
||||
|
||||
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000')
|
||||
monkeypatch.setenv('FREIGHT_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000')
|
||||
monkeypatch.setattr(session.time, 'monotonic', monotonic)
|
||||
monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None)
|
||||
monkeypatch.setattr(session, '_debug_dsv_stage', lambda *_args, **_kwargs: None)
|
||||
@@ -533,7 +534,7 @@ def test_dsv_sso_return_timeout_is_explicit(monkeypatch):
|
||||
worker = _load_freight_rpa_worker()
|
||||
session = worker.dsv_session
|
||||
import dsv_auth
|
||||
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000')
|
||||
monkeypatch.setenv('FREIGHT_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000')
|
||||
|
||||
class _Page:
|
||||
url = 'https://auth.dbschenker.com/as/authorization.ping'
|
||||
@@ -569,9 +570,9 @@ def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
|
||||
worker = _load_freight_rpa_worker()
|
||||
key = Fernet.generate_key()
|
||||
cipher = Fernet(key)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", key.decode("ascii"))
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_CREDENTIAL_KEY", key.decode("ascii"))
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_USERNAME", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_DSV_USERNAME", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_DSV_PASSWORD", raising=False)
|
||||
source = {
|
||||
@@ -582,43 +583,40 @@ def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
|
||||
},
|
||||
}
|
||||
with worker._profile_credentials(source):
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "test-user"
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "test-password"
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == ""
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == ""
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "test-user"
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "test-password"
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == ""
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == ""
|
||||
|
||||
|
||||
def test_worker_prefers_canonical_rpa_env_over_legacy_name(monkeypatch):
|
||||
"""新旧 RPA 变量同时存在时必须使用统一的新命名空间,避免旧部署值覆盖新配置。"""
|
||||
def test_worker_ignores_legacy_rpa_name_without_compat(monkeypatch):
|
||||
"""无兼容层:历史旧名(FREIGHT_RPA_MOCK)不作为 FREIGHT_RPA_WORKER_MOCK 的回退,也不发弃用警告。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_MOCK", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
|
||||
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "false"
|
||||
|
||||
|
||||
def test_worker_reads_legacy_rpa_env_during_migration(monkeypatch):
|
||||
"""规范变量缺失时允许读取旧名称,保障 Windows Worker 分阶段迁移不中断。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
|
||||
|
||||
with pytest.warns(DeprecationWarning, match="FREIGHT_RPA_MOCK is deprecated"):
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "true"
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
# 断言 1:仅设置历史旧名时,规范名直读为空、带默认值读回默认值(旧名不被咨询)。
|
||||
assert worker._env("FREIGHT_RPA_WORKER_MOCK") == ""
|
||||
assert worker._env("FREIGHT_RPA_WORKER_MOCK", "false") == "false"
|
||||
# 断言 2:读取过程不产生任何 DeprecationWarning(兼容层已删除)。
|
||||
assert not any(issubclass(item.category, DeprecationWarning) for item in caught)
|
||||
|
||||
|
||||
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
|
||||
"""配置 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
"""配置 FREIGHT_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
|
||||
# 等价迁移:文件日志实现已提取至公共 worker_logging 模块,本用例改测公共接口。
|
||||
worker_logging = _load_worker_logging()
|
||||
log_path = tmp_path / "logs" / "worker.log"
|
||||
timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ")
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(log_path))
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_FILE", str(log_path))
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
|
||||
try:
|
||||
resolved = worker._configure_file_logging()
|
||||
resolved = worker_logging.configure_file_logging()
|
||||
print("hello stdout")
|
||||
print("hello stderr", file=sys.stderr)
|
||||
finally:
|
||||
@@ -644,16 +642,17 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
|
||||
|
||||
|
||||
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
|
||||
"""日志超过 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
"""日志超过 FREIGHT_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
|
||||
# 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。
|
||||
worker_logging = _load_worker_logging()
|
||||
log_path = tmp_path / "worker.log"
|
||||
log_path.write_text("current-log", encoding="utf-8")
|
||||
Path(f"{log_path}.1").write_text("old-1", encoding="utf-8")
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2")
|
||||
|
||||
worker._rotate_log_file_if_needed(log_path)
|
||||
worker_logging.rotate_log_file_if_needed(log_path)
|
||||
|
||||
assert not log_path.exists()
|
||||
assert Path(f"{log_path}.1").read_text(encoding="utf-8") == "current-log"
|
||||
@@ -662,21 +661,44 @@ def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
|
||||
|
||||
def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp_path):
|
||||
"""备份数量为 0 时,超过大小的当前日志应直接删除。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
# 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。
|
||||
worker_logging = _load_worker_logging()
|
||||
log_path = tmp_path / "worker.log"
|
||||
log_path.write_text("current-log", encoding="utf-8")
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "0")
|
||||
|
||||
worker._rotate_log_file_if_needed(log_path)
|
||||
worker_logging.rotate_log_file_if_needed(log_path)
|
||||
|
||||
assert not log_path.exists()
|
||||
|
||||
|
||||
def _load_worker_logging():
|
||||
"""加载 scripts/freight_rpa/common/worker_logging.py 供单测直接断言。
|
||||
|
||||
历史背景:文件日志实现(tee/轮转/时间戳)原内置于 inventory_rpa_worker.py,
|
||||
已提取为公共模块;Worker 内部私有名(_configure_file_logging 等)已删除,
|
||||
日志行为用例统一改测公共接口,行为断言保持等价。
|
||||
"""
|
||||
common_dir = _repo_root() / "scripts" / "freight_rpa" / "common"
|
||||
if str(common_dir) not in sys.path:
|
||||
sys.path.insert(0, str(common_dir))
|
||||
module_path = common_dir / "worker_logging.py"
|
||||
spec = importlib.util.spec_from_file_location("worker_logging_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
# 模块顶层 `from rpa_common import _env` 依赖 sys.path,须先登记再执行;
|
||||
# _ACTIVE_* 运行态按用例独立加载实例,避免跨用例状态串扰。
|
||||
sys.modules[spec.name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _load_worker_disk_cleanup():
|
||||
"""加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py"
|
||||
"""加载 scripts/freight_rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py"
|
||||
spec = importlib.util.spec_from_file_location("worker_disk_cleanup_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
@@ -762,8 +784,8 @@ def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypat
|
||||
(orphan_run / "Cookies").write_text("drop", encoding="utf-8")
|
||||
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "7")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "7")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
stats = cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
@@ -810,8 +832,8 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
|
||||
orphan_run.mkdir()
|
||||
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "0")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "0")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
@@ -823,8 +845,41 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
|
||||
assert not orphan_run.exists()
|
||||
|
||||
|
||||
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。"""
|
||||
def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
|
||||
"""
|
||||
崩溃残留的 receipt_* 临时 Profile 超期必须被清理;_session 目录保留。
|
||||
|
||||
断言意图:收料 Worker 的一次性 Profile 以 receipt_ 前缀创建,异常中断后
|
||||
残留目录同样按孤儿 Profile 规则清理;会话复用目录按名豁免(与年龄无关);
|
||||
未超期的 receipt_* Profile 正在使用中,前缀匹配不得误删。
|
||||
"""
|
||||
cleanup = _load_worker_disk_cleanup()
|
||||
root = tmp_path / "browser_profile"
|
||||
stale_receipt = root / "receipt_abcd1234"
|
||||
stale_receipt.mkdir(parents=True)
|
||||
(stale_receipt / "Cookies").write_text("drop", encoding="utf-8")
|
||||
young_receipt = root / "receipt_fresh5678"
|
||||
young_receipt.mkdir()
|
||||
session_dir = root / "dsv_session"
|
||||
session_dir.mkdir()
|
||||
now = time.time()
|
||||
old = now - 10 * 24 * 3600
|
||||
os.utime(stale_receipt, (old, old))
|
||||
os.utime(young_receipt, (now - 3600, now - 3600))
|
||||
os.utime(session_dir, (old, old))
|
||||
stats = cleanup.DiskCleanupStats()
|
||||
|
||||
# cutoff 对齐真实调用语义:run_worker_disk_cleanup 传入 now - 孤儿最大存活(默认 24h)
|
||||
cleanup.cleanup_orphan_runtime_profiles(root, cutoff_unix=now - 24 * 3600, stats=stats)
|
||||
|
||||
# 过期 receipt_* 目录树删除;未过期 receipt_* 与 _session 结尾目录即使过期也保留
|
||||
assert not stale_receipt.exists() and session_dir.exists()
|
||||
assert young_receipt.exists()
|
||||
assert stats.deleted_dirs == 1
|
||||
|
||||
|
||||
def test_open_browser_uses_freight_rpa_common_profile_fallback(monkeypatch):
|
||||
"""未配置 profile 根目录时,应回退到 freight_rpa/common 布局的 browser_profile。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
@@ -848,12 +903,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "true")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
temp_roots: list[Path] = []
|
||||
@@ -872,7 +926,8 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
|
||||
assert context is not None
|
||||
assert page is not None
|
||||
expected_root = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
|
||||
# 断言意图:bare-run 默认值必须等于 freight_rpa 三层布局的 common/browser_profile
|
||||
expected_root = _repo_root() / "backend" / "data" / "freight_rpa" / "common" / "browser_profile"
|
||||
assert temp_roots == [expected_root]
|
||||
assert runtime_profile_dir == expected_root / "run_unit"
|
||||
assert runtime_profile_dir.parent == expected_root
|
||||
@@ -888,7 +943,7 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa
|
||||
"""profile 根目录配置为 data/shipping_notice 时,应按 backend 根目录解析。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"data/shipping_notice/freight_rpa/browser_profile",
|
||||
)
|
||||
|
||||
@@ -897,30 +952,32 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa
|
||||
assert worker._browser_profile_root() == expected.resolve()
|
||||
|
||||
|
||||
def test_browser_profile_root_remaps_legacy_freight_rpa_path(monkeypatch):
|
||||
"""本机残留旧 profile 路径时,应强制迁到 shipping_notice 命名空间。"""
|
||||
def test_browser_profile_root_keeps_freight_rpa_layout_without_remap(monkeypatch, capsys):
|
||||
"""profile 配置为 freight_rpa 布局路径时,应按字面解析:不改写、不告警(无兼容层红线)。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"backend/data/freight_rpa/browser_profile",
|
||||
"FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"data/freight_rpa/browser_profile",
|
||||
)
|
||||
|
||||
expected = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
|
||||
# 断言意图:迁移期 remap 已删除,旧布局形状的配置值必须原样落到 backend 根下
|
||||
expected = _repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"
|
||||
|
||||
assert worker._browser_profile_root() == expected.resolve()
|
||||
# 断言意图:不得再输出 legacy 改写告警
|
||||
assert "legacy" not in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_browser_profile_root_remaps_absolute_legacy_freight_rpa_path(monkeypatch):
|
||||
"""本机环境变量保存绝对旧路径时,也应迁到 shipping_notice 命名空间。"""
|
||||
def test_browser_profile_root_keeps_absolute_freight_rpa_layout_without_remap(monkeypatch, capsys):
|
||||
"""绝对 freight_rpa 路径同样按字面解析,证明 remap 分支已完全移除。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
str(_repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"),
|
||||
)
|
||||
profile_dir = _repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(profile_dir))
|
||||
|
||||
expected = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
|
||||
|
||||
assert worker._browser_profile_root() == expected.resolve()
|
||||
# 断言意图:绝对路径不再被强制迁往 shipping_notice 命名空间
|
||||
assert worker._browser_profile_root() == profile_dir.resolve()
|
||||
# 断言意图:不得再输出 legacy 改写告警
|
||||
assert "legacy" not in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path):
|
||||
@@ -944,7 +1001,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
out_file.write_bytes(b"fake inventory content")
|
||||
return out_file
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
@@ -1002,8 +1059,8 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
processed_dir = trigger_dir / "processed"
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -1064,7 +1121,7 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
|
||||
def raise_no_inventory(_trigger: dict, _drop: Path):
|
||||
raise worker.NoInventoryDataError("DSV report has no inventory data")
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
@@ -1129,7 +1186,7 @@ def test_real_upload_requires_connection_config_enabled(monkeypatch, tmp_path):
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
|
||||
with pytest.raises(RuntimeError, match="not enabled for this connection"):
|
||||
worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={"upload_config_json": {"enabled": False}})
|
||||
@@ -1140,8 +1197,8 @@ def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
events: list[tuple[str, object]] = []
|
||||
|
||||
class _Locator:
|
||||
@@ -1187,7 +1244,7 @@ def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
|
||||
runtime_profile = tmp_path / "profile"
|
||||
runtime_profile.mkdir()
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir, **_kwargs: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
|
||||
def fake_result(_page, filename):
|
||||
return {"reference": "", "success_evidence": {"kind": "dsv_upload_success_dom", "selector": ".alert.alert-success", "filename": filename, "reference": None, "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<div/>", "dom_sha256": "abc"}}
|
||||
@@ -1217,8 +1274,8 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
events: list[tuple[str, object]] = []
|
||||
|
||||
class _Locator:
|
||||
@@ -1256,7 +1313,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
runtime_profile = tmp_path / "profile"
|
||||
runtime_profile.mkdir()
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir, **_kwargs: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda _page, _filename: {"reference": "", "success_evidence": {}})
|
||||
|
||||
assert worker._upload_shipment_with_browser(
|
||||
@@ -1348,7 +1405,7 @@ def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch):
|
||||
return clock["value"]
|
||||
|
||||
monkeypatch.setattr(worker.time, "monotonic", monotonic)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000")
|
||||
|
||||
with pytest.raises(RuntimeError, match="did not confirm a green success status"):
|
||||
worker._wait_for_dsv_upload_history_receipt(_Page(), "shipment.xlsx")
|
||||
@@ -1484,7 +1541,7 @@ def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path):
|
||||
"task_no": "SN-UPLOAD-FAIL", "file_path": str(queue_file), "attempt_id": 8, "callback_id": "rpa:8",
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_upload_shipment_with_browser", lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("success marker missing")))
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
@@ -1507,7 +1564,7 @@ def test_upload_empty_queue_path_reports_failed_callback(monkeypatch, tmp_path):
|
||||
"task_no": "SN-UPLOAD-EMPTY", "attempt_id": 9, "callback_id": "rpa:9",
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
|
||||
@@ -1573,12 +1630,11 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", "msedge")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads")
|
||||
@@ -1621,9 +1677,8 @@ def test_open_browser_reuses_session_profile_per_connector_and_rpa_profile(monke
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
@@ -1665,8 +1720,8 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
@@ -1791,6 +1846,190 @@ def test_fill_dsv_username_reuses_detected_email_locator(monkeypatch):
|
||||
assert locator.value == "user@example.com"
|
||||
|
||||
|
||||
def test_maybe_switch_dsv_locale_to_zh_cn_skips_when_already_zh(monkeypatch):
|
||||
"""已是中文简体时不重复点语言下拉。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._maybe_switch_dsv_locale_to_zh_cn.__globals__
|
||||
clicks = {"value": 0}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, text: str = "") -> None:
|
||||
self.first = self
|
||||
self._text = text
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return self._text
|
||||
|
||||
def click(self, *args, **kwargs) -> None:
|
||||
clicks["value"] += 1
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if selector == "#lanNavSel":
|
||||
return _FakeLocator("中文简体")
|
||||
return _FakeLocator("")
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeFrame().locator(selector)
|
||||
|
||||
monkeypatch.setitem(auth_globals, "_dsv_switch_zh_cn_enabled", lambda: True)
|
||||
assert worker._maybe_switch_dsv_locale_to_zh_cn(_FakePage()) is True
|
||||
assert clicks["value"] == 0
|
||||
|
||||
|
||||
def test_maybe_switch_dsv_locale_to_zh_cn_clicks_english_to_simplified(monkeypatch):
|
||||
"""English 时点 #kc_locale 再选中文简体,并在标签变为中文后返回 True。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._maybe_switch_dsv_locale_to_zh_cn.__globals__
|
||||
state = {"label": "English", "opened": False, "clicks": []}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, kind: str) -> None:
|
||||
self.first = self
|
||||
self._kind = kind
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return state["label"]
|
||||
|
||||
def click(self, *args, **kwargs) -> None:
|
||||
state["clicks"].append(self._kind)
|
||||
if self._kind == "toggle":
|
||||
state["opened"] = True
|
||||
if self._kind == "zh":
|
||||
state["label"] = "中文简体"
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if selector == "#lanNavSel":
|
||||
return _FakeLocator("label")
|
||||
if selector == "#kc_locale":
|
||||
return _FakeLocator("toggle")
|
||||
if "中文简体" in selector:
|
||||
if not state["opened"]:
|
||||
raise RuntimeError("menu closed")
|
||||
return _FakeLocator("zh")
|
||||
raise RuntimeError(f"unexpected selector {selector}")
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeFrame().locator(selector)
|
||||
|
||||
monkeypatch.setitem(auth_globals, "_dsv_switch_zh_cn_enabled", lambda: True)
|
||||
monkeypatch.setattr(auth_globals["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
current = ticks["value"]
|
||||
ticks["value"] += 0.5
|
||||
return current
|
||||
|
||||
monkeypatch.setattr(auth_globals["time"], "monotonic", fake_monotonic)
|
||||
|
||||
assert worker._maybe_switch_dsv_locale_to_zh_cn(_FakePage()) is True
|
||||
assert state["clicks"] == ["toggle", "zh"]
|
||||
assert state["label"] == "中文简体"
|
||||
|
||||
|
||||
def test_maybe_switch_dsv_locale_to_zh_cn_disabled_by_env(monkeypatch):
|
||||
"""环境变量关闭时不尝试切语言。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._maybe_switch_dsv_locale_to_zh_cn.__globals__
|
||||
monkeypatch.setitem(auth_globals, "_dsv_switch_zh_cn_enabled", lambda: False)
|
||||
assert worker._maybe_switch_dsv_locale_to_zh_cn(object()) is False
|
||||
|
||||
|
||||
def test_is_dsv_password_method_label_matches_english_subtitle_row():
|
||||
"""
|
||||
英文 MFA 页「Password + Enter your password to sign in.」整行须识别为密码方式;
|
||||
Passkey / Mobile App / E-Mail Code 不得误判(对应 2026-09-16 worker 失败页)。
|
||||
"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
assert worker._is_dsv_password_method_label("Password") is True
|
||||
assert worker._is_dsv_password_method_label("Password\nEnter your password to sign in.") is True
|
||||
assert worker._is_dsv_password_method_label("密码") is True
|
||||
assert worker._is_dsv_password_method_label("Passkey\nUse this device to sign in.") is False
|
||||
assert worker._is_dsv_password_method_label("Mobile App (iPhone 11)\nUse your PingID app to sign in.") is False
|
||||
assert worker._is_dsv_password_method_label("E-Mail Code\nEnter a 6-digit code sent to your inbox.") is False
|
||||
assert worker._is_dsv_password_method_label("Forgot password") is False
|
||||
|
||||
|
||||
def test_click_dsv_password_method_clicks_english_choose_sign_in_row(monkeypatch):
|
||||
"""
|
||||
当页面只有带副标题的 Password 行(无旧 mfaForm 精确标题)时,仍应点击并确认过渡。
|
||||
"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._click_dsv_password_method.__globals__
|
||||
clicked = {"value": False}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, text: str = "") -> None:
|
||||
self.first = self
|
||||
self._text = text
|
||||
|
||||
def all(self):
|
||||
return [self] if self._text else []
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return self._text
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
if not self._text:
|
||||
raise RuntimeError("not visible")
|
||||
|
||||
def scroll_into_view_if_needed(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def click(self, *args, **kwargs) -> None:
|
||||
clicked["value"] = True
|
||||
|
||||
def evaluate(self, *args, **kwargs) -> None:
|
||||
clicked["value"] = True
|
||||
|
||||
class _FakeFrame:
|
||||
def evaluate(self, script: str, *args, **kwargs):
|
||||
# 脚本路径故意失败,迫使走 Playwright 行点击兜底
|
||||
return False
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if "listitem" in selector or "mb-2" in selector or "device-list" in selector:
|
||||
return _FakeLocator("Password\nEnter your password to sign in.")
|
||||
return _FakeLocator("")
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
url = "https://auth.dbschenker.com/as/mock/resume/as/authorization.ping"
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeFrame().locator(selector)
|
||||
|
||||
monkeypatch.setattr(auth_globals["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
current = ticks["value"]
|
||||
ticks["value"] += 0.1
|
||||
return current
|
||||
|
||||
monkeypatch.setattr(auth_globals["time"], "monotonic", fake_monotonic)
|
||||
monkeypatch.setitem(auth_globals, "_find_dsv_password_locator", lambda *args, **kwargs: object())
|
||||
monkeypatch.setitem(auth_globals, "_wait_for_visible_selector", lambda *args, **kwargs: object())
|
||||
monkeypatch.setitem(auth_globals, "_looks_like_dsv_login_method_page", lambda page: False)
|
||||
|
||||
assert worker._click_dsv_password_method(_FakePage()) is True
|
||||
assert clicked["value"] is True
|
||||
|
||||
|
||||
def test_click_dsv_password_method_ignores_forgot_password_link(monkeypatch):
|
||||
"""密码页的“忘记密码/Forgot password”链接不能被当成密码登录方式点击。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -1988,7 +2227,7 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch):
|
||||
|
||||
def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch):
|
||||
"""登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。"""
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_export.py"
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_export.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_export_retry_test", module_path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
dsv_report_export = importlib.util.module_from_spec(spec)
|
||||
@@ -2188,7 +2427,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
|
||||
|
||||
worker._fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"Owner",
|
||||
"CADU-0000000100",
|
||||
)
|
||||
@@ -2224,7 +2463,7 @@ def test_fill_dsv_filter_if_needed_accepts_report_name_kwarg():
|
||||
|
||||
worker._fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"Owner",
|
||||
"CADU-0000000100",
|
||||
report_name="On Hand Inventory by Location",
|
||||
@@ -2380,26 +2619,26 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
|
||||
"""
|
||||
手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。
|
||||
|
||||
默认跳过;仅当 SHIPPING_NOTICE_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码:
|
||||
- SHIPPING_NOTICE_RPA_WORKER_MOCK=false
|
||||
- SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false(建议首次调试)
|
||||
- SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
|
||||
- SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD
|
||||
默认跳过;仅当 FREIGHT_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码:
|
||||
- FREIGHT_RPA_WORKER_MOCK=false
|
||||
- FREIGHT_RPA_WORKER_HEADLESS=false(建议首次调试)
|
||||
- FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
|
||||
- FREIGHT_RPA_WORKER_DSV_USERNAME / FREIGHT_RPA_WORKER_DSV_PASSWORD
|
||||
"""
|
||||
if str(os.getenv("SHIPPING_NOTICE_RPA_WORKER_E2E") or "").strip().lower() != "true":
|
||||
pytest.skip("set SHIPPING_NOTICE_RPA_WORKER_E2E=true to run real freight RPA export")
|
||||
if str(os.getenv("FREIGHT_RPA_WORKER_E2E") or "").strip().lower() != "true":
|
||||
pytest.skip("set FREIGHT_RPA_WORKER_E2E=true to run real freight RPA export")
|
||||
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger = _build_inventory_export_trigger("SN-20260629-2EDADC77")
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS"):
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
|
||||
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR"):
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
if not os.getenv("FREIGHT_RPA_WORKER_HEADLESS"):
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false")
|
||||
if not os.getenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR"):
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
str(tmp_path / "browser_profile"),
|
||||
)
|
||||
|
||||
@@ -2409,3 +2648,45 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
|
||||
assert out_file.parent == drop_dir
|
||||
assert out_file.suffix.lower() in {".xlsx", ".xls", ".csv"}
|
||||
assert out_file.stat().st_size > 0
|
||||
|
||||
|
||||
def test_ensure_dsv_session_continues_auto_login_after_goto_abort(monkeypatch):
|
||||
"""未登录时 goto 被 SSO 重定向以 ERR_ABORTED 中止:应继续自动登录,而不是判死整个源。"""
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_export.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_export_abort_test", module_path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
dsv_report_export = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(dsv_report_export)
|
||||
|
||||
class _FakeGotoAbort(Exception):
|
||||
pass
|
||||
|
||||
login_calls: list[str] = []
|
||||
goto_calls: list[str] = []
|
||||
|
||||
monkeypatch.setattr(dsv_report_export, "_is_dsv_session_active", lambda page, entry_url: False)
|
||||
monkeypatch.setattr(
|
||||
dsv_report_export,
|
||||
"_goto_dsv_entry_url",
|
||||
lambda page, entry_url: (goto_calls.append(entry_url), (_ for _ in ()).throw(_FakeGotoAbort("Page.goto: net::ERR_ABORTED at https://s360.dbschenker.com/main/portal")))[0],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dsv_report_export,
|
||||
"_maybe_auto_login_dsv",
|
||||
lambda page: login_calls.append("login"),
|
||||
)
|
||||
monkeypatch.setattr(dsv_report_export, "_is_dsv_on_entry_site", lambda page, entry_url: True)
|
||||
monkeypatch.setattr(
|
||||
dsv_report_export,
|
||||
"_wait_for_dsv_home_ready",
|
||||
lambda page, timeout_ms=None: None,
|
||||
)
|
||||
monkeypatch.setattr(dsv_report_export, "_wait_for_dsv_reports_nav_stable", lambda page, timeout_ms=None: None)
|
||||
|
||||
entry_url = "https://s360.dbschenker.com/"
|
||||
dsv_report_export._ensure_dsv_session(object(), entry_url)
|
||||
|
||||
# [断言意图] goto 被中止后必须继续自动登录(正是未登录才会被 SSO 重定向打断);
|
||||
# 登录成功后直接等待首页就绪,不重复 goto entry(该二次跳转仅在 home-not-ready 分支出现)
|
||||
assert goto_calls == [entry_url]
|
||||
assert login_calls == ["login"]
|
||||
@@ -34,7 +34,7 @@ _RPA_MODULE_PATHS = {
|
||||
|
||||
def _load_rpa_module(module_name: str):
|
||||
rel = _RPA_MODULE_PATHS.get(module_name, f"{module_name}.py")
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / rel
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / rel
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
sys.path.insert(0, scripts_dir)
|
||||
@@ -59,12 +59,12 @@ def test_fill_report_parameter_multi_select(monkeypatch):
|
||||
page,
|
||||
{
|
||||
"name": "Warehouse",
|
||||
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"mode": "multi_select",
|
||||
"values": ["WH1", "WH2"],
|
||||
},
|
||||
)
|
||||
assert calls == [("SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
|
||||
assert calls == [("FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
|
||||
|
||||
|
||||
def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
|
||||
@@ -96,7 +96,7 @@ def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
|
||||
)
|
||||
assert calls == [
|
||||
{
|
||||
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"label": "Warehouse",
|
||||
"values": ["RTM"],
|
||||
"selectors": None,
|
||||
@@ -136,7 +136,7 @@ def test_fill_report_parameter_multi_select_jda_report_passes_template_selectors
|
||||
)
|
||||
assert calls == [
|
||||
{
|
||||
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"label": "Warehouse",
|
||||
"values": ["RTM"],
|
||||
"selectors": None,
|
||||
@@ -418,8 +418,8 @@ def test_dsv_existing_portal_session_skips_all_auth_probes(monkeypatch):
|
||||
"""持久化 Profile 已恢复 Portal 时,不得先等待用户名或认证页面。"""
|
||||
flow = _load_dsv_auth_login_flow()
|
||||
page = MagicMock()
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "user")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "password")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", "user")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "password")
|
||||
selector_wait = MagicMock()
|
||||
auth_ready = MagicMock()
|
||||
monkeypatch.setattr(flow, "_has_existing_dsv_portal_session", lambda _page: True)
|
||||
|
||||
@@ -91,7 +91,7 @@ def test_fetch_gate_positions_batched(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
ot_b = ShippingOrderTask(
|
||||
@@ -345,7 +345,7 @@ def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
@@ -412,3 +412,102 @@ def test_user_mode_review_status_must_human():
|
||||
review_status=rs,
|
||||
lifecycle_stage=None,
|
||||
) == 'must_human'
|
||||
|
||||
|
||||
def test_sql_todo_category_review_gate_blocked_is_review(app):
|
||||
"""订单复核 Gate 阻断必须进 review,不得落入 in_progress。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-REVIEW-BLOCK')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-REVIEW-BLOCK',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='order_review',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-SQL-REVIEW-BLOCK',
|
||||
task_id=int(ot.id),
|
||||
status='blocked',
|
||||
current_gate_code='order_field_extraction',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'review'
|
||||
|
||||
|
||||
def test_sql_todo_category_running_inventory_prep_is_in_progress(app):
|
||||
"""库存准备 Execution=active 才是系统处理中。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-RUNNING')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-RUNNING-PREP',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='processing',
|
||||
stage='notification_preparation',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-SQL-RUNNING-PREP',
|
||||
task_id=int(ot.id),
|
||||
status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'in_progress'
|
||||
|
||||
|
||||
def test_sql_todo_category_without_gate_is_not_in_progress(app):
|
||||
"""无 Gate 的 OT 不得进入处理中桶。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-NO-GATE')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-NO-GATE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='order_review',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'exception'
|
||||
@@ -9,7 +9,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
|
||||
"""POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
@@ -126,7 +126,7 @@ def _published_template(*, code: str) -> ShippingExcelTemplate:
|
||||
def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path):
|
||||
"""测试文件只能生成测试分析,重复发起复用运行,禁止创建生产库存快照。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -150,8 +150,8 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app,
|
||||
drop_dir = tmp_path / 'inventory_drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -170,7 +170,7 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app,
|
||||
|
||||
def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
|
||||
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -211,7 +211,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend
|
||||
|
||||
def test_empty_configuration_export_without_published_profile_is_rejected(app):
|
||||
"""没有受控解析定义时,空结果不能被用作站点可用性的替代证据。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -228,7 +228,7 @@ def test_empty_configuration_export_without_published_profile_is_rejected(app):
|
||||
|
||||
def test_configuration_test_automatically_verifies_compatible_bound_profile(app, tmp_path):
|
||||
"""当前绑定方案的核心栏位仍在时,历史无关列缺失也必须直接成为验证证据。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -248,7 +248,7 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app,
|
||||
|
||||
def test_verified_current_profile_automatically_enables_ready_source(app, tmp_path):
|
||||
"""当前解析验证通过且必要条件齐全时,站点无需人工确认即可自动启用。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -270,7 +270,7 @@ def test_verified_current_profile_automatically_enables_ready_source(app, tmp_pa
|
||||
|
||||
def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path):
|
||||
"""解析测试通过不绕过发货模板门禁,条件不完整的站点必须保持停用。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -291,7 +291,7 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm
|
||||
|
||||
def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path):
|
||||
"""固定仓查询成功但无库存时,也能在完整门禁下自动启用站点。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -314,7 +314,7 @@ def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path):
|
||||
|
||||
def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path):
|
||||
"""同连接站点一次投递,混合成功、空库存及失败后仍独立汇总为部分失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
) as write_trigger:
|
||||
@@ -356,7 +356,7 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app,
|
||||
|
||||
def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
||||
"""批次重试只新建失败站点运行,成功和空库存结果不会被重复导出。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -378,7 +378,7 @@ def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
||||
|
||||
def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app, tmp_path):
|
||||
"""配置变更后的旧批次回调必须失效,未知运行号不能污染同批次状态。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -406,7 +406,7 @@ def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app,
|
||||
|
||||
def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
|
||||
"""页面刷新只能恢复仍在执行的批次,已结束批次不会反复占用进度面板。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -428,7 +428,7 @@ def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
|
||||
|
||||
def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path):
|
||||
"""Worker 领取回调只更新本批次当前运行,终态运行不得被重新打开。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -461,7 +461,7 @@ def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path)
|
||||
def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_path):
|
||||
"""重开配置抽屉只能恢复当前版本测试;站点改动后可发起独立新测试而不复用旧运行。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -482,8 +482,8 @@ def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_
|
||||
def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
"""RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -511,8 +511,8 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
|
||||
def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
|
||||
"""同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -538,7 +538,7 @@ def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, t
|
||||
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
|
||||
"""确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -581,7 +581,7 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
|
||||
def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path):
|
||||
"""连接凭据或登录配置变更后,旧测试不得继续作为当前库存站点的启用证据。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -611,7 +611,7 @@ def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path):
|
||||
def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path):
|
||||
"""正式运行中的站点不能发起测试;站点配置变化后旧测试不得绑定。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -654,7 +654,7 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
|
||||
def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
|
||||
"""失败回调和非推荐方案均不得产生生产快照或修改站点解析方案。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
|
||||
@@ -114,7 +114,7 @@ def _excel_template_id() -> int:
|
||||
|
||||
def test_published_parsing_profile_can_be_shared_by_sources(app):
|
||||
"""同一 published Profile 应可绑定多个库存源,避免重复维护相同模板。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
parsing = _published_profile()
|
||||
login = shipping_inventory_service.save_profile({
|
||||
@@ -132,7 +132,7 @@ def test_published_parsing_profile_can_be_shared_by_sources(app):
|
||||
|
||||
def test_source_rejects_draft_parsing_profile(app):
|
||||
"""库存源只能绑定 published Profile,避免运行期读取可变草稿。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
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)
|
||||
@@ -175,7 +175,7 @@ def test_csv_parsing_profile_rejects_worksheet_configuration(app):
|
||||
|
||||
def test_new_published_version_does_not_retire_bound_version(app):
|
||||
"""发布新版本不得使现有库存源绑定的旧 published 版本失效。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
first = _published_profile()
|
||||
field_id = order_schema_service.get_state()['fields'][0]['id']
|
||||
@@ -195,7 +195,7 @@ def test_new_published_version_does_not_retire_bound_version(app):
|
||||
|
||||
def test_referenced_published_profile_cannot_be_retired(app):
|
||||
"""已绑定库存源的解析 Profile 必须先迁移 Source,不能直接退役。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
parsing = _published_profile()
|
||||
login = shipping_inventory_service.save_profile({
|
||||
|
||||
@@ -12,7 +12,7 @@ from pathlib import Path
|
||||
|
||||
def _load_worker():
|
||||
module_path = (
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
)
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
tests/test_line_closure_export.py
|
||||
|
||||
用途:验证滚动导出资格对已结案行的剔除(含"有库存的结案行也不导出"边缘场景)。
|
||||
依赖:pytest、reservation_service、fulfillment_workflow、核验/预约模型、行级履约决定。
|
||||
逻辑:两行均有可用预约,结案其一后,导出资格集合只保留未结案行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryVerification,
|
||||
ShippingInventoryVerificationLine,
|
||||
ShippingReservation,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import exportable_snapshot_line_ids
|
||||
from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
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')
|
||||
db.session.add(verification)
|
||||
db.session.flush()
|
||||
for index, snap_line in enumerate(fixture.snap_lines):
|
||||
reservation = ShippingReservation(
|
||||
task_id=fixture.order.id, snapshot_line_id=snap_line.id,
|
||||
reservation_id=f'RSV-CLOSE-{index}', po_number_normalized='PO-CLOSE',
|
||||
part_number=snap_line.part_number, required_qty=Decimal('10'), status='available',
|
||||
)
|
||||
db.session.add(reservation)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryVerificationLine(
|
||||
verification_id=verification.id, reservation_id=reservation.id,
|
||||
required_qty=Decimal('10'), available_qty=Decimal('10'), status='available',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_closed_line_with_inventory_is_not_exportable(app):
|
||||
"""结案行即使库存充足、核验 available 也不得进入导出资格集合。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_available_reservations(fixture)
|
||||
_seed_close_decision(fixture, 1)
|
||||
_verification, available = current_available_snapshot_line_ids(
|
||||
fixture.order, closed_snapshot_line_ids={int(fixture.snap_lines[1].id)},
|
||||
)
|
||||
# 断言:仅未结案的第 0 行可导出。
|
||||
assert available == {int(fixture.snap_lines[0].id)}
|
||||
|
||||
|
||||
def test_exportable_snapshot_line_ids_excludes_closed(app):
|
||||
"""滚动导出入口(exportable_snapshot_line_ids)自动剔除结案行。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_available_reservations(fixture)
|
||||
_seed_close_decision(fixture, 1)
|
||||
# 断言:导出集合不含结案行(该行预约仍 available,验证 closed 过滤优先)。
|
||||
assert exportable_snapshot_line_ids(fixture.order) == {int(fixture.snap_lines[0].id)}
|
||||
@@ -0,0 +1,141 @@
|
||||
"""
|
||||
tests/test_line_closure_fulfillment.py
|
||||
|
||||
用途:验证行结案(close_unfulfillable)在满足性聚合与整单门禁中的豁免语义。
|
||||
依赖:pytest、fulfillment_workflow、行级履约决定模型、冻结订单夹具。
|
||||
逻辑:两行订单关闭短缺行后整单应判定满足;全部行结案时整单不通过(无剩余履约内容)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
_closed_snapshot_line_ids_for_task,
|
||||
_recompute_task_match_aggregate,
|
||||
match_completed,
|
||||
)
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
|
||||
|
||||
def _seed_match_facts(fixture):
|
||||
"""第 0 行 matched+ready,第 1 行 not_found 短缺(历史阻塞点)。"""
|
||||
for snap_line, result, shortage in (
|
||||
(fixture.snap_lines[0], 'matched', '0'),
|
||||
(fixture.snap_lines[1], 'not_found', '10'),
|
||||
):
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
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',
|
||||
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,
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _seed_close_decision(fixture, line_index, *, case_no='SNRC-CLOSE-1', version=1):
|
||||
"""给已确认 Case 补一条活动结案决定(FK 不强制,挂哨兵父 id 即可)。"""
|
||||
case = ShippingOrderReviewCase.query.filter_by(case_no=case_no).first()
|
||||
if case is None:
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no=case_no, run_id=901, unit_id=902, document_id=903,
|
||||
owner_user_id=fixture.user.id, status='confirmed', confirmed_task_id=fixture.order.id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewLineDecision(
|
||||
review_case_id=case.id, draft_line_id=f'line-{line_index}', line_index=line_index,
|
||||
decision_version=version, decision_code='close_unfulfillable', decision_source='user',
|
||||
line_status='closed_unfulfillable', is_active=True, reason='该行不再发货',
|
||||
actor_user_id=fixture.user.id, snapshot_json={},
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_closed_line_ids_helper_mirrors_release_query(app):
|
||||
"""结案行集合必须与放行同款:活动决定 + line_index 映射快照行。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_close_decision(fixture, 1)
|
||||
# 断言:仅第 1 行(line_index=1)进入结案集合。
|
||||
assert _closed_snapshot_line_ids_for_task(fixture.order) == {int(fixture.snap_lines[1].id)}
|
||||
|
||||
|
||||
def test_aggregate_exempts_closed_shortage_line(app):
|
||||
"""关闭短缺行后聚合应判满足:closed 行不阻断、不进缺货列表。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
_seed_close_decision(fixture, 1)
|
||||
status, shortages = _recompute_task_match_aggregate(fixture.order)
|
||||
payload = fixture.order.step_payload_json or {}
|
||||
line_results = payload['current_match_projection']['line_results']
|
||||
# 断言:整单满足、缺货列表为空、结案行状态为 closed 而非 shortage。
|
||||
assert status == 'fulfillable'
|
||||
assert shortages == []
|
||||
assert line_results[1]['line_status'] == 'closed'
|
||||
|
||||
|
||||
def test_match_completed_passes_with_closed_line(app):
|
||||
"""整单满足性门禁对结案行豁免:一行 matched + 一行 closed 即通过。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
# 断言:结案前整单不通过(历史阻塞行为)。
|
||||
assert match_completed(fixture.order) is False
|
||||
_seed_close_decision(fixture, 1)
|
||||
# 断言:结案后整单通过(本任务修复目标)。
|
||||
assert match_completed(fixture.order) is True
|
||||
|
||||
|
||||
def test_all_lines_closed_fails_match_completed(app):
|
||||
"""全部行结案=无剩余履约内容:整单满足性不通过(此类单应走作废流程)。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
_seed_close_decision(fixture, 1, version=1)
|
||||
_seed_close_decision(fixture, 0, version=1)
|
||||
# 断言:无任何待履约行时 match_completed 返回 False,避免自动建空通知。
|
||||
assert match_completed(fixture.order) is False
|
||||
|
||||
|
||||
def test_all_lines_closed_aggregate_is_unfulfillable(app):
|
||||
"""全结案聚合口径锁定:结案行不计满足 ⇒ 整单 unfulfillable(与 match_completed 一致)。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
_seed_close_decision(fixture, 1, version=1)
|
||||
_seed_close_decision(fixture, 0, version=1)
|
||||
status, shortages = _recompute_task_match_aggregate(fixture.order)
|
||||
# 断言:无 ok 也无 block(无可履约内容)⇒ unfulfillable,且不产生缺货列表。
|
||||
assert status == 'unfulfillable'
|
||||
assert shortages == []
|
||||
|
||||
|
||||
def test_closed_status_precedence_over_ok(app):
|
||||
"""分类优先级锁定:matched+ready 行结案后记 closed(非 ok),且不再贡献整单满足。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
# 仅第 0 行有匹配事实(matched+ready)且已结案:聚合视角为单行订单。
|
||||
snap_line = fixture.snap_lines[0]
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
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',
|
||||
required_qty='10', available_qty='10', shortage_qty='0',
|
||||
reservation_id=snap_line.reservation_id, part_number=snap_line.part_number,
|
||||
is_current=True,
|
||||
))
|
||||
db.session.flush()
|
||||
_seed_close_decision(fixture, 0)
|
||||
status, shortages = _recompute_task_match_aggregate(fixture.order)
|
||||
payload = fixture.order.step_payload_json or {}
|
||||
line_results = payload['current_match_projection']['line_results']
|
||||
# 断言:结案分类优先于匹配满足;无 ok 无 block ⇒ 整单 unfulfillable。
|
||||
assert line_results[0]['line_status'] == 'closed'
|
||||
assert status == 'unfulfillable'
|
||||
assert shortages == []
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
tests/test_line_closure_gate_sync.py
|
||||
|
||||
用途:验证结案决定落库后的 Gate 重算联动(对齐放行路径),含 trigger 透传。
|
||||
依赖:pytest、order_review_fulfillment_decision_service、fulfillment_workflow、匹配事实夹具。
|
||||
逻辑:结案使聚合转为满足后,_sync 必须重算任务履约态并以 line_fulfillment_closed 触发编排。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
_sync_confirmed_task_fulfillment_gates,
|
||||
)
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
from tests.test_line_closure_fulfillment import _seed_close_decision, _seed_match_facts
|
||||
|
||||
|
||||
def test_close_decision_syncs_gates_with_closed_trigger(app, monkeypatch):
|
||||
"""结案行豁免使整单满足后,Gate 同步须重算并以 line_fulfillment_closed 触发编排。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
_seed_close_decision(fixture, 1)
|
||||
# 计划自审补齐:submit_auto_progress 仅在 OT 绑定活动 Execution 时触发,
|
||||
# 冻结订单夹具默认不带执行实例,须按结案现场补一条 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,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
fixture.order.active_process_execution_id = int(execution.id)
|
||||
db.session.flush()
|
||||
calls = []
|
||||
|
||||
def _capture_progress(*args, **kwargs):
|
||||
calls.append(('submit_auto_progress', kwargs.get('trigger')))
|
||||
|
||||
def _capture_enqueue(*args, **kwargs):
|
||||
calls.append(('enqueue_post_ot_auto_fulfill_job', kwargs.get('trigger')))
|
||||
|
||||
# 拦截编排出口:函数内为局部 import,直接 patch 源模块属性即可生效。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.auto_progress_controller.submit_auto_progress',
|
||||
_capture_progress,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job',
|
||||
_capture_enqueue,
|
||||
)
|
||||
fake_case = SimpleNamespace(confirmed_task_id=fixture.order.id)
|
||||
_sync_confirmed_task_fulfillment_gates(
|
||||
case=fake_case, actor_id=fixture.user.id, trigger='line_fulfillment_closed',
|
||||
)
|
||||
payload = fixture.order.step_payload_json or {}
|
||||
# 断言:任务履约态被重算为满足,且两个编排出口都带结案 trigger。
|
||||
assert payload['current_match_projection']['match_status'] == 'fulfillable'
|
||||
assert ('submit_auto_progress', 'line_fulfillment_closed') in calls
|
||||
assert ('enqueue_post_ot_auto_fulfill_job', 'line_fulfillment_closed') in calls
|
||||
@@ -1,7 +1,7 @@
|
||||
from types import SimpleNamespace
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService
|
||||
from app.services.integrations.oa.leave_workflow import OALeaveWorkflowService
|
||||
|
||||
|
||||
WORKFLOW_NS = 'http://webservices.workflow.weaver'
|
||||
|
||||
+211
-106
@@ -1,106 +1,211 @@
|
||||
"""Tests for OA userInfo_view → wecom_userid sync."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import User
|
||||
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oa_rows_for_local_user():
|
||||
return [
|
||||
{'workcode': '26030025', 'wecom_userid': '21784', 'name': 'sophie'},
|
||||
]
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_dry_run(app, oa_rows_for_local_user):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='26030025',
|
||||
email='26030025@test.local',
|
||||
employee_id='26030025',
|
||||
real_name='sophie',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('test123')
|
||||
from app import db
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
return_value=oa_rows_for_local_user,
|
||||
) as fetch_mock:
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
fetch_mock.assert_called_once_with(['26030025'])
|
||||
assert summary['local_candidates'] == 1
|
||||
assert summary['wecom_users'] == 1
|
||||
assert summary['local_matched'] == 1
|
||||
assert summary['would_update'] == 1
|
||||
assert summary['local_missing'] == 0
|
||||
assert summary['pending_updates'][0]['wecom_userid'] == '21784'
|
||||
|
||||
db.session.refresh(user)
|
||||
assert user.wecom_userid is None
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_apply(app, oa_rows_for_local_user):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='26030025',
|
||||
email='26030025@test.local',
|
||||
employee_id='26030025',
|
||||
real_name='sophie',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('test123')
|
||||
from app import db
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
return_value=oa_rows_for_local_user,
|
||||
):
|
||||
summary = sync_wecom_userids_from_oa(apply=True)
|
||||
|
||||
assert summary['updated'] == 1
|
||||
db.session.refresh(user)
|
||||
assert user.wecom_userid == '21784'
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_local_not_in_oa(app):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='missing_oa',
|
||||
email='missing_oa@test.local',
|
||||
employee_id='99999999',
|
||||
real_name='missing',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('test123')
|
||||
from app import db
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
return_value=[],
|
||||
) as fetch_mock:
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
fetch_mock.assert_called_once_with(['99999999'])
|
||||
assert summary['local_candidates'] == 1
|
||||
assert summary['wecom_users'] == 0
|
||||
assert summary['local_matched'] == 0
|
||||
assert summary['local_missing'] == 1
|
||||
|
||||
"""Tests for OA userInfo_view → wecom_userid sync."""
|
||||
|
||||
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
|
||||
from app.models import User
|
||||
|
||||
from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
def oa_rows_for_local_user():
|
||||
|
||||
return [
|
||||
|
||||
{'workcode': '26030025', 'wecom_userid': '21784', 'name': 'sophie'},
|
||||
|
||||
]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_dry_run(app, oa_rows_for_local_user):
|
||||
|
||||
with app.app_context():
|
||||
|
||||
user = User(
|
||||
|
||||
username='26030025',
|
||||
|
||||
email='26030025@test.local',
|
||||
|
||||
employee_id='26030025',
|
||||
|
||||
real_name='sophie',
|
||||
|
||||
role='user',
|
||||
|
||||
status='active',
|
||||
|
||||
)
|
||||
|
||||
user.set_password('test123')
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
with patch(
|
||||
|
||||
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
|
||||
return_value=oa_rows_for_local_user,
|
||||
|
||||
) as fetch_mock:
|
||||
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
|
||||
|
||||
fetch_mock.assert_called_once_with(['26030025'])
|
||||
|
||||
assert summary['local_candidates'] == 1
|
||||
|
||||
assert summary['wecom_users'] == 1
|
||||
|
||||
assert summary['local_matched'] == 1
|
||||
|
||||
assert summary['would_update'] == 1
|
||||
|
||||
assert summary['local_missing'] == 0
|
||||
|
||||
assert summary['pending_updates'][0]['wecom_userid'] == '21784'
|
||||
|
||||
|
||||
|
||||
db.session.refresh(user)
|
||||
|
||||
assert user.wecom_userid is None
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_apply(app, oa_rows_for_local_user):
|
||||
|
||||
with app.app_context():
|
||||
|
||||
user = User(
|
||||
|
||||
username='26030025',
|
||||
|
||||
email='26030025@test.local',
|
||||
|
||||
employee_id='26030025',
|
||||
|
||||
real_name='sophie',
|
||||
|
||||
role='user',
|
||||
|
||||
status='active',
|
||||
|
||||
)
|
||||
|
||||
user.set_password('test123')
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
with patch(
|
||||
|
||||
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
|
||||
return_value=oa_rows_for_local_user,
|
||||
|
||||
):
|
||||
|
||||
summary = sync_wecom_userids_from_oa(apply=True)
|
||||
|
||||
|
||||
|
||||
assert summary['updated'] == 1
|
||||
|
||||
db.session.refresh(user)
|
||||
|
||||
assert user.wecom_userid == '21784'
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_local_not_in_oa(app):
|
||||
|
||||
with app.app_context():
|
||||
|
||||
user = User(
|
||||
|
||||
username='missing_oa',
|
||||
|
||||
email='missing_oa@test.local',
|
||||
|
||||
employee_id='99999999',
|
||||
|
||||
real_name='missing',
|
||||
|
||||
role='user',
|
||||
|
||||
status='active',
|
||||
|
||||
)
|
||||
|
||||
user.set_password('test123')
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
with patch(
|
||||
|
||||
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
|
||||
return_value=[],
|
||||
|
||||
) as fetch_mock:
|
||||
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
|
||||
|
||||
fetch_mock.assert_called_once_with(['99999999'])
|
||||
|
||||
assert summary['local_candidates'] == 1
|
||||
|
||||
assert summary['wecom_users'] == 0
|
||||
|
||||
assert summary['local_matched'] == 0
|
||||
|
||||
assert summary['local_missing'] == 1
|
||||
|
||||
|
||||
@@ -29,6 +29,14 @@ RESERVATION_DEFINITION = {
|
||||
],
|
||||
}
|
||||
|
||||
LN_RESERVATION_DEFINITION = {
|
||||
'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1},
|
||||
'fields': DEFINITION['fields'] + [
|
||||
{'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line', 'required': True},
|
||||
{'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line'},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _row(po: str, part: str) -> dict:
|
||||
return {'status': 'parsed', 'issues': [], 'fields': [
|
||||
@@ -38,6 +46,12 @@ def _row(po: str, part: str) -> dict:
|
||||
]}
|
||||
|
||||
|
||||
def _ln_row(po: str, part: str, ln: str) -> dict:
|
||||
row = _row(po, part)
|
||||
row['fields'].append({'field_id': 'ln', 'value': ln, 'quote': ln})
|
||||
return row
|
||||
|
||||
|
||||
def _page_glyphs(*lines: str) -> list[dict]:
|
||||
"""构造跨页 Reservation 路由回归所需的最小坐标文字。"""
|
||||
glyphs = []
|
||||
@@ -152,6 +166,63 @@ def test_approved_pdf_marks_conflicting_reservation_region_for_review():
|
||||
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
|
||||
|
||||
|
||||
def test_approved_pdf_maps_reservation_by_printed_ln_when_ln_non_contiguous():
|
||||
"""PO_6075309 回归:LN=1/2/4/5 非连续时 L#n 必须按 LN 值落行,整单不转复核。
|
||||
|
||||
关键断言:L#4/L#5 分别写入 LN=4/LN=5 行(旧位置序会把 L#4 错配到 LN=5 并把
|
||||
L#5 误报 line_out_of_range);行级 reservation 已全部归属后 source_missing_fields
|
||||
不得残留 line_index 0 的假缺失(``or -1`` falsy bug)。
|
||||
"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=LN_RESERVATION_DEFINITION,
|
||||
table={'rows': [
|
||||
_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2'),
|
||||
_ln_row('PO-1', 'P-4', '4'), _ln_row('PO-1', 'P-5', '5'),
|
||||
]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '1000159370', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation L#1: 1000159370'},
|
||||
{'value': '1000159366', 'scope': 'line', 'line_no': 2, 'raw_text': 'Reservation L#2: 1000159366'},
|
||||
{'value': '1000159379', 'scope': 'line', 'line_no': 4, 'raw_text': 'Reservation L#4: 1000159379'},
|
||||
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
order = (orders or [])[0]
|
||||
assert order.get('reservation_region_status') != 'needs_review'
|
||||
assert 'source_missing_fields' not in order
|
||||
expected_by_ln = {'1': '1000159370', '2': '1000159366', '4': '1000159379', '5': '1000159236'}
|
||||
for line in order['lines']:
|
||||
ln = next(item['observations'][0]['value'] for item in line['fields'] if item['field_id'] == 'ln')
|
||||
assert any(
|
||||
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == expected_by_ln[ln]
|
||||
for item in line['fields']
|
||||
)
|
||||
|
||||
|
||||
def test_approved_pdf_keeps_reservation_review_when_referenced_ln_row_is_missing():
|
||||
"""被引用的印刷行号在解析行中不存在时必须转复核,不得按位置静默写入。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=LN_RESERVATION_DEFINITION,
|
||||
table={'rows': [_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2')]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
order = (orders or [])[0]
|
||||
assert order['reservation_region_status'] == 'needs_review'
|
||||
assert order['reservation_region_review_reasons'] == ['line_out_of_range']
|
||||
# LN=1/LN=2 行无对应候选,reservation 保持缺失供人工补录。
|
||||
assert all(
|
||||
not any(item['field_id'] == 'line-reservation' for item in line['fields'])
|
||||
for line in order['lines']
|
||||
)
|
||||
|
||||
|
||||
def test_enabled_reservation_region_reads_vendor_comments_across_pages():
|
||||
"""已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。"""
|
||||
result = _reservation_region_candidates(
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
"""
|
||||
tests/test_order_profile_header_identity.py
|
||||
|
||||
用途:锁定 schema_canonical_header_atoms / schema_canonical_header_tokens 的表头
|
||||
别名语义归一行为,及其在表头原子硬互斥(_header_discriminator_atoms_conflict)
|
||||
与 signature_conflict 二次机会门禁中的防回归契约;含真实故障单 PO_6075316
|
||||
(日期换词 + 相邻列并格 + 空串 token)的形状回归。
|
||||
依赖:order_profile_matcher.schema_canonical_header_atoms /
|
||||
schema_canonical_header_tokens / _header_token_atoms /
|
||||
_header_discriminator_atoms_conflict。
|
||||
逻辑:pure_unit;别名命中产出 field::<field_code> 标记原子(atoms 为集合语义、
|
||||
tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤;
|
||||
None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date
|
||||
别名的契约下跨措辞对齐,异义词不归并。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_header_discriminator_atoms_conflict,
|
||||
_header_token_atoms,
|
||||
schema_canonical_header_atoms,
|
||||
schema_canonical_header_tokens,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_none_or_empty_mapping_degrades_to_word_atoms():
|
||||
"""未配置别名表时必须与既有词级原子化完全一致(零行为变化)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', 'Unit Price']
|
||||
# 关键断言:None 与空 dict 均退化为 _header_token_atoms,结果与直接调用逐项相等
|
||||
assert schema_canonical_header_atoms(tokens, None) == _header_token_atoms(tokens)
|
||||
assert schema_canonical_header_atoms(tokens, {}) == _header_token_atoms(tokens)
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记原子
|
||||
assert not any(
|
||||
atom.startswith('field::')
|
||||
for atom in schema_canonical_header_atoms(tokens, None)
|
||||
)
|
||||
|
||||
|
||||
def test_exact_phrase_hit_emits_field_marker():
|
||||
"""别名精确命中时短语整体替换为 field::<field_code>,不残留短语内单词。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{'requested ship date': 'requested_receipt_date'},
|
||||
)
|
||||
# 关键断言:命中段落被消费,仅剩语义标记原子,词级原子 requested/ship/date 不再出现
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_merged_cell_greedy_decomposition():
|
||||
"""合并格长文案按贪心最长短语分解为多个 field 标记原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:两个别名短语各自命中并消费整段,互不残留单词原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date', 'field::unit_price'})
|
||||
|
||||
|
||||
def test_greedy_prefers_longest_phrase():
|
||||
"""同一位置长短短语重叠时必须取最长短语(贪心最长匹配)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{
|
||||
'ship date': 'ship_date',
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:最长短语胜出且整段消费,短短语不产生任何残留 field/词级原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_case_insensitive_matching():
|
||||
"""表头与别名 key 大小写不同仍命中(casefold 同源词管线)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['UNIT PRICE'],
|
||||
{'Unit Price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:大小写差异不阻断短语命中,field_code 保留别名表原样
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_unmatched_words_kept_and_short_words_filtered():
|
||||
"""未命中别名的词沿用既有过滤:长度 >=3 且非虚词才保留为词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Total Amount ok the ab'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:total/amount 保留;'ok'/'ab' 过短被滤;'the' 为虚词被滤
|
||||
assert atoms == frozenset({'total', 'amount'})
|
||||
|
||||
mixed = schema_canonical_header_atoms(
|
||||
['Unit Price Remarks ok'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:同一 token 内 field 标记原子与词级原子可共存
|
||||
assert mixed == frozenset({'field::unit_price', 'remarks'})
|
||||
|
||||
|
||||
def test_empty_tokens_skipped():
|
||||
"""空串/纯空白 token(MinerU 空格占位)直接跳过且不影响其余 token。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['', ' ', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:空白 token 不产生原子也不中断匹配,后续 token 照常命中
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_chinese_alias_yields_no_field_atom():
|
||||
"""中文别名切词为空 → 自然跳过(有意行为:词级原子只保留 [a-z0-9])。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['数量', 'Qty'],
|
||||
{'数量': 'quantity'},
|
||||
)
|
||||
# 关键断言:中文别名不产生 field:: 原子;词级原子口径不变(qty 长度 >=3 保留)
|
||||
assert atoms == frozenset({'qty'})
|
||||
|
||||
|
||||
def test_casefold_collision_phrase_discarded():
|
||||
"""同一短语 casefold 后映射到多个 field_code → 整体弃用,回退词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{
|
||||
'Ship Date': 'ship_date',
|
||||
'ship date': 'requested_ship_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:歧义短语不得产出任何 field:: 原子;未命中单词走既有过滤保留
|
||||
assert atoms == frozenset({'ship', 'date'})
|
||||
|
||||
|
||||
def test_casefold_equal_duplicate_alias_kept():
|
||||
"""同短语重复别名但 field_code 仅大小写不同 → 不视为歧义,短语保留。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{'Ship Date': 'ship_date', 'SHIP DATE': 'SHIP_DATE'},
|
||||
)
|
||||
# 关键断言:casefold 视角同码不构成身份歧义,短语照常产出标记原子
|
||||
assert atoms == frozenset({'field::ship_date'})
|
||||
|
||||
|
||||
# --- PO_6075316 真实故障形状回归:别名契约 vs 表头原子硬互斥 ---
|
||||
|
||||
_SIGNATURE_TRAINING_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Arrival Date', 'Unit Price', 'Extension',
|
||||
]
|
||||
_PO6075316_OBSERVED_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Ship Date Unit Price', '', 'Extension',
|
||||
]
|
||||
_SCHEMA_V4_HEADER_TO_FIELD = {
|
||||
'Requested Receipt Date': 'requested_receipt_date',
|
||||
'Requested Arrival Date': 'requested_receipt_date',
|
||||
'Requested Ship Date': 'requested_receipt_date',
|
||||
'Unit Price': 'unit_price',
|
||||
'Extension': 'line_amount_with_tax',
|
||||
'Part Number': 'customer_part_number',
|
||||
'Vendor Item': 'part_number',
|
||||
'Quantity': 'qty',
|
||||
'LN': 'customer_po_line_no',
|
||||
}
|
||||
|
||||
|
||||
def _po6075316_signature() -> dict:
|
||||
"""训练签名(命中模板 HYVE)的明细表 header_tokens 形状。"""
|
||||
return {'table_patterns': [{'header_tokens': list(_SIGNATURE_TRAINING_TOKENS)}]}
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_passes_with_ship_date_alias_contract():
|
||||
"""PO_6075316 形状(日期换词+并格+空串)在含 Ship Date 别名契约下不再互斥。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:两侧经 Schema 别名归一后字段语义原子全等,硬互斥判定为不冲突
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is False
|
||||
# 佐证:'Requested Ship Date' 与 'Requested Arrival Date' 归一为同一标记原子;
|
||||
# 并格长文案贪心分解出日期+单价两个标记原子;空串 token(MinerU 占位)零原子。
|
||||
assert schema_canonical_header_atoms(
|
||||
observed['header_tokens'], _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) == schema_canonical_header_atoms(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_still_conflicts_without_alias_contract():
|
||||
"""同形状不传契约(或契约缺 Ship Date 别名)时互斥仍在——豁免效果来自别名。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:不传 header_to_field 时两侧退化词级原子,arrival≠ship,既有互斥零变化
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(), observed=observed,
|
||||
) is True
|
||||
contract_without_ship_alias = {
|
||||
key: value
|
||||
for key, value in _SCHEMA_V4_HEADER_TO_FIELD.items()
|
||||
if key != 'Requested Ship Date'
|
||||
}
|
||||
# 关键断言:契约缺 Ship Date 别名时观测侧 ship 退回词级原子,互斥依旧成立
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=contract_without_ship_alias,
|
||||
) is True
|
||||
|
||||
|
||||
def test_po6075316_foreign_date_word_not_merged_by_alias():
|
||||
"""日期列换成未配别名的真正异义词(Customer PO Date)时不得归并,互斥仍触发。"""
|
||||
observed = {'header_tokens': [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Customer PO Date Unit Price', '', 'Extension',
|
||||
]}
|
||||
# 关键断言:别名契约只归并已治理措辞,不同语义字段(客户 PO 日期)保持互斥
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is True
|
||||
|
||||
|
||||
# --- schema_canonical_header_tokens:序列语义 canonical 归一(二次机会门禁供料) ---
|
||||
|
||||
def test_tokens_none_or_empty_mapping_returns_input_list_unchanged():
|
||||
"""None/空 dict 时原样返回输入列表(零归一,与 atoms 的退化口径一致)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', '']
|
||||
# 关键断言:None 与空 dict 均不做任何归一,列表内容原样返回
|
||||
assert schema_canonical_header_tokens(tokens, None) == tokens
|
||||
assert schema_canonical_header_tokens(tokens, {}) == tokens
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记项
|
||||
assert not any(item.startswith('field::') for item in schema_canonical_header_tokens(tokens, None))
|
||||
|
||||
|
||||
def test_tokens_hit_phrase_collapses_to_single_item_and_keeps_order():
|
||||
"""命中片段坍缩为单个 field 标记列表项,且保持在原 token 的序列位置。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Requested Ship Date', 'Remarks', 'Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:命中短语各坍缩为单列表项并按原顺序交错排列,短语内单词不残留
|
||||
assert canonical == [
|
||||
'field::requested_receipt_date', 'remarks', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_sequence_semantics_keeps_duplicates_and_unmatched_words():
|
||||
"""序列语义:允许重复、未命中词原样保留——与 atoms 的集合语义形成对照。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Unit Price', 'Total Amount ok the ab', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:重复 token 各自产出标记项(不去重);total/amount 原词保序保留;
|
||||
# 'ok'/'ab' 过短、'the' 为虚词被滤(与 atoms 同一过滤口径)
|
||||
assert canonical == [
|
||||
'field::unit_price', 'total', 'amount', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_dedup_equals_atoms_same_source_semantics():
|
||||
"""同源语义:同一输入下 tokens 版去重即 atoms 版结果(同管线同短语匹配)。"""
|
||||
tokens = ['', ' ', 'Requested Ship Date Unit Price', 'Vendor Item#', 'ok the ab']
|
||||
mapping = {
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
'vendor item': 'part_number',
|
||||
}
|
||||
canonical = schema_canonical_header_tokens(tokens, mapping)
|
||||
atoms = schema_canonical_header_atoms(tokens, mapping)
|
||||
# 关键断言:序列版去重后与集合版逐项相等——两条路径完全同源,不得漂移
|
||||
assert set(canonical) == set(atoms)
|
||||
# 关键断言:空白 token 不产出列表项(与 atoms 跳过口径一致)
|
||||
assert len(canonical) == len([item for item in canonical if item])
|
||||
|
||||
|
||||
def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias():
|
||||
"""PO_6075316 形状在含 Ship Date 别名下两侧 canonical 序列逐项相等(保序)。"""
|
||||
canonical_expected = schema_canonical_header_tokens(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
canonical_observed = schema_canonical_header_tokens(
|
||||
_PO6075316_OBSERVED_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
# 关键断言:并格长文案贪心分解出的标记原子序列与训练侧完全一致(含顺序),
|
||||
# 供二次机会门禁按序列比较得出满配额软分
|
||||
assert canonical_expected == canonical_observed
|
||||
# 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住)
|
||||
assert canonical_expected[0] == 'field::customer_po_line_no'
|
||||
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
tests/test_ot_inline_edit.py
|
||||
|
||||
用途:验证通知准备阶段(Notice 未建、仅 OT)的就地编辑全链路。
|
||||
依赖:pytest、task_workflow.update_notice_line、effective_order_view、有效视图夹具。
|
||||
逻辑:复现"FORMAL_NOTICE_REQUIRED"报错场景——OT task_no 直接走 update-notice-line 通道,
|
||||
编辑后有效值立即可见(库存匹配/Excel/通知行的统一读取口径)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
|
||||
|
||||
def test_update_notice_line_accepts_order_task_before_notice(app):
|
||||
"""通知准备阶段(无 Notice)编辑 OT 行字段必须成功且进入有效视图。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
response = update_notice_line({
|
||||
'task_id': fixture.order.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'part_number': 'D4-A08AR12000002'},
|
||||
'event_source': 'workspace_api',
|
||||
'reviewed_by_id': fixture.user.id,
|
||||
'expected_order_data_version': int(fixture.order.order_data_version or 1),
|
||||
})
|
||||
# 断言:服务层对 OT 放行(修复前 API 层 _require_formal_notice 报 FORMAL_NOTICE_REQUIRED)。
|
||||
assert response['status'] == 'ok'
|
||||
_header, lines = effective_order_field_values(fixture.order)
|
||||
# 断言:编辑后的料号进入有效视图(重新匹配库存的读取口径),旧值不再出现。
|
||||
assert lines[0]['f-part'] == 'D4-A08AR12000002'
|
||||
assert lines[1]['f-part'] == 'D4-B07BR07000001'
|
||||
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
tests/test_reservation_effective_view.py
|
||||
|
||||
用途:验证预约注册与核验比对消费「冻结快照 + 已接受人工修正」的有效订单值视图
|
||||
(修复编辑料号/数量后核验必抛 SHIPPING.RESERVATION_MISMATCH 的阻断缺陷)。
|
||||
依赖:pytest、reservation_service、task_order_field_editor、test_effective_order_view 夹具。
|
||||
逻辑:先按冻结值注册预约 → 就地编辑料号/数量 → 再次 ensure 应走同 OT 确认修订
|
||||
(transfer,自动接替未履约预约)而非抛错;核验比对按归一化料号匹配有效值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingReservation,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
ensure_task_reservations,
|
||||
record_inventory_verification,
|
||||
)
|
||||
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
|
||||
|
||||
# 预约层契约只接受 5/10 位纯数字预约号(validated_reservation_id);夹具的 'RSV-*'
|
||||
# 为占位值,须补成契约内值才能驱动预约注册,同时补 PO 以支撑二次注册的归属校验。
|
||||
_NUMERIC_RESERVATION_IDS = ('1234567890', '2234567890')
|
||||
|
||||
|
||||
def _seed_frozen_order_for_reservations():
|
||||
"""复用有效视图夹具并补齐预约层契约值:纯数字预约号 + 单头 PO。"""
|
||||
fixture = _seed_frozen_order()
|
||||
for snap_line, reservation_id in zip(fixture.snap_lines, _NUMERIC_RESERVATION_IDS):
|
||||
snap_line.reservation_id = reservation_id
|
||||
fixture.snapshot.customer_po_number = 'PO-0001'
|
||||
order_lines = ShippingOrderLine.query.filter_by(
|
||||
extraction_id=fixture.extraction.id,
|
||||
).order_by(ShippingOrderLine.position).all()
|
||||
for line, reservation_id in zip(order_lines, _NUMERIC_RESERVATION_IDS):
|
||||
for item in ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=fixture.extraction.id, line_id=line.id, field_id='f-rsv',
|
||||
).all():
|
||||
item.value_text = reservation_id
|
||||
item.value_json = reservation_id
|
||||
for item in ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=fixture.extraction.id, line_id=line.id, field_id='f-rsv',
|
||||
).all():
|
||||
item.resolved_value_json = reservation_id
|
||||
db.session.flush()
|
||||
return fixture
|
||||
|
||||
|
||||
def _registered_reservation(fixture, index: int = 0) -> ShippingReservation:
|
||||
"""按夹具第 index 行的预约号取全局预约注册行。"""
|
||||
return ShippingReservation.query.filter_by(
|
||||
task_id=fixture.order.id, reservation_id=_NUMERIC_RESERVATION_IDS[index],
|
||||
).one()
|
||||
|
||||
|
||||
def test_ensure_task_reservations_follows_effective_values(app):
|
||||
"""预约注册必须消费有效值:编辑料号后再次 ensure 应自动修订(transfer)而非校验失败。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order_for_reservations()
|
||||
# 第一次注册:按冻结值(带尾巴的旧料号)建预约。
|
||||
ensure_task_reservations(fixture.order)
|
||||
reservation = _registered_reservation(fixture)
|
||||
# 断言:初始注册值为冻结快照列原值。
|
||||
assert reservation.part_number == 'D4-A08AR12000002-'
|
||||
# 就地编辑第 0 行料号为正确值。
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
# 第二次 ensure(重匹配核验前的真实调用时序):必须成功且预约更新为有效值。
|
||||
ensure_task_reservations(fixture.order)
|
||||
db.session.refresh(reservation)
|
||||
# 断言:预约料号已随有效值修订,状态回 pending(可重新核验)。
|
||||
assert reservation.part_number == 'D4-A08AR12000002'
|
||||
assert reservation.status == 'pending'
|
||||
# 断言:修订走同 OT 确认修订路径,落 reservation_revision_confirmed 审计事件。
|
||||
assert any(
|
||||
event.event_type == 'reservation_revision_confirmed'
|
||||
for event in fixture.order.events
|
||||
)
|
||||
|
||||
|
||||
def test_ensure_task_reservations_revises_required_qty_from_effective_value(app):
|
||||
"""编辑数量后再次 ensure 必须按有效数量修订预约,而非保持冻结数量。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order_for_reservations()
|
||||
ensure_task_reservations(fixture.order)
|
||||
reservation = _registered_reservation(fixture)
|
||||
# 断言:初始注册数量为冻结值 10。
|
||||
assert reservation.required_qty == Decimal('10')
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='qty', value='15',
|
||||
)
|
||||
ensure_task_reservations(fixture.order)
|
||||
db.session.refresh(reservation)
|
||||
# 断言:需求数量已随有效值修订为 15,且版本在原 OT 上递增(不新建任务)。
|
||||
# order_data_version 经历两次 bump:编辑器写修正 +1,确认修订接替 +1。
|
||||
assert reservation.required_qty == Decimal('15')
|
||||
assert reservation.status == 'pending'
|
||||
assert fixture.order.order_data_version == 3
|
||||
assert fixture.order.progress_version == 2
|
||||
|
||||
|
||||
def test_record_inventory_verification_maps_effective_part_number(app):
|
||||
"""编辑料号后的库存核验必须能按有效料号(归一化后)映射预约,不再抛 RESERVATION_MISMATCH。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order_for_reservations()
|
||||
ensure_task_reservations(fixture.order)
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
# 模拟重匹配写入的有效值事实:第 0 行料号带大小写/空白差异(归一化后应相等)。
|
||||
verification = record_inventory_verification(
|
||||
fixture.order, inventory_snapshot_id=None, source_config_version='v1',
|
||||
line_results=[
|
||||
{
|
||||
'reservation_id': '1234567890', 'part_number': ' d4-a08ar12000002 ',
|
||||
'required_qty': Decimal('10'), 'available_qty': Decimal('10'), 'line_status': 'ok',
|
||||
},
|
||||
{
|
||||
'reservation_id': '2234567890', 'part_number': 'D4-B07BR07000001',
|
||||
'required_qty': Decimal('10'), 'available_qty': Decimal('10'), 'line_status': 'ok',
|
||||
},
|
||||
],
|
||||
)
|
||||
# 断言:核验轮次成功创建,修订后的预约按有效值完整满足并转 available。
|
||||
assert verification.lines[0].status == 'available'
|
||||
assert verification.result_json['available_count'] == 2
|
||||
|
||||
|
||||
def test_locked_reservation_still_rejects_effective_revision(app):
|
||||
"""已占用/已上传的预约不受有效值自动修订影响:保留 RESERVATION_REVISION_LOCKED 拒绝。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order_for_reservations()
|
||||
ensure_task_reservations(fixture.order)
|
||||
reservation = _registered_reservation(fixture)
|
||||
reservation.status = 'artifact_reserved'
|
||||
db.session.flush()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
# 断言:带 Artifact 锁的预约不得自动修订,必须走人工复核。
|
||||
with pytest.raises(ConflictError) as locked:
|
||||
ensure_task_reservations(fixture.order)
|
||||
assert locked.value.code == 'SHIPPING.RESERVATION_REVISION_LOCKED'
|
||||
db.session.refresh(reservation)
|
||||
# 断言:预约料号保持注册原值,未被静默改写。
|
||||
assert reservation.part_number == 'D4-A08AR12000002-'
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
tests/test_review_line_fulfillment_shortage_projection.py
|
||||
|
||||
用途:锁定行级履约投影的匹配事实关联(修复草稿行ID vs 快照行ID 键错位)。
|
||||
依赖:pytest、order_review_fulfillment_decision_service、有效视图夹具。
|
||||
逻辑:确认 Case + 短缺匹配事实下,投影必须报 has_shortage=True 且行级 is_shortage=True。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewDraft
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
project_review_case_line_decisions,
|
||||
)
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
|
||||
|
||||
def test_line_fulfillment_has_shortage_with_match_facts(app):
|
||||
"""修复键错位:草稿行经 _line_index 关联匹配事实,has_shortage 必须为真。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
# 短缺事实:第 0 行 not_found、缺 10。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
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',
|
||||
required_qty='10', available_qty='0', shortage_qty='10',
|
||||
reservation_id='RSV-1', part_number='D4-A08AR12000002-', is_current=True,
|
||||
))
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='SNRC-SHORTAGE-PROJ', run_id=911, unit_id=912, document_id=913,
|
||||
owner_user_id=fixture.user.id, status='confirmed', confirmed_task_id=fixture.order.id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewDraft(
|
||||
case_id=case.id, draft_version=1, schema_version_id=fixture.snapshot.schema_version_id,
|
||||
header_values_json={}, lines_json=[{'draft_line_id': 'line-1', 'part_number': 'D4-A08AR12000002-'}],
|
||||
))
|
||||
db.session.flush()
|
||||
case.current_draft_id = case.drafts[0].id if case.drafts else None
|
||||
db.session.flush()
|
||||
result = project_review_case_line_decisions(case)
|
||||
# 断言:修复前 has_shortage 恒 False(键错位);修复后为 True。
|
||||
assert result['has_shortage'] is True
|
||||
assert result['lines'][0]['is_shortage'] is True
|
||||
@@ -0,0 +1,79 @@
|
||||
"""trigger_consumer 公共模块测试。
|
||||
|
||||
用途:锁定 trigger 文件四态目录契约(根目录待领取 → processing 处理中 →
|
||||
processed/failed 终态)的领取与归档行为。
|
||||
依赖:标准库 tempfile/pathlib、scripts.rpa.common.trigger_consumer。
|
||||
逻辑:claim 原子性(二次领取返回 None)、归档落位、非法入参拒绝。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common"))
|
||||
|
||||
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
|
||||
|
||||
|
||||
def _write_trigger(root: Path, name: str = "batch_1.json") -> Path:
|
||||
path = root / name
|
||||
path.write_text('{"schema_version": "x"}', encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def test_claim_moves_file_into_processing(tmp_path):
|
||||
"""首次领取应把 trigger 原子移入 processing/ 并返回新路径。"""
|
||||
path = _write_trigger(tmp_path)
|
||||
claimed = claim_trigger(path)
|
||||
assert claimed == tmp_path / "processing" / path.name
|
||||
assert claimed.read_text(encoding="utf-8") == '{"schema_version": "x"}'
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def test_claim_twice_returns_none(tmp_path):
|
||||
"""同一 trigger 二次领取必须返回 None(防双消费/重复导出)。"""
|
||||
path = _write_trigger(tmp_path)
|
||||
assert claim_trigger(path) is not None
|
||||
assert claim_trigger(path) is None
|
||||
|
||||
|
||||
def test_archive_processed_and_failed(tmp_path):
|
||||
"""processing/ 中的文件按 outcome 归档到同名终态目录。"""
|
||||
path = _write_trigger(tmp_path)
|
||||
claimed = claim_trigger(path)
|
||||
done = archive_trigger(claimed, "processed")
|
||||
assert done == tmp_path / "processed" / path.name and done.exists()
|
||||
path2 = _write_trigger(tmp_path, "batch_2.json")
|
||||
claimed2 = claim_trigger(path2)
|
||||
failed = archive_trigger(claimed2, "failed")
|
||||
assert failed == tmp_path / "failed" / path2.name and failed.exists()
|
||||
|
||||
|
||||
def test_archive_rejects_bad_outcome_and_unclaimed_path(tmp_path):
|
||||
"""非法 outcome 与未经领取的路径都必须拒绝,防止归档错位。"""
|
||||
path = _write_trigger(tmp_path)
|
||||
with pytest.raises(ValueError):
|
||||
archive_trigger(path, "processed") # 未领取,不在 processing/ 下
|
||||
claimed = claim_trigger(_write_trigger(tmp_path, "batch_3.json"))
|
||||
with pytest.raises(ValueError):
|
||||
archive_trigger(claimed, "done") # outcome 白名单外
|
||||
|
||||
|
||||
def test_inventory_worker_scans_with_claim(tmp_path):
|
||||
"""库存 Worker 扫描必须先领取(processing/),不得原地消费根目录文件。"""
|
||||
root = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory"
|
||||
text = (root / "inventory_rpa_worker.py").read_text(encoding="utf-8")
|
||||
assert "claim_trigger" in text
|
||||
# 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent
|
||||
assert text.count('trigger_path.parent / "failed"') == 0
|
||||
|
||||
|
||||
def test_receipt_worker_runs_periodic_disk_cleanup():
|
||||
"""收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。"""
|
||||
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
|
||||
assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt
|
||||
cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
|
||||
assert '"receipt_"' in cleanup or "'receipt_'" in cleanup
|
||||
@@ -67,12 +67,12 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id=scope_id)
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
return trigger_dir
|
||||
|
||||
|
||||
@@ -132,11 +132,11 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
@@ -154,9 +154,9 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
|
||||
"""生产策略要求 Redis 时,写入失败应抛存储不可用。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
|
||||
lambda _worker: False,
|
||||
@@ -169,23 +169,35 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
|
||||
assert exc_info.value.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE
|
||||
|
||||
|
||||
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path):
|
||||
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
|
||||
"""fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
# 隔离:强制无 Redis 分支(_redis_client 为模块级单例,config 置空不可靠,须 monkeypatch);
|
||||
# 并清空心跳存储,确保走 no_worker_heartbeat + 进程内存储原因码。
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
|
||||
with app.app_context():
|
||||
with pytest.raises(ServiceUnavailableError) as exc_info:
|
||||
assert_inventory_rpa_worker_ready()
|
||||
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
|
||||
assert "no_worker_heartbeat" in (exc_info.value.details or {}).get("reasons", [])
|
||||
reasons = (exc_info.value.details or {}).get("reasons", [])
|
||||
assert "no_worker_heartbeat" in reasons
|
||||
# [断言意图] 无 Redis 时心跳存储为本进程内存,必须给出原因码与本地测试指引
|
||||
assert "heartbeat_store_process_local" in reasons
|
||||
assert (exc_info.value.details or {}).get("detail_message")
|
||||
|
||||
|
||||
@@ -194,7 +206,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path,
|
||||
import time as time_module
|
||||
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90
|
||||
base_now = time_module.time()
|
||||
|
||||
with app.app_context():
|
||||
@@ -218,7 +230,7 @@ def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post(
|
||||
@@ -258,11 +270,19 @@ def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path):
|
||||
def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypatch):
|
||||
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
# 隔离:强制无 Redis 分支(防真实心跳/单例缓存混入测试窗口)并清空存储,锁定离线 fail-fast 分支。
|
||||
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
|
||||
@@ -304,8 +324,8 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
|
||||
def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_path, monkeypatch):
|
||||
"""Redis 读取异常应报 heartbeat_storage_unavailable,而非 no_worker_heartbeat。"""
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
|
||||
class BrokenRedis:
|
||||
def smembers(self, _key):
|
||||
@@ -327,8 +347,8 @@ def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_pat
|
||||
def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch):
|
||||
"""test/prod Redis 策略:写入+读取成功时应 ready。"""
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
bucket: dict[str, Any] = {"index": set()}
|
||||
|
||||
class FakeRedis:
|
||||
@@ -370,8 +390,8 @@ def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path)
|
||||
trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
|
||||
trigger_dir.mkdir(parents=True)
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config.pop("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", None)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
assert shared_scope_id() == "hxops-rpa-test-data"
|
||||
@@ -385,15 +405,15 @@ def _enable_freight_upload_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-t
|
||||
upload_queue.mkdir()
|
||||
_write_shared_sentinel(upload_trigger, scope_id=scope_id)
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
|
||||
app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
return upload_trigger
|
||||
|
||||
|
||||
@@ -437,7 +457,7 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
|
||||
|
||||
_enable_freight_upload_checks(app, tmp_path)
|
||||
# 去掉凭据主密钥:即使 Redis 残留心跳,静态配置缺失也必须阻断。
|
||||
app.config.pop("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", None)
|
||||
app.config.pop("FREIGHT_RPA_CREDENTIAL_KEY", None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
with app.app_context():
|
||||
with pytest.raises(ServiceUnavailableError) as exc_info:
|
||||
|
||||
@@ -32,16 +32,16 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = ""
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_ENABLED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_USERNAMES"] = ""
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
return trigger_dir
|
||||
|
||||
|
||||
@@ -188,7 +188,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch
|
||||
import logging
|
||||
|
||||
_enable_alert_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
@@ -214,7 +214,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch
|
||||
def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatch):
|
||||
"""显式配置的用户名优先于 admin 回退。"""
|
||||
_enable_alert_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = "oncall_user"
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_USERNAMES"] = "oncall_user"
|
||||
|
||||
with app.app_context():
|
||||
from app import db
|
||||
@@ -325,7 +325,7 @@ def test_concurrent_first_claim_integrity_error_does_not_claim(app, monkeypatch)
|
||||
def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
|
||||
"""过期 sending 锁且 sending_target=offline 时,Worker 恢复后应发送恢复通知。"""
|
||||
_enable_alert_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS"] = 60
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS"] = 60
|
||||
|
||||
stale_sending = {
|
||||
"status": _STATUS_SENDING,
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""worker_logging 公共文件日志模块测试。
|
||||
|
||||
用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、
|
||||
按大小轮转滚动备份、shutdown 恢复标准流。
|
||||
依赖:标准库 + scripts/freight_rpa/common/worker_logging。
|
||||
逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common"))
|
||||
|
||||
from worker_logging import ( # noqa: E402
|
||||
WorkerLogTee,
|
||||
configure_file_logging,
|
||||
log_line_timestamp,
|
||||
rotate_log_file_if_needed,
|
||||
shutdown_logging,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _restore_streams():
|
||||
"""每用例后强制恢复标准流并关闭日志,避免污染其他测试。"""
|
||||
yield
|
||||
shutdown_logging()
|
||||
|
||||
|
||||
def test_tee_writes_timestamped_lines_to_both_streams(tmp_path, capsys):
|
||||
"""tee 应把带时间戳的行同时写入控制台与日志文件。"""
|
||||
log_file = (tmp_path / "worker.log").open("w", encoding="utf-8", buffering=1)
|
||||
tee = WorkerLogTee(sys.stdout, log_file)
|
||||
original_stdout = sys.stdout
|
||||
sys.stdout = tee
|
||||
try:
|
||||
print("hello-worker")
|
||||
finally:
|
||||
sys.stdout = original_stdout
|
||||
log_file.close()
|
||||
content = (tmp_path / "worker.log").read_text(encoding="utf-8")
|
||||
assert "hello-worker" in content
|
||||
assert content.startswith(log_line_timestamp()[:10]) # 日期前缀存在
|
||||
assert "hello-worker" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch):
|
||||
"""超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。"""
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "10")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2")
|
||||
path = tmp_path / "worker.log"
|
||||
for round_no in range(3):
|
||||
path.write_text(f"round-{round_no}-padding", encoding="utf-8")
|
||||
rotate_log_file_if_needed(path)
|
||||
# [断言意图] 滚动语义:最新内容滚入 .1,次新在 .2,最旧(round-0)被删,主文件位空缺待新写入
|
||||
assert Path(f"{path}.1").read_text(encoding="utf-8") == "round-2-padding"
|
||||
assert Path(f"{path}.2").read_text(encoding="utf-8") == "round-1-padding"
|
||||
assert not Path(f"{path}.3").exists()
|
||||
assert not path.exists() # 轮转后主文件位腾空,由调用方以追加模式重建
|
||||
|
||||
|
||||
def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monkeypatch, capsys):
|
||||
"""configure 启用落盘、print 双写;shutdown 恢复标准流且不再写文件。"""
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log"))
|
||||
enabled = configure_file_logging()
|
||||
assert enabled == tmp_path / "logs" / "worker.log"
|
||||
assert enabled.parent.is_dir() # 日志目录自动创建
|
||||
print("banner-line")
|
||||
shutdown_logging()
|
||||
content = (tmp_path / "logs" / "worker.log").read_text(encoding="utf-8")
|
||||
assert "banner-line" in content
|
||||
assert "[logging] tee enabled" in content
|
||||
out = capsys.readouterr().out
|
||||
assert "banner-line" in out
|
||||
|
||||
|
||||
def test_configure_without_env_is_noop(monkeypatch):
|
||||
"""未配置 LOG_FILE 时 configure 返回 None 且不改标准流。"""
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_LOG_FILE", raising=False)
|
||||
assert configure_file_logging() is None
|
||||
@@ -38,6 +38,7 @@ def test_platform_jobs_registered():
|
||||
assert "shipping-inventory-rpa" in keys
|
||||
assert "faq-aggregate-hot" in keys
|
||||
assert "fixed-assets-snapshot" in keys
|
||||
assert "accounting-voucher-po-print" in keys
|
||||
assert get_platform_job("shipping-inventory-rpa") is not None
|
||||
|
||||
|
||||
@@ -217,6 +218,8 @@ def test_get_platform_jobs_api(client, admin_jwt_headers):
|
||||
assert by_key["shipping-inventory-rpa"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
|
||||
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"
|
||||
assert by_key["accounting-voucher-oa-sales-release"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherOaSalesRelease"
|
||||
|
||||
defs = client.get("/api/admin/platform-tasks/definitions", headers=admin_jwt_headers)
|
||||
assert defs.status_code == 200
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
backend/tests/test_shipping_conversation_title.py
|
||||
|
||||
用途:验证订单抽取会话标题纯函数的派生规则(前缀剥离/截断/计数后缀/日期/回退)。
|
||||
依赖:纯函数,无 Flask/DB 夹具。
|
||||
逻辑:命名是内容派生的确定性函数,用逐条断言锁定规则,防止后续误改口径。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.shipping_notice.conversation_title import derive_order_extraction_title
|
||||
|
||||
|
||||
def test_strips_leading_mail_prefixes_and_appends_date():
|
||||
"""首个文件名循环剥离 Re/Fw/Fwd/回复/转发 前缀,末尾追加 MM-DD。"""
|
||||
title = derive_order_extraction_title(['回复:转发:FWD: PO#6075309.eml'], datetime(2026, 9, 15))
|
||||
assert title == 'PO#6075309 09-15'
|
||||
|
||||
|
||||
def test_multi_files_appends_count_suffix():
|
||||
"""文件总数大于 1 时追加「等 N 个文件」,N 按传入文件名总数计。"""
|
||||
title = derive_order_extraction_title(['PO#6075309.eml', 'invoice.pdf', 'list.pdf'], datetime(2026, 9, 15))
|
||||
assert title == 'PO#6075309 等 3 个文件 09-15'
|
||||
|
||||
|
||||
def test_truncates_long_name_to_24_chars():
|
||||
"""主名超过 24 字符截断,且不吞掉日期后缀。"""
|
||||
title = derive_order_extraction_title(['A' * 30 + '.pdf'], datetime(2026, 12, 31))
|
||||
assert title == 'A' * 24 + ' 12-31'
|
||||
|
||||
|
||||
def test_blank_filenames_fall_back_to_default():
|
||||
"""文件名全空(含空列表与纯空白项)回退写死标题「订单抽取」。"""
|
||||
assert derive_order_extraction_title([], datetime(2026, 9, 15)) == '订单抽取'
|
||||
assert derive_order_extraction_title(['', ' '], datetime(2026, 9, 15)) == '订单抽取'
|
||||
@@ -0,0 +1,227 @@
|
||||
"""
|
||||
backend/tests/test_shipping_done_line_report.py
|
||||
|
||||
用途:已完成通知明细行报表(done-lines)查询与专用导出的单测。
|
||||
依赖:pytest、openpyxl、ShippingNotice/OT/Snapshot/Artifact 夹具、done_line_report。
|
||||
逻辑:覆盖 12 字段映射(typed 列 + field_values_json 回源与回退)、可见性(非本人不可见、
|
||||
未上传成功不进报表)、客户/料号/发货通知日期筛选、分页、导出表头与留空行为。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
ShippingExportArtifact,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
)
|
||||
from app.services.shipping_notice.done_line_report import (
|
||||
DONE_REPORT_HEADERS,
|
||||
build_done_lines_xlsx,
|
||||
list_done_notice_lines,
|
||||
)
|
||||
|
||||
|
||||
def _seed_report_fixture(db, *, owner: int):
|
||||
"""最小报表夹具:一张已完成双行通知 + 一张仅 ready 未上传的通知(应被排除)。"""
|
||||
order = ShippingOrderTask(task_no="OT-DONE-LINE", source_type="direct_pdf", user_id=owner)
|
||||
pending_order = ShippingOrderTask(task_no="OT-DONE-LINE-PENDING", source_type="direct_pdf", user_id=owner)
|
||||
notice = ShippingNotice(task_no="SN-DONE-LINE", source_type="manual", user_id=owner)
|
||||
pending_notice = ShippingNotice(task_no="SN-DONE-LINE-PENDING", source_type="manual", user_id=owner)
|
||||
db.session.add_all([order, pending_order, notice, pending_notice])
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='DONELINE', display_name='DoneLine', version=1, status='published',
|
||||
storage_bucket='test', storage_key='done.xlsx', original_filename='done.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='DONELINE', display_name='DoneLine', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='DONELINE', display_name='DoneLine')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': []},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
|
||||
# 标准字段资产:约定出货日期(行级)与来源单号(表头级),值为 field_id 键 JSON。
|
||||
db.session.add(ShippingOrderField(
|
||||
id='f-req-date', field_code='required_date', scope='line', value_type='date',
|
||||
field_category='order_line', collection_mode='deterministic_context',
|
||||
asset_kind='system_standard', storage_mode='typed_column', storage_column='required_date',
|
||||
))
|
||||
db.session.add(ShippingOrderField(
|
||||
id='f-source-order', field_code='source_order_number', scope='header', value_type='string',
|
||||
field_category='order_header', collection_mode='deterministic_context',
|
||||
asset_kind='system_standard', storage_mode='json_only',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
customer_name='HYVE CS', customer_code='HC001', customer_po_number='306085',
|
||||
order_date=date(2026, 6, 1), required_date=date(2026, 6, 15),
|
||||
header_values_json={'f-source-order': '8301-2606010052'},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, line_no=1,
|
||||
part_number='B3-A08AR10000017-A6', qty=80, unit_price=1525.08,
|
||||
field_values_json={'f-req-date': '2026-06-15'},
|
||||
),
|
||||
ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=2, line_no=2,
|
||||
part_number='D4-A08AR12000001', qty=1000, unit_price=898.72,
|
||||
field_values_json={},
|
||||
),
|
||||
])
|
||||
order.order_snapshot_id = snapshot.id
|
||||
notice.order_task_id = order.id
|
||||
|
||||
extraction_two = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='e' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction_two)
|
||||
db.session.flush()
|
||||
pending_snapshot = ShippingOrderSnapshot(
|
||||
task_id=pending_order.id, extraction_id=extraction_two.id, schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
customer_name='PENDING CS', customer_code='PC001',
|
||||
)
|
||||
db.session.add(pending_snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=pending_snapshot.id, position=1, line_no=1, part_number='X-1', qty=1,
|
||||
))
|
||||
pending_order.order_snapshot_id = pending_snapshot.id
|
||||
pending_notice.order_task_id = pending_order.id
|
||||
|
||||
def add_artifact(target, *, artifact_no: str, status: str) -> None:
|
||||
"""为 Notice 建立报表口径所需的最小 Artifact。"""
|
||||
db.session.add(ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=target.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status=status,
|
||||
))
|
||||
|
||||
add_artifact(notice, artifact_no='ART-DONE-LINE', status='uploaded')
|
||||
add_artifact(pending_notice, artifact_no='ART-DONE-LINE-PENDING', status='ready')
|
||||
db.session.commit()
|
||||
return notice
|
||||
|
||||
|
||||
def test_list_done_notice_lines_maps_standard_fields(app):
|
||||
"""明细行平铺不按 OT 聚合;12 字段含 JSON 回源与表头回退,无数据源字段留空。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 88
|
||||
_seed_report_fixture(db, owner=owner)
|
||||
|
||||
result = list_done_notice_lines(owner, page=1, page_size=20)
|
||||
# 断言:仅 uploaded 通知进入报表;两行明细平铺,OT 不聚合。
|
||||
assert result["total"] == 2
|
||||
assert {item["line_no"] for item in result["items"]} == {1, 2}
|
||||
first = next(item for item in result["items"] if item["line_no"] == 1)
|
||||
# 断言:溯源编号 + 标准 12 字段映射。
|
||||
assert first["task_no"] == "SN-DONE-LINE"
|
||||
assert first["customer_name"] == "HYVE CS"
|
||||
assert first["customer_code"] == "HC001"
|
||||
assert first["order_date"] == "2026-06-01"
|
||||
assert first["part_number"] == "B3-A08AR10000017-A6"
|
||||
assert first["qty"] == 80.0
|
||||
# 行级 field_values_json 有值时优先于快照表头 typed 列。
|
||||
assert first["required_date"] == "2026-06-15"
|
||||
assert first["customer_po_number"] == "306085"
|
||||
assert first["source_order_number"] == "8301-2606010052"
|
||||
assert first["unit_price"] == 1525.08
|
||||
# 已用数量 / open qty 当前无数据源,契约留空。
|
||||
assert first["used_qty"] is None
|
||||
assert first["open_qty"] is None
|
||||
second = next(item for item in result["items"] if item["line_no"] == 2)
|
||||
# 断言:行级无 required_date 时回退快照表头 typed 列。
|
||||
assert second["required_date"] == "2026-06-15"
|
||||
assert second["source_order_number"] == "8301-2606010052"
|
||||
|
||||
# 断言:其他用户不可见(非管理员仅创建者)。
|
||||
assert list_done_notice_lines(999)["total"] == 0
|
||||
|
||||
|
||||
def test_list_done_notice_lines_filters_and_pagination(app):
|
||||
"""客户/料号/发货通知日期筛选与按明细行分页生效。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 89
|
||||
_seed_report_fixture(db, owner=owner)
|
||||
|
||||
# 客户模糊(大小写不敏感)。
|
||||
assert list_done_notice_lines(owner, customer="hyve")["total"] == 2
|
||||
assert list_done_notice_lines(owner, customer="不存在")["total"] == 0
|
||||
# 料号模糊(命中单行)。
|
||||
part_page = list_done_notice_lines(owner, part_number="B3-")
|
||||
assert part_page["total"] == 1
|
||||
assert part_page["items"][0]["part_number"] == "B3-A08AR10000017-A6"
|
||||
# 发货通知日期范围:今天闭区间命中;未来区间为空。
|
||||
today = datetime.utcnow().date()
|
||||
assert list_done_notice_lines(
|
||||
owner, notice_date_from=today.isoformat(), notice_date_to=today.isoformat(),
|
||||
)["total"] == 2
|
||||
tomorrow = (today + timedelta(days=1)).isoformat()
|
||||
assert list_done_notice_lines(owner, notice_date_from=tomorrow)["total"] == 0
|
||||
# 按明细行分页。
|
||||
page_one = list_done_notice_lines(owner, page=1, page_size=1)
|
||||
page_two = list_done_notice_lines(owner, page=2, page_size=1)
|
||||
assert page_one["total"] == 2
|
||||
assert {page_one["items"][0]["line_no"], page_two["items"][0]["line_no"]} == {1, 2}
|
||||
|
||||
|
||||
def test_build_done_lines_xlsx_writes_fixed_twelve_columns(app):
|
||||
"""导出严格 12 列标准格式:OT 编号不落列,无数据源列留空。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 90
|
||||
_seed_report_fixture(db, owner=owner)
|
||||
|
||||
stream, filename = build_done_lines_xlsx(owner)
|
||||
assert filename.startswith("done-lines-") and filename.endswith(".xlsx")
|
||||
workbook = load_workbook(stream)
|
||||
sheet = workbook.active
|
||||
rows = list(sheet.iter_rows(values_only=True))
|
||||
# 断言:表头为固定 12 列中文标准格式。
|
||||
assert tuple(rows[0]) == DONE_REPORT_HEADERS
|
||||
# 断言:两行明细,且不含 OT 编号列;数量/单价写数值,无数据源列留空。
|
||||
assert len(rows) == 3
|
||||
first_data = rows[1]
|
||||
assert first_data[0] == "HYVE CS"
|
||||
assert first_data[3] == 1
|
||||
assert first_data[4] == "B3-A08AR10000017-A6"
|
||||
assert first_data[5] == 80.0
|
||||
assert first_data[8] is None
|
||||
assert first_data[9] is None
|
||||
assert first_data[10] == "8301-2606010052"
|
||||
assert first_data[11] == 1525.08
|
||||
@@ -896,3 +896,260 @@ def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch
|
||||
with pytest.raises(RuntimeError, match='commit failed'):
|
||||
_commit_generated_export(str(path))
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def _build_multi_odm_notice(
|
||||
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
|
||||
):
|
||||
"""
|
||||
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
|
||||
|
||||
Args:
|
||||
odm_values: 单订单行场景下库存行命中的 ODM 值列表。
|
||||
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
|
||||
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
|
||||
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
|
||||
Returns:
|
||||
(notice, customer)。
|
||||
"""
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema); db.session.flush()
|
||||
part = _lookup_standard_fields('part_number')['part_number']
|
||||
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
||||
db.session.add(version); db.session.flush()
|
||||
draft = excel_template.create_draft(_workbook_upload(), {
|
||||
'template_code': 'ODMSCOPE', 'display_name': 'OdmScope',
|
||||
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
|
||||
{'sheet': 'Detail', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
|
||||
]},
|
||||
}, actor_id=None)
|
||||
published = excel_template.publish(draft['id'], actor_id=None)
|
||||
parsing = ShippingInventoryParsingProfile(
|
||||
profile_code='ODMSCOPE', display_name='OdmScope', version=1, status='published', file_format='xlsx',
|
||||
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
|
||||
)
|
||||
login = ShippingRpaProfile(
|
||||
profile_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', login_url='https://invalid',
|
||||
login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
db.session.add_all([parsing, login]); db.session.flush()
|
||||
db.session.add(ShippingInventorySource(
|
||||
source_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', rpa_profile_id=login.id,
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
customer = ShippingCustomer(
|
||||
standard_name='ODM范围客户', short_code='ODMSC', status='active',
|
||||
odm_ids=list(customer_odm_ids) if customer_odm_ids is not None else None,
|
||||
)
|
||||
db.session.add(customer); db.session.flush()
|
||||
ot = ShippingOrderTask(task_no='OT-ODMSCOPE', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(ot); db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction); db.session.flush()
|
||||
specs = line_specs or [{'part': 'PN-A', 'odm_values': odm_values}]
|
||||
snapshot_lines = []
|
||||
for index, spec in enumerate(specs, start=1):
|
||||
order_line = ShippingOrderLine(extraction_id=extraction.id, position=index, line_no=index)
|
||||
db.session.add(order_line); db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
|
||||
decision_status='accepted', resolved_value_json=spec['part'],
|
||||
)
|
||||
db.session.add(decision); db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
|
||||
value_text=spec['part'], decision_id=decision.id,
|
||||
))
|
||||
snapshot_lines.append((index, part.id, spec['part'], 1, f'100000000{index}'))
|
||||
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
|
||||
inventory_rows = []
|
||||
for spec in specs:
|
||||
for odm in spec['odm_values']:
|
||||
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
|
||||
storage_path=str(tmp_path / 'odm-scope.xlsx'),
|
||||
inventory_lines_json=inventory_rows,
|
||||
line_count=len(inventory_rows), share_mode='task_only', warehouse_id='DUB', source_code='ODMSCOPE',
|
||||
snapshot_status='ready',
|
||||
)
|
||||
db.session.add(inventory_file); db.session.flush()
|
||||
snapshot = _freeze_export_snapshot(
|
||||
ot, extraction, version,
|
||||
lines=snapshot_lines,
|
||||
customer_id=customer.id, inventory_file_id=inventory_file.id,
|
||||
)
|
||||
notice = _materialize_export_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
|
||||
)
|
||||
if choice_odm is not None:
|
||||
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
|
||||
match.chosen_odm_id = choice_odm
|
||||
db.session.flush()
|
||||
return notice, customer
|
||||
|
||||
|
||||
def test_export_narrows_odm_by_customer_range(app, tmp_path):
|
||||
"""客户 ODM ID 范围非空时,导出只取范围内库存行;范围命中唯一值写入表头。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['odm-2'],
|
||||
)
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_odm_range_excluding_all_raises_specific_error(app, tmp_path):
|
||||
"""客户范围把全部命中排除时,必须报指向客户数据的可行动错误而非「没有匹配」。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-9'],
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match='不在客户数据维护的 ODM ID 范围'):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_export_applies_notice_odm_choice(app, tmp_path):
|
||||
"""整单用户选择优先于多值冲突;选择经 casefold 归一后命中库存行。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], choice_odm='odm-2',
|
||||
)
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_auto_narrows_unique_feasible_odm_without_manual_choice(app, tmp_path):
|
||||
"""无范围、无选择时,整单唯一可行 ODM(各行命中交集恰一个)自动收敛。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
|
||||
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
|
||||
{'part': 'PN-B', 'odm_values': ['ODM-2']},
|
||||
])
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
|
||||
"""无范围、无选择且多值并存时维持折叠冲突阻断,等待用户整单选择。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'])
|
||||
|
||||
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
|
||||
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
|
||||
from app.core.errors import AppError
|
||||
from app.services.shipping_notice.notice_odm_choice_service import (
|
||||
notice_odm_options,
|
||||
set_notice_odm_choice,
|
||||
)
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-2', 'ODM-3'],
|
||||
)
|
||||
|
||||
options = notice_odm_options(task)
|
||||
|
||||
# [断言] 逐行候选是客户范围过滤后的集合,且保留库存行原始大小写。
|
||||
assert options['whitelist_applied'] is True
|
||||
assert options['customer_odm_ids'] == ['ODM-2', 'ODM-3']
|
||||
assert len(options['lines']) == 1
|
||||
assert options['lines'][0]['odm_values'] == ['ODM-2']
|
||||
assert options['lines'][0]['chosen_odm_id'] is None
|
||||
|
||||
snapshot_line_id = options['lines'][0]['snapshot_line_id']
|
||||
result = set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-2')
|
||||
|
||||
assert result['odm_id'] == 'ODM-2'
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
task_id=int(task.order_task_id), is_current=True,
|
||||
).all()
|
||||
assert matches and {m.chosen_odm_id for m in matches} == {'ODM-2'}
|
||||
options = notice_odm_options(task)
|
||||
assert options['lines'][0]['chosen_odm_id'] == 'ODM-2'
|
||||
|
||||
with pytest.raises(AppError) as exc:
|
||||
set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-9')
|
||||
assert getattr(exc.value, 'code', '') == 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
|
||||
|
||||
|
||||
def test_notice_odm_choice_syncs_same_snapshot_file_lines(app, tmp_path):
|
||||
"""同一快照文件的行:改任一行 ODM ID,其余行同步落库同一选择。"""
|
||||
from app.services.shipping_notice.notice_odm_choice_service import (
|
||||
notice_odm_options,
|
||||
set_notice_odm_choice,
|
||||
)
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
|
||||
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
|
||||
{'part': 'PN-B', 'odm_values': ['ODM-2', 'ODM-3']},
|
||||
])
|
||||
|
||||
options = notice_odm_options(task)
|
||||
# [断言] 每行有自己的候选;同文件两行的可行集=交集。
|
||||
by_sid = {str(item['snapshot_line_id']): item for item in options['lines']}
|
||||
assert len(by_sid) == 2
|
||||
assert options['lines'][0]['odm_values'] == ['ODM-1', 'ODM-2']
|
||||
|
||||
target_sid = options['lines'][0]['snapshot_line_id']
|
||||
result = set_notice_odm_choice(
|
||||
task, snapshot_line_id=target_sid, odm_id='ODM-2',
|
||||
)
|
||||
|
||||
# [断言] 同步范围=同一快照文件:两行当前匹配行写同一选择。
|
||||
assert result['synced_line_count'] == 2
|
||||
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
task_id=int(task.order_task_id), is_current=True,
|
||||
).all()
|
||||
assert len(matches) == 2
|
||||
assert {m.chosen_odm_id for m in matches} == {'ODM-2'}
|
||||
options = notice_odm_options(task)
|
||||
assert all(item['chosen_odm_id'] == 'ODM-2' for item in options['lines'])
|
||||
|
||||
|
||||
def test_notice_odm_options_empty_when_template_ignores_odm(app, tmp_path):
|
||||
"""模板不消费 odm 字段时投影为空候选,不产生任何选择入口。"""
|
||||
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1'])
|
||||
options = notice_odm_options(task)
|
||||
assert options['odm_field_id'] is not None
|
||||
assert options['lines'] and options['lines'][0]['odm_values'] == ['ODM-1']
|
||||
@@ -1,22 +1,28 @@
|
||||
"""
|
||||
backend/tests/test_shipping_formal_task_edit_audit.py
|
||||
|
||||
用途:验收正式任务编辑成功/拒绝与 change_effect 失效写入 ShippingAuditEvent。
|
||||
用途:验收正式任务编辑成功审计、反向锁拒绝审计与 change_effect 失效写入 ShippingAuditEvent。
|
||||
依赖:task_workflow、ShippingAuditEvent、test_shipping_review_formal_task_edit 种子助手。
|
||||
逻辑:editable 拒绝写 formal_task_edit_rejected;inventory 失效写
|
||||
formal_task_field_edited + inventory_match_invalidated + excel_export_invalidated。
|
||||
逻辑:未配置策略字段编辑成功写 formal_task_field_edited(old→new;reason/evidence 缺省落哨兵值);
|
||||
显式 editable=False 反向锁仍拒绝并写 formal_task_edit_rejected;Excel ready 冻结仍拒绝;
|
||||
inventory 失效写 formal_task_field_edited + inventory_match_invalidated + excel_export_invalidated。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, ShippingNoticeLineInventoryMatch
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderReviewEvent,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
from tests.test_shipping_review_formal_task_edit import (
|
||||
_attach_extraction,
|
||||
_link_order_task,
|
||||
_review_payload,
|
||||
_seed_ready_export_artifact,
|
||||
_task,
|
||||
)
|
||||
|
||||
@@ -31,10 +37,75 @@ def test_formal_task_edit_audit_event_types_frozen():
|
||||
})
|
||||
|
||||
|
||||
def test_formal_edit_rejection_writes_audit_event(app):
|
||||
"""Schema 禁止编辑时仍落 formal_task_edit_rejected,可被审计中心检索。"""
|
||||
def test_unconfigured_field_edit_writes_formal_task_edited_audit(app):
|
||||
"""新契约:未配置策略字段编辑成功,写 formal_task_field_edited(old→new 可检索)。"""
|
||||
with app.app_context():
|
||||
task = _task(task_no='SN-FORMAL-AUDIT-REJ-001')
|
||||
task = _task(task_no='SN-FORMAL-AUDIT-EDIT-001')
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
'task_no': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
**_review_payload(),
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
|
||||
edited = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(task_no=task.task_no, event_type='formal_task_field_edited')
|
||||
.one()
|
||||
)
|
||||
assert edited.result == 'success'
|
||||
meta = edited.metadata_json or {}
|
||||
field_changes = meta.get('field_changes') or []
|
||||
assert field_changes
|
||||
assert field_changes[0]['previous_value'] == '3000000001'
|
||||
assert field_changes[0]['new_value'] == '3000092917'
|
||||
|
||||
|
||||
def test_quick_edit_without_reason_evidence_uses_sentinel_audit_values(app):
|
||||
"""新契约:reason/evidence 缺省时编辑成功,审计落哨兵值(NOT NULL 审计列不破坏)。"""
|
||||
with app.app_context():
|
||||
task = _task(task_no='SN-FORMAL-AUDIT-SENTINEL-001')
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
'task_no': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
'event_source': 'workspace_api',
|
||||
'reviewed_by_id': 1,
|
||||
'expected_order_data_version': 1,
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
|
||||
edited = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(task_no=task.task_no, event_type='formal_task_field_edited')
|
||||
.one()
|
||||
)
|
||||
assert edited.result == 'success'
|
||||
assert (edited.metadata_json or {}).get('evidence_ref') == 'inline:match-table'
|
||||
|
||||
event = ShippingOrderReviewEvent.query.filter_by(task_id=task.id).one()
|
||||
assert event.evidence_ref == 'inline:match-table'
|
||||
assert event.reason == 'quick_field_edit'
|
||||
assert int(event.reviewed_by_id) == 1
|
||||
|
||||
|
||||
def test_explicit_readonly_field_still_rejected_with_audit(app):
|
||||
"""状态制下显式 editable=false 仍为反向锁:拒绝写入并落 formal_task_edit_rejected 审计。"""
|
||||
with app.app_context():
|
||||
task = _task(task_no='SN-FORMAL-AUDIT-RELOCK-001')
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
@@ -50,6 +121,9 @@ def test_formal_edit_rejection_writes_audit_event(app):
|
||||
})
|
||||
assert response['status'] == 'failed'
|
||||
assert response['data']['error_code'] == 'SHIPPING.ORDER_FIELD_EDIT_FORBIDDEN'
|
||||
# Excel 未 ready(无冻结),拒绝必须来自策略反向锁而非冻结门。
|
||||
from app.services.shipping_notice.schema_edit_policy import is_excel_ready_for_task
|
||||
assert is_excel_ready_for_task(task) is False
|
||||
|
||||
events = (
|
||||
ShippingAuditEvent.query
|
||||
@@ -59,6 +133,36 @@ def test_formal_edit_rejection_writes_audit_event(app):
|
||||
assert len(events) == 1
|
||||
assert events[0].result == 'rejected'
|
||||
assert events[0].error_code == 'SHIPPING.ORDER_FIELD_EDIT_FORBIDDEN'
|
||||
meta = events[0].metadata_json or {}
|
||||
assert meta.get('scope') == 'line'
|
||||
assert meta.get('field_codes') == ['reservation_id']
|
||||
|
||||
|
||||
def test_excel_ready_freeze_still_rejects_edit(app):
|
||||
"""Excel ready(ready Artifact)后全局冻结仍拒绝编辑,即使字段处于默认可编辑状态。"""
|
||||
with app.app_context():
|
||||
task = _task(task_no='SN-FORMAL-AUDIT-FROZEN-001')
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
)
|
||||
_seed_ready_export_artifact(task)
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
'task_no': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
**_review_payload(),
|
||||
})
|
||||
assert response['status'] == 'failed'
|
||||
assert response['data']['error_code'] == 'SHIPPING.ORDER_EXCEL_FROZEN'
|
||||
# 冻结门位于 _prepare_review_context(策略检查之前),当前不写 formal_task_edit_rejected 审计。
|
||||
assert (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(task_no=task.task_no, event_type='formal_task_edit_rejected')
|
||||
.count()
|
||||
) == 0
|
||||
|
||||
|
||||
def test_inventory_invalidation_writes_formal_edit_audit_chain(app):
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
tests/test_shipping_gate_audit_and_match_sync.py
|
||||
|
||||
用途:门禁审计失败不得回滚业务;库存就绪但尚未匹配时不得伪造成 match_failed。
|
||||
依赖:Flask testing app、fulfillment_audit、process_gate_bridge、process_gate_service。
|
||||
逻辑:审计 SAVEPOINT + 门禁 strict=False;sync 在无匹配行时保持 matching pending。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
complete_gate_attempt,
|
||||
ensure_execution_for_workflow_version,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
|
||||
def test_gate_audit_failure_does_not_rollback_complete_outcome(app, monkeypatch):
|
||||
"""[断言] 审计写入失败时 Gate passed 仍落库;业务结果不被审计打断。"""
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(task_no='OT-AUDIT-ISOLATE', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all():
|
||||
if gate.sequence_no < 13:
|
||||
gate.status = 'passed'
|
||||
prep = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
prep.status = 'queued'
|
||||
db.session.flush()
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
idempotency_key='audit-isolate-prep',
|
||||
input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
assert attempt is not None
|
||||
attempt.status = 'running'
|
||||
db.session.flush()
|
||||
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError('simulated_audit_db_failure')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.append_shipping_audit_event',
|
||||
_boom,
|
||||
)
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
outcome='passed',
|
||||
output_snapshot={'ok': True},
|
||||
effective_result_json={'findings': []},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
db.session.refresh(prep)
|
||||
db.session.refresh(attempt)
|
||||
assert prep.status == 'passed'
|
||||
assert attempt.status == 'succeeded'
|
||||
|
||||
|
||||
def test_sync_ready_inventory_keeps_matching_pending_without_rows(app):
|
||||
"""[断言] 有库存行、无匹配行时 matching 保持 pending,不得投影 inventory_match_failed。"""
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
with app.app_context():
|
||||
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',
|
||||
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}],
|
||||
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,
|
||||
))
|
||||
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
|
||||
# 前置 Gate 已通过;匹配尚未执行。清掉活动 Attempt,避免 sync 因 BUSY 早退。
|
||||
for attempt in ShippingProcessGateAttempt.query.join(ShippingProcessGate).filter(
|
||||
ShippingProcessGate.execution_id == int(execution.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
).all():
|
||||
attempt.status = 'superseded'
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all():
|
||||
if gate.gate_code == 'inventory_matching':
|
||||
gate.status = 'pending'
|
||||
gate.next_action_code = None
|
||||
gate.blocking_reason_code = None
|
||||
elif int(gate.sequence_no) <= 14:
|
||||
gate.status = 'passed'
|
||||
gate.blocking_reason_code = None
|
||||
db.session.flush()
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
db.session.commit()
|
||||
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_matching',
|
||||
).one()
|
||||
# pending=尚未入队;queued=已由 auto-progress 入队待跑。二者都不是「匹配失败」。
|
||||
assert matching.status in {'pending', 'queued', 'running'}
|
||||
assert matching.blocking_reason_code != 'inventory_match_failed'
|
||||
assert matching.status != 'blocked_retryable'
|
||||
@@ -135,7 +135,7 @@ def _confirm_direct_rpa_task_customer(task: ShippingOrderTask) -> None:
|
||||
|
||||
def test_encrypt_credential_round_trip_requires_runtime_key(app):
|
||||
"""凭据必须依赖环境主密钥加密,且可在受控运行时回读。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
ciphertext = encrypt_credential('not-a-real-password')
|
||||
assert ciphertext != 'not-a-real-password'
|
||||
@@ -144,7 +144,7 @@ def test_encrypt_credential_round_trip_requires_runtime_key(app):
|
||||
|
||||
def test_encrypt_credential_rejects_missing_runtime_key(app):
|
||||
"""关键加密主密钥缺失时拒绝写入凭据,避免产生不可恢复密文。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = ''
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = ''
|
||||
with app.app_context(), pytest.raises(ServiceUnavailableError):
|
||||
encrypt_credential('not-a-real-password')
|
||||
|
||||
|
||||
@@ -73,3 +73,79 @@ def test_active_inventory_file_for_notice_uses_order_task_link(app, tmp_path) ->
|
||||
assert active_inventory_file_for_task(notice) is not None
|
||||
assert active_inventory_file_for_task(notice).id == inventory_file.id
|
||||
assert len(resolve_inventory_lines_for_execution(notice)) == 1
|
||||
|
||||
|
||||
def test_resolve_inventory_lines_for_notice_reads_owner_ot_frozen_candidates(app, monkeypatch) -> None:
|
||||
"""Notice 导出必须回源所属 OT 读冻结候选合并行;不得退化成 active Link 单源。
|
||||
|
||||
复现:多源路由任务行级匹配命中 B 源快照后,生成 Excel 传 Notice 取数,
|
||||
冻结候选分支因 Notice 无候选集指针被跳过,退化成 A 源单文件 → 误报
|
||||
「订单行没有匹配的库存记录」。数据源在导出时禁止被切换。
|
||||
"""
|
||||
with app.app_context():
|
||||
# 先占用 Notice 自增 id=1,确保后续 Notice.id ≠ OT.id(复现生产错位)。
|
||||
db.session.add(ShippingNotice(
|
||||
task_no='SN-INV-NOTICE-CAND-BURN',
|
||||
user_id=1,
|
||||
source_type='manual',
|
||||
))
|
||||
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',
|
||||
storage_path='unused://notice-cand-link.xlsx',
|
||||
source_file_name='link-only.xlsx',
|
||||
snapshot_status='ready',
|
||||
inventory_lines_json=[{'part_number': 'ONLY_LINK_ROW'}],
|
||||
line_count=1,
|
||||
)
|
||||
db.session.add_all([ot, link_file])
|
||||
db.session.flush()
|
||||
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-INV-NOTICE-CAND',
|
||||
user_id=1,
|
||||
source_type='inventory_gate',
|
||||
order_task_id=int(ot.id),
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
assert int(notice.id) != int(ot.id)
|
||||
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=int(ot.id),
|
||||
inventory_file_id=int(link_file.id),
|
||||
is_active=True,
|
||||
access_mode='readonly',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
# 冻结候选事实只挂在 OT 上;Notice 自身查不到任何冻结源。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda task: ['SRC_A', 'SRC_B'] if isinstance(task, ShippingOrderTask) else [],
|
||||
)
|
||||
prepared_with = []
|
||||
|
||||
def _fake_prepare(task):
|
||||
prepared_with.append(task)
|
||||
return {
|
||||
'status': 'ready',
|
||||
'lines': [
|
||||
{'part_number': 'P1', '__source_code': 'SRC_A'},
|
||||
{'part_number': 'P2', '__source_code': 'SRC_B'},
|
||||
],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
|
||||
_fake_prepare,
|
||||
)
|
||||
|
||||
rows = resolve_inventory_lines_for_execution(notice)
|
||||
# 断言:合并候选行生效,且 prepare 回源到所属 OT(而非 Notice)。
|
||||
assert [row['__source_code'] for row in rows] == ['SRC_A', 'SRC_B']
|
||||
assert [int(t.id) for t in prepared_with] == [int(ot.id)]
|
||||
# 断言:Link 单源文件行不得混入导出输入(导出数据源未被切换)。
|
||||
assert all(row.get('part_number') != 'ONLY_LINK_ROW' for row in rows)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
backend/tests/test_shipping_my_todo_stage_counts.py
|
||||
|
||||
用途:「我的待办」count 聚合扩展单测(阶段 tab 计数 + 已完成子终态拆分)。
|
||||
依赖:pytest、ShippingNotice / ShippingOrderTask / Artifact 夹具、query_service.count_my_todos。
|
||||
逻辑:覆盖 processing_stage 权威 / 人工原因归属 Gate / todo_category 兜底三路阶段归类;
|
||||
done 桶拆分为已核验上传成功与 复核驳回/作废 两类终态计数。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingExportArtifact,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.shipping_notice.constants import RS_REJECTED
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
|
||||
|
||||
def test_count_my_todos_reports_stage_counts_and_done_breakdown(app):
|
||||
"""阶段 tab 计数按权威口径归类;done 拆分为上传成功与驳回作废两类。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
owner = 77
|
||||
# [STEP] 四个待处理条目分别覆盖三路归类路径:
|
||||
# OT.stage 权威(waiting_review→订单复核)、原因映射(upload_rpa_failed→货代上传、
|
||||
# inventory_source_unresolved→通知准备)、类别兜底(artifact ready 人工上传→货代上传)。
|
||||
review_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-REVIEW", stage="waiting_review",
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
upload_rpa_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-UPLOAD-RPA", pending_human_reason="upload_rpa_failed",
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
inventory_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-INVENTORY", pending_human_reason="inventory_source_unresolved",
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
rejected_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-REJECTED", review_status=RS_REJECTED,
|
||||
source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
manual_task = ShippingOrderTask(
|
||||
task_no="OT-STAGE-MANUAL", source_type="direct_pdf", user_id=owner,
|
||||
)
|
||||
manual_notice = ShippingNotice(task_no="SN-STAGE-MANUAL", source_type="manual", user_id=owner)
|
||||
done_notice = ShippingNotice(task_no="SN-STAGE-DONE", source_type="manual", user_id=owner)
|
||||
rejected_notice = ShippingNotice(task_no="SN-STAGE-REJECTED", source_type="manual", user_id=owner)
|
||||
db.session.add_all([
|
||||
review_task, upload_rpa_task, inventory_task, rejected_task, manual_task,
|
||||
manual_notice, done_notice, rejected_notice,
|
||||
])
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='STAGE', display_name='Stage', version=1, status='published',
|
||||
storage_bucket='test', storage_key='stage.xlsx', original_filename='stage.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='STAGE', display_name='Stage', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='STAGE', display_name='Stage')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
manual_notice.order_task_id = manual_task.id
|
||||
rejected_notice.order_task_id = rejected_task.id
|
||||
|
||||
def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact:
|
||||
"""为 Notice 建立待办分类所需的最小正式 Excel Artifact。"""
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=notice.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status=status,
|
||||
)
|
||||
db.session.add(artifact)
|
||||
return artifact
|
||||
|
||||
# 人工上传待登记(ready→manual_upload);已完成(uploaded→done/upload_complete);
|
||||
# 驳回终态(ready 但 OT 复核驳回→done/reject_void)。
|
||||
add_artifact(manual_notice, artifact_no='ART-STAGE-MANUAL', status='ready')
|
||||
add_artifact(done_notice, artifact_no='ART-STAGE-DONE-UP', status='uploaded')
|
||||
add_artifact(rejected_notice, artifact_no='ART-STAGE-REJ', status='ready')
|
||||
db.session.commit()
|
||||
|
||||
counts = count_my_todos(owner)
|
||||
|
||||
# 断言:四个待处理条目按权威口径落入正确阶段 tab。
|
||||
assert counts["pending"] == 4
|
||||
assert counts["stage_counts"] == {
|
||||
"intake_parse": 0,
|
||||
"order_review": 1,
|
||||
"fulfillment_prep": 1,
|
||||
"freight_upload": 2,
|
||||
}
|
||||
# 断言:done 拆分——uploaded Artifact 计上传成功,OT 复核驳回计驳回作废。
|
||||
assert counts["done"] == 2
|
||||
assert counts["done_counts"] == {"upload_complete": 1, "reject_void": 1}
|
||||
|
||||
# 断言:terminal_kind 子视图过滤——两个终态子 tab 各自只取对应集合,互不重叠。
|
||||
upload_page = list_my_todos(owner, bucket="done", terminal_kind="upload_complete")
|
||||
assert {item["task_no"] for item in upload_page["items"]} == {"SN-STAGE-DONE"}
|
||||
reject_page = list_my_todos(owner, bucket="done", terminal_kind="reject_void")
|
||||
assert {item["task_no"] for item in reject_page["items"]} == {"SN-STAGE-REJECTED"}
|
||||
# 无过滤参数时保持既有行为:done 全量。
|
||||
assert list_my_todos(owner, bucket="done")["total"] == 2
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
tests/test_shipping_notice_creation_effective.py
|
||||
|
||||
用途:验证正式通知行物化携带冻结后修正值,且整单建通知排除已结案行。
|
||||
依赖:pytest、shipping_notice_creation_service、notice_line_service、行级履约决定模型。
|
||||
逻辑:库存门禁通过(或行豁免)后建 Notice,断言 NoticeLine 的料号/数量来自有效视图,
|
||||
结案行既不进门禁目标集也不物化为通知行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
)
|
||||
from app.services.shipping_notice.shipping_notice_creation_service import (
|
||||
create_shipping_notice_after_inventory_gate,
|
||||
)
|
||||
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
from tests.test_line_closure_fulfillment import _seed_close_decision
|
||||
|
||||
|
||||
def _seed_customer(snapshot):
|
||||
"""给快照挂一个 active 客户(建 Notice 门禁必填)。"""
|
||||
customer = ShippingCustomer(standard_name='有效视图客户', short_code='EFFC', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
snapshot.customer_id = customer.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _seed_match_row(order, snap_line, *, match_result='matched', shortage='0'):
|
||||
"""给冻结行补一条当前匹配事实(matched+ready 表示门禁可过)。"""
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
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',
|
||||
required_qty='10', available_qty='10', shortage_qty=shortage,
|
||||
reservation_id=snap_line.reservation_id, part_number=snap_line.part_number,
|
||||
is_current=True,
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_notice_lines_carry_corrected_part_number(app):
|
||||
"""修正后的料号必须进入正式通知行(通知行会被 Excel/货代消费)。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_customer(fixture.snapshot)
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
_seed_match_row(fixture.order, fixture.snap_lines[0])
|
||||
# 注:brief 原文为整单调用,但夹具第二行无匹配事实会触发门禁 ConflictError(经控制器确认),
|
||||
# 改为仅选中第 0 行——与 Step 2 预期断言差异(单行)一致。
|
||||
notice = create_shipping_notice_after_inventory_gate(
|
||||
fixture.order, snapshot_line_ids={int(fixture.snap_lines[0].id)},
|
||||
)
|
||||
rows = ShippingNoticeLine.query.filter_by(notice_id=notice.id).all()
|
||||
# 断言:通知行料号是修正值,而不是快照冻结的带尾巴旧值。
|
||||
assert [row.part_number for row in rows] == ['D4-A08AR12000002']
|
||||
|
||||
|
||||
def test_notice_creation_skips_closed_line(app):
|
||||
"""一行 matched + 一行结案:整单建通知成功且通知行不含结案行。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_customer(fixture.snapshot)
|
||||
_seed_match_row(fixture.order, fixture.snap_lines[0])
|
||||
_seed_match_row(
|
||||
fixture.order, fixture.snap_lines[1], match_result='not_found', shortage='10',
|
||||
)
|
||||
_seed_close_decision(fixture, 1)
|
||||
notice = create_shipping_notice_after_inventory_gate(fixture.order)
|
||||
rows = ShippingNoticeLine.query.filter_by(notice_id=notice.id).all()
|
||||
# 断言:只有第 0 行进入通知;结案行既过门禁又被物化排除。
|
||||
assert [row.snapshot_line_id for row in rows] == [int(fixture.snap_lines[0].id)]
|
||||
|
||||
|
||||
def test_whole_order_notice_rejected_when_all_lines_closed(app):
|
||||
"""全部行结案=无可履约内容:整单建 Notice 必须按门禁未通过拒绝,防止建空通知。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_customer(fixture.snapshot)
|
||||
_seed_match_row(fixture.order, fixture.snap_lines[0])
|
||||
_seed_match_row(
|
||||
fixture.order, fixture.snap_lines[1], match_result='not_found', shortage='10',
|
||||
)
|
||||
_seed_close_decision(fixture, 1, version=1)
|
||||
_seed_close_decision(fixture, 0, version=1)
|
||||
# 断言:结案剔除后目标行集为空,整单调用走门禁未通过分支(与 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)
|
||||
@@ -130,7 +130,7 @@ def test_serialize_run_reads_inventory_raw_zip_available_from_summary(app):
|
||||
def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path):
|
||||
"""finalize 预生成应落盘 ZIP 并返回 summary 字段。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
xlsx.write_bytes(b"fake-xlsx-content")
|
||||
|
||||
@@ -176,7 +176,7 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p
|
||||
def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
|
||||
"""无可读快照时不生成 ZIP。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
with app.app_context():
|
||||
run = _make_inventory_run_with_created(
|
||||
@@ -193,7 +193,7 @@ def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_fi
|
||||
def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp_path):
|
||||
"""created 有记录但磁盘文件缺失时不应生成 ZIP。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
with app.app_context():
|
||||
run = _make_inventory_run_with_created(
|
||||
@@ -219,7 +219,7 @@ def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp
|
||||
def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path):
|
||||
"""下载解析应返回归档路径与建议文件名。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
xlsx.write_bytes(b"fake-xlsx-content")
|
||||
|
||||
@@ -262,7 +262,7 @@ def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app):
|
||||
def test_resolve_inventory_raw_zip_download_rejects_path_outside_archive_dir(app, tmp_path):
|
||||
"""summary 指向归档目录外的真实文件时必须 404。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
outside_zip = tmp_path / "outside.zip"
|
||||
outside_zip.write_bytes(b"fake-zip")
|
||||
@@ -286,7 +286,7 @@ def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path
|
||||
"""summary 指向非 .zip 后缀文件时必须 404。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
archive_dir.mkdir(parents=True)
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
fake_file = archive_dir / "RUN-ARCH-RESOLVE-BAD.txt"
|
||||
fake_file.write_bytes(b"not-a-zip")
|
||||
@@ -360,7 +360,7 @@ def test_build_schedule_run_wecom_jump_params_omits_raw_zip_without_archive(app)
|
||||
|
||||
def test_get_notify_base_url_prefers_wecom_public_over_notify_base_url(app):
|
||||
"""textcard 跳转应优先 HTTPS 公网域名,而非内网/端口 WECOM_NOTIFY_BASE_URL。"""
|
||||
from app.services.wecom_notify import _get_notify_base_url
|
||||
from app.services.integrations.wecom.notify import _get_notify_base_url
|
||||
|
||||
with app.app_context():
|
||||
app.config["WECOM_NOTIFY_BASE_URL"] = "http://ait.well-trust.com:8890/"
|
||||
@@ -371,7 +371,7 @@ def test_get_notify_base_url_prefers_wecom_public_over_notify_base_url(app):
|
||||
|
||||
def test_get_notify_base_url_falls_back_to_hxops_public_base_url(app):
|
||||
"""未配置 WECOM_PUBLIC 时应回退 HXOPS_PUBLIC_BASE_URL,而非 WECOM_NOTIFY_BASE_URL。"""
|
||||
from app.services.wecom_notify import _get_notify_base_url
|
||||
from app.services.integrations.wecom.notify import _get_notify_base_url
|
||||
|
||||
with app.app_context():
|
||||
app.config["WECOM_PUBLIC_BASE_URL"] = ""
|
||||
@@ -394,19 +394,19 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
|
||||
return {"errcode": 0}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify.send_wecom_textcard_message",
|
||||
"app.services.integrations.wecom.notify.send_wecom_textcard_message",
|
||||
_fake_send_textcard,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify._get_enabled_events",
|
||||
"app.services.integrations.wecom.notify._get_enabled_events",
|
||||
lambda: {"schedule_completed"},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify.upload_wecom_temp_media",
|
||||
"app.services.integrations.wecom.notify.upload_wecom_temp_media",
|
||||
lambda _data, filename: media_uploads.append(filename) or f"media-{len(media_uploads)}",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify.send_wecom_file_message",
|
||||
"app.services.integrations.wecom.notify.send_wecom_file_message",
|
||||
lambda _userid, media_id: file_sends.append(media_id) or {"errcode": 0},
|
||||
)
|
||||
|
||||
@@ -414,7 +414,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
|
||||
app.config["WECOM_NOTIFY_ENABLED"] = True
|
||||
app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com"
|
||||
app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/"
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
|
||||
|
||||
user = User(
|
||||
username="wecom_jump_user",
|
||||
@@ -482,7 +482,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
|
||||
):
|
||||
"""admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
xlsx.write_bytes(b"fake-xlsx-content")
|
||||
|
||||
|
||||
@@ -538,7 +538,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
|
||||
db.session.refresh(task)
|
||||
|
||||
assert result['status'] == 'ok', result
|
||||
assert result['data']['stage'] == 'step5_match_inventory'
|
||||
assert result['data']['stage'] == 'inventory_matching'
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one()
|
||||
snapshot = db.session.get(ShippingInventoryFile, link.inventory_file_id)
|
||||
assert snapshot is not None
|
||||
@@ -641,7 +641,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_mixed.xlsx"
|
||||
@@ -683,7 +683,7 @@ def test_rpa_snapshot_persists_confirmed_profile_mapping(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "inventory-mapping-confirmed.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -769,7 +769,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "batch_task_success.xlsx"
|
||||
@@ -854,7 +854,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(
|
||||
@@ -981,7 +981,7 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "crane-multi-warehouse.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("CRANE-WH").getvalue())
|
||||
|
||||
@@ -1054,7 +1054,7 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "crane-unresolved-link.xlsx"
|
||||
sample.write_bytes(
|
||||
inventory_xlsx_with_warehouse(
|
||||
@@ -1144,11 +1144,15 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code="inventory_matching",
|
||||
).one()
|
||||
assert preparation.status == "passed"
|
||||
assert preparation.blocking_reason_code is None
|
||||
assert execution.current_gate_code == "inventory_matching"
|
||||
assert matching.status == "blocked_retryable"
|
||||
assert matching.blocking_reason_code == "inventory_match_failed"
|
||||
assert preparation.status in {"passed", "queued", "running"}
|
||||
if preparation.status == "passed":
|
||||
assert preparation.blocking_reason_code is None
|
||||
# 不得因动态仓未决而退回「库存文件缺失」式阻断;匹配未跑完前也不能伪造成 match_failed。
|
||||
assert matching.blocking_reason_code != "inventory_match_failed"
|
||||
assert matching.status != "blocked_retryable"
|
||||
assert execution.current_gate_code in {
|
||||
"inventory_preparation", "inventory_field_mapping", "inventory_matching",
|
||||
}
|
||||
|
||||
|
||||
def test_inventory_callback_job_marks_business_failure_as_failed(app, monkeypatch):
|
||||
@@ -1297,7 +1301,7 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "orphan_task.xlsx"
|
||||
with open(sample, "wb") as handle:
|
||||
@@ -1394,7 +1398,7 @@ def test_inventory_trigger_writes_without_online_worker(app, tmp_path, monkeypat
|
||||
|
||||
with app.app_context():
|
||||
trigger_dir = tmp_path / 'inventory_triggers'
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR'] = str(trigger_dir)
|
||||
app.config['FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR'] = str(trigger_dir)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready',
|
||||
lambda: (_ for _ in ()).throw(AssertionError('trigger write must not require worker heartbeat')),
|
||||
@@ -1511,7 +1515,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "reuse_ingest_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1583,7 +1587,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
run_no = "RUN-REUSE-MISMATCH"
|
||||
|
||||
@@ -1638,7 +1642,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample_a = drop_dir / "task_a.xlsx"
|
||||
sample_b = drop_dir / "task_b.xlsx"
|
||||
sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1710,7 +1714,7 @@ def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path,
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "failed_before_confirm.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
callback_calls: list[dict] = []
|
||||
@@ -1771,7 +1775,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "shared.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
run_no = "RUN-SHARED-LINK"
|
||||
@@ -1847,7 +1851,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "post_commit.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1890,7 +1894,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "promote_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1984,7 +1988,7 @@ def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "move_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -2023,7 +2027,7 @@ def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, m
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "quarantine_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -2152,7 +2156,7 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat
|
||||
processed_dir = tmp_path / "processed"
|
||||
drop_dir.mkdir()
|
||||
processed_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir)
|
||||
|
||||
quarantine = drop_dir / ".hxops_quarantine"
|
||||
|
||||
@@ -103,7 +103,7 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
|
||||
"""排程 executor 应写入 inventory_export_batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -135,7 +135,7 @@ def test_run_task_now_defers_inventory_rpa_until_callback(app, tmp_path):
|
||||
"""run_task_now 写 trigger 后应保持 running 且 awaiting_rpa=true。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -157,7 +157,7 @@ def test_deferred_run_sets_started_at_when_missing(app, tmp_path):
|
||||
"""复用无 started_at 的 run 时,defer 应补写 started_at,避免立即超时回收。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -244,7 +244,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
|
||||
"""全部 source 成功但 Excel 导出失败时应降为 partial_failed 并写入 error_message。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_excel_fail.xlsx"
|
||||
@@ -309,7 +309,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
|
||||
"""finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_fail_finalize.xlsx"
|
||||
@@ -373,7 +373,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
|
||||
drop_dir.mkdir()
|
||||
processed_dir = drop_dir / "processed"
|
||||
processed_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_sample.xlsx"
|
||||
@@ -516,7 +516,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
|
||||
"""回调结果少于触发源数时,排程应 partial_failed。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_partial.xlsx"
|
||||
@@ -851,7 +851,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "missing_warehouse.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
@@ -881,7 +881,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "retry_snapshot.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
@@ -944,7 +944,7 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "retry_move.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
|
||||
@@ -337,7 +337,7 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
db.session.commit()
|
||||
|
||||
data = serialize_task_summary(task, viewer_user_id=11)
|
||||
assert data["todo_category"] == "in_progress"
|
||||
assert data["todo_category"] == "exception"
|
||||
assert data["created_by"] == 11
|
||||
assert data["can_handle"] is True
|
||||
# 无 Gate 且无 review_status:薄回退不投影 order_freeze
|
||||
@@ -1161,12 +1161,74 @@ def test_todo_category_sql_matches_formal_notice_facts(app):
|
||||
assert sql_category == expected
|
||||
|
||||
pending = list_my_todos(owner, bucket="pending", page=1, page_size=50)
|
||||
assert pending["total"] == 1
|
||||
assert pending["total"] == 2
|
||||
counts = count_my_todos(owner)
|
||||
assert counts["pending"] == 1
|
||||
assert counts["pending"] == 2
|
||||
assert counts["done"] == 1
|
||||
assert counts["processing"] == 0
|
||||
assert counts["total_pending_badge"] == 2
|
||||
|
||||
|
||||
def test_count_my_todos_running_gate_is_processing_and_not_double_counted(app):
|
||||
"""有 Notice 的 OT 只计 Notice 分支;active 库存准备进处理中。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
|
||||
owner = 91
|
||||
order_task = ShippingOrderTask(
|
||||
task_no="OT-RUN-ONCE", source_type="direct_pdf", user_id=owner,
|
||||
status="processing", stage="notification_preparation",
|
||||
)
|
||||
notice = ShippingNotice(task_no="SN-RUN-ONCE", source_type="manual", user_id=owner)
|
||||
db.session.add_all([order_task, notice])
|
||||
db.session.flush()
|
||||
notice.order_task_id = order_task.id
|
||||
db.session.add(ShippingProcessExecution(
|
||||
execution_no="SPE-RUN-ONCE",
|
||||
task_id=int(order_task.id),
|
||||
status="active",
|
||||
current_gate_code="inventory_preparation",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
counts = count_my_todos(owner)
|
||||
assert counts["processing"] == 1
|
||||
assert counts["total_pending_badge"] == 1
|
||||
processing = list_my_todos(owner, bucket="processing", page=1, page_size=50)
|
||||
assert processing["total"] == 1
|
||||
assert processing["items"][0]["task_no"] in {"SN-RUN-ONCE", "OT-RUN-ONCE"}
|
||||
|
||||
|
||||
def test_list_my_todos_order_review_gate_stays_in_pending(app):
|
||||
"""订单复核 blocked Gate 进入待处理,不进处理中。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
|
||||
owner = 92
|
||||
order_task = ShippingOrderTask(
|
||||
task_no="OT-REVIEW-PENDING", source_type="direct_pdf", user_id=owner,
|
||||
status="waiting_review", stage="order_review",
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessExecution(
|
||||
execution_no="SPE-REVIEW-PENDING",
|
||||
task_id=int(order_task.id),
|
||||
status="blocked",
|
||||
current_gate_code="order_field_extraction",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
counts = count_my_todos(owner)
|
||||
assert counts["processing"] == 0
|
||||
pending = list_my_todos(owner, bucket="pending", page=1, page_size=50)
|
||||
assert pending["total"] == 1
|
||||
assert pending["items"][0]["todo_category"] == "review"
|
||||
processing = list_my_todos(owner, bucket="processing", page=1, page_size=50)
|
||||
assert processing["total"] == 0
|
||||
|
||||
|
||||
def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
|
||||
|
||||
@@ -71,6 +71,18 @@ def test_validated_reservation_id_strips_optional_parenthesized_note():
|
||||
assert validated_reservation_id("30001129345") == ""
|
||||
|
||||
|
||||
def test_validated_reservation_id_strips_short_numeric_line_suffix():
|
||||
"""QUANTA IR# 等:合法 5/10 位本体 + 一段短数字后缀归一为本体;多段/非法左侧拒绝。"""
|
||||
assert validated_reservation_id("35354-1") == "35354"
|
||||
assert validated_reservation_id("3000112934-2") == "3000112934"
|
||||
assert validated_reservation_id("35354-1") == "35354"
|
||||
assert validated_reservation_id("35354_1") == "35354"
|
||||
assert validated_reservation_id("1234-1") == ""
|
||||
assert validated_reservation_id("35354-1-2") == ""
|
||||
assert validated_reservation_id("35354-a") == ""
|
||||
assert validated_reservation_id("35354123456-1") == ""
|
||||
|
||||
|
||||
def test_validated_reservation_id_rejects_amount_text_as_numeric_token():
|
||||
"""金额行中的五位整数片段不能被当成 Reservation ID。"""
|
||||
assert validated_reservation_id("941.76 28,252.80") == ""
|
||||
@@ -200,6 +212,35 @@ def test_reservation_region_requires_review_when_numbered_value_has_no_line_targ
|
||||
assert applied.review_reasons == ('line_field_unavailable',)
|
||||
|
||||
|
||||
def test_reservation_region_matches_line_by_printed_ln_number_not_position():
|
||||
"""LN 非连续(部分行已拆单)时必须按 LN 值定位逻辑行,禁止位置错配或误报越界。"""
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=extract_reservation_from_region_text(
|
||||
"Reservation L#1: 1000159370\nReservation L#2: 1000159366\n"
|
||||
"Reservation L#4: 1000159379\nReservation L#5: 1000159236"
|
||||
),
|
||||
header_field_id='header-reservation', line_field_id='line-reservation',
|
||||
line_count=4, line_numbers=[1, 2, 4, 5],
|
||||
)
|
||||
|
||||
assert applied.needs_review is False
|
||||
# 键是逻辑行序号:L#4→第 3 行(LN=4)、L#5→第 4 行(LN=5)。
|
||||
assert applied.line_values == {1: '1000159370', 2: '1000159366', 3: '1000159379', 4: '1000159236'}
|
||||
|
||||
|
||||
def test_reservation_region_flags_review_when_referenced_ln_number_is_absent():
|
||||
"""被引用的印刷行号在解析行中不存在时必须转复核,不得静默按位置写入。"""
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=extract_reservation_from_region_text("Reservation L#5: 1000159236"),
|
||||
header_field_id='header-reservation', line_field_id='line-reservation',
|
||||
line_count=2, line_numbers=[1, 2],
|
||||
)
|
||||
|
||||
assert applied.line_values == {}
|
||||
assert applied.needs_review is True
|
||||
assert applied.review_reasons == ('line_out_of_range',)
|
||||
|
||||
|
||||
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
|
||||
"""空订单或畸形行都不能被视为 Reservation 门禁通过。"""
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_
|
||||
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["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config.pop("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", None)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
|
||||
@@ -55,7 +55,7 @@ def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path):
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
|
||||
|
||||
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
|
||||
@@ -71,7 +71,7 @@ def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_p
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
with app.app_context():
|
||||
path = write_inventory_export_batch_trigger("RUN-DBS", [{
|
||||
"source_code": "UNKNOWN_FOR_TEST", "connector_type": "dbs", "rpa_profile_code": "DBS_TEST",
|
||||
@@ -92,7 +92,7 @@ def test_batch_trigger_writes_explicit_v2_callback_identity(app, tmp_path):
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
|
||||
source = {
|
||||
"source_code": "DBS",
|
||||
|
||||
@@ -459,8 +459,8 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
headers = _tool_headers(app)
|
||||
trigger = tmp_path / "inventory_triggers"
|
||||
trigger.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||||
lambda: None,
|
||||
|
||||
@@ -167,6 +167,67 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None:
|
||||
assert "stage_context" in detailed_state
|
||||
|
||||
|
||||
def test_build_task_ui_state_notice_uses_ot_stage_not_freeze_gate_lifecycle(app) -> None:
|
||||
"""
|
||||
Notice 路径必须读 OT.stage 做五阶段,禁止仅靠 order_freeze→order_review 兜底。
|
||||
|
||||
断言意图:OT.stage=order_creating 时,任务中心/详情与批次同为 fulfillment_prep,
|
||||
不得因 Notice 无 stage 列 + freeze Gate 显示「订单复核」。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import (
|
||||
_process_gate_user_summary_for_task,
|
||||
_task_lifecycle,
|
||||
)
|
||||
|
||||
user = User(
|
||||
username='ui-notice-ot-stage',
|
||||
email='ui-notice-ot-stage@example.com',
|
||||
password_hash='x',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-UI-NOTICE-OT-STAGE',
|
||||
user_id=user.id,
|
||||
source_type='direct_pdf',
|
||||
status='waiting_review',
|
||||
stage='order_creating',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-UI-NOTICE-OT-STAGE',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
order_task_id=int(order_task.id),
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=int(order_task.id), actor_type='system',
|
||||
)
|
||||
execution.status = 'blocked'
|
||||
execution.current_gate_code = 'order_freeze_readiness'
|
||||
order_task.active_process_execution_id = int(execution.id)
|
||||
# ensure_execution 在已有 Notice 时会 sync_order_task_stage_for_notice,
|
||||
# 可能把 stage 写成 waiting_review;本用例要验证「已写入的 order_creating」权威。
|
||||
order_task.stage = 'order_creating'
|
||||
order_task.status = 'waiting_review'
|
||||
db.session.commit()
|
||||
|
||||
process_gate = _process_gate_user_summary_for_task(notice)
|
||||
lifecycle = _task_lifecycle(task=notice, position=None, process_gate=process_gate)
|
||||
|
||||
assert lifecycle['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert lifecycle['lifecycle_authority'] == 'processing_stage'
|
||||
assert lifecycle['lifecycle_stage'] != 'order_review'
|
||||
|
||||
|
||||
def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None:
|
||||
"""无正式 Gate 时位置不能再推导五阶段或任何可写 UI 动作。"""
|
||||
with app.app_context():
|
||||
@@ -245,7 +306,8 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert state['lifecycle_authority'] == 'process_gate'
|
||||
# Notice/OT 无合法 stage 时由 Gate 抬升为 inventory_matching,权威记为 processing_stage。
|
||||
assert state['lifecycle_authority'] == 'processing_stage'
|
||||
assert state['stage']['code'] == 'fulfillment_prep'
|
||||
assert state['current_step']['code'] == 'fulfillment_prep'
|
||||
assert [entry['state'] for entry in state['lifecycle_entries']] == [
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_conversation_title.py
|
||||
|
||||
用途:验证订单抽取新建会话按 Intake 资产文件名派生标题,且已存在会话标题一律不动。
|
||||
依赖:全局 Flask/SQLite 测试夹具(app)、Run service 的会话解析内部函数。
|
||||
逻辑:新建分支走 conversation_title 派生;追加归属等存量路径保持原标题(含「订单抽取」)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatSession, FileAsset, ShippingOrderIntake, User
|
||||
from app.services.shipping_notice.order_extraction_run_service import _resolve_conversation
|
||||
|
||||
|
||||
def _seed_user_agent(suffix: str) -> tuple[User, Agent]:
|
||||
"""构造用户与货代 Agent;suffix 保证同文件内多用例数据隔离。"""
|
||||
user = User(username=f'title-user-{suffix}', email=f'title-{suffix}@example.com', password_hash='x')
|
||||
agent = Agent(
|
||||
name=f'Title Agent {suffix}',
|
||||
agent_code='shipping_notice',
|
||||
runtime_provider='hybrid',
|
||||
dify_app_id=f'title-agent-{suffix}',
|
||||
dify_api_key='test-key',
|
||||
is_active=True,
|
||||
)
|
||||
user.agents.append(agent)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
return user, agent
|
||||
|
||||
|
||||
def _seed_intake(suffix: str, user: User, filename: str, conversation_id: str | None = None) -> ShippingOrderIntake:
|
||||
"""构造带资产文件名的已解析 Intake。"""
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-TITLE-{suffix}',
|
||||
owner_user_id=user.id,
|
||||
original_filename=filename,
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/{filename}',
|
||||
content_hash=(suffix.lower() * 64)[:64],
|
||||
file_size=10,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'SNI-TITLE-{suffix}',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
return intake
|
||||
|
||||
|
||||
def test_new_session_title_derives_from_intake_filenames(app):
|
||||
"""新建会话:标题 = 首个文件名(剥离邮件前缀)+ 等 N 个文件 + 日期后缀。"""
|
||||
user, agent = _seed_user_agent('NEW')
|
||||
first = _seed_intake('NEW1', user, 'RE: PO#6075309 for HOXIN.eml')
|
||||
second = _seed_intake('NEW2', user, 'invoice.pdf')
|
||||
|
||||
session = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[first, second])
|
||||
|
||||
# 日期后缀来自 utcnow,断言前缀避免对当天日期产生脆弱依赖。
|
||||
assert session.title.startswith('PO#6075309 for HOXIN 等 2 个文件 ')
|
||||
|
||||
|
||||
def test_existing_session_title_stays_untouched(app):
|
||||
"""已存在会话:即便标题仍是写死的「订单抽取」,Intake 归属也不改标题。"""
|
||||
user, agent = _seed_user_agent('KEEP')
|
||||
session = ChatSession(session_id='title-session-keep', user_id=user.id, agent_id=agent.id, title='订单抽取')
|
||||
db.session.add(session)
|
||||
db.session.flush()
|
||||
intake = _seed_intake('KEEP1', user, 'RE: PO#6075309.eml', conversation_id=session.session_id)
|
||||
|
||||
resolved = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[intake])
|
||||
|
||||
assert resolved.session_id == session.session_id
|
||||
assert resolved.title == '订单抽取'
|
||||
@@ -1,7 +1,17 @@
|
||||
"""订单抽取 Worker 的单元级自动重试与技术失败收口测试。"""
|
||||
"""
|
||||
订单抽取 Worker 单元测试。
|
||||
|
||||
覆盖:物化顺序、partial waiting_layout、layout_ready_continue 自交接、
|
||||
runtime_budget_continue、layout 调度失败收口、continue_from_running 去重、
|
||||
以及同事务 finish→enqueue 避免 UniqueViolation。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.jobs.handlers.shipping_order_extraction import (
|
||||
_expansion_trigger_reason_codes,
|
||||
@@ -190,6 +200,7 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {101})
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True)
|
||||
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
|
||||
@@ -300,6 +311,7 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {201, 202})
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
|
||||
@@ -339,12 +351,15 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
|
||||
monkeypatch.setattr(
|
||||
handler, '_enqueue_ready_order_extraction_job',
|
||||
lambda _run, *, message: events.append(f'enqueue:{message}') or 999,
|
||||
lambda _run, *, message, continue_from_running=False: (
|
||||
events.append(f'enqueue:{message}:continue={continue_from_running}') or 999
|
||||
),
|
||||
)
|
||||
|
||||
def fake_finish(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
finished.update(kwargs)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', fake_finish)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
@@ -356,7 +371,7 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
|
||||
|
||||
assert 'processed:51' in events
|
||||
assert 'processed:52' not in events
|
||||
assert any(item.startswith('enqueue:') for item in events)
|
||||
assert any(item.startswith('enqueue:') and item.endswith(':continue=True') for item in events)
|
||||
assert 'terminalized' not in events
|
||||
assert 'persist_started' not in events
|
||||
assert run.status == 'processing'
|
||||
@@ -365,7 +380,347 @@ def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeyp
|
||||
assert finished['result']['budget_stopped'] is True
|
||||
assert finished['result']['waiting_continue'] is True
|
||||
assert finished['result']['handoff_status'] == 'runtime_budget_continue'
|
||||
assert finished['result']['continue_job_id'] == 999
|
||||
assert pending_unit.status == 'pending'
|
||||
# 方案 A:须先 finish(commit=False) 再 enqueue,避免 running 占唯一槽
|
||||
assert events.index('finished') < next(
|
||||
i for i, item in enumerate(events) if item.startswith('enqueue:')
|
||||
)
|
||||
|
||||
|
||||
def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(monkeypatch):
|
||||
"""
|
||||
开工快照仍 layout_pending,收口时 DB 已有 extractable ready work:须 layout_ready_continue 自交接。
|
||||
|
||||
断言:入队续抽且 continue_from_running=True;Run 不终态;handoff_status=layout_ready_continue。
|
||||
"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
finished: dict = {}
|
||||
enqueue_calls: list[dict] = []
|
||||
run = SimpleNamespace(
|
||||
id=6, user_id=9, run_no='SNER-WORKER-LAYOUT-CONTINUE', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
|
||||
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
|
||||
execution_result_json=None, extraction_completed_at=None,
|
||||
)
|
||||
job = SimpleNamespace(id=6, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
ready_unit = SimpleNamespace(
|
||||
id=61, document_id=301, intake_id=1, status='pending', result_json=None, position=1,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
stale_pending_unit = SimpleNamespace(
|
||||
id=62, document_id=302, intake_id=1, status='pending', result_json=None, position=2,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
plan = SimpleNamespace(id=6, unit_count=2, units=[ready_unit, stale_pending_unit])
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else ready_unit)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderProcessingRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
status=SimpleNamespace(in_=lambda *_a, **_k: True),
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: [ready_unit, stale_pending_unit]),
|
||||
),
|
||||
),
|
||||
))
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
|
||||
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
|
||||
# 开工快照:302 仍 pending;收口时 mock 为已有 ready work、layout 已全部就绪。
|
||||
monkeypatch.setattr(
|
||||
handler, 'order_extraction_layout_prerequisite_issues',
|
||||
lambda _run: {302: 'layout_pending'},
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {301})
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: True)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [ready_unit, stale_pending_unit])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
|
||||
lambda unit, *, target_status, **_k: setattr(unit, 'status', target_status),
|
||||
)
|
||||
|
||||
def _process(**_kwargs):
|
||||
events.append('processed')
|
||||
ready_unit.status = 'merging_supplement'
|
||||
return [{'po_number': 'PO-LAYOUT-CONTINUE', '_hxops_intake_id': 1}]
|
||||
|
||||
monkeypatch.setattr(handler, '_process_unit_with_retries', _process)
|
||||
monkeypatch.setattr(
|
||||
handler, 'merge_unit_orders',
|
||||
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {})
|
||||
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
|
||||
|
||||
def _fake_enqueue(_run, *, message, continue_from_running=False):
|
||||
enqueue_calls.append({'message': message, 'continue_from_running': continue_from_running})
|
||||
events.append(f'enqueue:continue={continue_from_running}')
|
||||
return 1006
|
||||
|
||||
monkeypatch.setattr(handler, '_enqueue_ready_order_extraction_job', _fake_enqueue)
|
||||
|
||||
def fake_finish(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
finished.update(kwargs)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', fake_finish)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
|
||||
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 6})
|
||||
|
||||
assert 'processed' in events
|
||||
assert 'progressed' in events
|
||||
assert 'terminalized' not in events
|
||||
assert 'persist_started' not in events
|
||||
assert enqueue_calls == [{
|
||||
'message': '附件版面已就绪,继续识别剩余附件',
|
||||
'continue_from_running': True,
|
||||
}]
|
||||
assert run.status == 'processing'
|
||||
assert run.phase == 'queued'
|
||||
assert run.current_job_id == 1006
|
||||
assert finished['result']['handoff_status'] == 'layout_ready_continue'
|
||||
assert finished['result']['waiting_continue'] is True
|
||||
assert finished['result']['waiting_layout'] is False
|
||||
assert finished['result']['continue_job_id'] == 1006
|
||||
assert stale_pending_unit.status == 'pending'
|
||||
assert events.index('finished') < events.index('enqueue:continue=True')
|
||||
|
||||
|
||||
def test_worker_layout_ready_continue_keeps_waiting_layout_when_siblings_still_pending(monkeypatch):
|
||||
"""
|
||||
收口时已有 ready work,但仍有兄弟 layout pending:自交接且 phase 保持 waiting_layout。
|
||||
|
||||
断言:handoff_status=layout_ready_continue;waiting_layout=True;不终态 Run。
|
||||
"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
finished: dict = {}
|
||||
run = SimpleNamespace(
|
||||
id=7, user_id=9, run_no='SNER-WORKER-LAYOUT-CONTINUE-PARTIAL', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
|
||||
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
|
||||
execution_result_json=None, extraction_completed_at=None,
|
||||
)
|
||||
job = SimpleNamespace(id=7, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
ready_unit = SimpleNamespace(
|
||||
id=71, document_id=401, intake_id=1, status='pending', result_json=None, position=1,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
stale_pending_unit = SimpleNamespace(
|
||||
id=72, document_id=402, intake_id=1, status='pending', result_json=None, position=2,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
plan = SimpleNamespace(id=7, unit_count=2, units=[ready_unit, stale_pending_unit])
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else ready_unit)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderProcessingRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
status=SimpleNamespace(in_=lambda *_a, **_k: True),
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: [ready_unit, stale_pending_unit]),
|
||||
),
|
||||
),
|
||||
))
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
|
||||
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(
|
||||
handler, 'order_extraction_layout_prerequisite_issues',
|
||||
lambda _run: {402: 'layout_pending'},
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {401})
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True)
|
||||
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: True)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [ready_unit, stale_pending_unit])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
|
||||
lambda unit, *, target_status, **_k: setattr(unit, 'status', target_status),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
handler, '_process_unit_with_retries',
|
||||
lambda **_kwargs: (setattr(ready_unit, 'status', 'merging_supplement') or [
|
||||
{'po_number': 'PO-PARTIAL-CONTINUE', '_hxops_intake_id': 1},
|
||||
]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
handler, 'merge_unit_orders',
|
||||
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: {})
|
||||
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: (_ for _ in ()).throw(
|
||||
AssertionError('must not terminalize'),
|
||||
))
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: None)
|
||||
monkeypatch.setattr(
|
||||
handler, '_enqueue_ready_order_extraction_job',
|
||||
lambda _run, *, message, continue_from_running=False: 1007,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
handler, 'finish_job',
|
||||
lambda *_a, **kwargs: finished.update(kwargs) or True,
|
||||
)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
|
||||
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 7})
|
||||
|
||||
assert run.status == 'processing'
|
||||
assert run.phase == 'waiting_layout'
|
||||
assert run.current_job_id == 1007
|
||||
assert finished['result']['handoff_status'] == 'layout_ready_continue'
|
||||
assert finished['result']['waiting_layout'] is True
|
||||
assert finished['result']['waiting_continue'] is True
|
||||
|
||||
|
||||
def test_enqueue_ready_order_extraction_job_continue_from_running_dedupes_queued_only(monkeypatch):
|
||||
"""
|
||||
continue_from_running=True 时 enqueue 必须只对 queued 去重,避免复用当前 running Job。
|
||||
|
||||
断言:传入 dedupe_statuses=('queued',)。
|
||||
"""
|
||||
from app.services.shipping_notice import order_extraction_run_service as svc
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
def _fake_enqueue(*_args, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return 42
|
||||
|
||||
monkeypatch.setattr('app.jobs.queue.enqueue', _fake_enqueue)
|
||||
monkeypatch.setattr(svc.db.session, 'get', lambda *_a, **_k: None)
|
||||
|
||||
run = SimpleNamespace(run_no='SNER-DEDUP', user_id=9)
|
||||
job_id = svc._enqueue_ready_order_extraction_job(
|
||||
run, message='续抽', continue_from_running=True,
|
||||
)
|
||||
|
||||
assert job_id == 42
|
||||
assert captured.get('dedupe_statuses') == ('queued',)
|
||||
assert captured.get('business_ref') == 'SNER-DEDUP'
|
||||
|
||||
|
||||
def test_order_extraction_handoff_finish_then_enqueue_same_txn(app):
|
||||
"""
|
||||
方案 A:同事务先 finish(commit=False) 再 enqueue,不得撞
|
||||
uq_jobs_shipping_order_extraction_active_ref。
|
||||
|
||||
断言:running 时直接 enqueue 失败;释放槽后同事务 INSERT 成功,旧 Job success。
|
||||
"""
|
||||
with app.app_context():
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.jobs.queue import enqueue, finish_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
run_no = 'SNER-HANDOFF-ATOMIC'
|
||||
running = Job(
|
||||
domain='shipping_notice',
|
||||
job_type=JobType.SHIPPING_ORDER_EXTRACTION.value,
|
||||
status='running',
|
||||
business_ref=run_no,
|
||||
payload_json={'run_no': run_no},
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
started_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(running)
|
||||
db.session.commit()
|
||||
running_id = int(running.id)
|
||||
|
||||
# 对照:仍 running 时直接 INSERT 必须撞唯一索引
|
||||
with pytest.raises(IntegrityError):
|
||||
enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run_no},
|
||||
domain='shipping_notice',
|
||||
business_ref=run_no,
|
||||
dedupe_statuses=('queued',),
|
||||
dedupe_active=True,
|
||||
commit=True,
|
||||
)
|
||||
db.session.rollback()
|
||||
|
||||
assert finish_job(
|
||||
running_id,
|
||||
result={'handoff_status': 'runtime_budget_continue'},
|
||||
message='handoff',
|
||||
owned_attempt=1,
|
||||
commit=False,
|
||||
) is True
|
||||
continue_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run_no},
|
||||
domain='shipping_notice',
|
||||
business_ref=run_no,
|
||||
dedupe_statuses=('queued',),
|
||||
dedupe_active=True,
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
db.session.expire_all()
|
||||
|
||||
old = db.session.get(Job, running_id)
|
||||
nxt = db.session.get(Job, int(continue_id))
|
||||
assert old is not None and old.status == 'success'
|
||||
assert nxt is not None and nxt.status == 'queued'
|
||||
assert nxt.id != running_id
|
||||
assert nxt.business_ref == run_no
|
||||
|
||||
|
||||
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
tests/test_shipping_order_field_purposes.py
|
||||
|
||||
用途:验证履约门禁只从冻结订单快照及其冻结策略读取预约单号。
|
||||
依赖:订单 Schema service、冻结快照模型、reservation_gate。
|
||||
逻辑:当前任务不得读取可变 FieldValue 或旧任务行投影;策略缺少能力时必须明确阻断。
|
||||
用途:验证履约门禁按有效视图(冻结快照 + 冻结后人工修正)读取预约单号。
|
||||
依赖:订单 Schema service、冻结快照模型、reservation_gate(内部经 effective_order_view 叠加修正)。
|
||||
逻辑:冻结后人工修正的预约单必须进入门禁判定(修正值生效);策略缺少能力时仍明确阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -87,15 +87,29 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool =
|
||||
return task
|
||||
|
||||
|
||||
def test_task_reservation_gate_uses_frozen_value_not_mutable_projection_or_field_value(app):
|
||||
"""门禁以冻结预约单为准,后续 FieldValue 变化均不得重解释履约。"""
|
||||
def test_task_reservation_gate_reads_effective_amendment_over_frozen_value(app):
|
||||
"""有效视图契约:冻结后人工修正的预约单必须进入门禁判定(修正值生效)。"""
|
||||
with app.app_context():
|
||||
task = _task_with_reservation('3000000001')
|
||||
# 模拟编辑窗的人工修正:当前 accepted Extraction 的 FieldValue 即修正事实,
|
||||
# 经 effective_order_view 对位叠加后必须被门禁消费(区别于旧冻结-only 契约)。
|
||||
value = ShippingOrderFieldValue.query.filter_by(extraction_id=task.current_order_extraction_id).one()
|
||||
value.value_text = '3000000002'
|
||||
value.value_json = '3000000002'
|
||||
db.session.commit()
|
||||
assert task_reservation_gate_issues(task) == []
|
||||
|
||||
|
||||
def test_task_reservation_gate_rejects_invalid_effective_amendment(app):
|
||||
"""有效视图契约:非法修正值同样进入门禁判定并被拦截(不再静默回退冻结值)。"""
|
||||
with app.app_context():
|
||||
task = _task_with_reservation('3000000001')
|
||||
value = ShippingOrderFieldValue.query.filter_by(extraction_id=task.current_order_extraction_id).one()
|
||||
value.value_text = 'INVALID'
|
||||
value.value_json = 'INVALID'
|
||||
db.session.commit()
|
||||
assert task_reservation_gate_issues(task) == []
|
||||
issues = task_reservation_gate_issues(task)
|
||||
assert issues != []
|
||||
|
||||
|
||||
def test_task_reservation_gate_blocks_snapshot_without_reservation_capability(app):
|
||||
|
||||
@@ -5,6 +5,7 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_extract_matching_signature,
|
||||
_observe_layout_features,
|
||||
_resolve_coordinate_transform,
|
||||
_signature_identity_header_tokens,
|
||||
match_frozen_coordinate_profiles,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile_signature import (
|
||||
@@ -1386,3 +1387,125 @@ def test_observe_layout_features_applies_business_row_clip():
|
||||
assert bbox is not None
|
||||
assert bbox[3] < 0.62
|
||||
assert bbox[3] > 0.50
|
||||
|
||||
|
||||
# --- PO_6075316 路由级合成回归:别名契约经二次机会门禁清空两道表头硬门禁 ---
|
||||
|
||||
# 训练签名(命中模板 HYVE)的明细表 header_tokens 形状。
|
||||
_PO6075316_TRAINING_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Arrival Date', 'Unit Price', 'Extension',
|
||||
]
|
||||
# 故障 PDF(PO_6075316)观测形状:日期词变更 + 相邻列并格 + 一个 MinerU 空串占位。
|
||||
_PO6075316_FAULT_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Ship Date Unit Price', '', 'Extension',
|
||||
]
|
||||
# Schema v4 相关别名(归一化 key → field_code),含治理后的 Requested Ship Date。
|
||||
_PO6075316_HEADER_TO_FIELD = {
|
||||
'Requested Receipt Date': 'requested_receipt_date',
|
||||
'Requested Arrival Date': 'requested_receipt_date',
|
||||
'Requested Ship Date': 'requested_receipt_date',
|
||||
'Unit Price': 'unit_price',
|
||||
'Extension': 'line_amount_with_tax',
|
||||
'Part Number': 'customer_part_number',
|
||||
'Vendor Item': 'part_number',
|
||||
'Quantity': 'qty',
|
||||
'LN': 'customer_po_line_no',
|
||||
}
|
||||
|
||||
|
||||
def _column_header_glyphs(tokens: list[str], *, x_start: float = 40.0, y0: float = 76.0, y1: float = 88.0, column_gap: float = 12.0) -> list[dict]:
|
||||
"""按列生成表头字符证据。
|
||||
|
||||
列内空格不额外步进(合并格文案保持为单一 span,空格由 boundary 恢复);
|
||||
列间留大间隔强制 positioned_token_spans 切分;空串列不产出字符。
|
||||
"""
|
||||
glyphs: list[dict] = []
|
||||
cursor = x_start
|
||||
for token in tokens:
|
||||
first_of_column = True
|
||||
for index, char in enumerate(token):
|
||||
if char == ' ':
|
||||
continue
|
||||
glyphs.append({
|
||||
'text': char,
|
||||
'bbox': {'x0': cursor, 'y0': y0, 'x1': cursor + 3, 'y1': y1},
|
||||
'boundary_before': 'none' if first_of_column else ('space' if index and token[index - 1] == ' ' else 'none'),
|
||||
})
|
||||
first_of_column = False
|
||||
cursor += 4.0
|
||||
cursor += column_gap
|
||||
return glyphs
|
||||
|
||||
|
||||
def _layout_with_column_header(tokens: list[str], *, page_width: float = 640) -> dict:
|
||||
"""以指定列 token 形状构造坐标 layout(沿用 _layout 骨架,整体替换表头字符)。"""
|
||||
layout = _layout()
|
||||
layout['coordinate_evidence']['pages']['1']['width'] = page_width
|
||||
header = _column_header_glyphs(tokens)
|
||||
layout['coordinate_evidence']['tables']['table-1'] = header
|
||||
layout['coordinate_evidence']['page_glyphs']['1'] = [
|
||||
*layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')],
|
||||
*header,
|
||||
]
|
||||
return layout
|
||||
|
||||
|
||||
def test_header_alias_contract_clears_all_po6075316_header_hard_gates():
|
||||
"""路由重放 PO_6075316:含 Ship Date 别名的契约清空 discriminator 与
|
||||
signature_conflict 两道表头硬门禁(二次机会:canonical 序列复评达标)。"""
|
||||
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
|
||||
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
|
||||
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
|
||||
|
||||
# 构造守卫:冻结签名 token 必须与训练形状逐字一致,防止证据管线漂移使断言空转。
|
||||
signature_body, _ = _extract_matching_signature(profile)
|
||||
assert _signature_identity_header_tokens(signature_body) == _PO6075316_TRAINING_TOKENS
|
||||
|
||||
with_contract = match_frozen_coordinate_profiles(
|
||||
profiles=[profile], layout=fault,
|
||||
header_to_field=_PO6075316_HEADER_TO_FIELD,
|
||||
)
|
||||
without_contract = match_frozen_coordinate_profiles(profiles=[profile], layout=fault)
|
||||
|
||||
contract_candidate = with_contract.candidates[0]
|
||||
plain_candidate = without_contract.candidates[0]
|
||||
# 关键断言:别名契约下第一道 discriminator 互斥被 canonical 原子全等豁免。
|
||||
assert 'profile_header_discriminator_conflict' not in contract_candidate.reason_codes
|
||||
# 关键断言:第二道 signature_conflict 门禁被二次机会清空——原始分被词级互斥
|
||||
# 压成 0 后,canonical 序列复用同一打分逻辑重估,effective >= 0.35 不再硬拒。
|
||||
assert 'profile_header_signature_conflict' not in contract_candidate.reason_codes
|
||||
# 关键断言:两道表头硬门禁全清后候选成为硬匹配(表头类原因码不为拦路面)。
|
||||
assert contract_candidate.hard_match is True
|
||||
# 关键断言:不传契约时同形状仍被词级原子互斥拒绝——互斥机制本身未被别名破坏。
|
||||
assert 'profile_header_discriminator_conflict' in plain_candidate.reason_codes
|
||||
|
||||
|
||||
def test_header_alias_contract_without_ship_date_alias_keeps_hard_rejection():
|
||||
"""反向用例:契约缺 Ship Date 别名时二次机会不生效,候选仍被表头硬门禁拒绝。
|
||||
|
||||
证明二次机会来自别名本身而非门禁放水。缺 Ship Date 别名时两侧 canonical
|
||||
原子不再全等,先触发 discriminator 分支——if/elif 结构下 signature_conflict
|
||||
分支被前置分支吸收(不得并列上报同根因),故拦路码为 discriminator;
|
||||
断言落点是「仍被硬拒」:hard_match False 且综合分归零。
|
||||
"""
|
||||
training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS)
|
||||
fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS)
|
||||
profile = _profile_without_required_anchors('PO_HYVE_6075316', training)
|
||||
contract_without_ship_alias = {
|
||||
key: value
|
||||
for key, value in _PO6075316_HEADER_TO_FIELD.items()
|
||||
if key != 'Requested Ship Date'
|
||||
}
|
||||
|
||||
partial = match_frozen_coordinate_profiles(
|
||||
profiles=[profile], layout=fault,
|
||||
header_to_field=contract_without_ship_alias,
|
||||
)
|
||||
candidate = partial.candidates[0]
|
||||
# 关键断言:缺 Ship Date 别名 → 跨措辞(ship vs arrival)无法归一 → 硬互斥仍在。
|
||||
assert 'profile_header_discriminator_conflict' in candidate.reason_codes
|
||||
# 关键断言:候选仍被硬拒(综合分归零、非硬匹配)——别名缺失绝不放行。
|
||||
assert candidate.hard_match is False
|
||||
assert candidate.score == 0.0
|
||||
@@ -372,7 +372,7 @@ def test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step(ap
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -451,7 +451,9 @@ def test_confirmed_review_case_serializes_editability_from_formal_order_task(app
|
||||
payload = serialize_review_case(case)
|
||||
|
||||
assert payload['has_formal_ot'] is True
|
||||
assert payload['formal_editable_field_ids'] == []
|
||||
# 新契约(状态制):冻结 Schema 未配置 task_edit_policy 的 qty-id 默认可编辑;
|
||||
# 正式 OT 无 ready Artifact(Excel 未就绪)不冻结,投影按状态制从 OT 判定可编辑字段。
|
||||
assert payload['formal_editable_field_ids'] == ['qty-id']
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
add_line,
|
||||
build_confirmable_draft_summary,
|
||||
@@ -2962,3 +2964,254 @@ def test_run_lineage_root_walk_loads_parent_runs_without_frozen_snapshot_columns
|
||||
for statement in point_loads:
|
||||
assert 'input_snapshot_json' not in statement
|
||||
assert 'result_json' not in statement
|
||||
|
||||
|
||||
def test_review_queue_flags_blocked_gate_cases_as_needs_attention(app):
|
||||
"""门禁 blocked_manual(如库存缺口)的已建任务单,队列必须下发 needs_attention=True。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NEEDS-ATTN')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-needs-attn',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-ATTN',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-REVIEW-QUEUE-NEEDS-ATTN',
|
||||
task_id=task.id,
|
||||
review_case_id=case.id,
|
||||
status='active',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id,
|
||||
gate_code='inventory_sufficiency',
|
||||
sequence_no=16,
|
||||
status='blocked_manual',
|
||||
))
|
||||
task.active_process_execution_id = execution.id
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
queue = serialize_review_queue([run])
|
||||
|
||||
# 关键断言:库存缺口类门禁阻塞必须在队列可见,不再只依赖当前单的完整详情。
|
||||
assert queue['items'][0]['needs_attention'] is True
|
||||
assert queue['items'][0]['lifecycle_stage'] == 'fulfillment_prep'
|
||||
# 关键断言:needs_attention 抬升 summary needs_action 桶,不得被计成完成/在办。
|
||||
assert queue['summary'] == {'total': 1, 'needs_action': 1, 'processing': 0, 'completed': 0}
|
||||
|
||||
|
||||
def test_review_queue_waiting_external_gate_is_not_needs_attention(app):
|
||||
"""RPA 外部等待(waiting_external)属于系统在办,不得标记 needs_attention。"""
|
||||
from app.models import ShippingProcessExecution, ShippingProcessGate
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-WAIT-EXT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-WAIT-EXT',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-wait-ext',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-WAIT',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-WAIT-EXT',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='freight_uploading',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-REVIEW-QUEUE-WAIT-EXT',
|
||||
task_id=task.id,
|
||||
review_case_id=case.id,
|
||||
status='waiting_external',
|
||||
current_gate_code='freight_upload_rpa',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=execution.id,
|
||||
gate_code='freight_upload_rpa',
|
||||
sequence_no=18,
|
||||
status='waiting_external',
|
||||
))
|
||||
task.active_process_execution_id = execution.id
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
# 关键断言:外部等待是在办不是待办,图标应走进行中而非需人工。
|
||||
assert item['needs_attention'] is False
|
||||
|
||||
|
||||
def test_review_queue_without_execution_is_not_needs_attention(app):
|
||||
"""已建任务但尚无 Execution(或缓存未命中)时,needs_attention 必须为 False。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NO-EXEC')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-NO-EXEC',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-no-exec',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-NOEXEC',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-NO-EXEC',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
# 关键断言:无门禁事实时不臆造需人工标志。
|
||||
assert item['needs_attention'] is False
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_terminal_stage_as_completed(app):
|
||||
"""OT.stage=completed(通知完成)的已建任务单计入 completed,不再计入 processing。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-DONE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-DONE',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-done',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMDONE',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-SUM-DONE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='completed',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:summary 与五态图标同口径——confirmed+终态=completed 而非 processing。
|
||||
assert summary['total'] == 1
|
||||
assert summary['completed'] == 1
|
||||
assert summary['processing'] == 0
|
||||
assert summary['needs_action'] == 0
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_quality_issue_as_needs_action(app):
|
||||
"""quality_issue(文件质量异常)从 completed 改归 needs_action,与黄⚠图标一致。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-QI')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-QI',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-qi',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMQI',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
case.status = 'quality_issue'
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:质量异常是待办不是完成。
|
||||
assert summary['needs_action'] == 1
|
||||
assert summary['completed'] == 0
|
||||
assert summary['processing'] == 0
|
||||
|
||||
|
||||
def test_review_queue_summary_counts_plain_confirmed_as_processing(app):
|
||||
"""已建任务、无阻塞、非终态的 confirmed 单计入 processing(对应转圈图标)。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-PROC')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-SUM-PROC',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-sum-proc',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-SUMPROC',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-REVIEW-QUEUE-SUM-PROC',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
status='processing',
|
||||
stage='inventory_preparation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = task.id
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_review_queue([run])['summary']
|
||||
|
||||
# 关键断言:已创建任务是在办不是完成。
|
||||
assert summary['processing'] == 1
|
||||
assert summary['completed'] == 0
|
||||
assert summary['needs_action'] == 0
|
||||
@@ -94,10 +94,10 @@ def test_override_pins_line_and_rematches_only_that_line(monkeypatch, app):
|
||||
assert pinned['audit']['action'] == 'override_line_inventory_source'
|
||||
assert pinned['audit']['after']['selected_source_code'] == 'SRC_X'
|
||||
assert retrigger_calls and retrigger_calls[0] == task.task_no
|
||||
# [回归] 库存源覆写后必须把 inventory_preparation 作为定向人工恢复重新推进(retry_rpa),
|
||||
# 否则 AutoProgress 读残留的 poll_inventory_preparation 只轮询、不触发 RPA。
|
||||
# [回归] 改源后必须定向回 inventory_preparation;mode=auto 按指定源复用快照(无文件才 RPA)。
|
||||
assert retrigger_kwargs and retrigger_kwargs[0].get('resume_gate_code') == 'inventory_preparation'
|
||||
assert retrigger_kwargs and retrigger_kwargs[0].get('inventory_mode') == 'retry_rpa'
|
||||
assert retrigger_kwargs and retrigger_kwargs[0].get('inventory_mode') == 'auto'
|
||||
assert retrigger_kwargs and retrigger_kwargs[0].get('trigger') == 'manual_override_source'
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human'}
|
||||
|
||||
|
||||
|
||||
@@ -151,3 +151,53 @@ def test_sync_manual_open_via_claim_and_run(app, monkeypatch):
|
||||
assert result.get('skipped') is False
|
||||
db.session.refresh(attempt)
|
||||
assert attempt.status in {'succeeded', 'failed'}
|
||||
|
||||
|
||||
def test_lock_execution_gate_attempt_parent_before_child(app):
|
||||
"""[断言] 助手按 Execution→Gate→Attempt 返回隶属一致的三元组;mark/complete 同步改 Gate。"""
|
||||
from app.models import ShippingProcessGate
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
_lock_execution_gate_attempt,
|
||||
complete_gate_attempt,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='lockord1')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
actor_type='system',
|
||||
actor_id='lock-order-test',
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='w1',
|
||||
idempotency_key='lock-order-1',
|
||||
)
|
||||
locked = _lock_execution_gate_attempt(int(attempt.id))
|
||||
assert locked is not None
|
||||
locked_execution, locked_gate, locked_attempt = locked
|
||||
assert int(locked_execution.id) == int(execution.id)
|
||||
assert int(locked_gate.execution_id) == int(locked_execution.id)
|
||||
assert int(locked_attempt.gate_id) == int(locked_gate.id)
|
||||
|
||||
mark_attempt_running(
|
||||
attempt_id=int(attempt.id),
|
||||
worker_id='worker-lock',
|
||||
lease_token='token-lock',
|
||||
lease_expires_at=datetime.utcnow() + timedelta(seconds=60),
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(id=int(attempt.gate_id)).one()
|
||||
assert gate.status == 'running'
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
outcome='passed',
|
||||
output_snapshot={'ok': True},
|
||||
)
|
||||
db.session.refresh(gate)
|
||||
db.session.refresh(attempt)
|
||||
assert gate.status == 'passed'
|
||||
assert attempt.status == 'succeeded'
|
||||
@@ -266,6 +266,60 @@ def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeyp
|
||||
assert queued[0]['gate_code'] == 'inventory_preparation'
|
||||
|
||||
|
||||
def test_auto_progress_seeds_pending_inventory_preparation_after_routing_pass(
|
||||
gate_execution, monkeypatch,
|
||||
):
|
||||
"""人工指定源使 routing passed 后,必须补种并入队 pending 的库存准备。
|
||||
|
||||
[回归] pending 门禁 next_action_code 为空时旧逻辑静默 return,工作台永久显示
|
||||
「库存文件未准备」;手动选源即定论,应按冻结源执行准备,不得再停在路由。
|
||||
"""
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
for prior_gate in ShippingProcessGate.query.filter(
|
||||
ShippingProcessGate.execution_id == int(gate_execution.id),
|
||||
ShippingProcessGate.sequence_no < 13,
|
||||
).all():
|
||||
prior_gate.status = 'passed'
|
||||
prior_gate.next_action_code = None
|
||||
|
||||
prep = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
prep.status = 'pending'
|
||||
prep.next_action_code = None
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
assert gate_execution.current_gate_code == 'inventory_preparation'
|
||||
assert prep.next_action_code is None
|
||||
|
||||
queued: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(
|
||||
process_gate_service,
|
||||
'queue_gate_attempt',
|
||||
lambda **kwargs: (queued.append(kwargs), SimpleNamespace(id=91))[1],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
routing = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='inventory_source_routing',
|
||||
).one()
|
||||
process_gate_service._enqueue_auto_progress_after_gate_pass(
|
||||
execution=gate_execution,
|
||||
gate=routing,
|
||||
)
|
||||
|
||||
assert prep.next_action_code == 'retry_inventory_preparation'
|
||||
assert gate_execution.primary_next_action_code == 'retry_inventory_preparation'
|
||||
assert len(queued) == 1
|
||||
assert queued[0]['gate_code'] == 'inventory_preparation'
|
||||
assert queued[0]['input_snapshot']['action_code'] == 'retry_inventory_preparation'
|
||||
assert queued[0]['input_snapshot']['payload']['trigger'] == 'gate_attempt_passed'
|
||||
|
||||
|
||||
def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch):
|
||||
"""已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。"""
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
@@ -334,6 +388,77 @@ def test_auto_progress_does_not_queue_manual_inventory_navigation(gate_execution
|
||||
assert queued == []
|
||||
|
||||
|
||||
def test_refresh_pointers_skips_stale_invalidated_when_downstream_blocked(gate_execution):
|
||||
"""已建单成功后又被标 invalidated 的上游,不得盖住下游真实 blocked_manual。
|
||||
|
||||
复现:task_creation 已 passed_at + invalidated,inventory_sufficiency=blocked_manual;
|
||||
刷新指针必须停在库存充足性,而不是「生成订单草稿」。
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all():
|
||||
if gate.gate_code == 'task_creation':
|
||||
gate.status = 'invalidated'
|
||||
gate.passed_at = now
|
||||
gate.invalidated_at = now
|
||||
gate.blocking_reason_code = 'gate_invalidated'
|
||||
gate.next_action_code = 'retry_task_creation'
|
||||
elif gate.gate_code in {
|
||||
'document_materialization', 'layout_parsing', 'document_profile_routing',
|
||||
'order_field_extraction', 'field_completeness', 'reservation_validation',
|
||||
'customer_resolution', 'duplicate_detection', 'field_conflict_resolution',
|
||||
'order_freeze_readiness', 'inventory_source_routing', 'inventory_preparation',
|
||||
'inventory_field_mapping', 'inventory_matching',
|
||||
}:
|
||||
gate.status = 'passed'
|
||||
gate.passed_at = now
|
||||
elif gate.gate_code == 'inventory_sufficiency':
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'inventory_shortage_review_required'
|
||||
gate.next_action_code = 'open_shortage_review'
|
||||
elif gate.gate_code == 'excel_readiness':
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'excel_not_ready'
|
||||
# 其余保持 pending
|
||||
db.session.flush()
|
||||
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
assert gate_execution.current_gate_code == 'inventory_sufficiency'
|
||||
assert gate_execution.primary_next_action_code == 'open_shortage_review'
|
||||
assert gate_execution.status == 'blocked'
|
||||
|
||||
|
||||
def test_refresh_pointers_keeps_invalidated_when_downstream_still_passed(gate_execution):
|
||||
"""故意失效且下游仍为 passed 时,current 必须停在 invalidated,等待重评。"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all():
|
||||
if gate.gate_code == 'task_creation':
|
||||
gate.status = 'invalidated'
|
||||
gate.passed_at = now
|
||||
gate.invalidated_at = now
|
||||
gate.blocking_reason_code = 'gate_invalidated'
|
||||
gate.next_action_code = 'retry_task_creation'
|
||||
else:
|
||||
gate.status = 'passed'
|
||||
gate.passed_at = now
|
||||
db.session.flush()
|
||||
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
assert gate_execution.current_gate_code == 'task_creation'
|
||||
assert gate_execution.status == 'blocked'
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -393,22 +518,8 @@ def test_upstream_invalidation_only_targets_dependents(gate_execution):
|
||||
|
||||
"""库存源变化只失效依赖下游,不碰无关前置门禁。"""
|
||||
|
||||
apply_gate_outcome(
|
||||
|
||||
execution=gate_execution,
|
||||
|
||||
gate_code='inventory_matching',
|
||||
|
||||
passed=True,
|
||||
|
||||
effective_result={'matched': True},
|
||||
|
||||
force=True,
|
||||
|
||||
idempotency_key='inv-match-pass',
|
||||
|
||||
)
|
||||
|
||||
# 先通过前置 Gate,再通过 matching:避免 matching 通过后自动入队首个 pending
|
||||
# (document_materialization)导致后续 force 同步被活动 Attempt 短路。
|
||||
apply_gate_outcome(
|
||||
|
||||
execution=gate_execution,
|
||||
@@ -425,6 +536,22 @@ def test_upstream_invalidation_only_targets_dependents(gate_execution):
|
||||
|
||||
)
|
||||
|
||||
apply_gate_outcome(
|
||||
|
||||
execution=gate_execution,
|
||||
|
||||
gate_code='inventory_matching',
|
||||
|
||||
passed=True,
|
||||
|
||||
effective_result={'matched': True},
|
||||
|
||||
force=True,
|
||||
|
||||
idempotency_key='inv-match-pass',
|
||||
|
||||
)
|
||||
|
||||
invalidated = invalidate_downstream_gates(
|
||||
|
||||
execution=gate_execution,
|
||||
|
||||
@@ -649,11 +649,12 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-RPA-LATE-SUCCESS', user_id=1, source_type='direct_pdf',
|
||||
@@ -661,11 +662,11 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
# 迟到成功回调已把库存行落库:绑定一份有效且已解析的库存快照。
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no='INV-RPA-LATE-SUCCESS', storage_path='test/inv.xlsx',
|
||||
source_file_name='inv.xlsx', snapshot_status='ready', line_count=1,
|
||||
inventory_lines_json=[{'part_number': 'PN-1', 'warehouse_id': 'WH-1'}],
|
||||
mapping_confirmed=True,
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
@@ -673,11 +674,22 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
task_id=task.id, inventory_file_id=inv_file.id, is_active=True,
|
||||
))
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
db.session.add(execution)
|
||||
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
|
||||
for attempt in ShippingProcessGateAttempt.query.join(ShippingProcessGate).filter(
|
||||
ShippingProcessGate.execution_id == int(execution.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
).all():
|
||||
attempt.status = 'superseded'
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all():
|
||||
if gate.gate_code == 'inventory_preparation':
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.blocking_reason_code = 'inventory_rpa_exhausted'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
elif gate.gate_code in {'inventory_field_mapping', 'inventory_matching'}:
|
||||
gate.status = 'pending'
|
||||
gate.next_action_code = None
|
||||
elif int(gate.sequence_no) < 13:
|
||||
gate.status = 'passed'
|
||||
db.session.flush()
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
@@ -688,11 +700,13 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='inventory_matching',
|
||||
).one()
|
||||
assert preparation.status == 'passed'
|
||||
assert preparation.blocking_reason_code is None
|
||||
# 断言自动推进确实进入后续匹配,而不是伪造“整条链路成功”。
|
||||
assert matching.status == 'blocked_retryable'
|
||||
assert matching.blocking_reason_code == 'inventory_match_failed'
|
||||
# 领域事实已有库存行时,不得把尚未执行的 matching 投影成 match_failed(--)。
|
||||
assert matching.status != 'blocked_retryable'
|
||||
assert matching.blocking_reason_code != 'inventory_match_failed'
|
||||
assert matching.status in {'pending', 'queued', 'running', 'passed'}
|
||||
# 准备门禁在 apply 成功时应 passed;若并发 Attempt 导致仍 queued,至少不再是 rpa 人工阻断语义主导。
|
||||
if preparation.status == 'passed':
|
||||
assert preparation.blocking_reason_code is None
|
||||
|
||||
|
||||
def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
|
||||
|
||||
@@ -230,18 +230,18 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
# 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。
|
||||
uploaded = SimpleNamespace(
|
||||
id=None,
|
||||
current_step='step7_upload', upload_status='uploaded', export_file_path=None,
|
||||
current_step='freight_uploading', upload_status='uploaded', export_file_path=None,
|
||||
)
|
||||
# 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
current_step='step7_upload', upload_status='pending', export_file_path='/x.xlsx',
|
||||
current_step='freight_uploading', upload_status='pending', export_file_path='/x.xlsx',
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
|
||||
|
||||
matching = SimpleNamespace(
|
||||
current_step='step5_match', upload_status='', match_status='matching', export_file_path=None,
|
||||
current_step='inventory_matching', upload_status='', match_status='matching', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ backend/tests/test_shipping_processing_projection_stage4.py
|
||||
用途:验收多 EML / 直接 PDF 阶段 4 — 统一 ShippingProcessingProjection 适配器。
|
||||
依赖:pytest、app fixture、User/FileAsset/upload mock、ShippingOrderIntake、projection helpers。
|
||||
逻辑:断言 status/stage 映射(direct_pdf 永不 email_adjudicating);
|
||||
project_intake_work_item 填充 current_gate / 失败恢复摘要;会话投影含 work_items。
|
||||
project_intake_work_item 填充 current_gate / 失败恢复摘要;会话投影含 work_items;
|
||||
摘要开放 Case + queued STP 不得误判 waiting_human。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -539,7 +540,7 @@ def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None
|
||||
owner_agent_id=int(agent.id),
|
||||
candidate_id=None,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -586,6 +587,60 @@ def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None
|
||||
assert str(primary.get('code') or '') != 'open_order_review'
|
||||
|
||||
|
||||
def test_order_creating_ot_not_pulled_back_to_order_review_by_stale_open_order_review(app) -> None:
|
||||
"""
|
||||
OT.stage 已 order_creating 时,不得因 status=waiting_review 合成 open_order_review
|
||||
把批次五阶段拉回「订单复核」。
|
||||
|
||||
断言意图:工作台按 OT.stage→通知准备;批次须同源,禁止再显示订单复核。
|
||||
"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
get_shipping_processing_work_item,
|
||||
)
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='OT-STAGE-NO-REWIND')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-STAGE-NO-REWIND',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
owner_agent_id=int(agent.id),
|
||||
candidate_id=None,
|
||||
status='waiting_review',
|
||||
stage='order_creating',
|
||||
progress_version=2,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-OT-STAGE-NO-REWIND',
|
||||
task_id=int(task.id),
|
||||
status='blocked',
|
||||
current_gate_code='order_freeze_readiness',
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
run.user_task_no = task.task_no
|
||||
db.session.commit()
|
||||
|
||||
item = get_shipping_processing_work_item(
|
||||
user_id=user.id,
|
||||
work_item_type='order_task',
|
||||
work_item_no=task.task_no,
|
||||
)
|
||||
|
||||
# 阶段文案治本:不得被 BE-04 / status 启发式拉回 order_review。
|
||||
assert item['stage'] == 'order_creating'
|
||||
assert item['ui_state']['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert item['ui_state']['lifecycle_stage'] != 'order_review'
|
||||
|
||||
|
||||
def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(app) -> None:
|
||||
"""历史 OT 不能借同 Run 的当前 Candidate 显示另一 PDF 的订单生命周期。"""
|
||||
with app.app_context():
|
||||
@@ -765,6 +820,67 @@ def test_batch_stage_summary_uses_the_same_user_group_as_file_counts() -> None:
|
||||
assert fulfillment['summary']['processing'] == 0
|
||||
|
||||
|
||||
def test_batch_waiting_human_has_zero_processing_on_card_and_stage() -> None:
|
||||
"""顶卡 processing_files 与阶段 processing 必须同时为 0。"""
|
||||
work_items = [{
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': 'OT-WAIT-CARD',
|
||||
'user_group': 'waiting_human',
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'waiting_review',
|
||||
'source_summary': {'document_id': 601, 'filename': 'review.pdf'},
|
||||
}]
|
||||
counts = _batch_file_counts(work_items)
|
||||
assert counts['processing_files'] == 0
|
||||
assert counts['waiting_human_files'] == 1
|
||||
order_review = next(
|
||||
node for node in _batch_lifecycle_nodes(work_items)
|
||||
if node['code'] == 'order_review'
|
||||
)
|
||||
assert order_review['summary']['processing'] == 0
|
||||
assert order_review['summary']['needs_action'] == 1
|
||||
assert _batch_ui_state_from_items(work_items)['status'] == 'waiting_human'
|
||||
|
||||
|
||||
def test_batch_ui_state_does_not_show_completed_when_human_wait_exists() -> None:
|
||||
"""需处理文件存在时批次主状态不得为 completed。"""
|
||||
work_items = [
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-DONE-FILE',
|
||||
'user_group': 'completed', 'user_status': 'completed',
|
||||
'user_stage': 'upload_complete',
|
||||
'source_summary': {'document_id': 602, 'filename': 'done.pdf'},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-WAIT-FILE',
|
||||
'user_group': 'waiting_human', 'user_status': 'running',
|
||||
'user_stage': 'waiting_review',
|
||||
'source_summary': {'document_id': 603, 'filename': 'wait.pdf'},
|
||||
},
|
||||
]
|
||||
assert _batch_ui_state_from_items(work_items)['status'] == 'waiting_human'
|
||||
assert _batch_file_counts(work_items)['processing_files'] == 0
|
||||
|
||||
|
||||
def test_unclassified_file_does_not_inflate_stage_processing() -> None:
|
||||
"""未分类文件不得把五阶段写成「N 份处理中」。"""
|
||||
work_items = [{
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': 'OT-UNCLASSIFIED',
|
||||
'user_group': 'unclassified',
|
||||
'user_status': 'unknown',
|
||||
'user_stage': 'freight_uploading',
|
||||
'source_summary': {'document_id': 604, 'filename': 'odd.pdf'},
|
||||
}]
|
||||
assert _batch_file_counts(work_items)['processing_files'] == 0
|
||||
freight = next(
|
||||
node for node in _batch_lifecycle_nodes(work_items)
|
||||
if node['code'] == 'freight_upload'
|
||||
)
|
||||
assert freight['summary']['processing'] == 0
|
||||
assert freight['summary']['total'] == 0
|
||||
|
||||
|
||||
def test_conversation_status_groups_use_the_same_current_file_representative() -> None:
|
||||
"""文件清单不能保留旧失败项,否则会与互斥统计和当前 CTA 相互矛盾。"""
|
||||
projection = _conversation_processing_from_work_items([
|
||||
@@ -1544,7 +1660,7 @@ def test_summary_loads_process_execution_by_order_task_id_not_candidate_id(app)
|
||||
intake_id=intake.id,
|
||||
candidate_id=candidate.id,
|
||||
status='waiting_review',
|
||||
stage='step3_inventory_prepare',
|
||||
stage='inventory_fetching',
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
@@ -1760,6 +1876,219 @@ def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> No
|
||||
assert summary_leaf['intake_parse_authorized'] is False
|
||||
|
||||
|
||||
def test_summary_leaf_surfaces_primary_validation_issue_for_open_case(app) -> None:
|
||||
"""摘要叶子对建单前 Case 必须透传首要资格 issue,而非 review_case_{status} 状态码。
|
||||
|
||||
回归:批次进度中心对"客户尚未确认"等具体阻断只显示「订单草稿待处理」状态文案,
|
||||
原因是叶子摘要用 Case 状态拼 blocking_reason.code;资格评估已把冻结
|
||||
explainability(code/message/next_action)持久化进 draft.validation_result_json,
|
||||
摘要路径应透传该裁决(drafts_by_id 已批量加载,零额外查询)。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-LEAF-ISSUE-REASON',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUMMARY-ISSUE-REASON', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='summary-issue-reason',
|
||||
order_extraction_run_id=run.id, is_current_version=True,
|
||||
candidate_status='accepted', po_number='PO-SUMMARY-ISSUE-REASON',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
review_case = ensure_run_review_cases(run=run)[0]
|
||||
review_case.status = 'draft'
|
||||
draft = review_case.current_draft
|
||||
assert draft is not None
|
||||
# 模拟资格评估落库的首要阻断 issue(与 order_build_eligibility 持久化结构一致)
|
||||
draft.validation_result_json = {
|
||||
'can_build': False,
|
||||
'can_auto_create': False,
|
||||
'issues': [{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
'message': '客户尚未确认',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
}],
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
summary_leaf = next(
|
||||
child
|
||||
for rows in payload['conversation_processing']['status_groups'].values()
|
||||
for row in rows
|
||||
for child in row.get('aggregate_children', [])
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
|
||||
reason = summary_leaf['ui_state']['blocking_reason']
|
||||
# 关键断言:透传契约三元组;不得再是 review_case_draft 状态码
|
||||
assert reason['code'] == 'customer_unresolved'
|
||||
assert reason['message'] == '客户尚未确认'
|
||||
assert reason['next_action'] == 'confirm_customer'
|
||||
|
||||
|
||||
def test_summary_leaf_open_case_with_queued_stp_is_running_not_waiting_human(app) -> None:
|
||||
"""开放 Case 若已有 queued STP Job,摘要必须进系统处理中,不得误报待人工。
|
||||
|
||||
回归:批次进度中心曾见 open Case 即 waiting_human,忽略 jobs 表中
|
||||
shipping_stp_auto_create 排队态;工作台已按 Job 投影为 running。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app.models import Job
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
build_stp_idempotency_key,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-STP-QUEUED',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUMMARY-STP-QUEUED',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='summary-stp-queued',
|
||||
order_extraction_run_id=run.id,
|
||||
is_current_version=True,
|
||||
candidate_status='accepted',
|
||||
po_number='PO-SUMMARY-STP-QUEUED',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
review_case = ensure_run_review_cases(run=run)[0]
|
||||
review_case.status = 'draft'
|
||||
draft = review_case.current_draft
|
||||
assert draft is not None
|
||||
assert review_case.confirmed_task_id is None
|
||||
business_ref = build_stp_idempotency_key(
|
||||
run_no=str(run.run_no),
|
||||
document_id=int(document.id),
|
||||
draft_version=int(draft.draft_version),
|
||||
)
|
||||
db.session.add(Job(
|
||||
domain='shipping_notice',
|
||||
job_type=JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||||
status='queued',
|
||||
business_ref=business_ref,
|
||||
payload_json={
|
||||
'case_no': review_case.case_no,
|
||||
'run_no': run.run_no,
|
||||
'document_id': int(document.id),
|
||||
'draft_version': int(draft.draft_version),
|
||||
},
|
||||
attempts=0,
|
||||
max_attempts=3,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
groups = payload['conversation_processing']['status_groups']
|
||||
# 关键断言:queued STP 时叶子必须在 processing,不得进 waiting_human。
|
||||
waiting_ids = {
|
||||
child['source_summary']['document_id']
|
||||
for row in groups.get('waiting_human') or []
|
||||
for child in row.get('aggregate_children') or []
|
||||
}
|
||||
processing_leaf = next(
|
||||
child
|
||||
for row in groups.get('processing') or []
|
||||
for child in row.get('aggregate_children') or []
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
assert document.id not in waiting_ids
|
||||
assert processing_leaf['user_status'] == 'running'
|
||||
assert processing_leaf['user_group'] == 'processing'
|
||||
assert processing_leaf['case_no'] == review_case.case_no
|
||||
assert processing_leaf.get('blocking_reason') is None
|
||||
assert (processing_leaf.get('ui_state') or {}).get('status') == 'running'
|
||||
assert 'edit_draft' not in (processing_leaf.get('available_actions') or [])
|
||||
assert processing_leaf.get('primary_action') is None
|
||||
|
||||
|
||||
def test_summary_leaf_waiting_to_start_without_job_is_running_and_hides_edit(app) -> None:
|
||||
"""can_auto_create 且无活跃 STP Job 时,摘要须为 running,且不得暴露 edit_draft。"""
|
||||
with app.app_context():
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-STP-WAITING',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUMMARY-STP-WAITING',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='summary-stp-waiting',
|
||||
order_extraction_run_id=run.id,
|
||||
is_current_version=True,
|
||||
candidate_status='accepted',
|
||||
po_number='PO-SUMMARY-STP-WAITING',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
review_case = ensure_run_review_cases(run=run)[0]
|
||||
review_case.status = 'draft'
|
||||
draft = review_case.current_draft
|
||||
assert draft is not None
|
||||
draft.validation_result_json = {
|
||||
'status': 'ready',
|
||||
'can_build': True,
|
||||
'can_auto_create': True,
|
||||
'validated_at': datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
groups = payload['conversation_processing']['status_groups']
|
||||
waiting_ids = {
|
||||
child['source_summary']['document_id']
|
||||
for row in groups.get('waiting_human') or []
|
||||
for child in row.get('aggregate_children') or []
|
||||
}
|
||||
processing_leaf = next(
|
||||
child
|
||||
for row in groups.get('processing') or []
|
||||
for child in row.get('aggregate_children') or []
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
assert document.id not in waiting_ids
|
||||
assert processing_leaf['user_status'] == 'running'
|
||||
assert 'edit_draft' not in (processing_leaf.get('available_actions') or [])
|
||||
assert processing_leaf.get('primary_action') is None
|
||||
|
||||
|
||||
def test_summary_leaf_uses_current_review_case_run_for_intake_parse_navigation(app) -> None:
|
||||
"""摘要投影的接收解析深链必须把同一 Case 的 Run 一并下发。"""
|
||||
with app.app_context():
|
||||
@@ -2598,7 +2927,7 @@ def test_single_order_task_work_item_includes_authoritative_lifecycle_ui_state(a
|
||||
conversation_id=session.session_id,
|
||||
intake_id=int(intake.id),
|
||||
extraction_run_id=int(run.id),
|
||||
current_step='step7_upload_freight',
|
||||
current_step='freight_uploading',
|
||||
status='automating',
|
||||
stage='freight_uploading',
|
||||
progress_version=1,
|
||||
@@ -2877,7 +3206,7 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
current_step='step7_upload_freight',
|
||||
current_step='freight_uploading',
|
||||
status='processing',
|
||||
stage='candidate_creating',
|
||||
progress_version=1,
|
||||
|
||||
@@ -36,6 +36,41 @@ def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage():
|
||||
)
|
||||
|
||||
|
||||
def test_stage_mapping_rejects_checkpoint_legacy_keys():
|
||||
"""CheckPoint stepN_* 遗留键已全部清除:阶段映射只认 15 阶契约码。
|
||||
|
||||
历史缺陷:step_key 被写进 OT.stage,靠投影别名兜底;现写路径只产出契约码
|
||||
(set_task_step_progress 校验 + 存量迁移清洗),别名不得再存在。
|
||||
"""
|
||||
legacy_keys = [
|
||||
'step1_notice_submit',
|
||||
'step2_parse_confirm',
|
||||
'step3_inventory_prepare',
|
||||
'step5_match_inventory',
|
||||
'step6_generate_file',
|
||||
'step7_upload_freight',
|
||||
]
|
||||
for key in legacy_keys:
|
||||
assert key not in LIFECYCLE_STAGE_BY_PROCESSING_STAGE, (
|
||||
f"CheckPoint 遗留键 {key!r} 不得再进入阶段映射"
|
||||
)
|
||||
for stage_code in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
|
||||
assert not str(stage_code).startswith('step'), (
|
||||
f"阶段映射出现非契约键 {stage_code!r}"
|
||||
)
|
||||
# 契约码本身仍能正常映射:库存匹配属通知准备,processing_stage 权威生效。
|
||||
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
|
||||
|
||||
result = project_lifecycle(
|
||||
current_gate={'gate_code': 'task_creation', 'status': 'invalidated'},
|
||||
blocking_reason={'code': 'gate_invalidated'},
|
||||
has_candidate_context=True,
|
||||
processing_stage='inventory_matching',
|
||||
)
|
||||
assert result['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert result['lifecycle_authority'] == 'processing_stage'
|
||||
|
||||
|
||||
def test_fifteen_stages_inventory_source_before_review():
|
||||
"""库存源解析必须排在人工复核与建单之前(跨面共用同一有序元组)。"""
|
||||
stages = list(SHIPPING_PROCESSING_STAGES)
|
||||
|
||||
@@ -405,9 +405,9 @@ def test_gate_maps_to_lifecycle_stage_b(app, gate_chain, scenario):
|
||||
"""五阶段门禁→生命周期 唯一映射必须正确(B 侧,真实 Notice 路径)。
|
||||
|
||||
`LIFECYCLE_STAGE_BY_GATE`(lifecycle_projection.py:30)是正式 Gate→五阶段业务码的唯一表。
|
||||
B(build_task_ui_state on Notice,processing_stage=None)经 project_lifecycle 走 Gate 兜底,
|
||||
必须按该表落到正确业务码。**freight_upload_rpa / manual_upload_handoff 必须属于 freight_upload**
|
||||
—— 这是用户确认的契约(方案 A)。
|
||||
B(build_task_ui_state on Notice)经 OT.stage + Gate 仅向前抬升后调用 project_lifecycle;
|
||||
履约 Gate(inventory_* / freight_*)须落到正确业务码。**freight_upload_rpa /
|
||||
manual_upload_handoff 必须属于 freight_upload** —— 这是用户确认的契约(方案 A)。
|
||||
"""
|
||||
gate_code, expected_stage = scenario
|
||||
with app.app_context():
|
||||
|
||||
@@ -20,15 +20,13 @@ def _receipt_config(source_id: int):
|
||||
|
||||
return ShippingReceiptReportConfig(
|
||||
inventory_source_id=source_id,
|
||||
enabled=True,
|
||||
report_path_json={
|
||||
'program_group': 'Bison',
|
||||
'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound',
|
||||
'report_name': 'Receipt Detail',
|
||||
},
|
||||
query_parameters_json=[],
|
||||
warehouse_ids_json=['AWSDU'],
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
tests/test_shipping_recheck_freeze_ot_extraction.py
|
||||
|
||||
用途:锁定冻结就绪重检从 OT 读 current_order_extraction_id,禁止 AttributeError。
|
||||
依赖:process_gate_executor._handle_recheck_freeze、unittest.mock。
|
||||
逻辑:模拟 OT(仅有 current_order_extraction_id)触发 recheck;断言能取到 Extraction 并调用评估。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
|
||||
def test_handle_recheck_freeze_uses_current_order_extraction_id():
|
||||
"""
|
||||
OT 无 order_extraction_id 字段;必须用 current_order_extraction_id,否则 Job 直接 failed。
|
||||
|
||||
断言意图:复现测试环境 AttributeError,修复后应进入评估而非 missing 短路。
|
||||
"""
|
||||
task = SimpleNamespace(id=7, current_order_extraction_id=42)
|
||||
assert not hasattr(task, 'order_extraction_id')
|
||||
extraction = SimpleNamespace(id=42)
|
||||
eval_calls: list[dict] = []
|
||||
|
||||
def _fake_eval(**kwargs):
|
||||
eval_calls.append(kwargs)
|
||||
return {
|
||||
'passed': False,
|
||||
'blocking_reason_code': 'freeze_not_ready',
|
||||
'issues': [],
|
||||
'findings': [],
|
||||
}
|
||||
|
||||
with (
|
||||
patch.object(executor, '_resolve_order_task', return_value=task),
|
||||
patch('app.models.ShippingOrderExtraction') as extraction_model,
|
||||
patch(
|
||||
'app.services.shipping_notice.freeze_readiness_service.evaluate_freeze_readiness_gate',
|
||||
side_effect=_fake_eval,
|
||||
),
|
||||
):
|
||||
extraction_model.query.get.return_value = extraction
|
||||
result = executor._handle_recheck_freeze(
|
||||
execution=SimpleNamespace(task_id=7),
|
||||
gate=SimpleNamespace(),
|
||||
payload={'freeze_mode': 'manual'},
|
||||
)
|
||||
|
||||
assert result['outcome'] == 'blocked_manual'
|
||||
assert result.get('output_snapshot', {}).get('missing') is not True
|
||||
extraction_model.query.get.assert_called_once_with(42)
|
||||
assert len(eval_calls) == 1
|
||||
assert eval_calls[0]['task'] is task
|
||||
assert eval_calls[0]['extraction'] is extraction
|
||||
@@ -1,11 +1,11 @@
|
||||
"""
|
||||
backend/tests/test_shipping_review_formal_task_edit.py
|
||||
|
||||
用途:验收正式任务字段写路径(Schema 策略 + order_data_version)与 change_effect 下游失效。
|
||||
用途:验收正式任务字段写路径(状态制编辑闸门 + order_data_version)与 change_effect 下游失效。
|
||||
依赖:task_workflow、schema_edit_policy、order_schema_service、ShippingOrderTask。
|
||||
逻辑:默认 reservation_id 不可写;Schema editable=True 可写并递增版本;
|
||||
rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并置 invalidated_from_stage;
|
||||
正式字段编辑以 Excel ready 为硬冻结,不再用 order_snapshot_id 阻断。
|
||||
逻辑:未配置 task_edit_policy 的字段默认可写(状态制),显式 editable=False 反向锁;
|
||||
可写成功递增 order_data_version;Excel ready 为硬冻结;
|
||||
rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并置 invalidated_from_stage。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -284,16 +284,13 @@ def _seed_ready_export_artifact(task: ShippingOrderTask, *, path: str | None = N
|
||||
return artifact
|
||||
|
||||
|
||||
def test_formal_edit_rejects_default_readonly_field(app):
|
||||
"""Schema 显式 editable=false 时拒绝,即使字段在 legacy 白名单内。"""
|
||||
def test_formal_edit_accepts_unconfigured_field_by_default(app):
|
||||
"""新契约:未配置 task_edit_policy 的字段在 Excel 未就绪时可直接编辑。"""
|
||||
with app.app_context():
|
||||
task = _task()
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
field_policies={
|
||||
'reservation_id': {'editable': False},
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
@@ -303,8 +300,9 @@ def test_formal_edit_rejects_default_readonly_field(app):
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
**_review_payload(),
|
||||
})
|
||||
assert response['status'] == 'failed'
|
||||
assert response['data']['error_code'] == 'SHIPPING.ORDER_FIELD_EDIT_FORBIDDEN'
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingOrderTask, task.id)
|
||||
assert int(refreshed.order_data_version) == 2
|
||||
|
||||
|
||||
def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
|
||||
@@ -283,7 +283,7 @@ def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(m
|
||||
id=1,
|
||||
order_task_id=9,
|
||||
upload_status='uploaded',
|
||||
current_step='step6_generate_file',
|
||||
current_step='excel_generating',
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
)
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
tests/test_shipping_review_workbench_state_isolation.py
|
||||
|
||||
用途:锁定复核工作台状态隔离契约——profile_match 管理员裁剪、automation 资格分层、
|
||||
Validation Snapshot 身份字段、用户 Gate 不把客户确认/技术 pending 当优先处理。
|
||||
Validation Snapshot 身份字段、用户 Gate 不把客户确认/技术 pending 当优先处理;
|
||||
STP 接手期间剥离草稿编辑动作并拒绝内容写入。
|
||||
依赖:pytest、order_review_projection、process_gate_projection、types.SimpleNamespace。
|
||||
逻辑:纯单元/轻量投影测试;不启 Flask 全应用。
|
||||
逻辑:纯单元/轻量投影测试;含 app fixture 的草稿写锁回归。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +13,7 @@ from __future__ import annotations
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_review_projection import (
|
||||
_inventory_rpa_is_running,
|
||||
_project_case_automation_status,
|
||||
@@ -160,6 +162,100 @@ def test_stp_failure_stays_on_order_creation_node_and_hides_review_entry():
|
||||
assert 'open_order_review' not in actions
|
||||
|
||||
|
||||
def test_stp_holding_statuses_strip_draft_edit_actions():
|
||||
"""waiting_to_start/queued/running 必须剥离 edit_draft/validate,禁止误改草稿。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_allowed_actions,
|
||||
)
|
||||
|
||||
case = SimpleNamespace(
|
||||
id=11,
|
||||
status='draft',
|
||||
candidate_id=90,
|
||||
disposition=None,
|
||||
confirmed_task_id=None,
|
||||
confirmed_task_no=None,
|
||||
)
|
||||
for status in ('waiting_to_start', 'queued', 'running'):
|
||||
with patch(
|
||||
'app.services.shipping_notice.workflow_ledger_service.find_item_by_current_case',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.tool_common.llm_review_enabled',
|
||||
return_value=True,
|
||||
):
|
||||
actions = project_case_allowed_actions(case, automation={'status': status})
|
||||
assert 'edit_draft' not in actions
|
||||
assert 'create_draft' not in actions
|
||||
assert 'validate' not in actions
|
||||
assert 'request_llm_suggestion' not in actions
|
||||
assert 'view' in actions
|
||||
|
||||
|
||||
def test_draft_mutation_rejects_when_stp_automation_holds(app, monkeypatch):
|
||||
"""STP 接手期间 patch 草稿必须 Conflict;显式 validate 仍放行给自动协调器。"""
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.shipping_notice import order_review_draft_service as draft_svc
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
patch_header_field,
|
||||
validate_draft,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='DRAFT-STP-LOCK')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json or {})
|
||||
schema = dict(snapshot.get('schema') or {})
|
||||
definition = dict(schema.get('definition') or {})
|
||||
definition['fields'] = [
|
||||
{
|
||||
'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header',
|
||||
'value_type': 'string', 'required': False, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'enabled': True,
|
||||
},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-1'}]}],
|
||||
'lines': [],
|
||||
}],
|
||||
}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
draft = case.current_draft
|
||||
assert draft is not None
|
||||
version = int(draft.draft_version)
|
||||
monkeypatch.setattr(draft_svc, '_stp_automation_holds_draft', lambda _case: True)
|
||||
|
||||
try:
|
||||
patch_header_field(
|
||||
user_id=user.id,
|
||||
case_no=case.case_no,
|
||||
field_id='po-id',
|
||||
value='PO-LOCKED',
|
||||
expected_draft_version=version,
|
||||
)
|
||||
except ConflictError as exc:
|
||||
assert exc.code == 'SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION'
|
||||
else:
|
||||
raise AssertionError('STP hold must block draft patch')
|
||||
|
||||
# 关键断言:自动协调仍可显式 validate(action=draft_validated 放行)。
|
||||
validated = validate_draft(
|
||||
user_id=user.id,
|
||||
case_no=case.case_no,
|
||||
expected_draft_version=version,
|
||||
)
|
||||
assert validated is not None
|
||||
|
||||
|
||||
def test_stale_running_stp_job_becomes_user_actionable_failure():
|
||||
"""超时的 running Job 必须停止,并投影当前 Gate 的明确用户动作。"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
@@ -28,6 +28,7 @@ from app.services.shipping_notice.reservation_service import (
|
||||
record_inventory_verification,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error
|
||||
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
|
||||
from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
@@ -240,26 +241,30 @@ def test_confirmed_task_revision_transfers_unfulfilled_reservation_with_audit(ap
|
||||
ensure_task_reservations(first_task)
|
||||
db.session.flush()
|
||||
original = ShippingReservation.query.filter_by(reservation_id=first_snapshot.lines[0].reservation_id).one()
|
||||
line = first_snapshot.lines[0]
|
||||
ot_id = int(first_task.id)
|
||||
ot_count = ShippingOrderTask.query.count()
|
||||
|
||||
# 修订沿用同一 OT:不新建任务/快照,仅改写冻结行数据并沿用该 OT,
|
||||
# 由 _transfer_confirmed_revision 完成 version bump 与 Reservation 接替。
|
||||
line = first_snapshot.lines[0]
|
||||
line.part_number = '000123-REV'
|
||||
line.qty = Decimal('13.5')
|
||||
# 修订沿用同一 OT:不新建任务/快照。契约翻转(有效视图):冻结快照不再就地改写,
|
||||
# 改经人工字段编辑器写入已接受修正,由预约层按有效值自动完成 transfer 接替。
|
||||
replace_current_line_field_value(task=first_task, position=0, field_code='part_number', value='000123-REV')
|
||||
replace_current_line_field_value(task=first_task, position=0, field_code='qty', value='13.5')
|
||||
db.session.flush()
|
||||
|
||||
registered = ensure_task_reservations(first_task)
|
||||
|
||||
# 同一 OT 上完成接替:不新建任务行,仅版本 bump,Reservation 仍指向该 OT。
|
||||
# (order_data_version 在冻结值 7 之上经历两次编辑器 bump 与一次确认修订 bump。)
|
||||
assert registered == [original]
|
||||
assert original.task_id == ot_id
|
||||
assert original.snapshot_line_id == line.id
|
||||
assert original.part_number == '000123-REV'
|
||||
assert original.required_qty == Decimal('13.5')
|
||||
assert first_task.order_data_version == 8
|
||||
assert first_task.order_data_version == 10
|
||||
assert first_task.progress_version == 2
|
||||
# 冻结快照保持审计锚点:强类型列不得被修订改写。
|
||||
assert line.part_number == '000123'
|
||||
assert line.qty == Decimal('12.50000000')
|
||||
# 不产生重复 OT 行。
|
||||
assert ShippingOrderTask.query.count() == ot_count
|
||||
# 审计事件落在该 OT 上。
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
"""
|
||||
backend/tests/test_shipping_schema_edit_policy.py
|
||||
|
||||
用途:验收正式任务 Schema 编辑策略默认只读与显式放行(无 legacy 绕过)。
|
||||
用途:验收正式任务 Schema 编辑策略状态制默认(未配置默认可写)与显式反向锁。
|
||||
依赖:schema_edit_policy、pytest。
|
||||
逻辑:无 task_edit_policy → 不可编辑;显式 editable=True → 可编辑;
|
||||
excel_ready 后全局关闭。
|
||||
逻辑:无 task_edit_policy → 默认可编辑(Excel ready 前状态制放行);显式 editable=False → 反向锁;
|
||||
excel_ready 后全局硬冻结。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.schema_edit_policy import (
|
||||
DEFAULT_EDITABLE_AFTER_TASK_CREATION,
|
||||
field_task_edit_policy,
|
||||
is_excel_ready_for_task,
|
||||
is_field_editable_for_formal_task,
|
||||
list_editable_formal_field_ids,
|
||||
@@ -18,13 +19,20 @@ from app.services.shipping_notice.schema_edit_policy import (
|
||||
)
|
||||
|
||||
|
||||
def test_default_formal_fields_are_readonly() -> None:
|
||||
"""默认创建任务后不可编辑。"""
|
||||
assert DEFAULT_EDITABLE_AFTER_TASK_CREATION is False
|
||||
assert not is_field_editable_for_formal_task({'field_id': 'po-id'})
|
||||
def test_default_formal_fields_are_editable_until_excel_ready() -> None:
|
||||
"""新契约:未配置策略的字段默认可编辑(状态制),显式 editable=false 仍可反向锁。"""
|
||||
assert DEFAULT_EDITABLE_AFTER_TASK_CREATION is True
|
||||
assert field_task_edit_policy(None)['editable'] is True
|
||||
assert field_task_edit_policy({'task_edit_policy': {'editable': False}})['editable'] is False
|
||||
# Excel 未就绪时未配置策略字段可写;Excel ready 后仍全局硬冻结。
|
||||
assert is_field_editable_for_formal_task({'field_id': 'po-id'}, excel_ready=False) is True
|
||||
assert is_field_editable_for_formal_task({'field_id': 'po-id'}, excel_ready=True) is False
|
||||
assert list_editable_formal_field_ids([
|
||||
{'field_id': 'po-id', 'field_code': 'po_number'},
|
||||
]) == []
|
||||
], excel_ready=False) == ['po-id']
|
||||
assert list_editable_formal_field_ids([
|
||||
{'field_id': 'po-id', 'field_code': 'po_number'},
|
||||
], excel_ready=True) == []
|
||||
|
||||
|
||||
def test_schema_explicit_editable_is_honored_until_excel_ready() -> None:
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_center_review_run_deep_link.py
|
||||
|
||||
用途:验收任务中心 Notice/OT 摘要注入 review_run_no 与 order_task_no,供 UI-04 深链
|
||||
与工作台右卡 work-item 投影键。
|
||||
用途:验收任务中心 Notice/OT 摘要注入 review_run_no / order_task_no / review_case_no,
|
||||
供 UI-04 深链(run_no + case_no)与工作台右卡 work-item 投影键。
|
||||
依赖:query_service._inject_unified_processing_fields、ShippingOrderTask、pytest。
|
||||
逻辑:Notice 挂 OT 时 SUMMARY 必含 review_run_no;直接序列化 OT 时 order_task_no
|
||||
必须等于自身 task_no(禁止 enrich 冲成 null)。
|
||||
必须等于自身 task_no(禁止 enrich 冲成 null);OT 有确认 Case 时必须注入
|
||||
review_case_no(缺它工作台选法 2 不拉 Case、身份链断裂、五阶段页签全锁)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -76,7 +77,7 @@ def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app):
|
||||
extraction_run_id=int(run.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=3,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
@@ -98,3 +99,50 @@ def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app):
|
||||
assert detail['order_task_no'] == 'OT-TC-OT-SELF-1'
|
||||
assert detail['task_no'] == 'OT-TC-OT-SELF-1'
|
||||
assert detail['review_run_no'] == run.run_no
|
||||
|
||||
|
||||
def test_serialize_order_task_injects_confirmed_review_case_no_for_workbench_deeplink(app):
|
||||
"""
|
||||
OT 摘要/详情必须携带确认 Case 号,任务中心 OT 直链才能绑定工作台工作项。
|
||||
|
||||
关键断言:无 case_no 的 OT 直链下,工作台对正式下游阶段任务走选法 2 不拉 Case,
|
||||
activeCase/displayCase/confirmedNoticeTaskNo 全空、五阶段页签全锁;
|
||||
review_case_no 是 openOrderProcessing 追加 case_no 深链参数的唯一来源,
|
||||
SUMMARY 与 workbench DETAIL 都必须注入。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingOrderReviewCase
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='TC-CASE-LINK')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-TC-CASE-LINK-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
status='blocked',
|
||||
stage='inventory_fetching',
|
||||
progress_version=2,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
# 模拟 RPA 超时阻断的正式下游 OT:存在一条已确认绑定该 OT 的复核 Case。
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='SNRC-TC-CASE-LINK', run_id=int(run.id),
|
||||
unit_id=int(run.extraction_plan.units[0].id),
|
||||
document_id=int(document.id), owner_user_id=user.id,
|
||||
status='confirmed', confirmed_task_id=int(order_task.id),
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_task_summary(order_task, viewer_user_id=user.id)
|
||||
detail = serialize_task_detail(
|
||||
order_task, viewer_user_id=user.id, include_stage_context=True, view='workbench',
|
||||
)
|
||||
# 关键断言:SUMMARY / workbench DETAIL 均注入确认 Case 号(深链 case_no 锚点)。
|
||||
assert summary['review_case_no'] == 'SNRC-TC-CASE-LINK'
|
||||
assert detail['review_case_no'] == 'SNRC-TC-CASE-LINK'
|
||||
@@ -91,7 +91,7 @@ def test_service_chain_customer_confirm_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.review_status = 'pending_confirm'
|
||||
notice.current_step = 'step4_match_inventory'
|
||||
notice.current_step = 'inventory_matching'
|
||||
notice.customer_id = 1
|
||||
db.session.commit()
|
||||
|
||||
@@ -112,7 +112,7 @@ def test_service_chain_inventory_match_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.match_status = 'matched'
|
||||
notice.current_step = 'step4_match_inventory'
|
||||
notice.current_step = 'inventory_matching'
|
||||
db.session.commit()
|
||||
|
||||
before, projection = _project_after_sync(notice, order_task, run)
|
||||
@@ -130,7 +130,7 @@ def test_service_chain_excel_generate_projection(app, workbench_chain_ids):
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.upload_status = 'pending'
|
||||
notice.current_step = 'step7_upload_freight'
|
||||
notice.current_step = 'freight_uploading'
|
||||
notice.export_file_path = '/tmp/fake-shipping.xlsx'
|
||||
db.session.commit()
|
||||
|
||||
@@ -148,7 +148,7 @@ def test_service_chain_freight_upload_retry_projection(app, workbench_chain_ids)
|
||||
"""
|
||||
with app.app_context():
|
||||
run, notice, order_task = _load_chain(workbench_chain_ids)
|
||||
notice.current_step = 'step7_upload_freight'
|
||||
notice.current_step = 'freight_uploading'
|
||||
notice.upload_status = 'failed'
|
||||
notice.export_file_path = '/tmp/fake-shipping.xlsx'
|
||||
db.session.commit()
|
||||
|
||||
@@ -2,7 +2,7 @@ import pytest
|
||||
from flask import Flask
|
||||
from app import create_app, db
|
||||
from app.models import ChatLog, Agent, User
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
import json
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -18,7 +18,7 @@ import pytest
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, AgentGuide, TrainingConfig, TrainingConfigResource, TrainingRecord, User
|
||||
from app.services import training_config_service, training_service
|
||||
from app.services import lean_training_service, training_config_service, training_service
|
||||
from app.services.training_service import _grade_answer_details, _normalize_question_bank
|
||||
from app.api.chat import preview_support
|
||||
|
||||
@@ -236,6 +236,119 @@ def test_training_user_progress_round_trip_and_completion(client, app):
|
||||
assert record.completion_time is not None
|
||||
|
||||
|
||||
def test_overseas_regulations_video_completion_creates_passed_result(client, app):
|
||||
"""关键断言:自定义编码的出国规章培训完整观看视频后无需题库作答,也必须落库为一次完成。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username="overseas_video_completion")
|
||||
agent = _create_training_agent(name="overseas_video_agent")
|
||||
db.session.add(TrainingConfig(
|
||||
training_type="overseas_policy_v2",
|
||||
name="出国规章培训",
|
||||
version="v1",
|
||||
status="published",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json={
|
||||
"agent_id": agent.id,
|
||||
"type": "overseas_policy_v2",
|
||||
"stage": "result",
|
||||
"score": 100,
|
||||
"passed": True,
|
||||
"attempt_count": 0,
|
||||
"answer_details": [],
|
||||
})
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["training_type"] == "overseas_policy_v2"
|
||||
assert body["stage"] == "result"
|
||||
assert body["passed"] is True
|
||||
assert body["status"] == "passed"
|
||||
assert isinstance(body["completion_time"], str) and body["completion_time"]
|
||||
|
||||
|
||||
def test_overseas_regulations_video_completion_sends_wecom_notice_each_time(client, app, monkeypatch):
|
||||
"""关键断言:每次出国规章视频完成都必须生成一次泰国出差准则企微通知,不能按历史完成记录去重。"""
|
||||
sent_messages = []
|
||||
monkeypatch.setattr(
|
||||
training_service,
|
||||
"send_wecom_event_message",
|
||||
lambda **kwargs: sent_messages.append(kwargs) or {"ok": True, "trace_id": "training-notice-trace"},
|
||||
)
|
||||
with app.app_context():
|
||||
user = _create_user(username="overseas_wecom_notice")
|
||||
db.session.add(TrainingConfig(
|
||||
training_type="overseas_notice_v1",
|
||||
name="出国规章培训",
|
||||
version="v1",
|
||||
status="published",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
payload = {
|
||||
"type": "overseas_notice_v1",
|
||||
"stage": "result",
|
||||
"score": 100,
|
||||
"passed": True,
|
||||
"attempt_count": 0,
|
||||
"answer_details": [],
|
||||
}
|
||||
first_response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json=payload)
|
||||
second_response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json=payload)
|
||||
|
||||
assert first_response.status_code == 200
|
||||
assert second_response.status_code == 200
|
||||
assert len(sent_messages) == 2
|
||||
assert all(message["event_type"] == "training_overseas_thailand_guidelines" for message in sent_messages)
|
||||
assert all(message["title"] == "中国员工出差泰国的行为准则" for message in sent_messages)
|
||||
assert all(message["content"] == "中国员工出差泰国的行为准则" for message in sent_messages)
|
||||
|
||||
|
||||
def test_overseas_regulations_wecom_notice_jumps_to_generic_entrance_chat(client, app, monkeypatch):
|
||||
"""关键断言:出国规章完成的企微通知必须跳转「通用入口」聊天页(/chat/<id>),不得落入 /workspace 应用管理页。"""
|
||||
sent_messages = []
|
||||
monkeypatch.setattr(
|
||||
training_service,
|
||||
"send_wecom_event_message",
|
||||
lambda **kwargs: sent_messages.append(kwargs) or {"ok": True, "trace_id": "training-notice-trace"},
|
||||
)
|
||||
with app.app_context():
|
||||
user = _create_user(username="overseas_wecom_jump")
|
||||
entrance_agent = Agent(
|
||||
name="通用入口",
|
||||
type="api",
|
||||
agent_code="generic",
|
||||
runtime_provider="dify",
|
||||
conversation_mode="chat",
|
||||
dify_app_type="chatflow",
|
||||
handler_config={"content_profile": "generic_entrance"},
|
||||
)
|
||||
db.session.add(entrance_agent)
|
||||
db.session.add(TrainingConfig(
|
||||
training_type="overseas_jump_v1",
|
||||
name="出国规章培训",
|
||||
version="v1",
|
||||
status="published",
|
||||
))
|
||||
db.session.commit()
|
||||
entrance_agent_id = entrance_agent.id
|
||||
|
||||
response = client.put("/api/user/training-record/progress", headers=_auth_headers(user), json={
|
||||
"type": "overseas_jump_v1",
|
||||
"stage": "result",
|
||||
"score": 100,
|
||||
"passed": True,
|
||||
"attempt_count": 0,
|
||||
"answer_details": [],
|
||||
})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert len(sent_messages) == 1
|
||||
# [ASSERT] 卡片跳转路径必须指向通用入口聊天页,员工点击后进入图二页面而非应用管理工作台
|
||||
assert sent_messages[0]["jump_path"] == f"/chat/{entrance_agent_id}"
|
||||
|
||||
|
||||
def test_safety_training_progress_round_trip(client, app):
|
||||
"""安全培训应持久化培训版本、考试模式、三级状态和级别进度。"""
|
||||
with app.app_context():
|
||||
@@ -583,11 +696,34 @@ def test_training_admin_list_stats_and_export_share_one_fact_source(client, app)
|
||||
workbook = load_workbook(BytesIO(export_res.data))
|
||||
sheet = workbook.active
|
||||
rows = list(sheet.iter_rows(values_only=True))
|
||||
assert rows[0] == ("入职日期", "完成日期", "部门", "姓名", "工号", "分数", "考试次数", "状态")
|
||||
assert rows[0] == ("入职日期", "完成日期", "培训类型", "部门", "姓名", "工号", "分数", "考试次数", "状态")
|
||||
assert len(rows) == 3
|
||||
assert rows[1][2] == "生产一部"
|
||||
assert rows[2][2] == "生产一部"
|
||||
assert {rows[1][7], rows[2][7]} == {"passed", "failed"}
|
||||
assert rows[1][3] == "生产一部"
|
||||
assert rows[2][3] == "生产一部"
|
||||
assert {rows[1][8], rows[2][8]} == {"已通过", "未通过"}
|
||||
|
||||
|
||||
def test_lean_dashboard_export_uses_page_time_and_status_labels(monkeypatch):
|
||||
"""精益看板 Excel 必须复用页面的分钟级时间格式与中文状态文案。"""
|
||||
monkeypatch.setattr(
|
||||
lean_training_service,
|
||||
"list_dashboard",
|
||||
lambda task_id: {
|
||||
"task": {"week_index": 2, "week_key": "2026-09-14", "due_at": "2026-09-20T23:59:59"},
|
||||
"completed": [{"employee_id": "EMP-001", "name": "张三", "department": "生产部", "videos": [{"name": "精益视频", "watched_at": "2026-09-15T08:30:45"}], "status": "completed", "summary_text": "已完成学习", "completed_at": "2026-09-15T09:00:12"}],
|
||||
"incomplete": [{"employee_id": "EMP-002", "name": "李四", "department": "品质部", "videos": [], "status": "overdue", "summary_text": None, "completed_at": None}],
|
||||
"periods": [],
|
||||
},
|
||||
)
|
||||
|
||||
file_data, _ = lean_training_service.export_dashboard_excel(1)
|
||||
rows = list(load_workbook(BytesIO(file_data)).active.iter_rows(values_only=True))
|
||||
|
||||
assert rows[1][2] == "2026-09-20 23:59"
|
||||
assert rows[1][7] == "2026-09-15 08:30"
|
||||
assert rows[1][8] == "已完成"
|
||||
assert rows[1][10] == "2026-09-15 09:00"
|
||||
assert rows[2][8] == "已延期"
|
||||
|
||||
|
||||
def test_training_preview_proxy_reads_kb_storage_without_http_callback(monkeypatch, tmp_path, app):
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
tests/test_ui_state_effective_values.py
|
||||
|
||||
用途:验证通知准备投影的值列(预约号/料号/需求数量)消费有效订单值视图。
|
||||
依赖:pytest、ui_state._build_stage_context 阶段上下文构建、有效视图夹具 _seed_frozen_order。
|
||||
逻辑:编辑料号后(重匹配前),frozen_order_lines 与 preparation.lines 的值列必须立即显示
|
||||
新值(有效值优先、快照列回退);匹配结果列不受影响,仍诚实反映最近一轮匹配。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
|
||||
|
||||
def test_preparation_value_columns_follow_effective_values(app):
|
||||
"""保存修正后(重匹配前)值列立即显示新值。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
from app.services.shipping_notice import ui_state
|
||||
# _build_stage_context 实签名为 (task, *, lifecycle_stage, stp_facts, process_gate);
|
||||
# 直接传正式 OT(夹具即 OT),经 _resolve_order_task_for_gate_lookup 原样返回。
|
||||
context = ui_state._build_stage_context(
|
||||
fixture.order,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
stp_facts=None,
|
||||
process_gate=None,
|
||||
)
|
||||
preparation = context['preparation']
|
||||
frozen_lines = preparation['frozen_order_lines']
|
||||
prep_lines = preparation['lines']
|
||||
# 断言:值列为有效值(而非快照冻结的带尾巴旧值)。
|
||||
assert frozen_lines[0]['part_number'] == 'D4-A08AR12000002'
|
||||
assert prep_lines[0]['part_number'] == 'D4-A08AR12000002'
|
||||
# 断言:未被编辑的第 1 行保持冻结值(对位叠加只影响被改行)。
|
||||
assert frozen_lines[1]['part_number'] == 'D4-B07BR07000001'
|
||||
assert prep_lines[1]['part_number'] == 'D4-B07BR07000001'
|
||||
@@ -394,7 +394,7 @@ def test_chat_completions_stream_success(client, mocker, mock_agent_query):
|
||||
mock_post.return_value.__enter__.return_value = mock_response
|
||||
|
||||
# Mock DB logging
|
||||
mocker.patch('app.services.dify.DifyService._log_chat')
|
||||
mocker.patch('app.services.integrations.dify.DifyService._log_chat')
|
||||
|
||||
# Setup decorator mocks
|
||||
mock_user = User(id=1, username="test_user")
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
"""
|
||||
backend/tests/test_voucher_check_permissions.py
|
||||
|
||||
用途:验收立账凭证改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、workspace voucher_check 蓝图。
|
||||
逻辑:授予 voucher_check Agent 后可查询任务列表,但不能触发强制重检、也不能改通知配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
"""创建落库用户,供 voucher-check API 走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role=role,
|
||||
status='active',
|
||||
real_name=f'{username}-实名',
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='财务部',
|
||||
)
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def _ensure_voucher_check_agent() -> Agent:
|
||||
"""确保存在启用中的立账凭证 Agent,供授权绑定。"""
|
||||
agent = Agent.query.filter_by(agent_code='voucher_check', is_active=True).first()
|
||||
if agent:
|
||||
return agent
|
||||
agent = Agent(
|
||||
name='立账凭证',
|
||||
agent_code='voucher_check',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(agent)
|
||||
return agent
|
||||
|
||||
|
||||
def _grant_voucher_check_agent(user: User) -> User:
|
||||
"""把立账凭证 Agent 授权给指定用户并重新取出,避免会话分离后丢失关系。"""
|
||||
agent = _ensure_voucher_check_agent()
|
||||
user_id = user.id
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.expunge(user)
|
||||
return db.session.get(User, user_id) or user
|
||||
|
||||
|
||||
def _json_error(response) -> dict:
|
||||
"""读取标准 envelope 的 error 对象。"""
|
||||
body = response.get_json()
|
||||
assert body.get('success') is False
|
||||
assert isinstance(body.get('error'), dict)
|
||||
return body['error']
|
||||
|
||||
|
||||
def test_voucher_check_api_forbids_user_without_agent(client, app):
|
||||
"""未授予 Agent 的普通用户查询任务或强制重检均返回 VOUCHER_CHECK.FORBIDDEN。"""
|
||||
with app.app_context():
|
||||
ordinary = _create_user(username='vc_api_denied')
|
||||
ordinary_id = ordinary.id
|
||||
_ensure_voucher_check_agent()
|
||||
db.session.expunge(ordinary)
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(ordinary_id),
|
||||
'X-Username': 'vc_api_denied',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
list_res = client.get('/api/workspace/accounting-voucher-check/runs', headers=headers)
|
||||
# 关键断言:登录不足够,Agent 授权缺失必须 403。
|
||||
assert list_res.status_code == 403
|
||||
assert _json_error(list_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
||||
|
||||
force_res = client.post(
|
||||
'/api/workspace/accounting-voucher-check/runs',
|
||||
headers=headers,
|
||||
json={'mode': 'force_all'},
|
||||
)
|
||||
assert force_res.status_code == 403
|
||||
assert _json_error(force_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
||||
|
||||
|
||||
def test_voucher_check_api_allows_granted_user(client, app):
|
||||
"""授予 voucher_check Agent 后普通用户可以查询检核任务。"""
|
||||
with app.app_context():
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_api_granted'))
|
||||
granted_id = granted.id
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(granted_id),
|
||||
'X-Username': 'vc_api_granted',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
list_res = client.get('/api/workspace/accounting-voucher-check/runs', headers=headers)
|
||||
# 关键断言:Agent 授权后不再 403,返回标准成功 envelope。
|
||||
assert list_res.status_code == 200
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
|
||||
|
||||
def test_voucher_check_api_allows_admin_without_agent_binding(client, app):
|
||||
"""平台 admin 即使未绑定该 Agent 也可查询检核任务。"""
|
||||
with app.app_context():
|
||||
admin = _create_user(username='vc_api_admin', role='admin')
|
||||
admin_id = admin.id
|
||||
_ensure_voucher_check_agent()
|
||||
db.session.expunge(admin)
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(admin_id),
|
||||
'X-Username': 'vc_api_admin',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
list_res = client.get('/api/workspace/accounting-voucher-check/runs', headers=headers)
|
||||
assert list_res.status_code == 200
|
||||
assert list_res.get_json().get('success') is True
|
||||
|
||||
|
||||
def test_voucher_check_force_requires_admin(client, app):
|
||||
"""已授权的普通用户可查任务,但不能触发强制重检。"""
|
||||
with app.app_context():
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_api_jobs_denied'))
|
||||
granted_id = granted.id
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(granted_id),
|
||||
'X-Username': 'vc_api_jobs_denied',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
# 关键断言:访问权不等于操作权,强制重检仅管理员。
|
||||
res = client.post(
|
||||
'/api/workspace/accounting-voucher-check/runs',
|
||||
headers=headers,
|
||||
json={'mode': 'force_all'},
|
||||
)
|
||||
assert res.status_code == 403
|
||||
assert _json_error(res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
|
||||
|
||||
def test_voucher_check_notify_config_requires_admin(client, app):
|
||||
"""已授权的普通用户可查任务,但不能读取或保存按类型接收人。"""
|
||||
with app.app_context():
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_api_notify_denied'))
|
||||
granted_id = granted.id
|
||||
|
||||
headers = {
|
||||
'X-User-Id': str(granted_id),
|
||||
'X-Username': 'vc_api_notify_denied',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
get_res = client.get('/api/workspace/accounting-voucher-check/notify-config', headers=headers)
|
||||
# 关键断言:通知配置读写均仅管理员。
|
||||
assert get_res.status_code == 403
|
||||
assert _json_error(get_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
|
||||
put_res = client.put(
|
||||
'/api/workspace/accounting-voucher-check/notify-config',
|
||||
headers=headers,
|
||||
json={'profile_code': 'sales', 'recipients': {'po_order': [granted_id]}},
|
||||
)
|
||||
assert put_res.status_code == 403
|
||||
assert _json_error(put_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
@@ -1,6 +1,6 @@
|
||||
import base64
|
||||
|
||||
from app.services.wecom_crypto import decrypt_wecom_aes, encrypt_wecom_aes, sha1_hex
|
||||
from app.services.integrations.wecom.crypto import decrypt_wecom_aes, encrypt_wecom_aes, sha1_hex
|
||||
|
||||
|
||||
def test_wecom_aes_roundtrip():
|
||||
|
||||
@@ -24,7 +24,7 @@ if str(BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND_ROOT))
|
||||
|
||||
from app import create_app # noqa: E402
|
||||
from app.services.wecom_notify import _get_access_token # noqa: E402
|
||||
from app.services.integrations.wecom.notify import _get_access_token # noqa: E402
|
||||
|
||||
|
||||
def _get_userid_by_mobile(mobile: str) -> dict[str, Any]:
|
||||
|
||||
@@ -25,7 +25,7 @@ if str(BACKEND_ROOT) not in sys.path:
|
||||
|
||||
from app import create_app, db # noqa: E402
|
||||
from app.models import User # noqa: E402
|
||||
from app.services.wecom_notify import _get_access_token, send_wecom_textcard_message # noqa: E402
|
||||
from app.services.integrations.wecom.notify import _get_access_token, send_wecom_textcard_message # noqa: E402
|
||||
|
||||
|
||||
def _resolve_target_userid(app, target: str) -> tuple[str, dict[str, Any] | None]:
|
||||
|
||||
Loaded 100 of 541 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user