Merge branch 'dev' into picture-feedback
This commit is contained in:
commit
34ad40778b
180 files changed
+13262
-5333
No files matched your search
@@ -2255,3 +2255,51 @@ def test_evidence_files_list_returns_today_size_and_presigned_url(
|
||||
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
|
||||
).one()
|
||||
assert audit.aggregate_id == EVIDENCE_SOURCE
|
||||
|
||||
|
||||
def test_evidence_file_download_streams_through_the_site(
|
||||
app, client, admin_headers, monkeypatch,
|
||||
):
|
||||
"""单文件下载由当前站点回传,保存名不用对象键。"""
|
||||
now = datetime.utcnow().replace(microsecond=0)
|
||||
source = _ensure_evidence_source()
|
||||
report = _seed_evidence_file(
|
||||
source, kind="inbound", filename="Inbound.xlsx",
|
||||
storage_key="evidence/one", sha="61" * 32, file_size=12,
|
||||
created_at=now,
|
||||
)
|
||||
_patch_archive_bytes(monkeypatch, {"evidence/one": b"PK-xlsx"})
|
||||
|
||||
response = client.get(
|
||||
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files/{report.id}?record_kind=inbound",
|
||||
headers=admin_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# [断言意图] 响应体是对象内容,不是跳到 MinIO 的地址。
|
||||
assert response.data == b"PK-xlsx"
|
||||
from app.api.in_transit_transfer import evidence_download_filename
|
||||
|
||||
download_name = evidence_download_filename(EVIDENCE_SOURCE, now, "Inbound.xlsx")
|
||||
# [断言意图] 保存名沿用库存源加东八区时间,浏览器不会落到哈希对象键。
|
||||
assert download_name in response.headers.get("Content-Disposition", "")
|
||||
|
||||
|
||||
def test_evidence_file_download_rejects_unavailable_file(app, client, admin_headers):
|
||||
"""已清理或不在可用窗口的归档不能经站点下载。"""
|
||||
now = datetime.utcnow().replace(microsecond=0)
|
||||
source = _ensure_evidence_source()
|
||||
report = _seed_evidence_file(
|
||||
source, kind="inbound", filename="Deleted.xlsx",
|
||||
storage_key="evidence/gone", sha="62" * 32, file_size=12,
|
||||
created_at=now, deleted=True,
|
||||
)
|
||||
|
||||
response = client.get(
|
||||
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files/{report.id}?record_kind=inbound",
|
||||
headers=admin_headers,
|
||||
)
|
||||
|
||||
# [断言意图] 清单里不会出现的文件,单文件下载同样拒绝。
|
||||
assert response.status_code == 404
|
||||
assert response.get_json()["error"]["code"] == "SHIPPING.INBOUND_FILE_NOT_FOUND"
|
||||
@@ -3,7 +3,7 @@ tests/services/admin/test_shipping_inventory_service.py
|
||||
|
||||
用途:验证库存主数据管理服务的安全性和关键业务约束。
|
||||
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
|
||||
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
|
||||
逻辑:管理后台写配置前锁定用户名可回显、密码与密文不回传、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +22,7 @@ from app.models import (
|
||||
FreightRpaSource,
|
||||
FreightRpaSourceParsingBindingAudit,
|
||||
FreightRpaOnhandStructureAnalysis,
|
||||
FreightRpaProfile,
|
||||
)
|
||||
|
||||
|
||||
@@ -160,15 +161,50 @@ def _published_route_field_id() -> str:
|
||||
)
|
||||
|
||||
|
||||
def test_profile_credentials_are_not_returned(app):
|
||||
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
|
||||
def test_profile_returns_username_and_keeps_password_secret(app):
|
||||
"""Profile 回执返回用户名明文,密码与密文不得出现。相同用户名再次保存不轮换密文。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
# 用户名是账号标识,管理端需要明文辨认;密码只报告已配置。
|
||||
assert payload['username'] == 'test-user'
|
||||
assert payload['password_configured'] is True
|
||||
assert payload['username_masked'] == 'configured'
|
||||
assert 'password' not in payload
|
||||
assert 'ciphertext' not in payload
|
||||
stored = db.session.get(FreightRpaProfile, payload['id'])
|
||||
original_username = stored.username_ciphertext
|
||||
original_password = stored.password_ciphertext
|
||||
original_updated_at = stored.credential_updated_at
|
||||
unchanged = _profile_data()
|
||||
unchanged.pop('password')
|
||||
unchanged['display_name'] = 'DBS EU renamed'
|
||||
again = freight_rpa_source_admin_service.save_profile(unchanged, actor_id=None, profile_id=payload['id'])
|
||||
# 回显后的原用户名随表单提交时,不得重加密或刷新凭据时间。
|
||||
assert again['username'] == 'test-user'
|
||||
db.session.refresh(stored)
|
||||
assert stored.username_ciphertext == original_username
|
||||
assert stored.password_ciphertext == original_password
|
||||
assert stored.credential_updated_at == original_updated_at
|
||||
assert stored.display_name == 'DBS EU renamed'
|
||||
|
||||
|
||||
def test_profile_username_change_reencrypts_without_touching_password(app):
|
||||
"""只改用户名时重写用户名密文,密码密文保持不变。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
stored = db.session.get(FreightRpaProfile, payload['id'])
|
||||
original_username = stored.username_ciphertext
|
||||
original_password = stored.password_ciphertext
|
||||
changed = _profile_data()
|
||||
changed.pop('password')
|
||||
changed['username'] = 'other-user'
|
||||
updated = freight_rpa_source_admin_service.save_profile(changed, actor_id=None, profile_id=payload['id'])
|
||||
assert updated['username'] == 'other-user'
|
||||
db.session.refresh(stored)
|
||||
assert stored.username_ciphertext != original_username
|
||||
assert stored.password_ciphertext == original_password
|
||||
|
||||
|
||||
def test_profile_rejects_page_operation_configuration(app):
|
||||
@@ -620,29 +656,23 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
|
||||
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
base_version = profile['config_version']
|
||||
upload_cfg = {
|
||||
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
|
||||
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
|
||||
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
|
||||
'enabled': True, 'entry_url': 'https://evil.example/steal',
|
||||
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file',
|
||||
}
|
||||
updated = freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
assert updated['config_version'] == base_version
|
||||
assert updated['upload_config_json']['enabled'] is True
|
||||
assert updated['upload_config_json'] == {'enabled': True}
|
||||
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
|
||||
bumped = freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
assert bumped['config_version'] == base_version + 1
|
||||
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
|
||||
# 上传配置必须是对象;页面字段不再作为校验对象。
|
||||
with pytest.raises(ValidationError):
|
||||
freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
||||
{**_profile_data(), 'upload_config_json': 'not-an-object'},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/tests/services/file_assets/test_storage_presign.py
|
||||
|
||||
用途:验证业务文件预签名下载地址使用浏览器可访问的 MinIO 主机。
|
||||
依赖:file_assets.storage、minio。
|
||||
逻辑:正式环境内网端点与公网基址不同;断言签名 URL 的主机是公网基址,读写客户端仍是内网端点。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.file_assets import storage as storage_mod
|
||||
from app.services.file_assets.storage import resolve_presign_endpoint
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _patch_minio_config(monkeypatch, *, public_base: str, secure: bool = False) -> None:
|
||||
"""把存储配置钉成正式环境形态:容器内网端点 + 浏览器公网基址。"""
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_ENDPOINT", "host.docker.internal:9000")
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_ACCESS_KEY", "test-access")
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECRET_KEY", "test-secret")
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECURE", secure)
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_PUBLIC_BASE_URL", public_base)
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_FILE_ASSETS_BUCKET", "hxops-file-assets")
|
||||
|
||||
|
||||
def test_resolve_presign_endpoint_keeps_explicit_port():
|
||||
"""公网基址的非默认端口必须留在预签名端点里。"""
|
||||
endpoint, secure = resolve_presign_endpoint(
|
||||
"http://ai.well-trust.com:9000",
|
||||
"host.docker.internal:9000",
|
||||
False,
|
||||
)
|
||||
# [断言意图] 正式环境浏览器入口是 9000,不能收成 80。
|
||||
assert endpoint == "ai.well-trust.com:9000"
|
||||
assert secure is False
|
||||
|
||||
|
||||
def test_resolve_presign_endpoint_falls_back_when_public_base_empty():
|
||||
"""公网基址为空时继续用内网端点,避免签出空主机。"""
|
||||
endpoint, secure = resolve_presign_endpoint("", "192.168.100.192:9000", False)
|
||||
# [断言意图] 未配置公网基址时行为与改前一致。
|
||||
assert endpoint == "192.168.100.192:9000"
|
||||
assert secure is False
|
||||
|
||||
|
||||
def test_presigned_get_url_uses_public_host(monkeypatch):
|
||||
"""正式环境下载链接的主机必须是 MINIO_PUBLIC_BASE_URL。"""
|
||||
_patch_minio_config(monkeypatch, public_base="http://ai.well-trust.com:9000")
|
||||
store = storage_mod.FileAssetStorage()
|
||||
monkeypatch.setattr(store, "_ensure_bucket_exists", lambda: None)
|
||||
|
||||
url = store.presigned_get_url(
|
||||
"shipping/outbound-reports/2026/10/1/abc.xlsx",
|
||||
expires_seconds=300,
|
||||
download_name="CRANE_20261020_1815.xlsx",
|
||||
)
|
||||
|
||||
# [断言意图] 浏览器打开的是公网 MinIO,签名里不能再出现容器内网主机。
|
||||
assert url.startswith(
|
||||
"http://ai.well-trust.com:9000/hxops-file-assets/shipping/outbound-reports/2026/10/1/abc.xlsx?"
|
||||
)
|
||||
assert "host.docker.internal" not in url
|
||||
assert "X-Amz-Signature=" in url
|
||||
assert "response-content-disposition=" in url
|
||||
# [断言意图] 读写仍走容器内网端点,避免把公网主机写进上传客户端。
|
||||
assert store.client is not store.presign_client
|
||||
assert store.client._base_url.host == "host.docker.internal:9000"
|
||||
assert store.presign_client._base_url.host == "ai.well-trust.com:9000"
|
||||
|
||||
|
||||
def test_presigned_get_url_reuses_client_when_hosts_match(monkeypatch):
|
||||
"""内网端点与公网基址相同时不另建客户端。"""
|
||||
_patch_minio_config(monkeypatch, public_base="http://host.docker.internal:9000")
|
||||
store = storage_mod.FileAssetStorage()
|
||||
# [断言意图] 开发环境两端点一致,预签名与读写共用同一客户端。
|
||||
assert store.presign_client is store.client
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
backend/tests/services/freight_rpa/test_crane_upload_recheck.py
|
||||
|
||||
用途:验证上传配置只保留开关,以及 Crane 分配中只排一次定时回查。
|
||||
依赖:page_contract、upload_attempt_service、crane_recheck、Flask 测试库。
|
||||
逻辑:先断言入口 URL 和行分类,再走 complete_attempt、定时回查和手动刷新。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.freight_rpa.upload.crane_recheck import (
|
||||
fire_scheduled_crane_recheck,
|
||||
request_manual_crane_refresh,
|
||||
)
|
||||
from app.services.freight_rpa.upload.page_contract import (
|
||||
build_upload_entry_url,
|
||||
classify_crane_order_row,
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
complete_attempt,
|
||||
project_notice_upload_status,
|
||||
start_rpa_attempt,
|
||||
)
|
||||
from tests.test_shipping_upload_attempt import _ready_artifact
|
||||
|
||||
|
||||
def test_upload_entry_url_comes_from_login_host_and_crane_row_is_classified():
|
||||
"""DBS/Crane 上传页由登录主机拼接;只有两句固定文案分别表示已分配和分配中。"""
|
||||
assert build_upload_entry_url('dbs', 'https://s360.dbschenker.com/login') == (
|
||||
'https://s360.dbschenker.com/main/portal/frame/WMSUpload2'
|
||||
)
|
||||
assert build_upload_entry_url('crane', 'https://wms-portal.craneww.com/') == (
|
||||
'https://wms-portal.craneww.com/#/shipping-order-upload'
|
||||
)
|
||||
assert classify_crane_order_row('Processing', 'Shipping Order Allocated') == 'allocated'
|
||||
assert classify_crane_order_row('Processing', 'Allocating the Shipping Order') == 'allocating'
|
||||
assert classify_crane_order_row('Completed', 'Shipping Order Allocated') == 'other'
|
||||
|
||||
|
||||
def test_allocating_schedules_one_recheck_and_blocks_another_upload(app):
|
||||
"""首次分配中写下 10 分钟回查;第二次回调不改到期时间,也不能重新上传。"""
|
||||
with app.app_context():
|
||||
notice, artifact, _reservation = _ready_artifact()
|
||||
artifact.file_name = 'MXI26082801.xlsx'
|
||||
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key')
|
||||
started = datetime(2026, 10, 23, 3, 0, 0)
|
||||
complete_attempt(attempt, success=False, callback_id='upload-1', result='allocating')
|
||||
# remember 使用 utcnow;这里只断言间隔为 10 分钟,不绑定测试开始时刻。
|
||||
due_at = datetime.fromisoformat(attempt.success_evidence_json['crane_recheck']['due_at'])
|
||||
assert timedelta(minutes=9) < due_at - datetime.utcnow() <= timedelta(minutes=10)
|
||||
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
|
||||
assert project_notice_upload_status(notice) == 'allocating'
|
||||
|
||||
complete_attempt(attempt, success=False, callback_id='recheck-1', result='allocating')
|
||||
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at.isoformat(timespec='seconds')
|
||||
|
||||
with pytest.raises(ConflictError) as blocked:
|
||||
start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key-2')
|
||||
assert blocked.value.code == 'SHIPPING.UPLOAD_CRANE_ALLOCATING'
|
||||
assert started < due_at
|
||||
|
||||
|
||||
def test_manual_refresh_does_not_move_the_one_scheduled_recheck(app):
|
||||
"""手动刷新另写一条状态回查,不改定时到期时间,也不把定时标记成已触发。"""
|
||||
with app.app_context():
|
||||
notice, artifact, _reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-manual')
|
||||
complete_attempt(attempt, success=False, callback_id='upload-manual', result='allocating')
|
||||
due_at = attempt.success_evidence_json['crane_recheck']['due_at']
|
||||
source = {'login_url': 'https://wms-portal.craneww.com/', 'connector_type': 'crane'}
|
||||
|
||||
first = request_manual_crane_refresh(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
|
||||
)
|
||||
assert first.endswith(f'upload_recheck_{notice.task_no}_manual.json')
|
||||
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
|
||||
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
|
||||
|
||||
with pytest.raises(ConflictError) as inflight:
|
||||
request_manual_crane_refresh(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
|
||||
)
|
||||
assert inflight.value.code == 'SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT'
|
||||
|
||||
future = datetime.fromisoformat(due_at) + timedelta(seconds=1)
|
||||
assert fire_scheduled_crane_recheck(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
|
||||
) is True
|
||||
assert fire_scheduled_crane_recheck(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
|
||||
) is False
|
||||
db.session.refresh(attempt)
|
||||
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
|
||||
assert attempt.success_evidence_json['crane_recheck']['fired'] is True
|
||||
@@ -1,16 +1,18 @@
|
||||
"""在途调拨单据级执行测试(execute_items 同步组合路径:门禁 + 组建单 + 逐单执行)。
|
||||
|
||||
用途:验证同步执行组合入口的两道门禁(①存在且可执行 ②文件版本对账,失败路径
|
||||
均携带 details 列表且外部系统 写入为 0;原「行级新鲜度 TTL」门禁已于
|
||||
2026-09-25 退役——items_stale 拒绝用例随之删除,TTL 降级为前端展示徽标)、
|
||||
D1 五元组建单与单据级写语义(一单一次 create_transfer、单内行共享单结果)、
|
||||
写前路由复查(漂移阻断)、result_unknown 不自动重试、单间失败隔离
|
||||
(不同组互不影响)、匹配 scope 执行入口(execute_matching_items)与按
|
||||
外部系统 单号投影。
|
||||
用途:验证同步执行组合入口的执行存在性门禁(①存在且可执行,失败携带 details
|
||||
列表且外部系统 写入为 0;原「文件版本对账」门禁已于 2026-10-22 退役——
|
||||
文件更新/缺失不再拦执行,行装饰 file_current 徽标仅提示,防错下沉 worker
|
||||
写前库存复查;原「行级新鲜度 TTL」门禁已于 2026-09-25 退役——items_stale
|
||||
拒绝用例随之删除,TTL 降级为前端展示徽标)、D1 五元组建单与单据级写语义
|
||||
(一单一次 create_transfer、单内行共享单结果)、写前路由复查(漂移阻断)、
|
||||
result_unknown 不自动重试、单间失败隔离(不同组互不影响)、匹配 scope
|
||||
执行入口(execute_matching_items)与按外部系统单号投影。
|
||||
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
|
||||
逻辑:T10 单据级重构后执行单元 = ERP 调拨单(TransferDocument);本文件为存量按行
|
||||
执行测试的按单改写版(场景不弱化:门禁/幂等/隔离/投影逐一保留);
|
||||
文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。
|
||||
来源文件状态投影经 patch_source_file_status 夹具注入替身(装饰断言另打
|
||||
matching_service 命名空间)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,6 +31,7 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
create_matching,
|
||||
list_executable_items,
|
||||
)
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
|
||||
@@ -252,35 +255,57 @@ def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_f
|
||||
assert _execution_runs() == []
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁②:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。"""
|
||||
# monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配",
|
||||
# (重跑匹配会把行原地刷成新版本,无法构造本场景)。
|
||||
def test_execute_items_proceeds_when_file_updated_and_decorates_not_current(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status, monkeypatch,
|
||||
):
|
||||
"""[2026-10-22 文件版本对账门禁退役] 文件已更新不再是执行门禁。
|
||||
|
||||
入站抓取是部分导出——新文件不含某行 ≠ 该行失效/已处理,按最新文件 sha
|
||||
对账曾把大量未处理行错误卡死(业务实测 557 行积压)。执行照常写 ERP;
|
||||
行装饰 file_current=False 仅提示不拦截,防错下沉 worker 写前库存复查。
|
||||
"""
|
||||
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
||||
# 装饰读取走 matching_service 命名空间的同名投影(退役后该函数仅剩展示
|
||||
# 消费方),此处同步打桩保持与执行侧替身同源。
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||
lambda *, source_code, record_kind="inbound": {
|
||||
"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": "REC-TEST", "file_sha256": "e" * 64,
|
||||
},
|
||||
)
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
# 断言:行当前性徽标如实提示「行评估版本戳 ≠ 最新可用文件」。
|
||||
listing = list_executable_items(deps=deps)
|
||||
decorated = {row.item_id: row for row in listing["items"]}
|
||||
assert all(decorated[item.id].file_current is False for item in items)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
assert _execution_runs() == []
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# 断言:徽标不拦截执行——同组两 Invoice 合并一单、一次写调用、行全 success。
|
||||
assert outcome.status == "success"
|
||||
assert len(erp.write_calls()) == 1
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in linked.values())
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁②:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。"""
|
||||
def test_execute_items_proceeds_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""[2026-10-22 门禁退役] 来源无可用文件同样不拦执行。
|
||||
|
||||
档是镜像事实,不随当日文件可用性消失(evidence_sync 已落档的行照常可执行)。
|
||||
"""
|
||||
patch_source_file_status({"DBS-AWSBI": None})
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# 断言:无可用文件不拒绝执行——照常组建单并写入外部系统。
|
||||
assert outcome.status == "success"
|
||||
assert len(erp.write_calls()) == 1
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in linked.values())
|
||||
|
||||
|
||||
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
|
||||
|
||||
用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、
|
||||
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
|
||||
匹配快照 Hash 稳定、缺文件等待与进度恢复、匹配顶替;专项用例锁生产默认 lag=2。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
|
||||
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
|
||||
外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行,
|
||||
@@ -1152,3 +1152,182 @@ def test_cancel_matching_releases_ledger_occupancy(transfer_db, dbs_ready_file):
|
||||
born = TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
assert len(born) == 2
|
||||
assert all(row.status == "ready_to_execute" for row in born)
|
||||
|
||||
|
||||
def test_create_matching_supersedes_covered_unwritten_matching(transfer_db, dbs_ready_file):
|
||||
"""新匹配盖住同一类型、同一来源、尚未写 ERP 的旧匹配时,旧匹配取消,货出现在新匹配上。
|
||||
|
||||
夹具两行异动日都是 2026-08-04。第一次与第二次都用 08-01~08-04,新范围盖住旧范围。
|
||||
"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
covered = dict(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
|
||||
first = create_matching(deps=deps, **covered)
|
||||
# [断言意图] 顶替前旧匹配自己先圈到夹具的两张单,证明后面的 2 不是「本来就没占上」。
|
||||
assert first.counts.executable_count == 2
|
||||
|
||||
second = create_matching(deps=deps, **covered)
|
||||
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
# [断言意图] 被盖住且未写 ERP 的旧匹配不再有效,其可执行行不能留在队列里二次写 ERP。
|
||||
assert first_matching.status == "cancelled"
|
||||
retired = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id).all()
|
||||
assert retired
|
||||
assert all(row.status == "cancelled" for row in retired)
|
||||
# [断言意图] 同一批货(HOM-001、HOX-002)出现在新匹配上,且仍可执行。
|
||||
assert second.counts.executable_count == 2
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
reborn = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
}
|
||||
assert reborn == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_create_matching_supersedes_covered_matching_with_only_blocked_rows(transfer_db, dbs_ready_file):
|
||||
"""全阻断的旧匹配状态虽是 success,只要还没写 ERP,新范围盖住时仍要顶替。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
covered = dict(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
first = create_matching(deps=deps, **covered)
|
||||
# [断言意图] 数量对不上时匹配状态是 success,不能因此被当成「已经写出单据」。
|
||||
assert first.status == "success"
|
||||
assert first.counts.executable_count == 0
|
||||
|
||||
second = create_matching(deps=deps, **covered)
|
||||
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
assert first_matching.status == "cancelled"
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
reborn = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
}
|
||||
assert reborn == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_create_matching_keeps_previous_when_new_range_does_not_cover(transfer_db, dbs_ready_file):
|
||||
"""新范围盖不住旧范围时,旧匹配保持有效,货仍留在旧匹配上。"""
|
||||
from app.models import TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
first = create_matching(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
second = create_matching(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-04",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
# [断言意图] 08-04~08-04 盖不住 08-01~08-04,旧匹配不能被取消。
|
||||
assert first_matching.status == "ready_to_execute"
|
||||
# [断言意图] 货仍被旧匹配占用,新匹配圈不到,清单不另列历史匹配编号。
|
||||
assert second.counts.executable_count == 0
|
||||
|
||||
|
||||
def test_supersede_keeps_manually_closed_goods_out_of_the_new_matching(transfer_db, dbs_ready_file):
|
||||
"""顶替后,人工关闭的单号不回到新匹配。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
covered = dict(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
first = create_matching(deps=deps, **covered)
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
closed = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id, invoice_no="HOX-002").one()
|
||||
manual_close_item(item_id=closed.id, reason="这批不再调拨")
|
||||
|
||||
second = create_matching(deps=deps, **covered)
|
||||
|
||||
# [断言意图] 人工关闭跨过顶替仍然有效,新匹配不能把 HOX-002 再圈成可执行。
|
||||
assert db.session.get(TransferInvoiceItem, closed.id).status == "manually_closed"
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
reborn = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
}
|
||||
assert reborn == {"HOM-001"}
|
||||
|
||||
|
||||
def test_unattached_item_does_not_block_a_new_matching(transfer_db, dbs_ready_file):
|
||||
"""没有挂上任何匹配的明细不占货,新匹配仍能圈到那张单。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching, TransferMovementLedger
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
ledger = TransferMovementLedger.query.filter_by(source_code="DBS-AWSBI", doc_no="HOM-001").first()
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None,
|
||||
ledger_record_id=ledger.id,
|
||||
source_code="DBS-AWSBI",
|
||||
invoice_no="HOM-001",
|
||||
material_no="MAT-001",
|
||||
movement_date="2026-08-04",
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
movement_quantity="1200",
|
||||
status="matching",
|
||||
result_code="pending_stock_check",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
|
||||
# [断言意图] 悬挂行没有匹配编号,不能挡住 HOM-001;两张夹具单都进新匹配。
|
||||
invoices = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||
}
|
||||
assert invoices == {"HOM-001", "HOX-002"}
|
||||
@@ -3,14 +3,20 @@
|
||||
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
|
||||
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
|
||||
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
|
||||
依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。
|
||||
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
|
||||
依赖:schedule.job_registry、job_options、inbound_trigger_service、
|
||||
transfer_type_config_service、in_transit_transfer_job。
|
||||
逻辑:只验证注册契约与调用形态(run_auto_transfer/run_daily_recovery 打桩),
|
||||
真实排程触发由 scheduler 驱动;七元组位序=(total, success, failed,
|
||||
skipped, results, errors, step_logs),errors 位只放真实错误。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome
|
||||
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome
|
||||
from app.services.schedule.job_options import is_known_options_source
|
||||
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
|
||||
|
||||
|
||||
@@ -22,14 +28,23 @@ def test_receipt_file_job_deregistered():
|
||||
|
||||
|
||||
def test_transfer_job_registered_with_schedule_defaults():
|
||||
"""自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。"""
|
||||
"""自动调拨 job 注册且含类型/来源/恢复参数契约;描述不得硬编码时刻。"""
|
||||
import re
|
||||
|
||||
job = get_platform_job("in-transit-transfer")
|
||||
assert job is not None
|
||||
assert job.enabled
|
||||
keys = {field.get("key") for field in job.params_schema}
|
||||
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
|
||||
assert {
|
||||
"transfer_types", "source_codes", "recover_history",
|
||||
"receipt_from_offset_days", "receipt_to_offset_days",
|
||||
} <= keys
|
||||
# 断言:调拨类型=multi_select 动态选项源(启用中的类型配置),留空=全部。
|
||||
types_field = next(f for f in job.params_schema if f.get("key") == "transfer_types")
|
||||
assert types_field.get("type") == "multi_select"
|
||||
assert types_field.get("options_source") == "transfer_types"
|
||||
assert types_field.get("default") == []
|
||||
assert is_known_options_source("transfer_types")
|
||||
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
|
||||
assert "notify_user_ids" not in keys
|
||||
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
||||
@@ -133,55 +148,108 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
|
||||
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
||||
|
||||
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
|
||||
def test_wanted_transfer_types_falls_back_to_all_enabled(monkeypatch):
|
||||
"""调拨类型留空=全部启用类型;显式选择优先;空配置/脏配置 fail-closed 落错误。"""
|
||||
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||
from app.services.schedule.in_transit_transfer_job import _wanted_transfer_types
|
||||
|
||||
errors: list[str] = []
|
||||
monkeypatch.setattr(type_mod, "get_enabled", lambda: [
|
||||
SimpleNamespace(code="in_transit_to_hub"), SimpleNamespace(code="hub_repair_out"),
|
||||
])
|
||||
assert _wanted_transfer_types({}, errors) == ["in_transit_to_hub", "hub_repair_out"]
|
||||
assert errors == []
|
||||
assert _wanted_transfer_types({"transfer_types": ["in_transit_to_hub"]}, errors) == ["in_transit_to_hub"]
|
||||
assert _wanted_transfer_types({"transfer_types": "hub_to_hub"}, errors) == ["hub_to_hub"]
|
||||
|
||||
monkeypatch.setattr(type_mod, "get_enabled", lambda: [])
|
||||
assert _wanted_transfer_types({}, errors) == []
|
||||
# 断言:空类型配置不静默——落错误由调用方硬失败(D8 fail-closed)。
|
||||
assert errors and "调拨类型" in errors[-1]
|
||||
|
||||
|
||||
def test_transfer_types_options_provider_lists_enabled(app, transfer_db):
|
||||
"""transfer_types 选项源:仅启用类型,label 取 names zh-CN,value=类型编码。"""
|
||||
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
|
||||
seed_transfer_type_config("in_transit_to_hub", enabled=True)
|
||||
seed_transfer_type_config("hub_repair_out", enabled=False)
|
||||
transfer_db.session.commit()
|
||||
|
||||
options = list_job_options("transfer_types")
|
||||
codes = {option["value"] for option in options}
|
||||
# 断言:停用类型不进选项(与排程留空=全部启用类型的口径一致)。
|
||||
assert "in_transit_to_hub" in codes
|
||||
assert "hub_repair_out" not in codes
|
||||
label = next(o["label"] for o in options if o["value"] == "in_transit_to_hub")
|
||||
assert label == "类型 in_transit_to_hub"
|
||||
|
||||
|
||||
def _patch_schedule_env(monkeypatch, *, types=None, sources=("CRANE_SGP",)):
|
||||
"""handler 单测公共打桩:来源/类型缺省口径 + 依赖与恢复隔离(不触库)。"""
|
||||
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: list(sources))
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
monkeypatch.setattr(
|
||||
type_mod, "get_enabled",
|
||||
lambda: [SimpleNamespace(code=code) for code in (types if types is not None else ["in_transit_to_hub"])],
|
||||
)
|
||||
return job_mod
|
||||
|
||||
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(全部类型均无 run 且无 errors):置静默标记抑制框架完成卡(C5)。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome()
|
||||
return AutoTransferOutcome()
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
|
||||
run = ScheduleRun(run_no="RUNR-1", status="running")
|
||||
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
total, success, failed, skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
|
||||
assert "sender" not in captured
|
||||
assert "recipients" not in captured
|
||||
# 断言:恢复在循环外只跑一次;run_auto_transfer 恒收 recover_history=False。
|
||||
assert captured["recover_history"] is False
|
||||
assert captured["movement_date_from"] is None
|
||||
assert captured["movement_date_to"] is None
|
||||
assert captured["source_codes"] == ["CRANE_SGP"]
|
||||
assert captured["recover_history"] is True
|
||||
assert captured["transfer_type"] == "in_transit_to_hub"
|
||||
assert run.response_summary_json["domain_notification_managed"] is True
|
||||
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
||||
assert results == []
|
||||
assert any("no executable items" in w for w in warnings)
|
||||
assert results == [] and errors == []
|
||||
# 断言:恢复汇总与空数据说明落 step_logs(dict),errors 位不受污染。
|
||||
assert step_logs[0]["step"] == "recovery"
|
||||
assert any(item.get("step") == "auto_transfer" for item in step_logs)
|
||||
|
||||
|
||||
def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
|
||||
from datetime import date
|
||||
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome()
|
||||
return AutoTransferOutcome()
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
|
||||
run = ScheduleRun(run_no="RUNR-4", status="running")
|
||||
@@ -195,79 +263,227 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
|
||||
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run with invalid offsets")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
run = ScheduleRun(run_no="RUNR-5", status="running")
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名;
|
||||
# failed_count=1 使终态为 failed(total=0+errors 会被框架误判 success,禁用)。
|
||||
assert (total, failed) == (1, 1)
|
||||
assert results == []
|
||||
assert any("异动日期起点" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
|
||||
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
||||
_total, _success, _failed, _skipped, _results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:小数偏移同样快速失败。
|
||||
assert any("异动日期终点" in e for e in errors)
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
def test_handler_runs_each_type_once_and_recovery_once(monkeypatch):
|
||||
"""多类型逐轮执行:每类型一次 run_auto_transfer(recover_history=False),恢复只跑一次。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=["in_transit_to_hub", "hub_repair_out"])
|
||||
recovery_calls: list[dict] = []
|
||||
|
||||
def _fake_recovery(**kwargs):
|
||||
recovery_calls.append(kwargs)
|
||||
return RecoveryOutcome(recovered_count=2)
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _fake_recovery)
|
||||
calls: list[dict] = []
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
calls.append(kwargs)
|
||||
return AutoTransferOutcome(run_no=f"TR-{len(calls)}", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={"transfer_types": ["in_transit_to_hub", "hub_repair_out"]})
|
||||
run = ScheduleRun(run_no="RUNR-6", status="running")
|
||||
total, success, failed, skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:逐类型各跑一轮且带类型编码;恢复与类型无关只跑一次。
|
||||
assert [c["transfer_type"] for c in calls] == ["in_transit_to_hub", "hub_repair_out"]
|
||||
assert all(c["recover_history"] is False for c in calls)
|
||||
assert len(recovery_calls) == 1
|
||||
# 断言:total=success+failed+recovered(2 成功 Run + 2 恢复行)。
|
||||
assert (total, success, failed, skipped) == (4, 2, 0, 0)
|
||||
assert [r["run_no"] for r in results] == ["TR-1", "TR-2"]
|
||||
assert errors == []
|
||||
# 断言:恢复汇总落 step_logs(recovered=2),errors 位只放真实错误。
|
||||
assert step_logs[0]["step"] == "recovery"
|
||||
assert step_logs[0]["detail"]["recovered"] == 2
|
||||
|
||||
|
||||
def test_handler_empty_type_config_fails_hard(monkeypatch):
|
||||
"""类型配置为空:fail-closed 硬失败(failed=1 → 框架 failed 终态),不执行。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=[])
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run without transfer types")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-7", status="running")
|
||||
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:空配置硬失败不执行、不静默,错误信息指向类型配置缺失。
|
||||
assert (total, failed) == (1, 1)
|
||||
assert results == []
|
||||
assert any("调拨类型" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-2", status="running")
|
||||
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
total, success, failed, skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
|
||||
# 断言:有 run 不抑制框架通知;run_no+类型落入 results 供完成卡/留痕展示。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results and results[0]["run_no"] == "TR-1"
|
||||
assert results[0]["transfer_type"] == "in_transit_to_hub"
|
||||
assert (total, success, failed, skipped) == (1, 1, 0, 0)
|
||||
assert errors == []
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
def test_handler_recovery_failure_counts_as_failed(monkeypatch):
|
||||
"""恢复复核抛异常:计一个 failed 单元——防止「恢复失败+空数据日」被框架判 success。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError("stock source offline")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _boom)
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
return AutoTransferOutcome() # 各类型均空数据(无 Run 无错误)
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-9", status="running")
|
||||
total, success, failed, _skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:恢复失败落 errors 且计 failed(终态 failed 交框架失败通知),
|
||||
# 恢复 step_log 标 failed;不置静默标记。
|
||||
assert (total, success, failed) == (1, 0, 1)
|
||||
assert results == []
|
||||
assert errors == ["recovery_failed: stock source offline"]
|
||||
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "failed"
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
|
||||
def test_handler_recovery_skipped_marks_step_log(monkeypatch):
|
||||
"""recover_history=false:恢复不执行,step_log 标 skipped 且不计 failed。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _must_not_recover(**_kwargs):
|
||||
raise AssertionError("run_daily_recovery must not run when recover_history is false")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _must_not_recover)
|
||||
monkeypatch.setattr(
|
||||
job_mod, "run_auto_transfer",
|
||||
lambda **_kwargs: AutoTransferOutcome(run_no="TR-10", run_status="success"),
|
||||
)
|
||||
|
||||
task = ScheduleTask(job_params={"recover_history": False})
|
||||
run = ScheduleRun(run_no="RUNR-10", status="running")
|
||||
total, success, failed, _skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:恢复被跳过(step_log=skipped、无恢复错误),Run 照常产出。
|
||||
assert (total, success, failed) == (1, 1, 0)
|
||||
assert results and results[0]["run_no"] == "TR-10"
|
||||
assert errors == []
|
||||
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "skipped"
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-3", status="running")
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
_total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results,
|
||||
# 该类型计入 failed_count(终态 failed 交框架失败通知)。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results == []
|
||||
assert errors == ["match pipeline boom"]
|
||||
assert failed == 1
|
||||
|
||||
|
||||
def test_handler_type_failure_isolated_per_type(monkeypatch):
|
||||
"""单类型硬失败不阻断其余类型;失败类型计入 failed,成功类型照常出 Run。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=["bad_type", "in_transit_to_hub"])
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
if kwargs["transfer_type"] == "bad_type":
|
||||
return AutoTransferOutcome(errors=["type config disabled"])
|
||||
return AutoTransferOutcome(run_no="TR-9", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-8", status="running")
|
||||
total, success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:好类型照常执行出 Run;坏类型落 errors 并计入 failed(部分失败终态)。
|
||||
assert (total, success, failed) == (2, 1, 1)
|
||||
assert len(results) == 1 and results[0]["transfer_type"] == "in_transit_to_hub"
|
||||
assert errors == ["type config disabled"]
|
||||
@@ -4,6 +4,7 @@ backend/tests/test_contract_payment_ledger_focus.py
|
||||
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
||||
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、进行中、本月应付合同后核对计数与 focus 筛选。
|
||||
金额和比例都为 0 的验收款不把合同算进逾期。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +13,7 @@ from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.services.contract_payment.ledger_focus import ledger_focus_counts
|
||||
from app.services.contract_payment.ledger_focus import classify_ledger_status, ledger_focus_counts
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
@@ -136,3 +137,37 @@ def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
|
||||
assert summary.get_json()['data']['active'] == 2
|
||||
assert 'needs_completion' not in summary.get_json()['data']
|
||||
assert empty.get_json()['data']['total'] == 0
|
||||
|
||||
|
||||
def test_zero_amount_stage_does_not_mark_contract_overdue():
|
||||
"""金额和比例都为 0 的阶段不参与逾期。"""
|
||||
status = classify_ledger_status(
|
||||
contract_status='active',
|
||||
parse_status='parsed',
|
||||
nodes=[
|
||||
{
|
||||
'status': 'paid',
|
||||
'percentage': '50',
|
||||
'amount': '4250.00',
|
||||
'due_date': date(2026, 9, 2),
|
||||
'anchor_date': date(2026, 9, 2),
|
||||
},
|
||||
{
|
||||
'status': 'active',
|
||||
'percentage': '0',
|
||||
'amount': '0.00',
|
||||
'due_date': date(2026, 9, 24),
|
||||
'anchor_date': date(2026, 9, 24),
|
||||
},
|
||||
{
|
||||
'status': 'active',
|
||||
'percentage': '0',
|
||||
'amount': '0.00',
|
||||
'due_date': date(2027, 3, 23),
|
||||
'anchor_date': date(2026, 9, 24),
|
||||
},
|
||||
],
|
||||
today=date(2026, 10, 27),
|
||||
)
|
||||
# 关键断言:预付款已付,验收款和质保款为 0,合同应为已完成而不是已逾期。
|
||||
assert status == 'completed'
|
||||
@@ -915,7 +915,14 @@ def test_erp_combined_payment_marks_prepayment_and_shipment_paid():
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
||||
|
||||
|
||||
def test_oa_company_dropdown_uses_selected_option(app):
|
||||
def test_erp_payment_matches_acceptance_amount_without_consuming_earlier_stages():
|
||||
"""关键断言:验收款金额单独命中时只标验收款,不把预付款或出货款记成已付。"""
|
||||
nodes = [
|
||||
(1, "prepayment", Decimal("16740")),
|
||||
(2, "shipment", Decimal("27900")),
|
||||
(3, "acceptance", Decimal("11160")),
|
||||
]
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("11160")]) == {3}
|
||||
"""关键断言:公司下拉框只取 selected 项,不把全部候选项拼进公司名。"""
|
||||
page = """
|
||||
<table><tr>
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
backend/tests/test_equipment_acceptance_e8.py
|
||||
|
||||
用途:E8 状态翻译、分组、查询语句,以及按使用部门担当组装收件人。
|
||||
依赖:e8_status、e8_group、e8_query、alert_service._drafts。不连接 OA,不启动 Flask。
|
||||
逻辑:暂停和撤销都停表。可以验收按 0=是翻转。第 1 档主送使用部门担当。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.alert_service import _drafts
|
||||
from app.services.equipment_acceptance.e8_group import group_e8_rows
|
||||
from app.services.equipment_acceptance.e8_query import build_e8_acceptance_sql
|
||||
from app.services.equipment_acceptance.e8_status import e8_flow_status
|
||||
from app.services.equipment_acceptance.snapshot_rules import EXCLUDED, classify_monitor_status
|
||||
|
||||
|
||||
def test_e8_null_status_follows_node_type_and_pause_stops():
|
||||
"""空的 currentstatus 看节点类型。暂停和撤销都收成 7。别的值不收成审批中。"""
|
||||
assert e8_flow_status("1", None) == 1
|
||||
assert e8_flow_status(" 3 ", "") == 3
|
||||
assert e8_flow_status("1", 0) == 7
|
||||
assert e8_flow_status("1", 1) == 7
|
||||
assert e8_flow_status("1", 9) is None
|
||||
|
||||
|
||||
def test_unknown_e8_status_is_not_watching():
|
||||
"""认不出的流程状态留空后,有计时起点也不进进行中。"""
|
||||
assert classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=None, timer_started=True
|
||||
) == EXCLUDED
|
||||
|
||||
|
||||
def test_e8_rows_group_owner_and_pending_handler():
|
||||
"""计时读 syddjssj,可以验收读 sfkys。当前未办人只留查询给出的 userid。"""
|
||||
drafts, skipped = group_e8_rows([
|
||||
{
|
||||
"requestid": 88,
|
||||
"ysddh": "YS-E8",
|
||||
"cgdh": "CG-1",
|
||||
"htbh": "HT-1",
|
||||
"flow_no": "LC-1",
|
||||
"request_title": "设备验收",
|
||||
"createdate": "2026-10-26",
|
||||
"createtime": "15:46:04",
|
||||
"syddjssj": "2026-08-01",
|
||||
"sfkys": 0,
|
||||
"sfzfth": None,
|
||||
"ycsm": "",
|
||||
"sybmdd": 15,
|
||||
"owner_name": "吴敏",
|
||||
"owner_job_num": "10086",
|
||||
"creater": 22,
|
||||
"applicant_name": "赵琴",
|
||||
"applicant_job_num": "20001",
|
||||
"currentnodetype": "1",
|
||||
"currentstatus": None,
|
||||
"currentnodeid": 6,
|
||||
"nodename": "使用部门担当",
|
||||
"userid": 15,
|
||||
"handler_name": "吴敏",
|
||||
"handler_job_num": "10086",
|
||||
},
|
||||
{"ysddh": "NO-ID"},
|
||||
])
|
||||
assert skipped == 1
|
||||
draft = drafts[0]
|
||||
assert draft.oa_system == "e8"
|
||||
assert draft.timer_started_at is not None
|
||||
assert draft.can_accept == 1
|
||||
assert draft.is_returned == 0
|
||||
assert draft.flow_status_raw == 1
|
||||
assert draft.owner_oa_id == 15
|
||||
assert draft.applicant_oa_id == 22
|
||||
assert draft.flow_no == "LC-1"
|
||||
assert draft.request_title == "设备验收"
|
||||
assert draft.request_created_at == datetime(2026, 10, 26, 15, 46, 4)
|
||||
assert [node.node_name for node in draft.nodes] == ["使用部门担当"]
|
||||
assert [item.user_id for item in draft.operators] == [15]
|
||||
|
||||
|
||||
def test_e8_sql_joins_current_node_and_unfinished_operator():
|
||||
"""当前节点用 currentnodeid。未办人用 isremark=0。不取流程编号。"""
|
||||
sql = build_e8_acceptance_sql().lower()
|
||||
assert "formtable_main_324" in sql
|
||||
assert "w.requestid = f.requestid" in sql
|
||||
assert "n.id = w.currentnodeid" in sql
|
||||
assert "op.nodeid = w.currentnodeid" in sql
|
||||
assert "isremark" in sql
|
||||
assert "w.currentnodetype is null" in sql
|
||||
assert "<> n'3'" in sql
|
||||
assert "w.creater" in sql
|
||||
assert "w.creator" not in sql
|
||||
assert "f.lcbh as flow_no" in sql
|
||||
assert "w.requestname as request_title" in sql
|
||||
assert "w.createdate" in sql
|
||||
assert "w.createtime" in sql
|
||||
assert "lastnodeid" not in sql
|
||||
|
||||
|
||||
def test_tier_one_sends_to_usage_owner_not_current_handler():
|
||||
"""第 1 档主送使用部门担当。当前节点上的另一名处理人不进收件人。"""
|
||||
order = SimpleNamespace(
|
||||
oa_system="e10",
|
||||
dwell_days=31,
|
||||
owner_oa_id=15,
|
||||
owner_name="吴敏",
|
||||
owner_job_num="10086",
|
||||
applicant_oa_id=22,
|
||||
applicant_name="赵琴",
|
||||
applicant_job_num="20001",
|
||||
)
|
||||
people = {
|
||||
15: {
|
||||
"name": "吴敏",
|
||||
"job_num": "10086",
|
||||
"superior_id": 30,
|
||||
"superior_name": "钱伟",
|
||||
"superior_job_num": "30001",
|
||||
"department_id": "9",
|
||||
},
|
||||
22: {"name": "赵琴", "job_num": "20001"},
|
||||
}
|
||||
deputies = {"9": [{"oa_id": 40, "name": "孙经理", "job_num": "40001"}]}
|
||||
users = {
|
||||
"10086": SimpleNamespace(id=7, wecom_userid="wx-owner", real_name="吴敏"),
|
||||
"30001": SimpleNamespace(id=8, wecom_userid="wx-boss", real_name="钱伟"),
|
||||
"20001": SimpleNamespace(id=9, wecom_userid="wx-buyer", real_name="赵琴"),
|
||||
"40001": SimpleNamespace(id=10, wecom_userid="wx-deputy", real_name="孙经理"),
|
||||
}
|
||||
drafts = _drafts(
|
||||
order,
|
||||
people,
|
||||
deputies,
|
||||
{},
|
||||
{},
|
||||
users,
|
||||
{},
|
||||
{"coo": None, "buyer": None, "executive": None},
|
||||
(30, 37, 44, 51),
|
||||
max_tier=3,
|
||||
)
|
||||
tier1 = drafts[0]
|
||||
assert tier1["tier"] == 1
|
||||
assert tier1["to_text"] == "吴敏"
|
||||
assert "钱伟" in (tier1["cc_text"] or "")
|
||||
assert "赵琴" in (tier1["cc_text"] or "")
|
||||
labels = [item["label"] for item in tier1["recipients"]]
|
||||
assert "当前处理人" not in labels
|
||||
assert "使用部门担当" in labels
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_equipment_acceptance_snapshot.py
|
||||
|
||||
用途:设备验收同步的状态、分组和 SQL 组装单测。
|
||||
依赖:snapshot_rules、source_group、query_sql。不连接 OA,也不启动 Flask。
|
||||
依赖:snapshot_rules、source_group、query_sql、sync_service 的搜索词整理。不连接 OA,也不启动 Flask。
|
||||
逻辑:停表规则、按 requestid 分组、SQL 不查 isremark,发送记录快照字段原样返回。
|
||||
"""
|
||||
|
||||
@@ -13,6 +13,7 @@ import pytest
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.query_sql import build_acceptance_sql, resolve_catalogs
|
||||
from app.services.equipment_acceptance.sync_service import _clean_search, _contains_pattern
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
EXCLUDED,
|
||||
NOT_STARTED,
|
||||
@@ -51,16 +52,16 @@ def test_returned_yes_stops_even_while_approving():
|
||||
assert status == STOPPED_RETURNED
|
||||
|
||||
|
||||
def test_cannot_accept_stops_and_null_can_accept_is_not_watching():
|
||||
"""can_accept=0 是不可以,停表;空值不是可以验收。"""
|
||||
def test_cannot_accept_stops_and_null_can_accept_still_watches():
|
||||
"""可以验收明确为否才停表。空值未标明,审批中且已计时仍监控。"""
|
||||
stopped = classify_monitor_status(
|
||||
can_accept=0, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
excluded = classify_monitor_status(
|
||||
watching = classify_monitor_status(
|
||||
can_accept=None, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
assert stopped == STOPPED_CANNOT_ACCEPT
|
||||
assert excluded == EXCLUDED
|
||||
assert watching == WATCHING
|
||||
|
||||
|
||||
def test_not_returned_and_can_accept_watches():
|
||||
@@ -204,10 +205,14 @@ def test_sql_uses_dictionary_catalogs_and_does_not_select_isremark():
|
||||
assert "workflow_requestbase" not in sql
|
||||
assert "[weaver_wfc].[dbo].[wfc_form_data]" in sql
|
||||
assert "d.dataid = f.FORM_DATA_ID" in sql
|
||||
assert "r.flowstatus is null or r.flowstatus <> 3" in sql.lower()
|
||||
assert "r.requestmark as flow_no" in sql.lower()
|
||||
assert "r.requestname as request_title" in sql.lower()
|
||||
assert "r.createdatetime" in sql.lower()
|
||||
assert "lcbh" not in sql
|
||||
assert "htbh1" not in sql
|
||||
assert "ysrq" not in sql
|
||||
assert "requestmark" not in sql
|
||||
assert "requestmark" in sql.lower()
|
||||
assert "operateround" not in sql.lower()
|
||||
assert "optgroupid" not in sql.lower()
|
||||
assert "batch_number" not in sql.lower()
|
||||
@@ -255,3 +260,11 @@ def test_send_record_payload_keeps_written_names():
|
||||
assert payload["threshold_days"] == 37
|
||||
assert payload["status"] == "sent"
|
||||
assert payload["sent_at"]
|
||||
|
||||
|
||||
def test_number_keyword_treats_like_wildcards_as_literal_text():
|
||||
"""单号搜索按包含匹配,% 和 _ 保持原字符,空白不参与过滤。"""
|
||||
assert _clean_search(" ") is None
|
||||
assert _clean_search(" 20260718 ") == "20260718"
|
||||
assert _contains_pattern("a%b_c") == "%a\\%b\\_c%"
|
||||
assert len(_clean_search("x" * 120) or "") == 100
|
||||
@@ -1410,7 +1410,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
|
||||
assert events[0] == ("session", "https://s360.dbschenker.com/")
|
||||
assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2")
|
||||
assert ("file", "#file2") in events
|
||||
assert ("file", "input#file2") in events
|
||||
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
|
||||
@@ -142,7 +142,7 @@ def _freeze_export_snapshot(
|
||||
|
||||
def _materialize_export_notice(
|
||||
*, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: FreightRpaOnhandReportFile,
|
||||
source_code: str, notice_no: str,
|
||||
source_code: str, notice_no: str, match_result: str = 'matched',
|
||||
) -> ShippingNotice:
|
||||
"""从 OT 的冻结快照构造正式 Notice、NoticeLine、匹配事实与活动库存链接。
|
||||
|
||||
@@ -168,7 +168,8 @@ def _materialize_export_notice(
|
||||
for line in snapshot.lines:
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no,
|
||||
match_result='matched', onhand_status='ready',
|
||||
line_index=int(line.line_no) - 1,
|
||||
match_result=match_result, onhand_status='ready',
|
||||
onhand_snapshot_id=inventory_file.id, source_code=source_code,
|
||||
is_current=True, detail_json={},
|
||||
))
|
||||
@@ -922,6 +923,8 @@ def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch
|
||||
|
||||
def _build_multi_odm_notice(
|
||||
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
|
||||
released_shortage: bool = False, unreleased_shortage: bool = False,
|
||||
order_part: str = 'PN-A', inventory_part: str | None = None,
|
||||
):
|
||||
"""
|
||||
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
|
||||
@@ -931,6 +934,11 @@ def _build_multi_odm_notice(
|
||||
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
|
||||
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
|
||||
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
|
||||
released_shortage: True 时唯一行构造为短缺放行场景——订单料号不在库存行
|
||||
(匹配键 0 命中)、事实落 not_found、并落已确认复核 Case 的系统放行决定
|
||||
(release_field_values 携带 ODM 证据值),整单无任何 matched 事实。
|
||||
unreleased_shortage: True 时事实落 not_found 但不落放行决定(未放行短缺)。
|
||||
order_part / inventory_part: 订单行与库存行的料号(放行场景两者必须不同)。
|
||||
Returns:
|
||||
(notice, customer)。
|
||||
"""
|
||||
@@ -979,7 +987,7 @@ def _build_multi_odm_notice(
|
||||
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}]
|
||||
specs = line_specs or [{'part': order_part, '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)
|
||||
@@ -998,7 +1006,7 @@ def _build_multi_odm_notice(
|
||||
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_rows.append({_inventory_field_id('part_number'): inventory_part or spec['part'], _inventory_field_id('odm_id'): odm})
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
|
||||
storage_path=str(tmp_path / 'odm-scope.xlsx'),
|
||||
@@ -1014,7 +1022,25 @@ def _build_multi_odm_notice(
|
||||
)
|
||||
notice = _materialize_export_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
|
||||
match_result='not_found' if (released_shortage or unreleased_shortage) else 'matched',
|
||||
)
|
||||
if released_shortage:
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='CASE-ODMSCOPE-RELEASE', run_id=931, unit_id=932, document_id=933,
|
||||
owner_user_id=1, status='confirmed', confirmed_task_id=int(ot.id),
|
||||
)
|
||||
db.session.add(case); db.session.flush()
|
||||
db.session.add(ShippingOrderReviewLineDecision(
|
||||
review_case_id=case.id, draft_line_id='line-1', line_index=0,
|
||||
decision_code='release_onhand_shortage', decision_source='system',
|
||||
line_status='released_shortage', is_active=True,
|
||||
snapshot_json={
|
||||
'release_field_values': {str(_inventory_field_id('odm_id')): 'ODM-1'},
|
||||
'release_evidence_scope': 'part_fallback',
|
||||
},
|
||||
))
|
||||
db.session.flush()
|
||||
if choice_odm is not None:
|
||||
for match in ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
|
||||
match.chosen_odm_id = choice_odm
|
||||
@@ -1113,6 +1139,60 @@ def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_export_released_shortage_only_notice_resolves_source_and_rows(app, tmp_path):
|
||||
"""整单短缺放行(0 条 matched 事实)也能解析库存源并按放行证据导出。
|
||||
|
||||
回归 OT-20261027-4BD4CEFF:预约键 0 命中→料号兜底自动放行后,行事实恒为
|
||||
not_found;_notice_source_code 只认 matched 会让整单放行的单报
|
||||
「库存源不存在或已停用」;prepare_export_match_inputs 的放行决定 join 须按
|
||||
confirmed_task_id(OT) 回链,Notice 身份调用不得丢放行行。
|
||||
"""
|
||||
from app.services.shipping_notice.export import _notice_source_code, prepare_export_match_inputs
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
notice, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, released_shortage=True,
|
||||
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
|
||||
)
|
||||
|
||||
# 断言意图 1:源解析把放行行事实与 matched 行同票,整单放行也能拿到唯一源。
|
||||
assert _notice_source_code(notice) == 'ODMSCOPE'
|
||||
|
||||
# 断言意图 2:以 Notice 身份准备导出输入,放行决定经 OT 回链可查到,
|
||||
# 放行行进入导出行集并携带审计补录值(无 matched 事实也不报「没有匹配」)。
|
||||
inputs = prepare_export_match_inputs(notice)
|
||||
assert inputs['released_snapshot_line_ids']
|
||||
assert inputs['released_export_line_indexes'] == {0}
|
||||
assert list(inputs['release_overrides_by_line'][0].values()) == ['ODM-1']
|
||||
assert [row['__order_line_index'] for row in inputs['line_values']] == [0]
|
||||
|
||||
# 断言意图 3:整单放行时证据快照仍落 Artifact 审计(matched-only 不再断证据链)。
|
||||
assert inputs['verification'] is not None
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(notice)
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-1'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_unreleased_shortage_notice_still_lacks_source(app, tmp_path):
|
||||
"""未放行的短缺行不得参与源解析:matched-only 语义对未放行场景保持不变。"""
|
||||
from app.services.shipping_notice.export import _notice_source_code
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
notice, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, unreleased_shortage=True,
|
||||
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
|
||||
)
|
||||
|
||||
# 断言意图:not_found 且无放行决定的事实不充当导出源依据(fail-closed 不变)。
|
||||
assert _notice_source_code(notice) is None
|
||||
|
||||
|
||||
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
|
||||
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
|
||||
from app.core.errors import AppError
|
||||
|
||||
@@ -3,13 +3,15 @@ backend/tests/test_voucher_check_permissions.py
|
||||
|
||||
用途:验收立账凭证改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、workspace voucher_check 蓝图。
|
||||
逻辑:授予 voucher_check Agent 后可查询任务列表,但不能触发强制重检、也不能改通知配置。
|
||||
逻辑:授予 voucher_check Agent 后可查询任务列表并下载企微记录 Excel,但不能触发强制重检、也不能改通知配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, User
|
||||
from app.models import Agent, ScheduleRun, ScheduleTask, User, VoucherCheckRun
|
||||
|
||||
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
@@ -176,3 +178,63 @@ def test_voucher_check_notify_config_requires_admin(client, app):
|
||||
)
|
||||
assert put_res.status_code == 403
|
||||
assert _json_error(put_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
|
||||
|
||||
def test_voucher_check_excel_download_uses_agent_access_not_schedule_notify(client, app):
|
||||
"""企微发送记录的 Excel 按立账凭证访问权下载,不要求是排程负责人或通知人。"""
|
||||
payload = b'voucher-excel'
|
||||
with app.app_context():
|
||||
owner = _create_user(username='vc_excel_owner')
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_excel_viewer'))
|
||||
denied = _create_user(username='vc_excel_denied')
|
||||
task = ScheduleTask(
|
||||
schedule_no='VC-EXCEL-1',
|
||||
name='立账凭证周检',
|
||||
owner_user_id=owner.id,
|
||||
cron_expr='0 6 * * 2',
|
||||
notify_user_ids_json=[],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
schedule_run = ScheduleRun(
|
||||
run_no='RUN-VC-EXCEL-1',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
excel_file_data=payload,
|
||||
excel_file_name='voucher_check.xlsx',
|
||||
excel_file_size=len(payload),
|
||||
)
|
||||
db.session.add(schedule_run)
|
||||
db.session.flush()
|
||||
db.session.add(VoucherCheckRun(
|
||||
id=88001,
|
||||
schedule_run_id=schedule_run.id,
|
||||
run_no='RUN-VC-EXCEL-1',
|
||||
profile_code='sales',
|
||||
profile_version='1',
|
||||
profile_snapshot_json={},
|
||||
period_month=date(2026, 9, 1),
|
||||
mode='incremental',
|
||||
status='success',
|
||||
))
|
||||
db.session.commit()
|
||||
schedule_run_id = schedule_run.id
|
||||
granted_id = granted.id
|
||||
denied_id = denied.id
|
||||
|
||||
granted_headers = {'X-User-Id': str(granted_id), 'X-Username': 'vc_excel_viewer'}
|
||||
url = f'/api/workspace/accounting-voucher-check/schedule-runs/{schedule_run_id}/excel'
|
||||
ok_res = client.get(url, headers=granted_headers)
|
||||
# 关键断言:不是排程通知人时,立账凭证授权用户仍能拿到 Excel 正文。
|
||||
assert ok_res.status_code == 200
|
||||
assert ok_res.data == payload
|
||||
|
||||
denied_headers = {'X-User-Id': str(denied_id), 'X-Username': 'vc_excel_denied'}
|
||||
denied_res = client.get(url, headers=denied_headers)
|
||||
assert denied_res.status_code == 403
|
||||
assert _json_error(denied_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
||||
|
||||
legacy = client.get(f'/api/workspace/schedule-runs/{schedule_run_id}/excel', headers=granted_headers)
|
||||
# 关键断言:旧排程下载口仍只认负责人/通知人,企微记录不能再走这条。
|
||||
assert legacy.status_code == 403
|
||||
assert _json_error(legacy)['code'] == 'AUTH.FORBIDDEN'
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
tests/test_wecom_textcard_source.py
|
||||
|
||||
用途:断言企微 textcard 标题带来源,以及账号类通知不加来源。
|
||||
依赖:app fixture、integrations.wecom.notify。
|
||||
逻辑:直接调用标题函数与发送出口,不经过具体业务模块。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.integrations.wecom.notify import (
|
||||
_with_agent_source_title,
|
||||
send_wecom_event_message,
|
||||
send_wecom_textcard_message,
|
||||
)
|
||||
|
||||
|
||||
def test_agent_source_prefix_stays_when_title_is_truncated():
|
||||
"""超长业务标题截断后,来源前缀仍完整留在最前面。"""
|
||||
title = _with_agent_source_title('缺' * 200)
|
||||
# [断言意图] 前缀不被 120 字上限切掉,业务标题从末尾被截断。
|
||||
assert title.startswith('AI智能体 · ')
|
||||
assert len(title) == 120
|
||||
assert title == f"AI智能体 · {'缺' * 112}"
|
||||
|
||||
|
||||
def test_agent_source_prefix_is_not_repeated():
|
||||
"""已经带来源的标题不再加第二次。"""
|
||||
once = _with_agent_source_title('精益管理培训逾期提醒')
|
||||
twice = _with_agent_source_title(once)
|
||||
# [断言意图] 重复经过发送出口时标题保持单层来源。
|
||||
assert once == 'AI智能体 · 精益管理培训逾期提醒'
|
||||
assert twice == once
|
||||
|
||||
|
||||
def test_textcard_payload_uses_agent_source_title(app, monkeypatch):
|
||||
"""实际发给企业微信的 textcard.title 带来源,调用方传入的仍是业务标题。"""
|
||||
captured = {}
|
||||
|
||||
def _fake_post(_url, params=None, json=None, timeout=None):
|
||||
captured['json'] = json
|
||||
|
||||
class _Resp:
|
||||
def json(self):
|
||||
return {'errcode': 0}
|
||||
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.integrations.wecom.notify._get_access_token',
|
||||
lambda: 'token',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.integrations.wecom.notify.requests.post',
|
||||
_fake_post,
|
||||
)
|
||||
with app.app_context():
|
||||
app.config['WECOM_AGENT_ID'] = '1000002'
|
||||
send_wecom_textcard_message(
|
||||
'wx-user',
|
||||
'销售开票附件缺件提醒',
|
||||
'正文',
|
||||
'https://example.com/detail',
|
||||
)
|
||||
# [断言意图] 企微载荷标题带来源,正文和按钮保持原样。
|
||||
assert captured['json']['textcard']['title'] == 'AI智能体 · 销售开票附件缺件提醒'
|
||||
assert captured['json']['textcard']['description'] == '正文'
|
||||
assert captured['json']['textcard']['btntxt'] == '查看详情'
|
||||
|
||||
|
||||
def test_account_events_keep_business_title(app, monkeypatch):
|
||||
"""密码重置和权限变更不加来源;业务提醒仍然加上。"""
|
||||
captured = {}
|
||||
|
||||
def _fake_send(_userid, title, _description, _jump_url, *, with_agent_source=True):
|
||||
captured['title'] = title
|
||||
captured['with_agent_source'] = with_agent_source
|
||||
return {'errcode': 0}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.integrations.wecom.notify.send_wecom_textcard_message',
|
||||
_fake_send,
|
||||
)
|
||||
with app.app_context():
|
||||
app.config['WECOM_NOTIFY_ENABLED'] = True
|
||||
app.config['WECOM_NOTIFY_EVENTS'] = (
|
||||
'password_reset,permission_request_approved,lean_training_overdue'
|
||||
)
|
||||
user = User(
|
||||
username='source-user',
|
||||
email='source@example.com',
|
||||
role='user',
|
||||
wecom_userid='wx-source',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
send_wecom_event_message(
|
||||
event_type='password_reset',
|
||||
user=user,
|
||||
title='和信AI智能工作台 密码重置',
|
||||
content='请重置密码',
|
||||
jump_url='https://example.com/reset',
|
||||
)
|
||||
# [断言意图] 密码重置不是智能体推送,发送出口关闭来源前缀。
|
||||
assert captured['with_agent_source'] is False
|
||||
assert captured['title'] == '和信AI智能工作台 密码重置'
|
||||
|
||||
send_wecom_event_message(
|
||||
event_type='permission_request_approved',
|
||||
user=user,
|
||||
title='权限申请已通过',
|
||||
content='已通过',
|
||||
)
|
||||
# [断言意图] 权限变更与密码重置同一排除名单。
|
||||
assert captured['with_agent_source'] is False
|
||||
|
||||
send_wecom_event_message(
|
||||
event_type='lean_training_overdue',
|
||||
user=user,
|
||||
title='精益管理培训逾期提醒',
|
||||
content='请完成学习',
|
||||
)
|
||||
# [断言意图] 业务提醒仍把来源交给 textcard 出口添加。
|
||||
assert captured['with_agent_source'] is True
|
||||
assert captured['title'] == '精益管理培训逾期提醒'
|
||||
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_dms_archive.py
|
||||
|
||||
用途:销售一期第 5 步归档(建文件夹、复制、同名跳过)单测。
|
||||
依赖:pytest;不连文档库。
|
||||
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy;断言同名不覆盖、缺月目录为技术失败。
|
||||
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy/Rename/Recycle;断言同名不覆盖、带「重命名」的落盘名改回原名、多余副本删除、缺月目录为技术失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,6 +19,10 @@ from app.services.voucher_check.dms_client import (
|
||||
SalesDmsClient,
|
||||
_extract_item_id,
|
||||
_is_name_conflict,
|
||||
canonical_leaf_name,
|
||||
dms_stored_leaf_name,
|
||||
leaf_names_match,
|
||||
row_display_name,
|
||||
)
|
||||
|
||||
|
||||
@@ -55,6 +59,280 @@ def test_ensure_folder_creates_when_missing(monkeypatch):
|
||||
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "new-folder"
|
||||
|
||||
|
||||
def test_recycle_items_posts_library_delete(monkeypatch):
|
||||
# 与文档库列表「删除」同一接口:ItemID 数组,进入回收站。
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
def post(path, payload, **_kwargs):
|
||||
seen["path"] = path
|
||||
seen["payload"] = payload
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
|
||||
SalesDmsClient.recycle_items(item_ids=["extra-1", "extra-2"])
|
||||
assert seen["path"] == "/Api/_api/APS/Public/Item/Recycle"
|
||||
assert seen["payload"] == {"ItemID": ["extra-1", "extra-2"]}
|
||||
|
||||
|
||||
def test_rename_item_posts_library_rename(monkeypatch):
|
||||
# 与文档库列表「重命名」同一接口:ItemID + 改回后的 LeafName。
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
def post(path, payload, **_kwargs):
|
||||
seen["path"] = path
|
||||
seen["payload"] = payload
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
|
||||
SalesDmsClient.rename_item(item_id="dest-r", leaf_name="INV001.pdf")
|
||||
assert seen["path"] == "/Api/_api/APS/Public/Item/Rename"
|
||||
assert seen["payload"] == {"ItemID": "dest-r", "LeafName": "INV001.pdf"}
|
||||
|
||||
|
||||
def test_canonical_leaf_name_strips_dms_rename_marker():
|
||||
# 现网复制后的名字是「原名.pdf(重命名).pdf」,还原后必须等于业务文件名。
|
||||
assert canonical_leaf_name("AK260929062-8501-2609290005.pdf(重命名).pdf") == (
|
||||
"AK260929062-8501-2609290005.pdf"
|
||||
)
|
||||
assert canonical_leaf_name("INV001(重命名).pdf") == "INV001.pdf"
|
||||
assert canonical_leaf_name("INV001.pdf") == "INV001.pdf"
|
||||
assert leaf_names_match("AK260929062-8501-2609290005.pdf(重命名).pdf", "AK260929062-8501-2609290005.pdf")
|
||||
assert leaf_names_match("OTHER.pdf(重命名).pdf", "AK260929062-8501-2609290005.pdf") is False
|
||||
assert canonical_leaf_name("QCG260921187-8501-2609210008.pdf (重命名) .pdf") == (
|
||||
"QCG260921187-8501-2609210008.pdf"
|
||||
)
|
||||
# 库内真实名字不带界面补上的第二个 .pdf。改回带 .pdf 的原名会被文档库判成同名。
|
||||
stored = "QCH2609188245-8501-2609170001.pdf(重命名)"
|
||||
assert canonical_leaf_name(stored) == "QCH2609188245-8501-2609170001.pdf"
|
||||
assert dms_stored_leaf_name("QCH2609188245-8501-2609170001.pdf") == "QCH2609188245-8501-2609170001"
|
||||
assert row_display_name({
|
||||
"LeafName": stored,
|
||||
"MainFileAttachment": {"Extension": ".pdf"},
|
||||
}) == "QCH2609188245-8501-2609170001.pdf(重命名).pdf"
|
||||
|
||||
|
||||
def test_find_child_file_accepts_renamed_copy(monkeypatch):
|
||||
# 目录里只有带「重命名」的文件时,按原名查找应命中,避免再次复制。
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{
|
||||
"ID": "dest-r",
|
||||
"LeafName": "AK260929062-8501-2609290005.pdf(重命名).pdf",
|
||||
"IsFolder": False,
|
||||
}],
|
||||
)
|
||||
row = SalesDmsClient.find_child_file(
|
||||
parent_folder_id="inv-folder",
|
||||
leaf_name="AK260929062-8501-2609290005.pdf",
|
||||
)
|
||||
assert row is not None
|
||||
assert row["ID"] == "dest-r"
|
||||
|
||||
|
||||
def test_copy_renames_existing_suffix_back_to_original(monkeypatch):
|
||||
# 目录里只有带「重命名」的文件时,改回原名,不再复制出新文件。
|
||||
files = {"rows": [{"ID": "dest-r", "LeafName": "INV001.pdf(重命名).pdf"}]}
|
||||
copies: list[object] = []
|
||||
renames: list[dict[str, str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return files["rows"]
|
||||
|
||||
def rename_item(**kwargs):
|
||||
renames.append(kwargs)
|
||||
files["rows"] = [{"ID": kwargs["item_id"], "LeafName": kwargs["leaf_name"]}]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copies.append(kwargs))
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["LeafName"] == "INV001"
|
||||
assert renames == [{"item_id": "dest-r", "leaf_name": "INV001"}]
|
||||
assert copies == []
|
||||
|
||||
|
||||
def test_copy_strips_rename_suffix_after_copy(monkeypatch):
|
||||
# 复制成功但落盘名带「重命名」时,立刻改回业务原名。
|
||||
files: dict[str, list[dict[str, str]]] = {"rows": []}
|
||||
renames: list[dict[str, str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return files["rows"]
|
||||
|
||||
def copy_items(**_kwargs):
|
||||
files["rows"] = [{"ID": "new-1", "LeafName": "INV001.pdf(重命名).pdf"}]
|
||||
return {"Code": 0}
|
||||
|
||||
def rename_item(**kwargs):
|
||||
renames.append(kwargs)
|
||||
files["rows"] = [{"ID": kwargs["item_id"], "LeafName": kwargs["leaf_name"]}]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", copy_items)
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is False
|
||||
assert row["ID"] == "new-1"
|
||||
assert row["LeafName"] == "INV001"
|
||||
assert renames == [{"item_id": "new-1", "leaf_name": "INV001"}]
|
||||
|
||||
|
||||
def test_copy_keeps_original_and_recycles_renamed_extras(monkeypatch):
|
||||
# 原名已在时不再复制、不再改名,只删除仍带「重命名」的多余副本。
|
||||
files = {
|
||||
"rows": [
|
||||
{"ID": "clean", "LeafName": "INV001.pdf"},
|
||||
{"ID": "extra", "LeafName": "INV001.pdf(重命名).pdf"},
|
||||
{"ID": "other", "LeafName": "别的资料.pdf"},
|
||||
]
|
||||
}
|
||||
recycled: list[list[str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return list(files["rows"])
|
||||
|
||||
def recycle_items(**kwargs):
|
||||
recycled.append(list(kwargs["item_ids"]))
|
||||
drop = set(kwargs["item_ids"])
|
||||
files["rows"] = [row for row in files["rows"] if row["ID"] not in drop]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应改名")))
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", recycle_items)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "clean"
|
||||
assert recycled == [["extra"]]
|
||||
assert [item["ID"] for item in files["rows"]] == ["clean", "other"]
|
||||
|
||||
|
||||
def test_copy_restores_one_of_three_renamed_copies_and_recycles_the_rest(monkeypatch):
|
||||
# 9 月这类目录只有三份带后缀的同一文件时:改回一份原名,删除另外两份。
|
||||
wanted = "QCG260921187-8501-2609210008.pdf"
|
||||
renamed = f"{wanted}(重命名).pdf"
|
||||
files = {
|
||||
"rows": [
|
||||
{"ID": "a", "LeafName": renamed},
|
||||
{"ID": "b", "LeafName": renamed},
|
||||
{"ID": "c", "LeafName": f"{wanted} (重命名) .pdf"},
|
||||
]
|
||||
}
|
||||
recycled: list[list[str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return list(files["rows"])
|
||||
|
||||
def rename_item(**kwargs):
|
||||
for item in files["rows"]:
|
||||
if item["ID"] == kwargs["item_id"]:
|
||||
item["LeafName"] = kwargs["leaf_name"]
|
||||
return {"Code": 0}
|
||||
|
||||
def recycle_items(**kwargs):
|
||||
recycled.append(list(kwargs["item_ids"]))
|
||||
drop = set(kwargs["item_ids"])
|
||||
files["rows"] = [row for row in files["rows"] if row["ID"] not in drop]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", recycle_items)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name=wanted,
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "a"
|
||||
assert row["LeafName"] == "QCG260921187-8501-2609210008"
|
||||
assert recycled == [["b", "c"]]
|
||||
assert [item["ID"] for item in files["rows"]] == ["a"]
|
||||
|
||||
|
||||
def test_copy_renames_real_dms_leaf_without_extension(monkeypatch):
|
||||
# 现网 LeafName 是「原名.pdf(重命名)」,扩展名在附件上。改名必须去掉扩展名,不能写成「原名.pdf」。
|
||||
wanted = "QCH2609188245-8501-2609170001.pdf"
|
||||
stored = f"{wanted}(重命名)"
|
||||
files = {
|
||||
"rows": [
|
||||
{"ID": "a", "LeafName": stored, "MainFileAttachment": {"Extension": ".pdf"}},
|
||||
{"ID": "b", "LeafName": stored, "MainFileAttachment": {"Extension": ".pdf"}},
|
||||
]
|
||||
}
|
||||
renames: list[dict[str, str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return list(files["rows"])
|
||||
|
||||
def rename_item(**kwargs):
|
||||
renames.append(kwargs)
|
||||
for item in files["rows"]:
|
||||
if item["ID"] == kwargs["item_id"]:
|
||||
item["LeafName"] = kwargs["leaf_name"]
|
||||
return {"Code": 0}
|
||||
|
||||
def recycle_items(**kwargs):
|
||||
drop = set(kwargs["item_ids"])
|
||||
files["rows"] = [row for row in files["rows"] if row["ID"] not in drop]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", recycle_items)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name=wanted,
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "a"
|
||||
assert renames == [{"item_id": "a", "leaf_name": "QCH2609188245-8501-2609170001"}]
|
||||
assert [item["ID"] for item in files["rows"]] == ["a"]
|
||||
|
||||
|
||||
def test_copy_skips_when_stored_leaf_is_already_the_stem(monkeypatch):
|
||||
# 改名成功后 LeafName 是不带扩展名的原名,下次检核不能再复制。
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{
|
||||
"ID": "a",
|
||||
"LeafName": "QCH2609188245-8501-2609170001",
|
||||
"MainFileAttachment": {"Extension": ".pdf"},
|
||||
}],
|
||||
)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应改名")))
|
||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应删除")))
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="QCH2609188245-8501-2609170001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "a"
|
||||
|
||||
|
||||
def test_copy_skips_when_dest_has_same_name(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
@@ -63,6 +341,11 @@ def test_copy_skips_when_dest_has_same_name(monkeypatch):
|
||||
)
|
||||
calls: list[object] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: calls.append(kwargs))
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{"ID": "dest-1", "LeafName": "INV001.pdf"}],
|
||||
)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
@@ -83,6 +366,11 @@ def test_copy_when_dest_has_no_same_name(monkeypatch):
|
||||
return {"ID": "dest-2", "LeafName": "INV001.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{"ID": "dest-2", "LeafName": "INV001.pdf"}],
|
||||
)
|
||||
copied: list[dict] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copied.append(kwargs) or {"Code": 0})
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
@@ -105,6 +393,11 @@ def test_copy_treats_api_same_name_error_as_skip(monkeypatch):
|
||||
return {"ID": "dest-3", "LeafName": "INV001.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{"ID": "dest-3", "LeafName": "INV001.pdf"}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"copy_items",
|
||||
|
||||
@@ -294,7 +294,7 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
||||
po_title, po_body = next((item[1], item[2]) for item in sent if item[0] == "wx-po-recv")
|
||||
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
||||
# 关键断言:卡片面向销售开票附件,不暴露业务方代号和批次号。
|
||||
assert po_title == "销售开票附件缺件"
|
||||
assert po_title == "销售开票附件缺件提醒"
|
||||
assert "2026年8月" in po_body
|
||||
assert "缺 2 份,涉及 1 张发票" in po_body
|
||||
assert "业务方" not in po_body
|
||||
|
||||
Reference in new issue
Block a user