From f3050164d043e6fa8074d30d850f015b4d16a74c Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Fri, 28 Aug 2026 17:12:33 +0800 Subject: [PATCH 1/2] =?UTF-8?q?refactor(rpa):=20=E9=87=8D=E6=9E=84=20scrip?= =?UTF-8?q?ts/rpa=20=E7=9B=AE=E5=BD=95=E7=BB=93=E6=9E=84=E4=B8=8E=E5=91=BD?= =?UTF-8?q?=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按 common/connectors/inventory/receipt 分层并重命名 - common/: rpa_common, rpa_heartbeat, download_artifact_fallback, new_rpa_worker_secret - connectors/dsv|crane/: 登录网站连接器,库存与收料共用 - inventory/: inventory_rpa_worker, run_inventory_batch_trigger, start_inventory_worker, register_inventory_worker_tasks - receipt/: receipt_rpa_worker, receipt_crane/dbs_export, start_receipt_worker 保留裸 import + sys.path 引导;修正懒加载路径; 按范围命名 register_rpa_background_tasks -> register_inventory_worker_tasks; 同步 backend 测试、start_local.ps1、.env 注释、docs 与 README 路径。 --- .env.dev | 2 +- .env.test | 4 +- backend/tests/test_crane_navigation.py | 2 +- backend/tests/test_crane_report_export.py | 2 +- backend/tests/test_crane_session.py | 4 +- backend/tests/test_dsv_report_parameters.py | 2 +- .../test_freight_receipt_worker_contract.py | 8 +- backend/tests/test_freight_rpa_heartbeat.py | 2 +- backend/tests/test_freight_rpa_worker.py | 6 +- ...est_freight_rpa_worker_inventory_params.py | 15 +- .../2026-08-19-freight-receipt-rpa-minimal.md | 10 +- docs/features/shipping-notice/technical.md | 56 +++---- scripts/rpa/README.md | 155 +++++++++--------- .../download_artifact_fallback.py | 0 .../{ => common}/new_rpa_worker_secret.ps1 | 0 scripts/rpa/{ => common}/rpa_common.py | 17 +- .../rpa_heartbeat.py} | 17 +- .../crane}/crane_login_smoke.py | 6 +- .../crane}/crane_navigation.py | 0 .../crane}/crane_report_export.py | 0 .../{ => connectors/crane}/crane_session.py | 0 scripts/rpa/{ => connectors/dsv}/dsv_auth.py | 15 ++ .../dsv}/dsv_auth_login_flow.py | 15 ++ scripts/rpa/{ => connectors/dsv}/dsv_debug.py | 17 +- .../rpa/{ => connectors/dsv}/dsv_driver.py | 15 ++ .../dsv}/dsv_export_timeout_diagnostics.py | 0 .../{ => connectors/dsv}/dsv_login_smoke.py | 6 +- .../{ => connectors/dsv}/dsv_navigation.py | 15 ++ .../{ => connectors/dsv}/dsv_report_export.py | 15 ++ .../dsv}/dsv_report_parameters.py | 0 .../rpa/{ => connectors/dsv}/dsv_session.py | 15 ++ .../inventory_rpa_worker.py} | 34 ++-- .../register_inventory_worker_tasks.ps1} | 20 +-- .../run_inventory_batch_trigger.py | 7 +- .../start_inventory_worker.ps1} | 2 +- .../receipt_crane_export.py} | 15 ++ .../receipt_dbs_export.py} | 15 ++ .../receipt_rpa_worker.py} | 33 ++-- .../start_receipt_worker.ps1} | 5 +- scripts/start_local.ps1 | 4 +- 40 files changed, 384 insertions(+), 172 deletions(-) rename scripts/rpa/{ => common}/download_artifact_fallback.py (100%) rename scripts/rpa/{ => common}/new_rpa_worker_secret.ps1 (100%) rename scripts/rpa/{ => common}/rpa_common.py (96%) rename scripts/rpa/{freight_rpa_heartbeat.py => common/rpa_heartbeat.py} (94%) rename scripts/rpa/{ => connectors/crane}/crane_login_smoke.py (90%) rename scripts/rpa/{ => connectors/crane}/crane_navigation.py (100%) rename scripts/rpa/{ => connectors/crane}/crane_report_export.py (100%) rename scripts/rpa/{ => connectors/crane}/crane_session.py (100%) rename scripts/rpa/{ => connectors/dsv}/dsv_auth.py (98%) rename scripts/rpa/{ => connectors/dsv}/dsv_auth_login_flow.py (97%) rename scripts/rpa/{ => connectors/dsv}/dsv_debug.py (95%) rename scripts/rpa/{ => connectors/dsv}/dsv_driver.py (62%) rename scripts/rpa/{ => connectors/dsv}/dsv_export_timeout_diagnostics.py (100%) rename scripts/rpa/{ => connectors/dsv}/dsv_login_smoke.py (91%) rename scripts/rpa/{ => connectors/dsv}/dsv_navigation.py (98%) rename scripts/rpa/{ => connectors/dsv}/dsv_report_export.py (99%) rename scripts/rpa/{ => connectors/dsv}/dsv_report_parameters.py (100%) rename scripts/rpa/{ => connectors/dsv}/dsv_session.py (97%) rename scripts/rpa/{freight_rpa_worker.py => inventory/inventory_rpa_worker.py} (98%) rename scripts/rpa/{register_rpa_background_tasks.ps1 => inventory/register_inventory_worker_tasks.ps1} (85%) rename scripts/rpa/{ => inventory}/run_inventory_batch_trigger.py (89%) rename scripts/rpa/{start_rpa_worker.ps1 => inventory/start_inventory_worker.ps1} (97%) rename scripts/rpa/{freight_receipt_crane_export.py => receipt/receipt_crane_export.py} (79%) rename scripts/rpa/{freight_receipt_dbs_export.py => receipt/receipt_dbs_export.py} (66%) rename scripts/rpa/{freight_receipt_rpa_worker.py => receipt/receipt_rpa_worker.py} (88%) rename scripts/rpa/{start_receipt_rpa_worker.ps1 => receipt/start_receipt_worker.ps1} (89%) diff --git a/.env.dev b/.env.dev index 3e8c9f08..5c96f5f0 100644 --- a/.env.dev +++ b/.env.dev @@ -137,7 +137,7 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/u SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile # AWS 库存列映射(可选 JSON 字符串) # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} -# 本地 RPA(scripts/rpa/freight_rpa_worker.py) +# 本地 RPA(scripts/rpa/inventory/inventory_rpa_worker.py) SHIPPING_NOTICE_RPA_WORKER_MOCK=false # 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false diff --git a/.env.test b/.env.test index 03bdd856..358ceee0 100644 --- a/.env.test +++ b/.env.test @@ -160,7 +160,7 @@ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false # 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微 # 两者皆无则告警只写日志、不会发企微 -SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 +SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true # 企微发送中短锁秒数(发送失败过期后可重试,默认 120) SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 @@ -174,7 +174,7 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queu SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers # AWS 库存列映射(可选 JSON 字符串) # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} -# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选) +# 本地 Mock RPA(scripts/rpa/inventory/inventory_rpa_worker.py,可选) # SHIPPING_NOTICE_RPA_WORKER_MOCK=true # SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 # SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY= diff --git a/backend/tests/test_crane_navigation.py b/backend/tests/test_crane_navigation.py index 7c8f7fc6..82523458 100644 --- a/backend/tests/test_crane_navigation.py +++ b/backend/tests/test_crane_navigation.py @@ -10,7 +10,7 @@ import pytest def _load_navigation(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_navigation.py" + module_path = Path(__file__).resolve().parents[2] / "scripts" / "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) diff --git a/backend/tests/test_crane_report_export.py b/backend/tests/test_crane_report_export.py index b52a4819..a904bbc4 100644 --- a/backend/tests/test_crane_report_export.py +++ b/backend/tests/test_crane_report_export.py @@ -10,7 +10,7 @@ import pytest def _load_export(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_report_export.py" + module_path = Path(__file__).resolve().parents[2] / "scripts" / "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) diff --git a/backend/tests/test_crane_session.py b/backend/tests/test_crane_session.py index 090f4b52..f6e3c398 100644 --- a/backend/tests/test_crane_session.py +++ b/backend/tests/test_crane_session.py @@ -8,7 +8,7 @@ from unittest.mock import MagicMock def _load_crane_session(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_session.py" + module_path = Path(__file__).resolve().parents[2] / "scripts" / "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) @@ -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" / "freight_rpa_worker.py" + worker_path = Path(__file__).resolve().parents[2] / "scripts" / "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) diff --git a/backend/tests/test_dsv_report_parameters.py b/backend/tests/test_dsv_report_parameters.py index 644d0c9e..eae5a371 100644 --- a/backend/tests/test_dsv_report_parameters.py +++ b/backend/tests/test_dsv_report_parameters.py @@ -7,7 +7,7 @@ from pathlib import Path def _load_module(): - path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "dsv_report_parameters.py" + path = Path(__file__).resolve().parents[2] / "scripts" / "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) diff --git a/backend/tests/test_freight_receipt_worker_contract.py b/backend/tests/test_freight_receipt_worker_contract.py index 4f241c86..8f87b1bc 100644 --- a/backend/tests/test_freight_receipt_worker_contract.py +++ b/backend/tests/test_freight_receipt_worker_contract.py @@ -7,7 +7,7 @@ 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' / 'freight_receipt_rpa_worker.py').read_text(encoding='utf-8') + 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 assert 'shipping_receipt_rpa.v1' in text @@ -19,8 +19,8 @@ def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract def test_receipt_crane_driver_forces_inbound_details_match_name(): """收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。""" root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' - receipt_driver = (root / 'freight_receipt_crane_export.py').read_text(encoding='utf-8') - crane_driver = (root / 'crane_report_export.py').read_text(encoding='utf-8') + 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 assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver @@ -28,7 +28,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' - module_path = root / 'freight_receipt_crane_export.py' + 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) assert spec and spec.loader diff --git a/backend/tests/test_freight_rpa_heartbeat.py b/backend/tests/test_freight_rpa_heartbeat.py index 6acea67e..6004c911 100644 --- a/backend/tests/test_freight_rpa_heartbeat.py +++ b/backend/tests/test_freight_rpa_heartbeat.py @@ -13,7 +13,7 @@ def _load_freight_rpa_heartbeat_module(): rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "rpa" if str(rpa_dir) not in sys.path: sys.path.insert(0, str(rpa_dir)) - module_path = rpa_dir / "freight_rpa_heartbeat.py" + module_path = rpa_dir / "common" / "rpa_heartbeat.py" spec = importlib.util.spec_from_file_location("freight_rpa_heartbeat_test", module_path) module = importlib.util.module_from_spec(spec) assert spec.loader is not None diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index c32e2e8a..48fbd552 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -26,8 +26,8 @@ def _repo_root() -> Path: def _load_freight_rpa_worker(): - module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py" - spec = importlib.util.spec_from_file_location("freight_rpa_worker_under_test", module_path) + module_path = _repo_root() / "scripts" / "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 module = importlib.util.module_from_spec(spec) @@ -1627,7 +1627,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" / "dsv_report_export.py" + module_path = _repo_root() / "scripts" / "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) diff --git a/backend/tests/test_freight_rpa_worker_inventory_params.py b/backend/tests/test_freight_rpa_worker_inventory_params.py index 7f138151..cc65faaf 100644 --- a/backend/tests/test_freight_rpa_worker_inventory_params.py +++ b/backend/tests/test_freight_rpa_worker_inventory_params.py @@ -20,8 +20,21 @@ def _load_dsv_auth_login_flow(): return _load_rpa_module("dsv_auth_login_flow") +_RPA_MODULE_PATHS = { + "freight_rpa_worker": "inventory/inventory_rpa_worker.py", + "inventory_rpa_worker": "inventory/inventory_rpa_worker.py", + "dsv_report_export": "connectors/dsv/dsv_report_export.py", + "dsv_auth_login_flow": "connectors/dsv/dsv_auth_login_flow.py", + "dsv_navigation": "connectors/dsv/dsv_navigation.py", + "dsv_auth": "connectors/dsv/dsv_auth.py", + "dsv_session": "connectors/dsv/dsv_session.py", + "dsv_debug": "connectors/dsv/dsv_debug.py", +} + + def _load_rpa_module(module_name: str): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py" + rel = _RPA_MODULE_PATHS.get(module_name, f"{module_name}.py") + module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / rel scripts_dir = str(module_path.parent) if scripts_dir not in sys.path: sys.path.insert(0, scripts_dir) diff --git a/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md b/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md index c616467e..ec7ffe94 100644 --- a/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md +++ b/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md @@ -12,7 +12,7 @@ ## Global Constraints -- 禁止修改 `scripts/rpa/freight_rpa_worker.py`、`shipping_inventory_rpa.v2`、`/api/shipping-notice/rpa/inventory-*` 与库存入库/匹配服务。 +- 禁止修改 `scripts/rpa/inventory/inventory_rpa_worker.py`、`shipping_inventory_rpa.v2`、`/api/shipping-notice/rpa/inventory-*` 与库存入库/匹配服务。 - 首版不实现库存和收料间的登录会话复用、同 Profile 互斥锁或跨排程协调;运维上错开使用同一 Profile 的排程时间。 - 收料 Worker 在单次排程内以 `connector_type + rpa_profile_id + login_url` 分组,每个分组登录一次、串行处理其全部单元。 - DBS 每个收料配置 Warehouse 展开一条单元;报表日期固定不传。Crane 每站点创建 `Inbound Details`,通过本次唯一 Description 轮询并下载。 @@ -88,10 +88,10 @@ ### Task 4: 实现独立 DBS/Crane 收料 Windows Worker **Files:** -- Create: `scripts/rpa/freight_receipt_rpa_worker.py` -- Create: `scripts/rpa/freight_receipt_dbs_export.py` -- Create: `scripts/rpa/freight_receipt_crane_export.py` -- Create: `scripts/rpa/start_receipt_rpa_worker.ps1` +- Create: `scripts/rpa/receipt/receipt_rpa_worker.py` +- Create: `scripts/rpa/receipt/receipt_dbs_export.py` +- Create: `scripts/rpa/receipt/receipt_crane_export.py` +- Create: `scripts/rpa/receipt/start_receipt_worker.ps1` - Modify: `scripts/rpa/README.md` - Test: `backend/tests/test_freight_receipt_worker_contract.py` diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 6dbb8923..acba73d0 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -1873,7 +1873,7 @@ GET /api/admin/shipping-order-schema/published-contract $env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key" $env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true" -python scripts/rpa/freight_rpa_worker.py +python scripts/rpa/inventory/inventory_rpa_worker.py ``` ### 1.5 库存导出 RPA 共享部署(Windows RPA + Ubuntu 后端) @@ -1941,24 +1941,24 @@ foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { 从项目仓库复制以下文件到 Windows RPA 主机: ```text -scripts\rpa\freight_rpa_worker.py -scripts\rpa\dsv_report_parameters.py -scripts\rpa\dsv_login_smoke.py -scripts\rpa\run_inventory_batch_trigger.py +scripts\rpa\inventory\inventory_rpa_worker.py +scripts\rpa\connectors\dsv\dsv_report_parameters.py +scripts\rpa\connectors\dsv\dsv_login_smoke.py +scripts\rpa\inventory\run_inventory_batch_trigger.py ``` 放置为: ```text -C:\HxopsRpaTest\scripts\rpa\freight_rpa_worker.py -C:\HxopsRpaTest\scripts\rpa\dsv_report_parameters.py -C:\HxopsRpaTest\scripts\rpa\dsv_login_smoke.py -C:\HxopsRpaTest\scripts\rpa\run_inventory_batch_trigger.py +C:\HxopsRpaTest\scripts\rpa\inventory\inventory_rpa_worker.py +C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_report_parameters.py +C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_login_smoke.py +C:\HxopsRpaTest\scripts\rpa\inventory\run_inventory_batch_trigger.py -C:\HxopsRpaProd\scripts\rpa\freight_rpa_worker.py -C:\HxopsRpaProd\scripts\rpa\dsv_report_parameters.py -C:\HxopsRpaProd\scripts\rpa\dsv_login_smoke.py -C:\HxopsRpaProd\scripts\rpa\run_inventory_batch_trigger.py +C:\HxopsRpaProd\scripts\rpa\inventory\inventory_rpa_worker.py +C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_report_parameters.py +C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_login_smoke.py +C:\HxopsRpaProd\scripts\rpa\inventory\run_inventory_batch_trigger.py ``` 不要复制 `.env*`、密码文件、`backend\data` 旧运行数据、浏览器 profile、旧 trigger / processed / failed 文件。 @@ -2093,7 +2093,7 @@ cat /mnt/hxops-rpa-test-data/inventory_triggers/.hxops_rpa_shared_mount 先验证 DSV 登录: ```powershell -python scripts\rpa\dsv_login_smoke.py +python scripts\rpa\connectors\dsv\dsv_login_smoke.py ``` 成功时会看到: @@ -2105,7 +2105,7 @@ SUCCESS — DSV session ready 库存 RPA 必须由 HXOPS 管理端的 Inventory Source + RPA Profile 生成 trigger;如需人工联调,选取已生成的 trigger,执行: ```powershell -python scripts\rpa\run_inventory_batch_trigger.py +python scripts\rpa\inventory\run_inventory_batch_trigger.py ``` 该入口不会读取 YAML 或本地账号密码,Profile 的密文凭据和页面操作均由平台生成的 trigger 提供。 @@ -2294,8 +2294,8 @@ DSV 库存导出默认使用一次性浏览器 Profile。仅在一个对应环 Windows 如禁止运行 `.ps1`,仅对单次 Secret 创建使用临时 Bypass: ```powershell -powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1" -Environment test -powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1" -Environment prod +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1" -Environment test +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1" -Environment prod ``` 若文件来自网络或压缩包并被标记为阻止,先执行 `Unblock-File`。也可用 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` 仅放行当前窗口。禁止永久设置 `Unrestricted` 或修改 `LocalMachine` 策略。 @@ -2306,8 +2306,8 @@ Windows PowerShell 5.1 读取无 BOM UTF-8 脚本时可能出现中文变乱和 ```powershell cd C:\HxopsRpaTest -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod ``` 默认 Secret 路径为 `C:\HxopsRpaSecrets\test.xml` 与 `prod.xml`。文件不得进入仓库、SMB 共享、日志或其他 Windows 用户目录。 @@ -2320,7 +2320,7 @@ DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Prof ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` - "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" ` + "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" ` -Environment test ` -ApiBase "http://:<端口>" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -2330,8 +2330,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` 若脚本来自网络或压缩包,先确认路径并按需解除文件阻止: ```powershell -Test-Path "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" -Unblock-File "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" +Test-Path "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" +Unblock-File "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" ``` `-ApiBase` 必须是 HXOPS 测试业务后端地址。`HXOPS_TOOLS_API_BASE`(例如 `:8890`)是 Tool API,不能填入 Worker 的 `-ApiBase`。如果使用 `http://192.168.100.192:5052`,必须先确认该地址确实是测试后端并可从 Windows Worker 访问: @@ -2346,7 +2346,7 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing 连通性确认后,也可以使用仓库原始命令: ```powershell -.\scripts\rpa\start_rpa_worker.ps1 ` +.\scripts\rpa\inventory\start_inventory_worker.ps1 ` -Environment test ` -ApiBase "http://测试后端:端口" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -2356,7 +2356,7 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing 手工启动 prod: ```powershell -C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1 ` +C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1 ` -Environment prod ` -ApiBase "http://正式后端:端口" ` -WorkerRoot "C:\HxopsRpaProd" ` @@ -2367,7 +2367,7 @@ C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1 ` #### 1.5.11 端到端验证 1. Windows 手工打开 Edge,确认能访问 DSV/Crane。 -2. Windows 执行 `python scripts\rpa\dsv_login_smoke.py`。 +2. Windows 执行 `python scripts\rpa\connectors\dsv\dsv_login_smoke.py`。 3. 在管理端创建一个库存 RPA trigger,确认其包含 Source、Profile 和密文凭据。 4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\inventory_triggers` 能看到。 5. Windows 按当前方案执行 `start_rpa_worker.ps1`;不要直接运行 `freight_rpa_worker.py`。 @@ -2435,7 +2435,7 @@ $env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "uploa $env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile" $env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log" -\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" +\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` 启动成功后,控制台会输出 `[freight_rpa_worker] started`,并持续轮询 trigger。另开一个 PowerShell 可检查日志和哨兵;本地未配置 shared scope 时不要求哨兵包含 test/prod scope: @@ -3110,7 +3110,7 @@ API 层 | `backend/tests/test_shipping_inventory_routing_engine.py` | 通用路由规则引擎单测 | | `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 | | `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 | -| `scripts/rpa/freight_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | +| `scripts/rpa/inventory/inventory_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | --- @@ -3147,7 +3147,7 @@ API 层 - **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充 - **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值) - **报表控件模板**(2026-08-26):同一参数名在不同报表的 SSRS 控件长相不同(`On Hand Inventory By Location 3lv` 的 Warehouse 是原生 select `ddValue`,JDA 版 `On Hand Inventory by Location` 是 txtValue/toggle/divDropDown 多选框下拉)。控件差异由 Worker 按归一化报表名登记在 `dsv_report_parameters._DSV_REPORT_PARAM_TEMPLATES`,填参时把 `report_name` 透传到模块解析;`selector_env/selectors` 继续不进入数据库,未登记报表回退参数名默认值。填参失败会输出参数区控件探针日志(`[dsv-filter] ... control probe`),便于定位控件 ID/类型漂移。 -- Worker:`scripts/rpa/freight_rpa_worker.py` → `_handle_inventory_batch_trigger` +- Worker:`scripts/rpa/inventory/inventory_rpa_worker.py` → `_handle_inventory_batch_trigger` - 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready` - **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts//`、创建 `shipping_inventory_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。 - **单票身份与失败收口**(2026-08-20):首次自动库存准备和用户重试均必须经 `ensure_all_required_sources_prepared` 创建逐源 Attempt;禁止写缺少 `source_run_no / lease_token / candidate_set_id / execution_id / gate_id` 的旧 task 级 trigger。Worker 发现 `trigger_identity_invalid` 时必须在 `results[]` 回传可用的 source 身份片段;后端按已定位的 Attempt 立即标记失败、同步 PreparationSourceAttempt、`inventory_preparation` Gate 与 `step3_inventory_prepare=needs_human`,不得等待库存轮询超时。 diff --git a/scripts/rpa/README.md b/scripts/rpa/README.md index a072ab77..91abf1d0 100644 --- a/scripts/rpa/README.md +++ b/scripts/rpa/README.md @@ -9,7 +9,7 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA 启动示例: ```powershell -.\scripts\rpa\start_receipt_rpa_worker.ps1 -Environment test -ApiBase "http://" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" +.\scripts\rpa\receipt\start_receipt_worker.ps1 -Environment test -ApiBase "http://" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` 收料 Worker 在同一排程内按 Profile 登录一次后串行处理单元;DBS 每个 Warehouse 导出一个文件且不传报表日期,Crane 无论 Profile 登录地址保存为门户首页还是其他页面,都会强制进入 `#/inbound-details-query`,不填写 Warehouse 或查询条件,直接使用页面默认条件生成/等待唯一 Description 对应的 `Inbound Details` 文件。不要把收料 trigger 手工复制到库存目录或反向复制。 @@ -32,19 +32,26 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA ## 模块结构 -| 文件 | 职责 | -| --------------------------------------------- | ------------------------------------------------------ | -| `freight_rpa_worker.py` | 轮询 trigger、打开浏览器、按 `connector_type` 分发、HTTP 回调(~900 行) | -| `rpa_common.py` | 环境变量、通用 Playwright 点击/填充工具 | -| `dsv_driver.py` | DSV 对外入口:`download_dsv360_inventory` | -| `dsv_auth.py` | DSV PingID 分步登录(表单/探测辅助) | -| `dsv_auth_login_flow.py` | DSV 自动登录主编排 `maybe_auto_login_dsv` | -| `dsv_session.py` | DSV portal 壳层检测、首页 ready、entry_url | -| `dsv_navigation.py` | DSV Reports 菜单 → 报表参数页 | -| `dsv_report_export.py` | DSV 填参、View Report、Excel 导出、batch 复用 | -| `dsv_debug.py` | DSV 调试探针与链路日志 | -| `dsv_report_parameters.py` | SSRS 参数控件填充(已有) | -| `crane_session.py` / `crane_report_export.py` | Crane 登录与异步导出 | +| 目录 / 文件 | 职责 | +| ----------------------------------- | ------------------------------------------------------ | +| `common/` | **跨域通用**(与流程、连接器无关) | +| `common/rpa_common.py` | 环境变量、通用 Playwright 点击/填充工具 | +| `common/download_artifact_fallback.py` | 浏览器已落盘但 Playwright 未返回 Download 时的下载适配器 | +| `common/rpa_heartbeat.py` | 向后端上报心跳 + 共享目录哨兵(原 `freight_rpa_heartbeat.py`) | +| `common/new_rpa_worker_secret.ps1` | 生成当前用户可解密的 DPAPI Secret 文件 | +| `connectors/` | **登录网站 / 报表系统自动化**(库存与收料共用) | +| `connectors/dsv/` | DSV 360 连接器:`dsv_driver` / `dsv_auth` / `dsv_auth_login_flow` / `dsv_session` / `dsv_navigation` / `dsv_report_export` / `dsv_debug` / `dsv_report_parameters` / `dsv_login_smoke` / `dsv_export_timeout_diagnostics` | +| `connectors/crane/` | Crane FootPrint 连接器:`crane_session` / `crane_navigation` / `crane_report_export` / `crane_login_smoke` | +| `inventory/` | **库存(发货通知)RPA 流程编排** | +| `inventory/inventory_rpa_worker.py` | 库存 Worker:轮询 trigger、按 `connector_type` 分发、HTTP 回调(原 `freight_rpa_worker.py`) | +| `inventory/run_inventory_batch_trigger.py` | 手工执行一条数据库生成的 inventory batch trigger | +| `inventory/start_inventory_worker.ps1` | 启动库存 Worker 的 PowerShell 启动脚本(原 `start_rpa_worker.ps1`) | +| `inventory/register_inventory_worker_tasks.ps1` | 注册 test/prod 库存 Worker 后台计划任务(headless + hidden) | +| `receipt/` | **收料 RPA 流程编排** | +| `receipt/receipt_rpa_worker.py` | 独立收料 Worker:仅消费 receipt trigger、专用目录与回调(原 `freight_receipt_rpa_worker.py`) | +| `receipt/receipt_crane_export.py` | Crane 收料报表导出适配器(强制 Inbound Details) | +| `receipt/receipt_dbs_export.py` | DBS 收料报表导出适配器(按 Warehouse) | +| `receipt/start_receipt_worker.ps1` | 启动收料 Worker 的 PowerShell 启动脚本(原 `start_receipt_rpa_worker.ps1`) | @@ -243,11 +250,11 @@ Get-ChildItem C:\HxopsRpaProd\data 验证关键文件: ```powershell -Test-Path C:\HxopsRpaTest\scripts\rpa\freight_rpa_worker.py -Test-Path C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1 -Test-Path C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1 -Test-Path C:\HxopsRpaProd\scripts\rpa\freight_rpa_worker.py -Test-Path C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1 +Test-Path C:\HxopsRpaTest\scripts\rpa\inventory\inventory_rpa_worker.py +Test-Path C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1 +Test-Path C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1 +Test-Path C:\HxopsRpaProd\scripts\rpa\inventory\inventory_rpa_worker.py +Test-Path C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1 ``` 每一行都应返回 `True`。不要复制 `.env*`、旧 trigger、旧 `processed/failed`、旧浏览器 profile 和真实密钥文件。 @@ -259,10 +266,10 @@ Windows PowerShell 5.1 如仍已经报中文变乱,请在仓库根目录用 Po ```powershell $utf8Bom = New-Object System.Text.UTF8Encoding($true) foreach ($path in @( - "C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1", - "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1", - "C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1", - "C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1" + "C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1", + "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1", + "C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1", + "C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1" )) { $text = [System.IO.File]::ReadAllText($path, [System.Text.UTF8Encoding]::new($false)) [System.IO.File]::WriteAllText($path, $text, $utf8Bom) @@ -328,7 +335,7 @@ Secret 必须用最终运行任务的同一 Windows 账号创建。 powershell.exe ` -NoProfile ` -ExecutionPolicy Bypass ` - -File "C:\HxopsTest\scripts\rpa\new_rpa_worker_secret.ps1" ` + -File "C:\HxopsTest\scripts\rpa\common\new_rpa_worker_secret.ps1" ` -Environment test ``` @@ -338,15 +345,15 @@ powershell.exe ` powershell.exe ` -NoProfile ` -ExecutionPolicy Bypass ` - -File "C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1" ` + -File "C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1" ` -Environment prod ``` 如果仍然提示文件被阻止,先解除从网络或压缩包复制来的文件标记,再重试: ```powershell -Unblock-File "C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1" -Unblock-File "C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1" +Unblock-File "C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1" +Unblock-File "C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1" ``` 也可以只对当前 PowerShell 窗口临时放行: @@ -358,7 +365,7 @@ Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass 然后再执行: ```powershell -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test ``` 不要执行 `Set-ExecutionPolicy Unrestricted` 或 `Set-ExecutionPolicy RemoteSigned -Scope LocalMachine` 等永久放宽系统策略的命令。后台任务自身已使用 `-ExecutionPolicy Bypass`,不需要修改系统策略。 @@ -367,7 +374,7 @@ Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass ```powershell cd C:\HxopsRpaTest -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test ``` 按提示输入两项: @@ -381,7 +388,7 @@ DSV/Crane 登录地址、账号和密码不在 Windows 部署时输入:它们 ```powershell cd C:\HxopsRpaProd -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod ``` 这次必须输入 prod 的 Tool API Key 和 RPA Credential Key,不要复制 test 值。DSV/Crane 凭据仍在 HXOPS prod RPA Profile 中配置。 @@ -540,7 +547,7 @@ docker compose --env-file .env.prod exec -T hxops-backend sh -lc 'ls -ld /mnt/hx ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` - "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" ` + "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" ` -Environment test ` -ApiBase "http://192.168.100.192:8890" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -550,13 +557,13 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` 先确认脚本确实已复制到 Worker 根目录: ```powershell -Test-Path "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" +Test-Path "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" ``` 若脚本来自网络或压缩包且仍被标记为阻止,可只解除该文件的阻止标记: ```powershell -Unblock-File "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" +Unblock-File "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" ``` `-ApiBase` 必须填 Worker 实际可达的 HXOPS API 入口,判据是 `{base}/api/shipping-notice/rpa/heartbeat` 能访问到后端。Docker Compose 部署下后端容器内部监听 `5000`(`backend/deploy/gunicorn_config.py` 绑定 `0.0.0.0:5000`),而 `docker-compose.yml` 把宿主 `5052` 映射到容器内一个无监听端口,因此 `http://:5052` 直连不可用;前端 nginx 网关(宿主 `8890`)把 `/api/` 反代到 `hxops-backend:5000`(见 `frontend/nginx.conf`),所以 Worker 应填网关地址,如 `http://192.168.100.192:8890`。该地址与 `HXOPS_TOOLS_API_BASE` 指向同一对外网关(都经 `/api/` 反代),实际以“`{base}/api/...` 可达”为准,不必拘泥于 Tool API / 业务后端的命名区分。启动前先验证网关端口连通: @@ -571,7 +578,7 @@ Test-NetConnection 192.168.100.192 -Port 8890 ```powershell cd C:\HxopsRpaTest -.\scripts\rpa\start_rpa_worker.ps1 ` +.\scripts\rpa\inventory\start_inventory_worker.ps1 ` -Environment test ` -ApiBase "http://:<端口>" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -582,7 +589,7 @@ cd C:\HxopsRpaTest ```powershell cd C:\HxopsRpaProd -.\scripts\rpa\start_rpa_worker.ps1 ` +.\scripts\rpa\inventory\start_inventory_worker.ps1 ` -Environment prod ` -ApiBase "http://:<端口>" ` -WorkerRoot "C:\HxopsRpaProd" ` @@ -636,12 +643,12 @@ $Principal = New-ScheduledTaskPrincipal ` $TestAction = New-ScheduledTaskAction ` -Execute $PowerShellExe ` - -Argument "-NoProfile -ExecutionPolicy Bypass -File `"C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1`" -Environment test -ApiBase `"$TestApiBase`" -WorkerRoot `"C:\HxopsRpaTest`" -SecretFile `"C:\HxopsRpaSecrets\test.xml`" -PythonExe `"$PythonExe`"" ` + -Argument "-NoProfile -ExecutionPolicy Bypass -File `"C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1`" -Environment test -ApiBase `"$TestApiBase`" -WorkerRoot `"C:\HxopsRpaTest`" -SecretFile `"C:\HxopsRpaSecrets\test.xml`" -PythonExe `"$PythonExe`"" ` -WorkingDirectory "C:\HxopsRpaTest" $ProdAction = New-ScheduledTaskAction ` -Execute $PowerShellExe ` - -Argument "-NoProfile -ExecutionPolicy Bypass -File `"C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1`" -Environment prod -ApiBase `"$ProdApiBase`" -WorkerRoot `"C:\HxopsRpaProd`" -SecretFile `"C:\HxopsRpaSecrets\prod.xml`" -PythonExe `"$PythonExe`"" ` + -Argument "-NoProfile -ExecutionPolicy Bypass -File `"C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1`" -Environment prod -ApiBase `"$ProdApiBase`" -WorkerRoot `"C:\HxopsRpaProd`" -SecretFile `"C:\HxopsRpaSecrets\prod.xml`" -PythonExe `"$PythonExe`"" ` -WorkingDirectory "C:\HxopsRpaProd" $Trigger = New-ScheduledTaskTrigger -AtLogOn -User $RunAsUser @@ -772,16 +779,16 @@ foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { 从待部署的已审核仓库版本复制整个 `scripts\rpa` 目录到 test/prod 的 `scripts\rpa`,保证 Worker、driver、session、heartbeat、调试工具和公共模块来自同一版本。其中至少包含: ```text -scripts\rpa\freight_rpa_worker.py -scripts\rpa\rpa_common.py -scripts\rpa\freight_rpa_heartbeat.py -scripts\rpa\dsv_driver.py -scripts\rpa\dsv_login_smoke.py -scripts\rpa\dsv_report_parameters.py -scripts\rpa\run_inventory_batch_trigger.py -scripts\rpa\crane_login_smoke.py -scripts\rpa\new_rpa_worker_secret.ps1 -scripts\rpa\start_rpa_worker.ps1 +scripts\rpa\inventory\inventory_rpa_worker.py +scripts\rpa\common\rpa_common.py +scripts\rpa\common\rpa_heartbeat.py +scripts\rpa\connectors\dsv\dsv_driver.py +scripts\rpa\connectors\dsv\dsv_login_smoke.py +scripts\rpa\connectors\dsv\dsv_report_parameters.py +scripts\rpa\inventory\run_inventory_batch_trigger.py +scripts\rpa\connectors\crane\crane_login_smoke.py +scripts\rpa\common\new_rpa_worker_secret.ps1 +scripts\rpa\inventory\start_inventory_worker.ps1 ``` 不得复制 `.env*`、密码文件、`backend\data` 旧运行数据、旧浏览器 profile、旧 trigger 以及 `processed` / `failed` 文件。 @@ -863,14 +870,14 @@ $env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "请替换为Crane密码" 先执行登录烟测: ```powershell -python scripts\rpa\dsv_login_smoke.py -python scripts\rpa\crane_login_smoke.py +python scripts\rpa\connectors\dsv\dsv_login_smoke.py +python scripts\rpa\connectors\crane\crane_login_smoke.py ``` DSV 成功时会输出 `SUCCESS — DSV session ready`。如需人工联调已由平台生成的 trigger,执行: ```powershell -python scripts\rpa\run_inventory_batch_trigger.py +python scripts\rpa\inventory\run_inventory_batch_trigger.py ``` 该入口不从 YAML 或本地文件读取账号密码;Profile 密文凭据和页面操作由平台 trigger 提供。 @@ -1027,7 +1034,7 @@ services: ### 1.10 端到端验收 1. Windows 手工打开 Edge,确认能访问 DSV/Crane。 -2. Windows 执行 `python scripts\rpa\dsv_login_smoke.py` 和必要的 Crane smoke。 +2. Windows 执行 `python scripts\rpa\connectors\dsv\dsv_login_smoke.py` 和必要的 Crane smoke。 3. 在管理端创建库存 RPA trigger,确认其包含 Source、Profile 和密文凭据。 4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认对应文件可见,然后删除测试文件。 5. Windows 按“步骤 10”使用 `start_rpa_worker.ps1` 启动对应环境 Worker。 @@ -1100,7 +1107,7 @@ $env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "uploa $env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile" $env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log" -\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase "http://:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" +\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase "http://:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` 若只验证 trigger 扫描、文件流转与回调而不访问真实货代网站,可把 `SHIPPING_NOTICE_RPA_WORKER_MOCK` 设为 `true`。真实库存导出保持 `false`,并使用 HXOPS RPA Profile 随 trigger 下发的加密凭据。 @@ -1213,7 +1220,7 @@ docker compose --env-file .env.test up -d --force-recreate hxops-backend ```powershell cd C:\HxopsRpaTest -\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase "http://:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" +\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase "http://:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` 应同时验证以下四项后,再在管理端对**停用的库存站点**发起“测试导出”: @@ -1257,7 +1264,7 @@ docker compose --env-file .env.test stop hxops-kb-worker hxops-backend ```powershell $TaskName = "HXOPS Inventory RPA Worker TEST" $WorkerRoot = "C:\HxopsRpaTest" -$Launcher = "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" +$Launcher = "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" $SecretFile = "C:\HxopsRpaSecrets\test.xml" $ApiBase = "http://<测试后端地址>:<端口>" $RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name @@ -1297,7 +1304,7 @@ Register-ScheduledTask ` ```powershell $TaskName = "HXOPS Inventory RPA Worker PROD" $WorkerRoot = "C:\HxopsRpaProd" -$Launcher = "C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1" +$Launcher = "C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1" $SecretFile = "C:\HxopsRpaSecrets\prod.xml" $ApiBase = "http://<正式后端地址>:<端口>" ``` @@ -1308,8 +1315,8 @@ test 和 prod 可在同一台主机、同一个交互式用户会话中并行, ```powershell cd C:\HxopsRpaTest -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod ``` Secret 文件默认位于 `C:\HxopsRpaSecrets\test.xml` 和 `prod.xml`,使用当前 Windows 用户 DPAPI 保护;不得复制到仓库、共享目录或其他账号。 @@ -1356,15 +1363,15 @@ Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false #### 2.3.1 headless 后台模式(无可见 Edge,完全后台) > 适用:希望彻底摆脱「可见 Edge + 交互式桌面」,让 Worker 无控制台、无浏览器窗口地后台常驻。 -> 交付脚本:`scripts/rpa/register_rpa_background_tasks.ps1`(test/prod 双任务,headless + 隐藏控制台,仍为 RPA 账号的 `AtLogOn + Interactive` 任务)。 +> 交付脚本:`scripts/rpa/inventory/register_inventory_worker_tasks.ps1`(test/prod 双任务,headless + 隐藏控制台,仍为 RPA 账号的 `AtLogOn + Interactive` 任务)。 **切换前必须先完成 headless 冒烟预检(风险最高,不要跳过):** ```powershell $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "true" # 在 RPA 主机验证真实登录/导出可通: -python scripts\rpa\dsv_login_smoke.py -python scripts\rpa\crane_login_smoke.py +python scripts\rpa\connectors\dsv\dsv_login_smoke.py +python scripts\rpa\connectors\crane\crane_login_smoke.py # 若触及上传,再验证一次 headless 下的上传流程 ``` @@ -1374,16 +1381,16 @@ python scripts\rpa\crane_login_smoke.py ```powershell cd C:\HxopsRpaTest -.\scripts\rpa\register_rpa_background_tasks.ps1 # 注册 test/prod 两个任务 -.\scripts\rpa\register_rpa_background_tasks.ps1 -Start # 立即启动(默认 all) -.\scripts\rpa\register_rpa_background_tasks.ps1 -Status # 查看状态(默认 all) -.\scripts\rpa\register_rpa_background_tasks.ps1 -Stop # 停止(默认 all) -.\scripts\rpa\register_rpa_background_tasks.ps1 -Unregister # 注销(默认 all) +.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 # 注册 test/prod 两个任务 +.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start # 立即启动(默认 all) +.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Status # 查看状态(默认 all) +.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Stop # 停止(默认 all) +.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Unregister # 注销(默认 all) # 区分环境:用 -Scope test|prod|all(默认 all) -.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test -Status # 只看 test -.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope prod -Start # 只启动 prod -.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test -Unregister # 只注销 test +.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test -Status # 只看 test +.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope prod -Start # 只启动 prod +.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test -Unregister # 只注销 test ``` - **`-Scope test|prod|all`**:`Start/Stop/Status/Unregister`(以及默认注册)都可只作用于单个环境;不带 `-Scope` 时默认操作 test 和 prod 两个任务。两个任务是独立命名的(`HXOPS Inventory RPA Worker TEST` / `...PROD`),也可用原生 `Get-ScheduledTask -TaskName <任务名>` 单独查询。 @@ -1423,12 +1430,12 @@ cd C:\HxopsRpaTest ```powershell cd C:\HxopsRpaProd -.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod -.\scripts\rpa\start_rpa_worker.ps1 -Environment prod -ApiBase "http://<正式后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaProd" -SecretFile "C:\HxopsRpaSecrets\prod.xml" +.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod +.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment prod -ApiBase "http://<正式后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaProd" -SecretFile "C:\HxopsRpaSecrets\prod.xml" # 关闭并重新打开 PowerShell 后执行 cd C:\HxopsRpaProd -\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" +\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` @@ -1506,7 +1513,7 @@ $env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:SHIPPING_NOTICE_TOOL_API_KEY = "<与 backend 一致>" $env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true" # 四个 SHIPPING_NOTICE_RPA_SHARED_* 目录与 backend 相同 -python scripts/rpa/freight_rpa_worker.py +python scripts/rpa/inventory/inventory_rpa_worker.py ``` 1. 在 Chat 中走 `ensure_inventory` / `upload_to_freight`,worker 会自动回调 `/api/shipping-notice/rpa/*`。 @@ -1542,7 +1549,7 @@ $env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "" $env:SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME = "" $env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "" -python scripts/rpa/freight_rpa_worker.py +python scripts/rpa/inventory/inventory_rpa_worker.py ``` 说明:`SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR` 现在仅作为“运行时 profile 根目录”。每次库存导出都会在该目录下自动创建一个全新的临时子目录,并在任务结束后清理,不会复用任何已有 profile。 @@ -1568,7 +1575,7 @@ Crane 登录烟测(仅验证 User Name / Password / Sign in): ```powershell $env:SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME = "" $env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "" -backend\venv\Scripts\python.exe scripts\rpa\crane_login_smoke.py +backend\venv\Scripts\python.exe scripts\rpa\connectors\crane\crane_login_smoke.py ``` 若页面出现 MFA、验证码或 SSO 二次确认,worker 会失败并回调错误,需要人工处理后重试。 diff --git a/scripts/rpa/download_artifact_fallback.py b/scripts/rpa/common/download_artifact_fallback.py similarity index 100% rename from scripts/rpa/download_artifact_fallback.py rename to scripts/rpa/common/download_artifact_fallback.py diff --git a/scripts/rpa/new_rpa_worker_secret.ps1 b/scripts/rpa/common/new_rpa_worker_secret.ps1 similarity index 100% rename from scripts/rpa/new_rpa_worker_secret.ps1 rename to scripts/rpa/common/new_rpa_worker_secret.ps1 diff --git a/scripts/rpa/rpa_common.py b/scripts/rpa/common/rpa_common.py similarity index 96% rename from scripts/rpa/rpa_common.py rename to scripts/rpa/common/rpa_common.py index 2f27b374..3e35e2e6 100644 --- a/scripts/rpa/rpa_common.py +++ b/scripts/rpa/common/rpa_common.py @@ -8,6 +8,21 @@ scripts/rpa/rpa_common.py from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + import json import os import sys @@ -203,7 +218,7 @@ def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: import importlib.util from pathlib import Path - module_path = Path(__file__).resolve().parent / "dsv_report_parameters.py" + module_path = _RPA_ROOT / "connectors" / "dsv" / "dsv_report_parameters.py" spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) diff --git a/scripts/rpa/freight_rpa_heartbeat.py b/scripts/rpa/common/rpa_heartbeat.py similarity index 94% rename from scripts/rpa/freight_rpa_heartbeat.py rename to scripts/rpa/common/rpa_heartbeat.py index 2a7fc0f9..a1028b89 100644 --- a/scripts/rpa/freight_rpa_heartbeat.py +++ b/scripts/rpa/common/rpa_heartbeat.py @@ -1,5 +1,5 @@ """ -scripts/rpa/freight_rpa_heartbeat.py +scripts/rpa/common/rpa_heartbeat.py 用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。 依赖:rpa_common.env、urllib、socket。 @@ -8,6 +8,21 @@ scripts/rpa/freight_rpa_heartbeat.py from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + import json import os import socket diff --git a/scripts/rpa/crane_login_smoke.py b/scripts/rpa/connectors/crane/crane_login_smoke.py similarity index 90% rename from scripts/rpa/crane_login_smoke.py rename to scripts/rpa/connectors/crane/crane_login_smoke.py index 83c43266..8d4305c9 100644 --- a/scripts/rpa/crane_login_smoke.py +++ b/scripts/rpa/connectors/crane/crane_login_smoke.py @@ -21,9 +21,9 @@ from pathlib import Path def _load_worker(): - repo_root = Path(__file__).resolve().parents[2] - module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py" - spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_smoke", module_path) + repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2]) + module_path = repo_root / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py" + spec = importlib.util.spec_from_file_location("inventory_rpa_worker_crane_smoke", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) diff --git a/scripts/rpa/crane_navigation.py b/scripts/rpa/connectors/crane/crane_navigation.py similarity index 100% rename from scripts/rpa/crane_navigation.py rename to scripts/rpa/connectors/crane/crane_navigation.py diff --git a/scripts/rpa/crane_report_export.py b/scripts/rpa/connectors/crane/crane_report_export.py similarity index 100% rename from scripts/rpa/crane_report_export.py rename to scripts/rpa/connectors/crane/crane_report_export.py diff --git a/scripts/rpa/crane_session.py b/scripts/rpa/connectors/crane/crane_session.py similarity index 100% rename from scripts/rpa/crane_session.py rename to scripts/rpa/connectors/crane/crane_session.py diff --git a/scripts/rpa/dsv_auth.py b/scripts/rpa/connectors/dsv/dsv_auth.py similarity index 98% rename from scripts/rpa/dsv_auth.py rename to scripts/rpa/connectors/dsv/dsv_auth.py index ad6d2460..cab1100e 100644 --- a/scripts/rpa/dsv_auth.py +++ b/scripts/rpa/connectors/dsv/dsv_auth.py @@ -8,6 +8,21 @@ scripts/rpa/dsv_auth.py from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + import sys import time from typing import Any, Callable diff --git a/scripts/rpa/dsv_auth_login_flow.py b/scripts/rpa/connectors/dsv/dsv_auth_login_flow.py similarity index 97% rename from scripts/rpa/dsv_auth_login_flow.py rename to scripts/rpa/connectors/dsv/dsv_auth_login_flow.py index 59886237..f00c9b50 100644 --- a/scripts/rpa/dsv_auth_login_flow.py +++ b/scripts/rpa/connectors/dsv/dsv_auth_login_flow.py @@ -8,6 +8,21 @@ scripts/rpa/dsv_auth_login_flow.py from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + import sys import time from typing import Any, Callable diff --git a/scripts/rpa/dsv_debug.py b/scripts/rpa/connectors/dsv/dsv_debug.py similarity index 95% rename from scripts/rpa/dsv_debug.py rename to scripts/rpa/connectors/dsv/dsv_debug.py index 48c055b4..a7a8d5f7 100644 --- a/scripts/rpa/dsv_debug.py +++ b/scripts/rpa/connectors/dsv/dsv_debug.py @@ -8,6 +8,21 @@ scripts/rpa/dsv_debug.py from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + import json import sys import time @@ -163,7 +178,7 @@ def _debug_dsv_stage(page: Any, stage: str, *, target_text: str = "") -> None: # #region debug-point A:reports-debug-server def _debug_server_config() -> tuple[str, str]: """读取 reports-menu-stuck 调试会话配置,未命中时回退默认本地地址。""" - env_path = Path(__file__).resolve().parents[2] / ".dbg" / "reports-menu-stuck.env" + env_path = _RPA_ROOT.parents[1] / ".dbg" / "reports-menu-stuck.env" url = "http://127.0.0.1:7778/event" session_id = "reports-menu-stuck" try: diff --git a/scripts/rpa/dsv_driver.py b/scripts/rpa/connectors/dsv/dsv_driver.py similarity index 62% rename from scripts/rpa/dsv_driver.py rename to scripts/rpa/connectors/dsv/dsv_driver.py index 1d68cb6d..03d7f296 100644 --- a/scripts/rpa/dsv_driver.py +++ b/scripts/rpa/connectors/dsv/dsv_driver.py @@ -8,6 +8,21 @@ scripts/rpa/dsv_driver.py from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + from typing import Any from dsv_report_export import ( diff --git a/scripts/rpa/dsv_export_timeout_diagnostics.py b/scripts/rpa/connectors/dsv/dsv_export_timeout_diagnostics.py similarity index 100% rename from scripts/rpa/dsv_export_timeout_diagnostics.py rename to scripts/rpa/connectors/dsv/dsv_export_timeout_diagnostics.py diff --git a/scripts/rpa/dsv_login_smoke.py b/scripts/rpa/connectors/dsv/dsv_login_smoke.py similarity index 91% rename from scripts/rpa/dsv_login_smoke.py rename to scripts/rpa/connectors/dsv/dsv_login_smoke.py index 7c689a8e..577908e3 100644 --- a/scripts/rpa/dsv_login_smoke.py +++ b/scripts/rpa/connectors/dsv/dsv_login_smoke.py @@ -21,9 +21,9 @@ from pathlib import Path def _load_worker(): - repo_root = Path(__file__).resolve().parents[2] - module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py" - spec = importlib.util.spec_from_file_location("freight_rpa_worker_smoke", module_path) + repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2]) + module_path = repo_root / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py" + spec = importlib.util.spec_from_file_location("inventory_rpa_worker_smoke", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) diff --git a/scripts/rpa/dsv_navigation.py b/scripts/rpa/connectors/dsv/dsv_navigation.py similarity index 98% rename from scripts/rpa/dsv_navigation.py rename to scripts/rpa/connectors/dsv/dsv_navigation.py index c6744486..775cb772 100644 --- a/scripts/rpa/dsv_navigation.py +++ b/scripts/rpa/connectors/dsv/dsv_navigation.py @@ -8,6 +8,21 @@ scripts/rpa/dsv_navigation.py from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + import json import sys import time diff --git a/scripts/rpa/dsv_report_export.py b/scripts/rpa/connectors/dsv/dsv_report_export.py similarity index 99% rename from scripts/rpa/dsv_report_export.py rename to scripts/rpa/connectors/dsv/dsv_report_export.py index f0f55b9c..f8c980e0 100644 --- a/scripts/rpa/dsv_report_export.py +++ b/scripts/rpa/connectors/dsv/dsv_report_export.py @@ -8,6 +8,21 @@ scripts/rpa/dsv_report_export.py from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + import importlib.util import sys import time diff --git a/scripts/rpa/dsv_report_parameters.py b/scripts/rpa/connectors/dsv/dsv_report_parameters.py similarity index 100% rename from scripts/rpa/dsv_report_parameters.py rename to scripts/rpa/connectors/dsv/dsv_report_parameters.py diff --git a/scripts/rpa/dsv_session.py b/scripts/rpa/connectors/dsv/dsv_session.py similarity index 97% rename from scripts/rpa/dsv_session.py rename to scripts/rpa/connectors/dsv/dsv_session.py index 5e51ae20..59120788 100644 --- a/scripts/rpa/dsv_session.py +++ b/scripts/rpa/connectors/dsv/dsv_session.py @@ -8,6 +8,21 @@ scripts/rpa/dsv_session.py from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + import sys import time from typing import Any, Callable diff --git a/scripts/rpa/freight_rpa_worker.py b/scripts/rpa/inventory/inventory_rpa_worker.py similarity index 98% rename from scripts/rpa/freight_rpa_worker.py rename to scripts/rpa/inventory/inventory_rpa_worker.py index 134d20b9..db2402a0 100644 --- a/scripts/rpa/freight_rpa_worker.py +++ b/scripts/rpa/inventory/inventory_rpa_worker.py @@ -5,7 +5,7 @@ Freight RPA worker (PoC). DSV 逻辑见 dsv_driver / dsv_session / dsv_navigation / dsv_report_export;Crane 见 crane_*。 Usage: - python scripts/rpa/freight_rpa_worker.py + python scripts/rpa/inventory/inventory_rpa_worker.py Required env (same as backend): HXOPS_API_BASE e.g. http://127.0.0.1:5052 @@ -53,9 +53,19 @@ from typing import Any, Callable, TextIO from cryptography.fernet import Fernet, InvalidToken import sys as _sys -_RPA_DIR = Path(__file__).resolve().parent -if str(_RPA_DIR) not in _sys.path: - _sys.path.insert(0, str(_RPA_DIR)) +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) from rpa_common import ( # noqa: E402 browser_timeout_ms as _browser_timeout_ms, @@ -70,7 +80,7 @@ import dsv_navigation # noqa: E402 import dsv_report_export # noqa: E402 from dsv_report_export import NoInventoryDataError # noqa: E402 import dsv_session # noqa: E402 -import freight_rpa_heartbeat # noqa: E402 +import rpa_heartbeat # noqa: E402 # 测试与 smoke 向后兼容 re-export _maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv @@ -255,7 +265,7 @@ def _backend_dir() -> Path: Returns: Path: backend 目录的绝对路径。 """ - return Path(__file__).resolve().parents[2] / "backend" + return _RPA_ROOT.parents[1] / "backend" def _resolve_backend_relative_path(value: str, *, default: Path | None = None) -> Path: @@ -727,7 +737,7 @@ def _load_crane_session_module() -> Any: import importlib.util from pathlib import Path - module_path = Path(__file__).resolve().parent / "crane_session.py" + module_path = _RPA_ROOT / "connectors" / "crane" / "crane_session.py" spec = importlib.util.spec_from_file_location("crane_session_runtime", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) @@ -806,7 +816,7 @@ def _load_crane_report_export_module() -> Any: import importlib.util from pathlib import Path - module_path = Path(__file__).resolve().parent / "crane_report_export.py" + module_path = _RPA_ROOT / "connectors" / "crane" / "crane_report_export.py" spec = importlib.util.spec_from_file_location("crane_report_export_runtime", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) @@ -2107,13 +2117,13 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None: for path in sorted(trigger_dir.glob("*.json")): if not path.is_file(): continue - freight_rpa_heartbeat.set_worker_runtime_status("busy") + rpa_heartbeat.set_worker_runtime_status("busy") try: handler(path, *extra_args) except Exception as exc: print(f"[error] {path.name}: {exc}", file=sys.stderr) finally: - freight_rpa_heartbeat.set_worker_runtime_status("idle") + rpa_heartbeat.set_worker_runtime_status("idle") def main() -> None: @@ -2145,7 +2155,7 @@ def main() -> None: print(f" queue={upload_queue_dir}") # 启动时立即上报一次,让管理端第一时间看到 Worker 上线。 - freight_rpa_heartbeat.maybe_send_heartbeat( + rpa_heartbeat.maybe_send_heartbeat( trigger_dir=inv_trigger_dir, drop_dir=drop_dir, last_sent_mono=0.0, @@ -2153,7 +2163,7 @@ def main() -> None: ) # 心跳节奏交由独立守护线程承担:批量站点导出会长时间阻塞主循环, # 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。 - freight_rpa_heartbeat.start_heartbeat_loop( + rpa_heartbeat.start_heartbeat_loop( trigger_dir=inv_trigger_dir, drop_dir=drop_dir, interval_seconds=heartbeat_seconds, diff --git a/scripts/rpa/register_rpa_background_tasks.ps1 b/scripts/rpa/inventory/register_inventory_worker_tasks.ps1 similarity index 85% rename from scripts/rpa/register_rpa_background_tasks.ps1 rename to scripts/rpa/inventory/register_inventory_worker_tasks.ps1 index b5fb7435..bcfcbd87 100644 --- a/scripts/rpa/register_rpa_background_tasks.ps1 +++ b/scripts/rpa/inventory/register_inventory_worker_tasks.ps1 @@ -9,7 +9,7 @@ Differences vs the standard "visible" scheduled task (README step 11 / 2.3): - powershell.exe gets -WindowStyle Hidden -> no console window to close by accident. - - start_rpa_worker.ps1 gets -Headless -> no visible Edge / no interactive desktop. + - start_inventory_worker.ps1 gets -Headless -> no visible Edge / no interactive desktop. Shape constraints (same as README 2.3): - Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows). @@ -26,13 +26,13 @@ All actions can target one environment or both via -Scope test|prod|all (default all). Usage (run in the RPA account's PowerShell): - .\scripts\rpa\register_rpa_background_tasks.ps1 # register test+prod - .\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test # register only test - .\scripts\rpa\register_rpa_background_tasks.ps1 -Start # start both now - .\scripts\rpa\register_rpa_background_tasks.ps1 -Start -Scope prod # start only prod - .\scripts\rpa\register_rpa_background_tasks.ps1 -Status -Scope test # only test - .\scripts\rpa\register_rpa_background_tasks.ps1 -Stop -Scope prod # stop only prod - .\scripts\rpa\register_rpa_background_tasks.ps1 -Unregister # unregister both + .\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 # register test+prod + .\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test # register only test + .\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start # start both now + .\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start -Scope prod # start only prod + .\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Status -Scope test # only test + .\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Stop -Scope prod # stop only prod + .\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Unregister # unregister both #> [CmdletBinding()] param( @@ -69,7 +69,7 @@ function Get-TasksForScope { function Assert-Launcher { # Validate the launcher and DPAPI Secret file required for one environment. param([string]$Root, [string]$Environment) - $launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1" + $launcher = Join-Path $Root "scripts\rpa\inventory\start_inventory_worker.ps1" if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) { throw "Launcher not found: $launcher" } @@ -86,7 +86,7 @@ function New-TaskDefinition { [string]$ApiBase, [string]$EnvName ) - $launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1" + $launcher = Join-Path $Root "scripts\rpa\inventory\start_inventory_worker.ps1" $secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName) # Key differences vs the visible scheduled task: diff --git a/scripts/rpa/run_inventory_batch_trigger.py b/scripts/rpa/inventory/run_inventory_batch_trigger.py similarity index 89% rename from scripts/rpa/run_inventory_batch_trigger.py rename to scripts/rpa/inventory/run_inventory_batch_trigger.py index d76a74a1..42f188d8 100644 --- a/scripts/rpa/run_inventory_batch_trigger.py +++ b/scripts/rpa/inventory/run_inventory_batch_trigger.py @@ -9,6 +9,9 @@ from pathlib import Path def _repo_root() -> Path: """Return the HXOPS repository root for relative operational directories.""" + for _p in Path(__file__).resolve().parents: + if (_p / "backend").is_dir() and (_p / "frontend").is_dir() and (_p / "scripts").is_dir(): + return _p return Path(__file__).resolve().parents[2] @@ -28,8 +31,8 @@ def _load_dotenv_dev() -> None: def _load_worker(): """Load the polling worker module so manual runs share the production trigger contract.""" - module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py" - spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_runner", module_path) + module_path = _repo_root() / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py" + spec = importlib.util.spec_from_file_location("inventory_rpa_worker_batch_runner", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) diff --git a/scripts/rpa/start_rpa_worker.ps1 b/scripts/rpa/inventory/start_inventory_worker.ps1 similarity index 97% rename from scripts/rpa/start_rpa_worker.ps1 rename to scripts/rpa/inventory/start_inventory_worker.ps1 index 1a81cce8..2c07a350 100644 --- a/scripts/rpa/start_rpa_worker.ps1 +++ b/scripts/rpa/inventory/start_inventory_worker.ps1 @@ -34,7 +34,7 @@ $ErrorActionPreference = "Stop" if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。" } -$workerScript = Join-Path $WorkerRoot "scripts\rpa\freight_rpa_worker.py" +$workerScript = Join-Path $WorkerRoot "scripts\rpa\inventory\inventory_rpa_worker.py" if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" } diff --git a/scripts/rpa/freight_receipt_crane_export.py b/scripts/rpa/receipt/receipt_crane_export.py similarity index 79% rename from scripts/rpa/freight_receipt_crane_export.py rename to scripts/rpa/receipt/receipt_crane_export.py index 61b6b687..64d0aefd 100644 --- a/scripts/rpa/freight_receipt_crane_export.py +++ b/scripts/rpa/receipt/receipt_crane_export.py @@ -2,6 +2,21 @@ from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + from typing import Any, Callable from urllib.parse import urlsplit, urlunsplit diff --git a/scripts/rpa/freight_receipt_dbs_export.py b/scripts/rpa/receipt/receipt_dbs_export.py similarity index 66% rename from scripts/rpa/freight_receipt_dbs_export.py rename to scripts/rpa/receipt/receipt_dbs_export.py index b7357189..978f9904 100644 --- a/scripts/rpa/freight_receipt_dbs_export.py +++ b/scripts/rpa/receipt/receipt_dbs_export.py @@ -2,6 +2,21 @@ from __future__ import annotations +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) + from typing import Any import dsv_report_export diff --git a/scripts/rpa/freight_receipt_rpa_worker.py b/scripts/rpa/receipt/receipt_rpa_worker.py similarity index 88% rename from scripts/rpa/freight_receipt_rpa_worker.py rename to scripts/rpa/receipt/receipt_rpa_worker.py index 7335e036..9b4fd8c5 100644 --- a/scripts/rpa/freight_receipt_rpa_worker.py +++ b/scripts/rpa/receipt/receipt_rpa_worker.py @@ -16,18 +16,29 @@ from typing import Any from cryptography.fernet import Fernet, InvalidToken -_RPA_DIR = Path(__file__).resolve().parent -if str(_RPA_DIR) not in __import__('sys').path: - __import__('sys').path.insert(0, str(_RPA_DIR)) +import sys as _sys +from pathlib import Path as _Path + +_RPA_ROOT = next( + (_c for _c in _Path(__file__).resolve().parents + if (_c / "connectors").is_dir() and (_c / "common").is_dir() + and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()), + None, +) +if _RPA_ROOT is not None: + for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): + _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) + if _dir not in _sys.path: + _sys.path.insert(0, _dir) from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402 -import freight_receipt_crane_export # noqa: E402 -import freight_receipt_dbs_export # noqa: E402 +import receipt_crane_export # noqa: E402 +import receipt_dbs_export # noqa: E402 def _backend_dir() -> Path: """从脚本位置确定 backend 根目录,避免计划任务 cwd 漂移。""" - return Path(__file__).resolve().parents[2] / 'backend' + return _RPA_ROOT.parents[1] / 'backend' def _require_dir(variable: str) -> Path: @@ -98,7 +109,7 @@ def _open_browser(download_dir: Path): from playwright.sync_api import sync_playwright except ImportError as exc: raise RuntimeError('Playwright is required for real receipt RPA') from exc - profile_root = _require_dir('SHIPPING_NOTICE_RPA_WORKER_RECEIPT_BROWSER_PROFILE_DIR') + profile_root = _require_dir('SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR') runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root))) playwright = sync_playwright().start() options: dict[str, Any] = {'headless': env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false').lower() == 'true', 'accept_downloads': True, 'downloads_path': str(download_dir)} @@ -172,9 +183,9 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None: if connector == 'dbs': if index: page = context.new_page(); page.set_default_timeout(browser_timeout_ms()) - download = freight_receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0) + download = receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0) else: - download = freight_receipt_crane_export.export_receipt_report(page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), select_or_fill=select_or_fill, click_text=click_text, first_in_profile=index == 0) + download = receipt_crane_export.export_receipt_report(page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), select_or_fill=select_or_fill, click_text=click_text, first_in_profile=index == 0) output = _save_download(download, drop_dir, unit) _post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit['callback_id'], 'status': 'success', 'file_path': str(output), 'original_filename': output.name, 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()}) except Exception as exc: @@ -202,7 +213,9 @@ def _claim_and_process(path: Path, drop_dir: Path, processed_dir: Path, failed_d _process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir) processed_dir.mkdir(parents=True, exist_ok=True) claimed.replace(processed_dir / claimed.name) - except Exception: + except (Exception, SystemExit): + # SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception), + # 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。 failed_dir.mkdir(parents=True, exist_ok=True) claimed.replace(failed_dir / claimed.name) raise diff --git a/scripts/rpa/start_receipt_rpa_worker.ps1 b/scripts/rpa/receipt/start_receipt_worker.ps1 similarity index 89% rename from scripts/rpa/start_receipt_rpa_worker.ps1 rename to scripts/rpa/receipt/start_receipt_worker.ps1 index b4e7f870..14a217ec 100644 --- a/scripts/rpa/start_receipt_rpa_worker.ps1 +++ b/scripts/rpa/receipt/start_receipt_worker.ps1 @@ -18,7 +18,7 @@ param( $ErrorActionPreference = 'Stop' if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile" } -$workerScript = Join-Path $WorkerRoot 'scripts\rpa\freight_receipt_rpa_worker.py' +$workerScript = Join-Path $WorkerRoot 'scripts\rpa\receipt\receipt_rpa_worker.py' if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" } function ConvertTo-PlainText { @@ -44,7 +44,8 @@ $processVars = [ordered]@{ SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3' SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers' SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop' - SHIPPING_NOTICE_RPA_WORKER_RECEIPT_BROWSER_PROFILE_DIR = Join-Path $dataRoot 'browser_profile' + # 浏览器 Profile 目录复用既有标准变量(与库存 RPA Worker 一致),不另设 RECEIPT_* 冗余变量。 + SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $WorkerRoot 'data\shipping_notice\freight_rpa\browser_profile' } foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') } try { diff --git a/scripts/start_local.ps1 b/scripts/start_local.ps1 index 1c403008..829823c7 100644 --- a/scripts/start_local.ps1 +++ b/scripts/start_local.ps1 @@ -72,7 +72,7 @@ function Stop-StaleHxopsPythonProcesses { [regex]::Escape((Join-Path $BackendPath "workers\worker_kb.py")), [regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")), [regex]::Escape((Join-Path $BackendPath "workers\worker_scheduler.py")), - [regex]::Escape((Join-Path $RepoRoot "scripts\rpa\freight_rpa_worker.py")) + [regex]::Escape((Join-Path $RepoRoot "scripts\rpa\inventory\inventory_rpa_worker.py")) ) # 说明:上面同时包含 backend/ 根目录的旧部署入口与 workers/ 目录的新单实例入口。 # 两套在仓库中并存(旧路径用于生产多进程部署,新路径推荐用于本地 IDE 单实例调试)。 @@ -445,7 +445,7 @@ function Start-FreightRpaWorkerWindow { -Title "freight-rpa-worker" ` -WorkingDirectory $RepoRoot ` -EnvPrefix $envPrefix ` - -Command "& '$BackendPath\.venv\Scripts\python.exe' .\scripts\rpa\freight_rpa_worker.py" + -Command "& '$BackendPath\.venv\Scripts\python.exe' .\scripts\rpa\inventory\inventory_rpa_worker.py" } function Start-FrontendWindow { From 6b53b563e7451b6138f2929d3635cf728d5ed286 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Fri, 28 Aug 2026 17:16:06 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat(in-transit-transfer):=20=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E5=9C=A8=E9=80=94=E4=BB=93=E8=87=AA=E5=8A=A8=E8=B0=83?= =?UTF-8?q?=E6=8B=A8Agent=E4=B8=80=E6=9C=9F=E5=AE=8C=E6=95=B4=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 包含后端服务层、任务处理器与消费Worker、前端聊天组件、数据库模型与迁移脚本、测试用例,同时新增外部系统连接器框架基础能力并更新相关文档。 --- .env.prod | 6 +- .env.shared | 18 + backend/app/api/__init__.py | 4 + backend/app/api/in_transit_transfer.py | 428 +++++++++++++ backend/app/api/integration_connector.py | 302 +++++++++ backend/app/core/config/settings.py | 22 + backend/app/jobs/handlers/__init__.py | 3 + .../jobs/handlers/in_transit_transfer_item.py | 29 + .../handlers/in_transit_transfer_precheck.py | 55 ++ .../jobs/handlers/in_transit_transfer_run.py | 29 + backend/app/jobs/types.py | 7 + backend/app/models/__init__.py | 28 + backend/app/models/in_transit_transfer.py | 352 +++++++++++ backend/app/models/integration_connector.py | 193 ++++++ .../app/models/shipping_inventory_config.py | 12 +- backend/app/models/shipping_receipt_report.py | 5 + .../agent_registry/catalog_bindings.py | 1 + .../agent_registry/data/catalog_manifest.yaml | 32 + .../agent_registry/handlers/bootstrap.py | 2 + .../handlers/in_transit_transfer.py | 34 ++ backend/app/services/chat/action_registry.py | 3 + .../services/in_transit_transfer/__init__.py | 8 + .../services/in_transit_transfer/archive.py | 168 +++++ .../app/services/in_transit_transfer/audit.py | 182 ++++++ .../in_transit_transfer/auto_transfer.py | 71 +++ .../in_transit_transfer/backlog_service.py | 141 +++++ .../in_transit_transfer/cancellation.py | 65 ++ .../in_transit_transfer/chat_actions.py | 100 +++ .../in_transit_transfer/concurrency.py | 25 + .../services/in_transit_transfer/contracts.py | 200 ++++++ .../in_transit_transfer/date_policy.py | 81 +++ .../app/services/in_transit_transfer/deps.py | 118 ++++ .../in_transit_transfer/erp_adapter.py | 295 +++++++++ .../in_transit_transfer/excel_export.py | 125 ++++ .../in_transit_transfer/execution_service.py | 399 ++++++++++++ .../in_transit_transfer/file_parser.py | 179 ++++++ .../in_transit_transfer/file_preparation.py | 96 +++ .../in_transit_transfer/gateway_adapter.py | 80 +++ .../in_transit_transfer/invoice_aggregator.py | 91 +++ .../manual_close_service.py | 66 ++ .../services/in_transit_transfer/metrics.py | 56 ++ .../in_transit_transfer/movement_contract.py | 75 +++ .../movement_file_repository.py | 125 ++++ .../in_transit_transfer/notification.py | 84 +++ .../in_transit_transfer/orchestrator.py | 83 +++ .../in_transit_transfer/precheck_service.py | 578 ++++++++++++++++++ .../services/in_transit_transfer/quantity.py | 61 ++ .../receipt_callback_bridge.py | 57 ++ .../receipt_trigger_service.py | 101 +++ .../services/in_transit_transfer/recovery.py | 87 +++ .../in_transit_transfer/recovery_service.py | 66 ++ .../in_transit_transfer/retry_service.py | 120 ++++ .../in_transit_transfer/serializers.py | 77 +++ .../in_transit_transfer/source_file_status.py | 63 ++ .../in_transit_transfer/source_job_service.py | 70 +++ .../services/in_transit_transfer/status.py | 217 +++++++ .../services/in_transit_transfer/strategy.py | 61 ++ .../integration_connector/__init__.py | 7 + .../services/integration_connector/binding.py | 105 ++++ .../integration_connector/capability.py | 125 ++++ .../services/integration_connector/engine.py | 153 +++++ .../services/integration_connector/errors.py | 104 ++++ .../services/integration_connector/gateway.py | 27 + .../services/integration_connector/mapping.py | 210 +++++++ .../integration_connector/security.py | 83 +++ .../transports/__init__.py | 18 + .../integration_connector/transports/base.py | 73 +++ .../integration_connector/transports/rest.py | 62 ++ .../integration_connector/transports/soap.py | 28 + .../schedule/in_transit_receipt_file_job.py | 57 ++ .../schedule/in_transit_transfer_job.py | 59 ++ backend/app/services/schedule/job_registry.py | 63 ++ .../inventory_parsing_profile.py | 62 +- .../ic1a2b3c4d5f_add_integration_connector.py | 157 +++++ ...d_purpose_to_inventory_parsing_profiles.py | 45 ++ ...d_parsing_profile_id_to_receipt_configs.py | 53 ++ ...5i_add_file_ready_to_source_jobs_status.py | 42 ++ .../it1a2b3c4d5e_add_in_transit_transfer.py | 275 +++++++++ .../tests/api/test_in_transit_transfer_api.py | 448 ++++++++++++++ .../api/test_integration_connector_api.py | 146 +++++ backend/tests/conftest.py | 71 +++ .../jobs/test_in_transit_transfer_jobs.py | 101 +++ .../performance/test_in_transit_transfer.py | 53 ++ .../services/in_transit_transfer/__init__.py | 1 + .../in_transit_transfer/assertions.py | 44 ++ .../services/in_transit_transfer/conftest.py | 39 ++ .../services/in_transit_transfer/factories.py | 63 ++ .../services/in_transit_transfer/fakes.py | 242 ++++++++ .../in_transit_transfer/repo_fakes.py | 88 +++ .../in_transit_transfer/test_archive.py | 97 +++ .../in_transit_transfer/test_audit.py | 145 +++++ .../test_backlog_service.py | 75 +++ .../in_transit_transfer/test_cancellation.py | 59 ++ .../in_transit_transfer/test_chat_actions.py | 114 ++++ .../in_transit_transfer/test_contracts.py | 145 +++++ .../in_transit_transfer/test_date_policy.py | 78 +++ .../in_transit_transfer/test_erp_adapter.py | 219 +++++++ .../in_transit_transfer/test_excel_export.py | 79 +++ .../test_execution_service.py | 224 +++++++ .../test_file_preparation.py | 128 ++++ .../test_invoice_aggregator.py | 117 ++++ .../in_transit_transfer/test_metrics.py | 46 ++ .../test_migration_execution.py | 72 +++ .../test_migration_revision.py | 59 ++ .../in_transit_transfer/test_models.py | 213 +++++++ .../test_movement_contract.py | 62 ++ .../test_movement_file_repository.py | 81 +++ .../test_movement_parser.py | 94 +++ .../in_transit_transfer/test_notification.py | 54 ++ .../in_transit_transfer/test_orchestrator.py | 69 +++ .../test_precheck_service.py | 164 +++++ .../test_quantity_match.py | 76 +++ .../test_query_inventory_gateway.py | 96 +++ .../test_receipt_file_parser.py | 123 ++++ .../test_receipt_trigger_service.py | 72 +++ .../test_recovery_service.py | 76 +++ .../test_retry_and_manual_close.py | 117 ++++ .../in_transit_transfer/test_schedule_jobs.py | 46 ++ .../test_source_file_status.py | 88 +++ .../test_source_job_service.py | 88 +++ .../test_status_machine.py | 123 ++++ .../test_strategy_policy.py | 63 ++ .../test_worker_recovery.py | 84 +++ .../integration_connector/test_binding.py | 122 ++++ .../integration_connector/test_capability.py | 59 ++ .../integration_connector/test_engine.py | 162 +++++ .../integration_connector/test_mapping.py | 96 +++ .../integration_connector/test_migration.py | 64 ++ .../integration_connector/test_models.py | 119 ++++ .../integration_connector/test_security.py | 73 +++ .../integration_connector/test_transports.py | 104 ++++ backend/tests/test_agent_registry_catalog.py | 12 +- ...test_agent_registry_in_transit_transfer.py | 69 +++ backend/tests/test_parsing_profile_purpose.py | 69 +++ .../test_in_transit_transfer_worker.py | 23 + backend/workers/worker_in_transit_transfer.py | 24 + docker-compose.yml | 46 ++ docs/demand.md | 7 + docs/features/README.md | 2 +- .../features/in-transit-transfer/technical.md | 95 +++ docs/funclist.md | 30 + docs/platform/README.md | 2 + .../integration-connector-framework-design.md | 385 ++++++++++++ docs/tec.md | 4 + .../features/chat/api/transfer.api.spec.ts | 78 +++ .../src/features/chat/api/transfer.api.ts | 112 ++++ .../chat/components/ChatMessageList.vue | 13 +- .../chat/components/ChatViewContent.vue | 15 +- .../components/messages/ChatMessageBubble.vue | 11 + .../messages/TransferBacklogSummaryCard.vue | 90 +++ .../messages/TransferFileProgressCard.vue | 50 ++ .../messages/TransferHomePanel.spec.ts | 131 ++++ .../components/messages/TransferHomePanel.vue | 134 ++++ .../messages/TransferManualCloseDialog.vue | 67 ++ .../messages/TransferMessageView.spec.ts | 173 ++++++ .../messages/TransferMessageView.vue | 243 ++++++++ .../messages/TransferPrecheckCard.vue | 157 +++++ .../messages/TransferProgressCard.vue | 60 ++ .../messages/TransferResultCard.vue | 131 ++++ .../messages/TransferSourceSelectCard.spec.ts | 89 +++ .../messages/TransferSourceSelectCard.vue | 246 ++++++++ .../components/messages/transferCards.spec.ts | 147 +++++ .../chat/composables/transferLocales.spec.ts | 34 ++ .../chat/composables/useChatTransfer.spec.ts | 113 ++++ .../chat/composables/useChatTransfer.ts | 259 ++++++++ .../chat/e2e/in-transit-transfer.spec.ts | 117 ++++ .../src/features/chat/types/chat.types.ts | 2 +- .../src/features/chat/types/transfer.types.ts | 174 ++++++ frontend/src/locales/en/chat.json | 97 ++- frontend/src/locales/en/errors.json | 27 +- frontend/src/locales/th/chat.json | 97 ++- frontend/src/locales/th/errors.json | 27 +- frontend/src/locales/zh-CN/chat.json | 97 ++- frontend/src/locales/zh-CN/errors.json | 27 +- frontend/src/locales/zh-TW/chat.json | 97 ++- frontend/src/locales/zh-TW/errors.json | 27 +- .../src/shared/utils/agent-registry.utils.ts | 1 + 177 files changed, 17260 insertions(+), 36 deletions(-) create mode 100644 backend/app/api/in_transit_transfer.py create mode 100644 backend/app/api/integration_connector.py create mode 100644 backend/app/jobs/handlers/in_transit_transfer_item.py create mode 100644 backend/app/jobs/handlers/in_transit_transfer_precheck.py create mode 100644 backend/app/jobs/handlers/in_transit_transfer_run.py create mode 100644 backend/app/models/in_transit_transfer.py create mode 100644 backend/app/models/integration_connector.py create mode 100644 backend/app/services/agent_registry/handlers/in_transit_transfer.py create mode 100644 backend/app/services/in_transit_transfer/__init__.py create mode 100644 backend/app/services/in_transit_transfer/archive.py create mode 100644 backend/app/services/in_transit_transfer/audit.py create mode 100644 backend/app/services/in_transit_transfer/auto_transfer.py create mode 100644 backend/app/services/in_transit_transfer/backlog_service.py create mode 100644 backend/app/services/in_transit_transfer/cancellation.py create mode 100644 backend/app/services/in_transit_transfer/chat_actions.py create mode 100644 backend/app/services/in_transit_transfer/concurrency.py create mode 100644 backend/app/services/in_transit_transfer/contracts.py create mode 100644 backend/app/services/in_transit_transfer/date_policy.py create mode 100644 backend/app/services/in_transit_transfer/deps.py create mode 100644 backend/app/services/in_transit_transfer/erp_adapter.py create mode 100644 backend/app/services/in_transit_transfer/excel_export.py create mode 100644 backend/app/services/in_transit_transfer/execution_service.py create mode 100644 backend/app/services/in_transit_transfer/file_parser.py create mode 100644 backend/app/services/in_transit_transfer/file_preparation.py create mode 100644 backend/app/services/in_transit_transfer/gateway_adapter.py create mode 100644 backend/app/services/in_transit_transfer/invoice_aggregator.py create mode 100644 backend/app/services/in_transit_transfer/manual_close_service.py create mode 100644 backend/app/services/in_transit_transfer/metrics.py create mode 100644 backend/app/services/in_transit_transfer/movement_contract.py create mode 100644 backend/app/services/in_transit_transfer/movement_file_repository.py create mode 100644 backend/app/services/in_transit_transfer/notification.py create mode 100644 backend/app/services/in_transit_transfer/orchestrator.py create mode 100644 backend/app/services/in_transit_transfer/precheck_service.py create mode 100644 backend/app/services/in_transit_transfer/quantity.py create mode 100644 backend/app/services/in_transit_transfer/receipt_callback_bridge.py create mode 100644 backend/app/services/in_transit_transfer/receipt_trigger_service.py create mode 100644 backend/app/services/in_transit_transfer/recovery.py create mode 100644 backend/app/services/in_transit_transfer/recovery_service.py create mode 100644 backend/app/services/in_transit_transfer/retry_service.py create mode 100644 backend/app/services/in_transit_transfer/serializers.py create mode 100644 backend/app/services/in_transit_transfer/source_file_status.py create mode 100644 backend/app/services/in_transit_transfer/source_job_service.py create mode 100644 backend/app/services/in_transit_transfer/status.py create mode 100644 backend/app/services/in_transit_transfer/strategy.py create mode 100644 backend/app/services/integration_connector/__init__.py create mode 100644 backend/app/services/integration_connector/binding.py create mode 100644 backend/app/services/integration_connector/capability.py create mode 100644 backend/app/services/integration_connector/engine.py create mode 100644 backend/app/services/integration_connector/errors.py create mode 100644 backend/app/services/integration_connector/gateway.py create mode 100644 backend/app/services/integration_connector/mapping.py create mode 100644 backend/app/services/integration_connector/security.py create mode 100644 backend/app/services/integration_connector/transports/__init__.py create mode 100644 backend/app/services/integration_connector/transports/base.py create mode 100644 backend/app/services/integration_connector/transports/rest.py create mode 100644 backend/app/services/integration_connector/transports/soap.py create mode 100644 backend/app/services/schedule/in_transit_receipt_file_job.py create mode 100644 backend/app/services/schedule/in_transit_transfer_job.py create mode 100644 backend/migrations/versions/ic1a2b3c4d5f_add_integration_connector.py create mode 100644 backend/migrations/versions/if1b2c3d4e5g_add_purpose_to_inventory_parsing_profiles.py create mode 100644 backend/migrations/versions/if1b2c3d4e5h_add_parsing_profile_id_to_receipt_configs.py create mode 100644 backend/migrations/versions/if1b2c3d4e5i_add_file_ready_to_source_jobs_status.py create mode 100644 backend/migrations/versions/it1a2b3c4d5e_add_in_transit_transfer.py create mode 100644 backend/tests/api/test_in_transit_transfer_api.py create mode 100644 backend/tests/api/test_integration_connector_api.py create mode 100644 backend/tests/jobs/test_in_transit_transfer_jobs.py create mode 100644 backend/tests/performance/test_in_transit_transfer.py create mode 100644 backend/tests/services/in_transit_transfer/__init__.py create mode 100644 backend/tests/services/in_transit_transfer/assertions.py create mode 100644 backend/tests/services/in_transit_transfer/conftest.py create mode 100644 backend/tests/services/in_transit_transfer/factories.py create mode 100644 backend/tests/services/in_transit_transfer/fakes.py create mode 100644 backend/tests/services/in_transit_transfer/repo_fakes.py create mode 100644 backend/tests/services/in_transit_transfer/test_archive.py create mode 100644 backend/tests/services/in_transit_transfer/test_audit.py create mode 100644 backend/tests/services/in_transit_transfer/test_backlog_service.py create mode 100644 backend/tests/services/in_transit_transfer/test_cancellation.py create mode 100644 backend/tests/services/in_transit_transfer/test_chat_actions.py create mode 100644 backend/tests/services/in_transit_transfer/test_contracts.py create mode 100644 backend/tests/services/in_transit_transfer/test_date_policy.py create mode 100644 backend/tests/services/in_transit_transfer/test_erp_adapter.py create mode 100644 backend/tests/services/in_transit_transfer/test_excel_export.py create mode 100644 backend/tests/services/in_transit_transfer/test_execution_service.py create mode 100644 backend/tests/services/in_transit_transfer/test_file_preparation.py create mode 100644 backend/tests/services/in_transit_transfer/test_invoice_aggregator.py create mode 100644 backend/tests/services/in_transit_transfer/test_metrics.py create mode 100644 backend/tests/services/in_transit_transfer/test_migration_execution.py create mode 100644 backend/tests/services/in_transit_transfer/test_migration_revision.py create mode 100644 backend/tests/services/in_transit_transfer/test_models.py create mode 100644 backend/tests/services/in_transit_transfer/test_movement_contract.py create mode 100644 backend/tests/services/in_transit_transfer/test_movement_file_repository.py create mode 100644 backend/tests/services/in_transit_transfer/test_movement_parser.py create mode 100644 backend/tests/services/in_transit_transfer/test_notification.py create mode 100644 backend/tests/services/in_transit_transfer/test_orchestrator.py create mode 100644 backend/tests/services/in_transit_transfer/test_precheck_service.py create mode 100644 backend/tests/services/in_transit_transfer/test_quantity_match.py create mode 100644 backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py create mode 100644 backend/tests/services/in_transit_transfer/test_receipt_file_parser.py create mode 100644 backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py create mode 100644 backend/tests/services/in_transit_transfer/test_recovery_service.py create mode 100644 backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py create mode 100644 backend/tests/services/in_transit_transfer/test_schedule_jobs.py create mode 100644 backend/tests/services/in_transit_transfer/test_source_file_status.py create mode 100644 backend/tests/services/in_transit_transfer/test_source_job_service.py create mode 100644 backend/tests/services/in_transit_transfer/test_status_machine.py create mode 100644 backend/tests/services/in_transit_transfer/test_strategy_policy.py create mode 100644 backend/tests/services/in_transit_transfer/test_worker_recovery.py create mode 100644 backend/tests/services/integration_connector/test_binding.py create mode 100644 backend/tests/services/integration_connector/test_capability.py create mode 100644 backend/tests/services/integration_connector/test_engine.py create mode 100644 backend/tests/services/integration_connector/test_mapping.py create mode 100644 backend/tests/services/integration_connector/test_migration.py create mode 100644 backend/tests/services/integration_connector/test_models.py create mode 100644 backend/tests/services/integration_connector/test_security.py create mode 100644 backend/tests/services/integration_connector/test_transports.py create mode 100644 backend/tests/test_agent_registry_in_transit_transfer.py create mode 100644 backend/tests/test_parsing_profile_purpose.py create mode 100644 backend/tests/workers/test_in_transit_transfer_worker.py create mode 100644 backend/workers/worker_in_transit_transfer.py create mode 100644 docs/features/in-transit-transfer/technical.md create mode 100644 docs/platform/integration-connector-framework-design.md create mode 100644 frontend/src/features/chat/api/transfer.api.spec.ts create mode 100644 frontend/src/features/chat/api/transfer.api.ts create mode 100644 frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue create mode 100644 frontend/src/features/chat/components/messages/TransferFileProgressCard.vue create mode 100644 frontend/src/features/chat/components/messages/TransferHomePanel.spec.ts create mode 100644 frontend/src/features/chat/components/messages/TransferHomePanel.vue create mode 100644 frontend/src/features/chat/components/messages/TransferManualCloseDialog.vue create mode 100644 frontend/src/features/chat/components/messages/TransferMessageView.spec.ts create mode 100644 frontend/src/features/chat/components/messages/TransferMessageView.vue create mode 100644 frontend/src/features/chat/components/messages/TransferPrecheckCard.vue create mode 100644 frontend/src/features/chat/components/messages/TransferProgressCard.vue create mode 100644 frontend/src/features/chat/components/messages/TransferResultCard.vue create mode 100644 frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts create mode 100644 frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue create mode 100644 frontend/src/features/chat/components/messages/transferCards.spec.ts create mode 100644 frontend/src/features/chat/composables/transferLocales.spec.ts create mode 100644 frontend/src/features/chat/composables/useChatTransfer.spec.ts create mode 100644 frontend/src/features/chat/composables/useChatTransfer.ts create mode 100644 frontend/src/features/chat/e2e/in-transit-transfer.spec.ts create mode 100644 frontend/src/features/chat/types/transfer.types.ts diff --git a/.env.prod b/.env.prod index 348a8491..d304b57e 100644 --- a/.env.prod +++ b/.env.prod @@ -119,8 +119,8 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 # MinerU 订单附件表格结构化(服务地址由 Jenkins/系统环境注入,未配置时保持关闭) -SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false -SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL= +SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=true +SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=http://192.168.100.230:8100/ SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10 SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300 SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=10 @@ -140,7 +140,7 @@ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 # 企微心跳告警总开关(默认关闭;需要时改为 true) SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false # 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微 -SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 +SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 diff --git a/.env.shared b/.env.shared index a402ff20..ae16bdd9 100644 --- a/.env.shared +++ b/.env.shared @@ -165,6 +165,24 @@ EDKB_WORD_FILE_TIMEOUT_SEC=420 # --- 9. 业务模块 --- +# 在途仓自动调拨 Agent(来源并发 / ERP 查询并发 / ERP 写并发恒 1 / 确认有效期 10 分钟 / 老化阈值) +IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=2 +IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=2 +IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=1 +IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=60 +IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=60 +IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=600 +IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3 +IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5 +IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7 +# ERP SOAP 地址与凭据仅由环境/Secret 注入(WSDL 冻结前留空 = fail-closed,禁止写入本文件) +# IN_TRANSIT_TRANSFER_ERP_ENDPOINT= +# IN_TRANSIT_TRANSFER_ERP_USERNAME= +# IN_TRANSIT_TRANSFER_ERP_PASSWORD= +IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG= +# 归档 bucket(MinIO;凭据复用 MINIO_*) +IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer + # chat回答的评分与评论 FEEDBACK_ENABLED=true # 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表) diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index dd5d73df..cd642cf2 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -44,6 +44,8 @@ def register_blueprints(app: Flask) -> None: from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp, voucher_check_tools_bp from app.api.files import files_bp from app.api.procurement_contract_tools import procurement_contract_bp + from app.api.in_transit_transfer import in_transit_transfer_bp + from app.api.integration_connector import integration_connector_bp app.register_blueprint(chat_bp, url_prefix='/api/chat') app.register_blueprint(admin_bp, url_prefix='/api/admin') @@ -73,3 +75,5 @@ def register_blueprints(app: Flask) -> None: app.register_blueprint(training_admin_bp, url_prefix='/api/admin') app.register_blueprint(files_bp, url_prefix='/api/files') app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract') + app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer') + app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector') diff --git a/backend/app/api/in_transit_transfer.py b/backend/app/api/in_transit_transfer.py new file mode 100644 index 00000000..4fae26b8 --- /dev/null +++ b/backend/app/api/in_transit_transfer.py @@ -0,0 +1,428 @@ +"""backend/app/api/in_transit_transfer.py + +用途:在途仓自动调拨用户态 API(仓库管理人员)。 +依赖:app.core.auth.jwt、app.core.errors、app.core.response、precheck_service、deps。 +逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id); + Phase 1 提供预检创建(POST /prechecks)与进度恢复(GET /prechecks/{id})。 +""" + +from __future__ import annotations + +from functools import wraps +from typing import Any + +from flask import Blueprint, g, request, send_file + +from app.core.auth.jwt import get_current_user +from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError +from app.core.response import ok +from app.models import Agent +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.cancellation import cancel_run +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.excel_export import _MIME, build_exceptions_workbook +from app.services.in_transit_transfer.execution_service import ( + execute_precheck, + get_run, + serialize_run_result, +) +from app.services.in_transit_transfer.manual_close_service import manual_close_item +from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck +from app.services.in_transit_transfer.retry_service import retry_item +from app.services.in_transit_transfer.serializers import ( + serialize_item, + serialize_source, + serialize_summary, +) + +in_transit_transfer_bp = Blueprint("in_transit_transfer", __name__) + +TRANSFER_AGENT_CODE = "in_transit_transfer" + + +def _require_user(): + """校验当前登录用户;未认证抛 UnauthorizedError。""" + user = get_current_user() + if not user: + raise UnauthorizedError("Unauthorized") + return user + + +def require_transfer_permission(f): + """装饰器:admin 放行,或持有 in_transit_transfer Agent 权限的用户放行。""" + + @wraps(f) + def decorated(*args, **kwargs): + user = _require_user() + if user.role == "admin": + return f(*args, **kwargs) + agent = Agent.query.filter_by(agent_code=TRANSFER_AGENT_CODE, is_active=True).first() + if agent is None or agent not in user.agents: + raise ForbiddenError("Transfer agent permission required") + return f(*args, **kwargs) + + return decorated + + +def _ok(payload: Any, *, status: int = 200): + """统一成功 envelope(带 request_id)。""" + return ok(payload, request_id=getattr(g, "request_id", None), status=status) + + +@in_transit_transfer_bp.route("/prechecks", methods=["POST"]) +@require_transfer_permission +def create_precheck_api(): + """创建或复用一次调拨预检(只读,不写 ERP)。 + + 请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选)}。 + 响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。 + """ + body = request.get_json(silent=True) or {} + if not isinstance(body, dict): + raise ValidationError("request body must be a JSON object") + source_codes = body.get("source_codes") + if not isinstance(source_codes, list) or not source_codes: + raise ValidationError("source_codes is required") + business_date = str(body.get("business_date") or business_date_now()) + deps = transfer_deps.get_transfer_dependencies() + summary = create_precheck( + source_codes=[str(item).strip() for item in source_codes], + business_date=business_date, + deps=deps, + ) + return _ok(serialize_summary(summary), status=201) + + +@in_transit_transfer_bp.route("/prechecks/", methods=["GET"]) +@require_transfer_permission +def get_precheck_api(precheck_id: str): + """恢复预检进度与明细(页面刷新/会话恢复)。""" + restored = restore_precheck(precheck_id) + return _ok({ + "summary": serialize_summary(restored["summary"]), + "items": [serialize_item(item) for item in restored["items"]], + "sources": [serialize_source(source) for source in restored["sources"]], + }) + + +@in_transit_transfer_bp.route("/prechecks//execute", methods=["POST"]) +@require_transfer_permission +def execute_precheck_api(precheck_id: str): + """确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。 + + 请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。 + 响应:201 envelope,data 为 run_no / run 状态 / ERP 单号聚合结果。 + """ + body = request.get_json(silent=True) or {} + invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None + if invoice_nos is not None and not isinstance(invoice_nos, list): + raise ValidationError("invoice_nos must be a list") + deps = transfer_deps.get_transfer_dependencies() + outcome = execute_precheck( + precheck_id=precheck_id, + deps=deps, + selected_invoice_nos=invoice_nos, + ) + return _ok({ + "run_no": outcome.run_no, + "status": outcome.status, + "result": serialize_run_result(outcome.result), + }, status=201) + + +@in_transit_transfer_bp.route("/runs/", methods=["GET"]) +@require_transfer_permission +def get_run_api(run_no: str): + """恢复 Run 最终结果(页面刷新/会话恢复)。""" + return _ok(get_run(run_no)) + + +@in_transit_transfer_bp.route("/runs//cancel", methods=["POST"]) +@require_transfer_permission +def cancel_run_api(run_no: str): + """请求停止剩余任务(原因必填,已成功单据保留)。""" + body = request.get_json(silent=True) or {} + reason = body.get("reason") if isinstance(body, dict) else None + return _ok(cancel_run(run_no=run_no, reason=reason)) + + +@in_transit_transfer_bp.route("/items//retry", methods=["POST"]) +@require_transfer_permission +def retry_item_api(item_id: int): + """人工重试异常项(基于冻结文件仅重新查询 ERP,创建新 Attempt)。 + + 请求体:{"kind": "erp_recheck"}(可选,默认 erp_recheck)。 + """ + body = request.get_json(silent=True) or {} + kind = body.get("kind") if isinstance(body, dict) else None + deps = transfer_deps.get_transfer_dependencies() + return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "erp_recheck")) + + +@in_transit_transfer_bp.route("/items//manual-close", methods=["POST"]) +@require_transfer_permission +def manual_close_item_api(item_id: int): + """人工关闭异常项(原因必填,永久排除)。""" + body = request.get_json(silent=True) or {} + reason = body.get("reason") if isinstance(body, dict) else None + return _ok(manual_close_item(item_id=item_id, reason=reason)) + + +@in_transit_transfer_bp.route("/runs//exceptions.xlsx", methods=["GET"]) +@require_transfer_permission +def exceptions_excel_api(run_no: str): + """下载本次 Run 的七 Sheet 异常 Excel(下载行为记录访问审计)。""" + import io + + from app import db + from app.services.in_transit_transfer.audit import build_transfer_audit_event + + data = build_exceptions_workbook(run_no) + user = _require_user() + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_EXCEL_DOWNLOADED", + aggregate_type="transfer_run", + aggregate_id=run_no, + run_no=run_no, + actor_type="user", + actor_id=str(user.id) if user.id else None, + actor_display=str(getattr(user, "name", "") or ""), + request_id=getattr(g, "request_id", None), + result="success", + )) + db.session.commit() + return send_file( + io.BytesIO(data), + mimetype=_MIME, + as_attachment=True, + download_name=f"transfer-exceptions-{run_no}.xlsx", + ) + + +@in_transit_transfer_bp.route("/runs//receipt-files", methods=["GET"]) +@require_transfer_permission +def receipt_files_api(run_no: str): + """下载本次收料来源文件(清单 + 原始行追溯,zip);记录访问审计。""" + import io + import json + import zipfile + + from app import db + from app.models import TransferInvoiceItem, TransferRun + from app.services.in_transit_transfer.audit import build_transfer_audit_event + + run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + precheck = run.prechecks[0] if run.prechecks else None + file_snapshot = precheck.file_snapshot_json if precheck and isinstance(precheck.file_snapshot_json, dict) else {} + + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive: + for source_code in run.source_codes_json: + manifest = { + "source_code": source_code, + "business_date": run.business_date, + **dict(file_snapshot.get(source_code) or {}), + } + archive.writestr(f"{source_code}-receipt-info.json", json.dumps(manifest, ensure_ascii=False, indent=2)) + rows = [] + for item in TransferInvoiceItem.query.filter_by(run_id=run.id).all(): + for line in (item.raw_lines_json or []): + rows.append({ + "invoice_no": item.invoice_no, "source_code": item.source_code, + "sheet": line.get("sheet", ""), "row_no": line.get("row_no", ""), + "file_version": line.get("file_version", ""), + }) + archive.writestr("raw-line-trace.json", json.dumps(rows, ensure_ascii=False, indent=2)) + + user = _require_user() + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED", + aggregate_type="transfer_run", + aggregate_id=run_no, + run_no=run_no, + actor_type="user", + actor_id=str(user.id) if user.id else None, + actor_display=str(getattr(user, "name", "") or ""), + request_id=getattr(g, "request_id", None), + result="success", + )) + db.session.commit() + return send_file( + io.BytesIO(buffer.getvalue()), + mimetype="application/zip", + as_attachment=True, + download_name=f"receipt-files-{run_no}.zip", + ) + + +@in_transit_transfer_bp.route("/runs//erp-inventory", methods=["GET"]) +@require_transfer_permission +def erp_inventory_api(run_no: str): + """下载本次预检冻结的 ERP 库存表(csv);记录访问审计。""" + import io + + from app import db + from app.models import TransferInvoiceItem, TransferRun + from app.services.in_transit_transfer.audit import build_transfer_audit_event + + run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,erp_quantity,result,erp_document_no"] + for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all(): + lines.append(",".join([ + str(item.invoice_no), str(item.source_code), str(item.material_no), + str(item.from_warehouse), str(item.to_warehouse), + str(item.receipt_quantity), str(item.erp_quantity or ""), + str(item.result_code or item.status), str(item.erp_document_no or ""), + ])) + data = ("\n".join(lines) + "\n").encode("utf-8") + + user = _require_user() + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED", + aggregate_type="transfer_run", + aggregate_id=run_no, + run_no=run_no, + actor_type="user", + actor_id=str(user.id) if user.id else None, + actor_display=str(getattr(user, "name", "") or ""), + request_id=getattr(g, "request_id", None), + result="success", + )) + db.session.commit() + return send_file( + io.BytesIO(data), + mimetype="text/csv", + as_attachment=True, + download_name=f"erp-inventory-{run_no}.csv", + ) + + +@in_transit_transfer_bp.route("/metrics", methods=["GET"]) +@require_transfer_permission +def transfer_metrics_api(): + """调拨运营指标(成功率/失败类型/待处理老化/通知失败),供运营看板。""" + from app.services.in_transit_transfer.metrics import collect_metrics + + return _ok(collect_metrics()) + + +@in_transit_transfer_bp.route("/sources", methods=["GET"]) +@require_transfer_permission +def transfer_sources_api(): + """来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。 + + 每来源附收料文件状态(ready/fetching/failed/none + has_ready_file), + 供前端门禁(无 ready 文件时禁止确认预检)与状态标识。只读复用已启用库存来源。 + """ + from app.models import ShippingInventorySource + from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + + rows = ShippingInventorySource.query.filter_by(enabled=True).order_by( + ShippingInventorySource.connector_type, ShippingInventorySource.source_code, + ).all() + return _ok([ + { + "source_code": source.source_code, + "display_name": source.display_name, + "platform": source.connector_type, + "enabled": bool(source.enabled), + **resolve_source_file_status(source_code=source.source_code), + } + for source in rows + ]) + + +@in_transit_transfer_bp.route("/sources//retry-rpa", methods=["POST"]) +@require_transfer_permission +def retry_source_rpa_api(source_code: str): + """对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。 + + 响应:{"source_code", "file_status", "ok"};配置缺失时 fail-closed(ok=False)。 + """ + from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa + from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + from app.services.in_transit_transfer.date_policy import business_date_now + + source_code = str(source_code).strip() + outcome = trigger_receipt_rpa( + source_code=source_code, + business_date=str(business_date_now()), + reason="transfer_retry_receipt", + ) + status = resolve_source_file_status(source_code=source_code) + if not outcome.get("ok"): + return _ok({ + "source_code": source_code, + "ok": False, + "file_status": status["file_status"], + "error_code": outcome.get("error_code"), + }) + return _ok({ + "source_code": source_code, + "ok": True, + "file_status": "fetching", + "callback_id": outcome.get("callback_id"), + }, status=202) + + +@in_transit_transfer_bp.route("/backlog", methods=["GET"]) +@require_transfer_permission +def backlog_api(): + """待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。""" + from app import db + from app.services.in_transit_transfer.audit import build_transfer_audit_event + from app.services.in_transit_transfer.backlog_service import list_backlog + + items = list_backlog() + user = _require_user() + db.session.add(build_transfer_audit_event( + event_type='TRANSFER_BACKLOG_VIEWED', + aggregate_type='transfer_backlog', + aggregate_id='backlog', + actor_type='user', + actor_id=str(user.id) if user.id else None, + actor_display=str(getattr(user, 'name', '') or ''), + request_id=getattr(g, 'request_id', None), + result='success', + after={'item_count': len(items)}, + )) + db.session.commit() + return _ok([_serialize_backlog_item(item) for item in items]) + + +@in_transit_transfer_bp.route("/backlog/summary", methods=["GET"]) +@require_transfer_permission +def backlog_summary_api(): + """待处理异常汇总(含 3/5/7 天老化分级)。""" + from app.services.in_transit_transfer.backlog_service import backlog_summary + + summary = backlog_summary() + return _ok({ + 'recoverable': summary.recoverable_count, + 'closed': summary.closed_count, + 'unknown': summary.unknown_count, + 'aging': { + 'warn_3d': summary.warn_3d, + 'escalate_5d': summary.escalate_5d, + 'critical_7d': summary.critical_7d, + }, + }) + + +def _serialize_backlog_item(item) -> dict[str, Any]: + """待处理池项序列化。""" + return { + 'item_id': item.item_id, + 'source_code': item.source_code, + 'invoice_no': item.invoice_no, + 'material_no': item.material_no, + 'status': item.status, + 'reason': item.reason, + 'age_days': item.age_days, + 'aging_level': item.aging_level, + 'last_attempt_at': item.last_attempt_at, + } diff --git a/backend/app/api/integration_connector.py b/backend/app/api/integration_connector.py new file mode 100644 index 00000000..12d716ed --- /dev/null +++ b/backend/app/api/integration_connector.py @@ -0,0 +1,302 @@ +"""api/integration_connector.py + +用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。 +依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。 +逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key}, + 拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。 +注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有 + /api/integration Dify 文件代理)。 +""" + +from __future__ import annotations + +import uuid + +from flask import Blueprint, request + +from app.core.decorators import require_admin +from app.core.errors import NotFoundError, ValidationError +from app.core.response import ok +from app.models import ( + IntegrationBinding, + IntegrationClientInstance, + IntegrationCredentialReference, + IntegrationInterfaceDefinition, +) +from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities +from app.services.integration_connector.gateway import get_capability_gateway +from app.services.integration_connector.transports.base import IntegrationCallResult + +integration_connector_bp = Blueprint('integration_connector', __name__) + +VALID_CONNECTOR_TYPES = ('rest', 'soap') +VALID_STATUSES = ('draft', 'published', 'retired') + + +def _require(value, field: str) -> None: + """字段必填校验。""" + if value is None or (isinstance(value, str) and not value.strip()): + raise ValidationError(f'{field} is required', details={'field': field}) + + +def _serialize_client(client) -> dict: + return { + 'id': client.id, 'code': client.code, 'name': client.name, + 'connector_type': client.connector_type, 'environment': client.environment, + 'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code, + 'enabled': client.enabled, + } + + +def _serialize_interface(iface) -> dict: + return { + 'id': iface.id, 'code': iface.code, 'name': iface.name, + 'client_instance_code': iface.client_instance_code, 'connector_type': iface.connector_type, + 'request_spec_json': iface.request_spec_json or {}, 'input_schema_json': iface.input_schema_json or {}, + 'response_mapping_json': iface.response_mapping_json or {}, 'output_schema_json': iface.output_schema_json or {}, + 'version': iface.version, 'status': iface.status, 'enabled': iface.enabled, + } + + +def _serialize_binding(binding) -> dict: + return { + 'id': binding.id, 'capability': binding.capability, + 'context_selector_json': binding.context_selector_json or {}, + 'client_instance_code': binding.client_instance_code, + 'interface_definition_code': binding.interface_definition_code, + 'mapping_version': binding.mapping_version, 'priority': binding.priority, + 'environment': binding.environment, 'effective_from': binding.effective_from, + 'effective_to': binding.effective_to, 'status': binding.status, + } + + +def _serialize_credential(cred) -> dict: + return { + 'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref, + 'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type, + 'version': cred.version, 'status': cred.status, + 'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None, + } + + +def _result_to_dict(result: IntegrationCallResult) -> dict: + return { + 'status': result.status, + 'data': result.data, + 'error_code': result.error_code, + 'error_message': result.error_message, + 'document_no': result.document_no, + 'trace_id': result.trace_id, + } + + +# ---- 能力清单与调用 ---- + +@integration_connector_bp.route('/capabilities', methods=['GET']) +@require_admin +def list_capabilities_endpoint(): + ensure_capabilities_loaded() + data = [{ + 'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency, + 'input_schema': spec.input_schema, 'output_schema': spec.output_schema, + } for spec in list_capabilities()] + return ok(data) + + +@integration_connector_bp.route('/capabilities/', methods=['POST']) +@require_admin +def call_capability(capability): + body = request.get_json(silent=True) or {} + if body.get('interface_id') is not None: + raise ValidationError( + 'interface_id is not allowed for capability calls', + code='INTEGRATION.INTERFACE_ID_NOT_ALLOWED', + ) + params = body.get('params') or {} + context = body.get('context') or {} + operation_id = str(body.get('operation_id') or f'api-{uuid.uuid4().hex}') + idempotency_key = body.get('idempotency_key') + result = get_capability_gateway().call( + capability=capability, context=context, params=params, + operation_id=operation_id, idempotency_key=idempotency_key, + ) + return ok(_result_to_dict(result)) + + +# ---- 客户端实例 ---- + +@integration_connector_bp.route('/client-instances', methods=['GET']) +@require_admin +def list_client_instances(): + rows = IntegrationClientInstance.query.order_by(IntegrationClientInstance.code).all() + return ok([_serialize_client(row) for row in rows]) + + +@integration_connector_bp.route('/client-instances', methods=['POST']) +@require_admin +def create_client_instance(): + body = request.get_json(silent=True) or {} + connector_type = str(body.get('connector_type') or '').strip() + _require(body.get('code'), 'code') + _require(body.get('name'), 'name') + if connector_type not in VALID_CONNECTOR_TYPES: + raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)}) + if IntegrationClientInstance.query.filter_by(code=body['code']).first(): + raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT') + client = IntegrationClientInstance( + code=str(body['code']).strip(), name=str(body['name']).strip(), + connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(), + config_json=body.get('config_json') or {}, + credential_ref_code=body.get('credential_ref_code'), + enabled=bool(body.get('enabled', True)), + ) + from app import db + db.session.add(client) + db.session.commit() + return ok(_serialize_client(client), status=201) + + +@integration_connector_bp.route('/client-instances/', methods=['GET']) +@require_admin +def get_client_instance(code): + client = IntegrationClientInstance.query.filter_by(code=code).first() + if client is None: + raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND') + return ok(_serialize_client(client)) + + +@integration_connector_bp.route('/client-instances/', methods=['DELETE']) +@require_admin +def delete_client_instance(code): + client = IntegrationClientInstance.query.filter_by(code=code).first() + if client is None: + raise NotFoundError('client instance not found') + from app import db + db.session.delete(client) + db.session.commit() + return ok({'deleted': True}) + + +# ---- 接口定义 ---- + +@integration_connector_bp.route('/interface-definitions', methods=['GET']) +@require_admin +def list_interface_definitions(): + rows = IntegrationInterfaceDefinition.query.order_by(IntegrationInterfaceDefinition.code).all() + return ok([_serialize_interface(row) for row in rows]) + + +@integration_connector_bp.route('/interface-definitions', methods=['POST']) +@require_admin +def create_interface_definition(): + body = request.get_json(silent=True) or {} + code = str(body.get('code') or '').strip() + _require(code, 'code') + _require(body.get('client_instance_code'), 'client_instance_code') + connector_type = str(body.get('connector_type') or '') + if connector_type not in VALID_CONNECTOR_TYPES: + raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)}) + status = str(body.get('status') or 'draft') + if status not in VALID_STATUSES: + raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) + iface = IntegrationInterfaceDefinition( + code=code, name=str(body.get('name') or code).strip(), + client_instance_code=body['client_instance_code'], connector_type=connector_type, + request_spec_json=body.get('request_spec_json') or {}, + input_schema_json=body.get('input_schema_json') or {}, + response_mapping_json=body.get('response_mapping_json') or {}, + output_schema_json=body.get('output_schema_json') or {}, + version=int(body.get('version') or 1), status=status, + enabled=bool(body.get('enabled', True)), + ) + from app import db + db.session.add(iface) + db.session.commit() + return ok(_serialize_interface(iface), status=201) + + +# ---- Binding ---- + +@integration_connector_bp.route('/bindings', methods=['GET']) +@require_admin +def list_bindings(): + rows = IntegrationBinding.query.order_by(IntegrationBinding.capability, IntegrationBinding.priority.desc()).all() + return ok([_serialize_binding(row) for row in rows]) + + +@integration_connector_bp.route('/bindings', methods=['POST']) +@require_admin +def create_binding(): + body = request.get_json(silent=True) or {} + _require(body.get('capability'), 'capability') + _require(body.get('client_instance_code'), 'client_instance_code') + _require(body.get('interface_definition_code'), 'interface_definition_code') + status = str(body.get('status') or 'draft') + if status not in VALID_STATUSES: + raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) + binding = IntegrationBinding( + capability=body['capability'], + context_selector_json=body.get('context_selector_json') or {}, + client_instance_code=body['client_instance_code'], + interface_definition_code=body['interface_definition_code'], + mapping_version=int(body.get('mapping_version') or 1), + priority=int(body.get('priority') or 0), + environment=str(body.get('environment') or 'prod').strip(), + status=status, + ) + from app import db + db.session.add(binding) + db.session.commit() + return ok(_serialize_binding(binding), status=201) + + +# ---- 凭据引用 ---- + +@integration_connector_bp.route('/credential-references', methods=['GET']) +@require_admin +def list_credential_references(): + rows = IntegrationCredentialReference.query.order_by(IntegrationCredentialReference.code).all() + return ok([_serialize_credential(row) for row in rows]) + + +@integration_connector_bp.route('/credential-references', methods=['POST']) +@require_admin +def create_credential_reference(): + body = request.get_json(silent=True) or {} + _require(body.get('code'), 'code') + _require(body.get('secret_ref'), 'secret_ref') + from app import db + cred = IntegrationCredentialReference( + code=str(body['code']).strip(), + secret_ref=str(body['secret_ref']).strip(), + secret_provider=str(body.get('secret_provider') or 'env').strip(), + credential_type=str(body.get('credential_type') or 'password').strip(), + version=int(body.get('version') or 1), + status=str(body.get('status') or 'active'), + ) + db.session.add(cred) + db.session.commit() + # 永不回显真实凭据值;只回元数据。 + return ok(_serialize_credential(cred), status=201) + + +# ---- 连接测试 ---- + +@integration_connector_bp.route('/client-instances//test', methods=['POST']) +@require_admin +def test_connection(code): + client = IntegrationClientInstance.query.filter_by(code=code).first() + if client is None: + raise NotFoundError('client instance not found') + gateway = get_capability_gateway() + transport = gateway.transports.get(client.connector_type) + if transport is None: + raise ValidationError( + 'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN', + ) + raw = transport.call( + client={'config_json': client.config_json or {}, 'credential': {}}, + interface={'request_spec_json': {}}, + request={}, + ) + return ok({'ok': True, 'status': raw.get('status') or 'success', 'result': raw}) diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 709cf3b2..8df7fde3 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -260,6 +260,28 @@ class Config: SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower() SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2')) SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2')) + # 在途仓自动调拨(独立业务模块)参数;ERP 凭据仅由环境/Secret 注入,未配置时 fail-closed。 + IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY', '2')) + IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY', '2')) + IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY', '1')) + IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS = int( + os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS', '60') or '60' + ) + IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS = int( + os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS', '60') or '60' + ) + IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int( + os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600' + ) + IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3') + IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5') + IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7') + # ERP SOAP:WSDL/endpoint 冻结前保持空(SoapErpTransport fail-closed)。 + IN_TRANSIT_TRANSFER_ERP_ENDPOINT = os.getenv('IN_TRANSIT_TRANSFER_ERP_ENDPOINT', '').strip() + IN_TRANSIT_TRANSFER_ERP_USERNAME = os.getenv('IN_TRANSIT_TRANSFER_ERP_USERNAME', '').strip() + IN_TRANSIT_TRANSFER_ERP_PASSWORD = os.getenv('IN_TRANSIT_TRANSFER_ERP_PASSWORD', '').strip() + IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG = os.getenv('IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG', '').strip() + IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip() SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float( os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420') ) diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index f0589dcd..1c221aad 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -7,6 +7,9 @@ backend/app/jobs/handlers/__init__.py from app.jobs.handlers import ( # noqa: F401 file_check_run, + in_transit_transfer_item, + in_transit_transfer_precheck, + in_transit_transfer_run, kb_clean, kb_dify_sync, procurement_contract_review, diff --git a/backend/app/jobs/handlers/in_transit_transfer_item.py b/backend/app/jobs/handlers/in_transit_transfer_item.py new file mode 100644 index 00000000..c2e90f3b --- /dev/null +++ b/backend/app/jobs/handlers/in_transit_transfer_item.py @@ -0,0 +1,29 @@ +"""backend/app/jobs/handlers/in_transit_transfer_item.py + +用途:Invoice 级执行 Job:对单个明细执行写前复查 + ERP 原子写入。 +依赖:execution_service.execute_item、transfer deps、Job 注册表。 +逻辑:payload 携带 item_id;单项结果不影响其他项。 +""" + +from __future__ import annotations + +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.execution_service import execute_item + + +@register_handler(JobType.TRANSFER_ITEM) +def run_in_transit_transfer_item(_ctx, payload: dict) -> None: + """执行单个 Invoice(异步路径)。 + + 【AI 触发时机】:仅由 Item 入队路径调用;页面直连走 API 同步路径。 + """ + payload = payload if isinstance(payload, dict) else {} + item_id = payload.get("item_id") + if item_id is None: + raise RuntimeError("missing_transfer_item_id") + execute_item( + item_id=int(item_id), + deps=transfer_deps.get_transfer_dependencies(), + ) diff --git a/backend/app/jobs/handlers/in_transit_transfer_precheck.py b/backend/app/jobs/handlers/in_transit_transfer_precheck.py new file mode 100644 index 00000000..b43dc20c --- /dev/null +++ b/backend/app/jobs/handlers/in_transit_transfer_precheck.py @@ -0,0 +1,55 @@ +"""backend/app/jobs/handlers/in_transit_transfer_precheck.py + +用途:异步执行在途调拨预检(文件准备 + 只读预检),并更新预检状态。 +依赖:Job 注册表、precheck_service、transfer 模型、transfer deps。 +逻辑:领取后按 payload.precheck_id 加载预检,运行 run_precheck 并回写 + 状态/计数/Hash;预检不存在时 fail-closed 抛 RuntimeError。 +""" + +from __future__ import annotations + +from app import db +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.models import TransferPrecheck +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.precheck_service import run_precheck + + +@register_handler(JobType.TRANSFER_PRECHECK) +def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None: + """执行一次预检 Job 并更新预检状态。 + + 【AI 触发时机】:仅由预检创建异步路径入队;页面直连走 API 同步路径。 + """ + payload = payload if isinstance(payload, dict) else {} + precheck_no = str(payload.get("precheck_id") or "").strip() + if not precheck_no: + raise RuntimeError("missing_transfer_precheck_id") + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=precheck_no).first() + if precheck is None: + raise RuntimeError(f"missing_transfer_precheck: {precheck_no}") + + deps = transfer_deps.get_transfer_dependencies() + source_codes = list(precheck.scope_json.get("source_codes") or []) if isinstance( + precheck.scope_json, dict + ) else [] + result = run_precheck( + source_codes=source_codes, + business_date=precheck.business_date, + deps=deps, + run_no=precheck.run.run_no if precheck.run else "RUN-PENDING", + ) + summary = result.summary + precheck.status = summary.status + precheck.counts_json = { + "file_invoice_count": summary.counts.file_invoice_count, + "not_matured_count": summary.counts.not_matured_count, + "prechecked_count": summary.counts.prechecked_count, + "executable_count": summary.counts.executable_count, + "blocked_count": summary.counts.blocked_count, + } + precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity + precheck.estimated_erp_write_count = summary.estimated_erp_write_count + precheck.precheck_hash = summary.precheck_hash + db.session.commit() diff --git a/backend/app/jobs/handlers/in_transit_transfer_run.py b/backend/app/jobs/handlers/in_transit_transfer_run.py new file mode 100644 index 00000000..161ed59f --- /dev/null +++ b/backend/app/jobs/handlers/in_transit_transfer_run.py @@ -0,0 +1,29 @@ +"""backend/app/jobs/handlers/in_transit_transfer_run.py + +用途:Run 级执行 Job:加载预检并驱动执行服务完成全部可执行项写入。 +依赖:execution_service、transfer deps、Job 注册表。 +逻辑:payload 携带 precheck_id;执行后预检与 Run 落库终态。 +""" + +from __future__ import annotations + +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.execution_service import execute_precheck + + +@register_handler(JobType.TRANSFER_RUN) +def run_in_transit_transfer_run(_ctx, payload: dict) -> None: + """执行一个 Run(异步路径)。 + + 【AI 触发时机】:仅由执行 Run 入队路径调用;页面直连走 API 同步路径。 + """ + payload = payload if isinstance(payload, dict) else {} + precheck_id = str(payload.get("precheck_id") or "").strip() + if not precheck_id: + raise RuntimeError("missing_transfer_precheck_id") + execute_precheck( + precheck_id=precheck_id, + deps=transfer_deps.get_transfer_dependencies(), + ) diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 5d4b6f54..134e8147 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -36,6 +36,10 @@ class JobType(StrEnum): FILE_CHECK_RUN = 'file_check_run' WECOM_DIRECTORY_SYNC = 'wecom_directory_sync' PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review' + # 在途仓自动调拨:文件准备 + 只读预检(Phase 1);执行 Run/Item 在 Phase 2 注册。 + TRANSFER_PRECHECK = 'in_transit_transfer_precheck' + TRANSFER_RUN = 'in_transit_transfer_run' + TRANSFER_ITEM = 'in_transit_transfer_item' class JobStatus(StrEnum): @@ -75,6 +79,9 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { }), 'contract': frozenset({'procurement_contract_review'}), 'schedule': frozenset({'schedule_run'}), + 'transfer': frozenset({ + 'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item', + }), } diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index cf357e86..a5276e6c 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -183,6 +183,22 @@ from app.models.shipping_inventory_preparation import ( ShippingInventoryPreparationSourceAttempt, ) from app.models.shipping_inventory_mapping import ShippingInventoryMapping +from app.models.in_transit_transfer import ( + TransferArchive, + TransferAttempt, + TransferAuditEvent, + TransferInvoiceItem, + TransferPrecheck, + TransferRun, + TransferSourceJob, +) +from app.models.integration_connector import ( + IntegrationBinding, + IntegrationCall, + IntegrationClientInstance, + IntegrationCredentialReference, + IntegrationInterfaceDefinition, +) from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigResource from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem @@ -356,4 +372,16 @@ __all__ = [ 'ShippingTaskInventoryRpaAttempt', 'VoucherCheckInvoiceState', 'VoucherCheckRunItem', + 'TransferRun', + 'TransferSourceJob', + 'TransferPrecheck', + 'TransferInvoiceItem', + 'TransferAttempt', + 'TransferAuditEvent', + 'TransferArchive', + 'IntegrationCredentialReference', + 'IntegrationClientInstance', + 'IntegrationInterfaceDefinition', + 'IntegrationBinding', + 'IntegrationCall', ] diff --git a/backend/app/models/in_transit_transfer.py b/backend/app/models/in_transit_transfer.py new file mode 100644 index 00000000..2b4d93a5 --- /dev/null +++ b/backend/app/models/in_transit_transfer.py @@ -0,0 +1,352 @@ +"""models/in_transit_transfer.py + +用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Precheck、InvoiceItem、 + Attempt、AuditEvent 与 Archive。 +依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。 +逻辑:Run 是异步真相源;InvoiceItem 按(precheck_id, invoice_no)唯一防止重复建单; + Attempt 保留每次恢复/重查事实,旧 Attempt 永不覆盖; + AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import ( + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + String, + Text, + UniqueConstraint, + event, + text, +) +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.core.errors import ValidationError +from app.models.base import Base + +# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。 +TRANSFER_ITEM_STATUSES = ( + 'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing', + 'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', + 'result_unknown', 'manually_closed', 'cancelled', 'notification_failed', +) +TRANSFER_RUN_STATUSES = ( + 'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing', + 'success', 'partial_failed', 'failed', 'cancelled', +) +TRANSFER_SOURCE_JOB_STATUSES = ( + 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', + 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', +) +TRANSFER_PRECHECK_STATUSES = ( + 'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing', + 'success', 'failed', 'cancelled', 'expired', +) +TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'erp_query', 'erp_write') +TRANSFER_ATTEMPT_STATUSES = ( + 'queued', 'running', 'waiting_external', 'success', 'failed', + 'result_unknown', 'superseded', +) +TRANSFER_AUDIT_ACTOR_TYPES = ('user', 'system', 'worker', 'admin', 'rpa', 'schedule') + + +class TransferRun(Base): + """一次调拨执行(或只读预检)的业务真相源。""" + + __tablename__ = 'transfer_runs' + __table_args__ = ( + UniqueConstraint('run_no', name='uq_transfer_runs_run_no'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_RUN_STATUSES)})", + name='ck_transfer_runs_status', + ), + CheckConstraint( + "notification_status IN ('pending', 'success', 'failed')", + name='ck_transfer_runs_notification_status', + ), + CheckConstraint( + "trigger_type IN ('manual', 'schedule')", + name='ck_transfer_runs_trigger_type', + ), + Index('ix_transfer_runs_status_created', 'status', 'created_at'), + Index('ix_transfer_runs_business_date', 'business_date'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + run_no: Mapped[str] = mapped_column(String(64), nullable=False) + trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual') + business_date: Mapped[str] = mapped_column(String(16), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') + source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list) + counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + result_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + notification_status: Mapped[str] = mapped_column( + String(16), nullable=False, default='pending', server_default='pending', + ) + notification_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + notification_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + source_jobs: Mapped[list['TransferSourceJob']] = relationship( + back_populates='run', cascade='all, delete-orphan', + ) + prechecks: Mapped[list['TransferPrecheck']] = relationship( + back_populates='run', cascade='all, delete-orphan', + ) + items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='run') + + +class TransferSourceJob(Base): + """来源实例级的文件准备/预检执行单元;来源间互不阻断。""" + + __tablename__ = 'transfer_source_jobs' + __table_args__ = ( + UniqueConstraint('run_id', 'source_code', name='uq_transfer_source_jobs_run_source'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_SOURCE_JOB_STATUSES)})", + name='ck_transfer_source_jobs_status', + ), + Index('ix_transfer_source_jobs_source_status', 'source_code', 'status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + run_id: Mapped[int] = mapped_column(ForeignKey('transfer_runs.id'), nullable=False, index=True) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + source_config_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') + file_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + lease_until: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + run: Mapped[TransferRun] = relationship(back_populates='source_jobs') + + +class TransferPrecheck(Base): + """一次冻结快照的预检结果;确认/执行绑定其 Hash。""" + + __tablename__ = 'transfer_prechecks' + __table_args__ = ( + UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_PRECHECK_STATUSES)})", + name='ck_transfer_prechecks_status', + ), + Index('ix_transfer_prechecks_run_status', 'run_id', 'status'), + Index('ix_transfer_prechecks_business_date', 'business_date'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + precheck_no: Mapped[str] = mapped_column(String(64), nullable=False) + run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True, index=True) + business_date: Mapped[str] = mapped_column(String(16), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='prechecking', server_default='prechecking') + scope_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + file_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + strategy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) + estimated_erp_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) + precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False) + expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + run: Mapped[Optional[TransferRun]] = relationship(back_populates='prechecks') + items: Mapped[list['TransferInvoiceItem']] = relationship( + back_populates='precheck', cascade='all, delete-orphan', + ) + + +class TransferInvoiceItem(Base): + """预检明细项;同一预检内 Invoice 唯一,保留原始行追溯。""" + + __tablename__ = 'transfer_invoice_items' + __table_args__ = ( + UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})", + name='ck_transfer_invoice_items_status', + ), + Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'), + Index('ix_transfer_invoice_items_run_id', 'run_id'), + Index('ix_transfer_invoice_items_erp_document_no', 'erp_document_no'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + precheck_id: Mapped[int] = mapped_column(ForeignKey('transfer_prechecks.id'), nullable=False, index=True) + run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + invoice_no: Mapped[str] = mapped_column(String(64), nullable=False) + material_no: Mapped[str] = mapped_column(String(64), nullable=False) + material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='') + specification: Mapped[str] = mapped_column(String(200), nullable=False, default='') + receipt_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) + to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) + # 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。 + receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False) + erp_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) + status: Mapped[str] = mapped_column(String(32), nullable=False) + result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + # 原始文件行追溯:Sheet + 行号 + 文件版本(决策 11)。 + raw_lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list) + attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) + manually_closed_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + precheck: Mapped[TransferPrecheck] = relationship(back_populates='items') + run: Mapped[Optional[TransferRun]] = relationship(back_populates='items') + attempts: Mapped[list['TransferAttempt']] = relationship( + back_populates='item', cascade='all, delete-orphan', + ) + + +class TransferAttempt(Base): + """一次恢复/重查/执行尝试;每次恢复创建新 Attempt,旧记录不可覆盖。""" + + __tablename__ = 'transfer_attempts' + __table_args__ = ( + UniqueConstraint('item_id', 'attempt_no', name='uq_transfer_attempts_item_no'), + CheckConstraint( + f"kind IN ({', '.join(repr(s) for s in TRANSFER_ATTEMPT_KINDS)})", + name='ck_transfer_attempts_kind', + ), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_ATTEMPT_STATUSES)})", + name='ck_transfer_attempts_status', + ), + Index('ix_transfer_attempts_item_created', 'item_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + item_id: Mapped[int] = mapped_column(ForeignKey('transfer_invoice_items.id'), nullable=False) + attempt_no: Mapped[int] = mapped_column(Integer, nullable=False) + kind: Mapped[str] = mapped_column(String(16), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') + request_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + item: Mapped[TransferInvoiceItem] = relationship(back_populates='attempts') + + +class TransferAuditEvent(Base): + """调拨领域只追加审计事件;禁止更新与删除。""" + + __tablename__ = 'transfer_audit_events' + __table_args__ = ( + CheckConstraint( + f"actor_type IN ({', '.join(repr(s) for s in TRANSFER_AUDIT_ACTOR_TYPES)})", + name='ck_transfer_audit_events_actor_type', + ), + CheckConstraint( + "result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')", + name='ck_transfer_audit_events_result', + ), + Index('ix_transfer_audit_events_aggregate_created', 'aggregate_type', 'aggregate_id', 'created_at'), + Index('ix_transfer_audit_events_run_created', 'run_no', 'created_at'), + Index('ix_transfer_audit_events_invoice_created', 'invoice_no', 'created_at'), + Index('ix_transfer_audit_events_operation_created', 'operation_id', 'created_at'), + Index('ix_transfer_audit_events_event_hash', 'event_hash'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + event_type: Mapped[str] = mapped_column(String(64), nullable=False) + aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False) + aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False) + run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + precheck_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + invoice_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + attempt_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system') + actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + actor_role: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + actor_display: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + result: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + before_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + after_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + diff_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + before_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + after_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + event_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class TransferArchive(Base): + """大对象归档索引(MinIO);Hash 用于归档完整性校验。""" + + __tablename__ = 'transfer_archives' + __table_args__ = ( + UniqueConstraint('archive_no', name='uq_transfer_archives_archive_no'), + UniqueConstraint('object_type', 'object_id', 'sha256', name='uq_transfer_archives_object_sha'), + CheckConstraint("file_size >= 0", name='ck_transfer_archives_file_size'), + Index('ix_transfer_archives_object', 'object_type', 'object_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + archive_no: Mapped[str] = mapped_column(String(64), nullable=False) + object_type: Mapped[str] = mapped_column(String(64), nullable=False) + object_id: Mapped[str] = mapped_column(String(128), nullable=False) + storage_provider: Mapped[str] = mapped_column(String(32), nullable=False) + storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False) + storage_key: Mapped[str] = mapped_column(String(1024), nullable=False) + original_filename: Mapped[str] = mapped_column(String(255), nullable=False) + content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + file_size: Mapped[int] = mapped_column(Integer, nullable=False) + sha256: Mapped[str] = mapped_column(String(64), nullable=False) + archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +@event.listens_for(TransferAuditEvent, 'before_update') +def _reject_transfer_audit_update(_mapper, _connection, _target) -> None: + """拒绝 ORM 更新,确保审计事件不可改写。""" + raise ValidationError('Transfer audit event is append-only', code='IN_TRANSIT_TRANSFER.AUDIT_IMMUTABLE') + + +@event.listens_for(TransferAuditEvent, 'before_delete') +def _reject_transfer_audit_delete(_mapper, _connection, _target) -> None: + """拒绝 ORM 删除,保留跨生命周期追溯事实。""" + raise ValidationError('Transfer audit event is append-only', code='IN_TRANSIT_TRANSFER.AUDIT_IMMUTABLE') diff --git a/backend/app/models/integration_connector.py b/backend/app/models/integration_connector.py new file mode 100644 index 00000000..3d2d5690 --- /dev/null +++ b/backend/app/models/integration_connector.py @@ -0,0 +1,193 @@ +"""models/integration_connector.py + +用途:Integration Connector(外部系统连接器框架)P1 配置与运行时模型: + CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。 +依赖:models.base.Base、SQLAlchemy 2.0 ORM。 +逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding) + 维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。 + 连接器类型(rest/soap)与状态均用 CheckConstraint 兜底,fail-closed 语义在服务层。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import ( + Boolean, + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + String, + UniqueConstraint, + text, +) +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.dialects.postgresql import JSONB + +from app.models.base import Base + +# P1 仅落地 REST/SOAP;后续扩 RPA/SQL/FILE 时放宽约束并新建迁移。 +CONNECTOR_TYPES = ('rest', 'soap') +CONFIG_STATUSES = ('draft', 'published', 'retired') +CREDENTIAL_STATUSES = ('active', 'rotating', 'retired') + +# context_selector_json 需要参与唯一约束/索引:PostgreSQL 的 JSON 无默认 btree 操作符表, +# 无法建唯一索引;映射为 JSONB 即可。SQLite/测试仍用 JSON(TEXT)。 +CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql') + + +class IntegrationCredentialReference(Base): + """凭据引用:只存 secret_ref 键 + 元数据,真实凭据由 Secret 服务注入,绝不落库明文。""" + + __tablename__ = 'integration_credential_references' + __table_args__ = ( + UniqueConstraint('code', name='uq_integration_credential_references_code'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in CREDENTIAL_STATUSES)})", + name='ck_integration_credential_references_status', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + code: Mapped[str] = mapped_column(String(64), nullable=False) + secret_ref: Mapped[str] = mapped_column(String(128), nullable=False) + secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env') + credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password') + version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active') + last_verified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + +class IntegrationClientInstance(Base): + """客户端实例:一份到外部系统的连接配置(连到哪 + 凭据引用 + 超时/TLS/默认 org)。""" + + __tablename__ = 'integration_client_instances' + __table_args__ = ( + UniqueConstraint('code', name='uq_integration_client_instances_code'), + CheckConstraint( + f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})", + name='ck_integration_client_instances_connector_type', + ), + Index('ix_integration_client_instances_type_env', 'connector_type', 'environment'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + code: Mapped[str] = mapped_column(String(64), nullable=False) + name: Mapped[str] = mapped_column(String(128), nullable=False) + connector_type: Mapped[str] = mapped_column(String(16), nullable=False) + environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod') + config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + credential_ref_code: Mapped[Optional[str]] = mapped_column( + ForeignKey('integration_credential_references.code'), nullable=True, + ) + enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('true')) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + +class IntegrationInterfaceDefinition(Base): + """接口定义:一个可调操作(请求模板 + 入参 Schema + 返回值映射 + 出参 Schema)。""" + + __tablename__ = 'integration_interface_definitions' + __table_args__ = ( + UniqueConstraint('code', name='uq_integration_interface_definitions_code'), + CheckConstraint( + f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})", + name='ck_integration_interface_definitions_connector_type', + ), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})", + name='ck_integration_interface_definitions_status', + ), + Index('ix_integration_interface_definitions_client', 'client_instance_code'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + code: Mapped[str] = mapped_column(String(64), nullable=False) + name: Mapped[str] = mapped_column(String(128), nullable=False) + client_instance_code: Mapped[str] = mapped_column( + ForeignKey('integration_client_instances.code'), nullable=False, + ) + connector_type: Mapped[str] = mapped_column(String(16), nullable=False) + request_spec_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + input_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + response_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + output_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') + enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=text('true')) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + +class IntegrationBinding(Base): + """绑定:(Capability, context_selector) → 客户端 + 接口 + 映射版本;版本化、可发布、可退役。""" + + __tablename__ = 'integration_bindings' + __table_args__ = ( + UniqueConstraint( + 'capability', 'environment', 'context_selector_json', name='uq_integration_bindings_cap_env_ctx', + ), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in CONFIG_STATUSES)})", + name='ck_integration_bindings_status', + ), + CheckConstraint( + "priority >= 0", name='ck_integration_bindings_priority', + ), + Index('ix_integration_bindings_cap_env_status', 'capability', 'environment', 'status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + capability: Mapped[str] = mapped_column(String(128), nullable=False) + context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict) + client_instance_code: Mapped[str] = mapped_column( + ForeignKey('integration_client_instances.code'), nullable=False, + ) + interface_definition_code: Mapped[str] = mapped_column( + ForeignKey('integration_interface_definitions.code'), nullable=False, + ) + mapping_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + priority: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) + environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod') + effective_from: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + effective_to: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + +class IntegrationCall(Base): + """一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。""" + + __tablename__ = 'integration_calls' + __table_args__ = ( + UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'), + Index('ix_integration_calls_capability_created', 'capability', 'created_at'), + Index('ix_integration_calls_trace_id', 'trace_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + operation_id: Mapped[str] = mapped_column(String(128), nullable=False) + capability: Mapped[str] = mapped_column(String(128), nullable=False) + binding_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + request_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + status: Mapped[str] = mapped_column(String(32), nullable=False) + elapsed_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) + trace_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='') + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/models/shipping_inventory_config.py b/backend/app/models/shipping_inventory_config.py index d162f91f..5831deea 100644 --- a/backend/app/models/shipping_inventory_config.py +++ b/backend/app/models/shipping_inventory_config.py @@ -158,16 +158,26 @@ class ShippingInventorySourceParsingBindingAudit(Base): class ShippingInventoryParsingProfile(Base): - """可跨库存源复用的库存文件结构、样本证据与订单匹配配置。""" + """可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。 + + purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义); + purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date), + 供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。 + """ __tablename__ = 'shipping_inventory_parsing_profiles' __table_args__ = ( UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'), Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'), Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'), + CheckConstraint( + "purpose IN ('inventory', 'movement')", + name='ck_shipping_inventory_parsing_profiles_purpose', + ), ) id: Mapped[int] = mapped_column(primary_key=True) + purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='inventory', server_default='inventory') profile_code: Mapped[str] = mapped_column(String(64), nullable=False) display_name: Mapped[str] = mapped_column(String(128), nullable=False) version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) diff --git a/backend/app/models/shipping_receipt_report.py b/backend/app/models/shipping_receipt_report.py index aefda816..4a2a2605 100644 --- a/backend/app/models/shipping_receipt_report.py +++ b/backend/app/models/shipping_receipt_report.py @@ -30,6 +30,10 @@ class ShippingReceiptReportConfig(Base): ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True, ) enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False) + # 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。 + parsing_profile_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True, + ) report_path_json: Mapped[dict[str, Any]] = mapped_column( JSON, default=dict, server_default=text("'{}'"), nullable=False, ) @@ -47,6 +51,7 @@ class ShippingReceiptReportConfig(Base): updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) inventory_source: Mapped['ShippingInventorySource'] = relationship(back_populates='receipt_report_config') + parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship() class ShippingReceiptRpaUnitRun(Base): diff --git a/backend/app/services/agent_registry/catalog_bindings.py b/backend/app/services/agent_registry/catalog_bindings.py index bc2b871a..45e78647 100644 --- a/backend/app/services/agent_registry/catalog_bindings.py +++ b/backend/app/services/agent_registry/catalog_bindings.py @@ -12,4 +12,5 @@ from __future__ import annotations RUNTIME_HANDLER_BINDINGS: dict[str, str] = { 'shipping_notice': 'shipping_notice', 'file_check': 'file_check', + 'in_transit_transfer': 'in_transit_transfer', } diff --git a/backend/app/services/agent_registry/data/catalog_manifest.yaml b/backend/app/services/agent_registry/data/catalog_manifest.yaml index 2f085a4f..3bf2d7f9 100644 --- a/backend/app/services/agent_registry/data/catalog_manifest.yaml +++ b/backend/app/services/agent_registry/data/catalog_manifest.yaml @@ -129,3 +129,35 @@ agent_types: file_upload: true human_confirm: false handler_config_schema: {} + in_transit_transfer: + label: 在途仓自动调拨 + conversation_mode_default: task_chat + runtime_provider_default: hybrid + models: + - TransferRun + - TransferPrecheck + - TransferInvoiceItem + required_fields: [] + default_capabilities: + task_progress: true + human_confirm: true + forced_capabilities: + human_confirm: true + progress_contract: + enabled: true + data_source: + type: domain_state + domain: in_transit_transfer + update: + transport: sse + event: transfer_ui_state + binding: + type: conversation_context + keys: + - run_no + - precheck_id + requires_schedule_task: false + presentation: + layout: card + visualization: stepper + handler_config_schema: {} diff --git a/backend/app/services/agent_registry/handlers/bootstrap.py b/backend/app/services/agent_registry/handlers/bootstrap.py index 649d389d..db66d775 100644 --- a/backend/app/services/agent_registry/handlers/bootstrap.py +++ b/backend/app/services/agent_registry/handlers/bootstrap.py @@ -30,10 +30,12 @@ def load_handlers() -> None: import importlib import app.services.agent_registry.handlers.file_check as file_check_mod + import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod import app.services.agent_registry.handlers.shipping_notice as shipping_mod importlib.reload(file_check_mod) importlib.reload(shipping_mod) + importlib.reload(in_transit_transfer_mod) logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys())) _handlers_loaded = True diff --git a/backend/app/services/agent_registry/handlers/in_transit_transfer.py b/backend/app/services/agent_registry/handlers/in_transit_transfer.py new file mode 100644 index 00000000..e4497caa --- /dev/null +++ b/backend/app/services/agent_registry/handlers/in_transit_transfer.py @@ -0,0 +1,34 @@ +""" +用途:在途仓自动调拨 Hybrid Handler。 + +依赖:agent_registry.handlers.base/registry。 +逻辑:在途调拨的进度与结果卡由 Chat Action(transfer.precheck / transfer.execute) + 输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid + 运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入 + Dify Chatflow 生命周期。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext +from app.services.agent_registry.handlers.registry import register_handler + + +@register_handler('in_transit_transfer') +class InTransitTransferHandler(AgentHandler): + """ + 在途仓自动调拨业务 Handler。 + + 核心逻辑:预检/执行/结果卡不进入普通 Dify 生命周期(后台 Run 持久化 + 卡片消息 + + Run API 恢复);prepare_stream / build_ui_state_event 预留领域扩展位。 + """ + + def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext: + """Dify 流开始前:校验领域上下文(预留 run_no/precheck_id 锚点)。""" + return ctx + + def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None: + """构造 transfer_ui_state SSE 事件(预留;进度由卡片消息 + Run API 提供)。""" + return None diff --git a/backend/app/services/chat/action_registry.py b/backend/app/services/chat/action_registry.py index 21ddb00f..f55591c4 100644 --- a/backend/app/services/chat/action_registry.py +++ b/backend/app/services/chat/action_registry.py @@ -17,6 +17,7 @@ from app.services.chat.turn_context import TurnContext # action_type 前缀 → 允许的 agent_code 集合;空集合表示不限制。 ACTION_AGENT_CODES: dict[str, tuple[str, ...]] = { "shipping.": ("shipping_notice",), + "transfer.": ("in_transit_transfer",), } @@ -79,5 +80,7 @@ def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler: def ensure_handlers_loaded() -> None: """延迟导入各领域 handler 模块以完成注册。""" from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401 + from app.services.in_transit_transfer import chat_actions as _transfer_actions # noqa: F401 _ = _shipping_extended + _ = _transfer_actions diff --git a/backend/app/services/in_transit_transfer/__init__.py b/backend/app/services/in_transit_transfer/__init__.py new file mode 100644 index 00000000..66994844 --- /dev/null +++ b/backend/app/services/in_transit_transfer/__init__.py @@ -0,0 +1,8 @@ +"""backend/app/services/in_transit_transfer/__init__.py + +用途:在途仓自动调拨 Agent 一期独立领域模块入口。 +依赖:同包 date_policy / status / quantity / strategy / contracts / audit; + Phase 1 起扩展 file_preparation / precheck_service 等。 +逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析; + 对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。 +""" diff --git a/backend/app/services/in_transit_transfer/archive.py b/backend/app/services/in_transit_transfer/archive.py new file mode 100644 index 00000000..7964f634 --- /dev/null +++ b/backend/app/services/in_transit_transfer/archive.py @@ -0,0 +1,168 @@ +"""在途调拨 MinIO 归档与 Hash 校验。 + +用途:将大型快照/报文/Excel 归档到对象存储(MinIO),索引与 Hash 留库; + 归档必须重新计算 Hash 并写审计事件(决策/规格 §11.3)。 +依赖:typing.Protocol 对象存储协议、models.TransferArchive、audit。 +逻辑:默认实现 MinioObjectStore 直连 MinIO(配置来自环境);测试注入 Fake。 + 凭据只来自环境/配置,绝不写入归档内容或索引。 +""" + +from __future__ import annotations + +import hashlib +import io +import uuid +from datetime import datetime +from typing import Any, Protocol + +from app import db +from app.core.errors import AppError +from app.models import TransferArchive +from app.services.in_transit_transfer.audit import build_transfer_audit_event + +ARCHIVE_STORAGE_PROVIDER = "minio" +DEFAULT_ARCHIVE_BUCKET = "hxops-transfer" + + +class ObjectStore(Protocol): + """对象存储协议(MinIO 或测试替身)。""" + + def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str: + """写入对象,返回对象键。""" + + def get_bytes(self, *, bucket: str, key: str) -> bytes: + """读取对象字节。""" + + def delete_object(self, *, bucket: str, key: str) -> None: + """删除对象。""" + + +class MinioObjectStore: + """默认 MinIO 对象存储;凭据仅来自 Flask config / 环境变量。""" + + def __init__(self, bucket: str = DEFAULT_ARCHIVE_BUCKET) -> None: + from flask import current_app + + self.bucket = str(current_app.config.get("IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET") or bucket) + endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip() + access_key = str(current_app.config.get("MINIO_ACCESS_KEY") or "").strip() + secret_key = str(current_app.config.get("MINIO_SECRET_KEY") or "").strip() + secure = bool(current_app.config.get("MINIO_SECURE", False)) + if not endpoint: + raise AppError( + code="TRANSFER.ARCHIVE_NOT_CONFIGURED", + message="MinIO endpoint not configured", + http_status=503, + ) + from minio import Minio + + self.client = Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=secure) + + def _ensure_bucket(self) -> None: + """确保 bucket 存在(幂等)。""" + if not self.client.bucket_exists(self.bucket): + self.client.make_bucket(self.bucket) + + def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str: + """写入对象并返回键。""" + self._ensure_bucket() + self.client.put_object( + bucket_name=bucket or self.bucket, + object_name=key, + data=io.BytesIO(data), + length=len(data), + content_type=content_type, + ) + return key + + def get_bytes(self, *, bucket: str, key: str) -> bytes: + """读取对象字节。""" + response = self.client.get_object(bucket_name=bucket or self.bucket, object_name=key) + try: + return response.read() + finally: + response.close() + response.release_conn() + + def delete_object(self, *, bucket: str, key: str) -> None: + """删除对象。""" + self.client.remove_object(bucket_name=bucket or self.bucket, object_name=key) + + +def _safe_filename(name: str) -> str: + """清洗文件名片段。""" + return "".join(char for char in str(name or "archive") if char.isalnum() or char in {"-", "_", "."}) or "archive" + + +def archive_snapshot( + *, + object_type: str, + object_id: str, + data: bytes, + original_filename: str, + content_type: str, + object_store: ObjectStore, + bucket: str = DEFAULT_ARCHIVE_BUCKET, + request_id: str | None = None, +) -> TransferArchive: + """归档一份对象并持久化索引 + 审计。 + + Args: + object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。 + object_id: 业务对象编号(precheck_no / run_no)。 + data: 待归档字节。 + original_filename: 原始文件名。 + content_type: MIME。 + object_store: 对象存储替身。 + bucket: 目标 bucket。 + Returns: + TransferArchive 索引记录。 + """ + digest = hashlib.sha256(data).hexdigest() + key = ( + f"{object_type}/{object_id}/{datetime.utcnow():%Y%m%d}/" + f"{uuid.uuid4().hex[:8]}-{_safe_filename(original_filename)}" + ) + object_store.put_bytes(bucket=bucket, key=key, data=data, content_type=content_type) + archive = TransferArchive( + archive_no=f"ARC-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:6].upper()}", + object_type=object_type, + object_id=object_id, + storage_provider=ARCHIVE_STORAGE_PROVIDER, + storage_bucket=bucket, + storage_key=key, + original_filename=original_filename, + content_type=content_type, + file_size=len(data), + sha256=digest, + ) + db.session.add(archive) + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_ARCHIVED", + aggregate_type=object_type, + aggregate_id=object_id, + actor_type="worker", + request_id=request_id, + result="success", + after={"storage_key": key, "sha256": digest, "file_size": len(data)}, + )) + db.session.commit() + return archive + + +def verify_archive_hash(archive: TransferArchive, *, object_store: ObjectStore) -> bool: + """复核归档 Hash(下载对象重新计算)。 + + Args: + archive: TransferArchive 索引。 + object_store: 对象存储替身。 + Returns: + True 一致;False 损坏/篡改。 + """ + data = object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key) + return hashlib.sha256(data).hexdigest() == archive.sha256 + + +def restore_archive_bytes(archive: TransferArchive, *, object_store: ObjectStore) -> bytes: + """恢复归档对象字节。""" + return object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key) diff --git a/backend/app/services/in_transit_transfer/audit.py b/backend/app/services/in_transit_transfer/audit.py new file mode 100644 index 00000000..d0027221 --- /dev/null +++ b/backend/app/services/in_transit_transfer/audit.py @@ -0,0 +1,182 @@ +"""在途调拨审计服务。 + +用途:构建只追加审计事件(TransferAuditEvent),对快照脱敏并计算 + before/after Hash 与事件 Hash,保证 Phase 4 Hash 校验可复算。 +依赖:app.models.TransferAuditEvent、标准库 hashlib/json。 +逻辑:所有快照先 sanitize(剔除密码/Token/密钥),再参与 Hash; + event_hash 由事件自身稳定字段复算,不依赖对象内部状态。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Mapping + +import hashlib +import json + +from app.models import TransferAuditEvent + +# 敏感字段片段:命中即从审计快照中剔除(Secret 永不进入审计/Hash/日志)。 +AUDIT_FORBIDDEN_KEY_FRAGMENTS = ( + "password", "secret", "token", "ciphertext", "credential", + "api_key", "apikey", "webhook", "authorization", "auth", +) + + +def is_forbidden_audit_key(key: str) -> bool: + """判断键名是否命中敏感片段(大小写不敏感)。""" + lowered = str(key or "").lower() + return any(fragment in lowered for fragment in AUDIT_FORBIDDEN_KEY_FRAGMENTS) + + +def sanitize_snapshot(value: Any) -> Any: + """递归剔除敏感键,返回可安全持久化的快照副本。 + + Args: + value: 原始快照(dict/list/标量)。 + Returns: + 脱敏后的副本。 + """ + if isinstance(value, dict): + return { + str(key): sanitize_snapshot(item) + for key, item in value.items() + if not is_forbidden_audit_key(str(key)) + } + if isinstance(value, (list, tuple)): + return [sanitize_snapshot(item) for item in value] + return value + + +def canonical_hash(value: Any) -> str: + """对脱敏快照计算 SHA-256(键排序 + 紧凑 JSON)。 + + Args: + value: 任意 JSON 可序列化值。 + Returns: + 64 位十六进制 Hash。 + """ + payload = json.dumps( + sanitize_snapshot(value), + ensure_ascii=True, sort_keys=True, separators=(",", ":"), default=str, + ) + return hashlib.sha256(payload.encode("ascii")).hexdigest() + + +def snapshot_diff(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, Any]: + """计算前后快照顶层差异。 + + Args: + before: 变更前快照。 + after: 变更后快照。 + Returns: + {"added": {...}, "removed": {...}, "changed": {key: (before, after)}}。 + """ + before_keys = set(before) + after_keys = set(after) + return { + "added": {key: after[key] for key in sorted(after_keys - before_keys)}, + "removed": {key: before[key] for key in sorted(before_keys - after_keys)}, + "changed": { + key: (before[key], after[key]) + for key in sorted(before_keys & after_keys) + if before[key] != after[key] + }, + } + + +def _event_hash_inputs(event: TransferAuditEvent) -> dict[str, Any]: + """事件 Hash 的稳定输入字段(含 created_at,保证复算一致)。""" + created = event.created_at or datetime.utcnow() + return { + "event_type": event.event_type, + "aggregate_type": event.aggregate_type, + "aggregate_id": event.aggregate_id, + "run_no": event.run_no, + "precheck_no": event.precheck_no, + "invoice_no": event.invoice_no, + "item_id": event.item_id, + "attempt_no": event.attempt_no, + "actor_type": event.actor_type, + "actor_id": event.actor_id, + "actor_role": event.actor_role, + "actor_display": event.actor_display, + "request_id": event.request_id, + "operation_id": event.operation_id, + "source": event.source, + "result": event.result, + "error_code": event.error_code, + "before_hash": event.before_hash, + "after_hash": event.after_hash, + "created_at": created.isoformat(), + } + + +def compute_event_hash(event: TransferAuditEvent) -> str: + """由存储字段复算事件 Hash(Hash 校验作业的复算口径)。""" + return canonical_hash(_event_hash_inputs(event)) + + +def build_transfer_audit_event( + *, + event_type: str, + aggregate_type: str, + aggregate_id: str, + run_no: str | None = None, + precheck_no: str | None = None, + invoice_no: str | None = None, + item_id: str | None = None, + attempt_no: str | None = None, + actor_type: str = "system", + actor_id: str | None = None, + actor_role: str | None = None, + actor_display: str | None = None, + request_id: str | None = None, + operation_id: str | None = None, + source: str | None = None, + result: str | None = None, + error_code: str | None = None, + before: Any = None, + after: Any = None, +) -> TransferAuditEvent: + """构造一条已计算 Hash 的审计事件(未落库,由调用方提交)。 + + Args: + event_type / aggregate_type / aggregate_id: 事件类型与聚合对象。 + run_no / precheck_no / invoice_no / item_id / attempt_no: 业务关联。 + actor_*: 操作者(user/worker/schedule/admin/rpa)。 + request_id / operation_id: 关联上下文。 + before / after: 前后快照(自动脱敏并计算 Hash)。 + Returns: + TransferAuditEvent 实例(before_hash/after_hash/event_hash 已填)。 + """ + before_sanitized = sanitize_snapshot(before if before is not None else {}) + after_sanitized = sanitize_snapshot(after if after is not None else {}) + created_at = datetime.utcnow() + event = TransferAuditEvent( + event_type=event_type, + aggregate_type=aggregate_type, + aggregate_id=aggregate_id, + run_no=run_no, + precheck_no=precheck_no, + invoice_no=invoice_no, + item_id=item_id, + attempt_no=attempt_no, + actor_type=actor_type, + actor_id=actor_id, + actor_role=actor_role, + actor_display=actor_display, + request_id=request_id, + operation_id=operation_id, + source=source, + result=result, + error_code=error_code, + before_json=before_sanitized, + after_json=after_sanitized, + before_hash=canonical_hash(before_sanitized), + after_hash=canonical_hash(after_sanitized), + created_at=created_at, + ) + event.event_hash = compute_event_hash(event) + return event diff --git a/backend/app/services/in_transit_transfer/auto_transfer.py b/backend/app/services/in_transit_transfer/auto_transfer.py new file mode 100644 index 00000000..792d536f --- /dev/null +++ b/backend/app/services/in_transit_transfer/auto_transfer.py @@ -0,0 +1,71 @@ +"""在途调拨自动排程编排(09:00 自动调拨)。 + +用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知", + 供 in-transit-transfer platform job 调用。 +依赖:recovery_service、precheck_service、execution_service、notification。 +逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from app import db +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.notification import WeComSender, notify_run_summary +from app.services.in_transit_transfer.precheck_service import TransferDeps, create_precheck +from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery + + +@dataclass +class AutoTransferOutcome: + """自动调拨阶段结果。""" + + run_no: str | None = None + run_status: str | None = None + recovery: RecoveryOutcome = field(default_factory=RecoveryOutcome) + notification_status: str | None = None + errors: list[str] = field(default_factory=list) + + +def run_auto_transfer(*, business_date: str, deps: TransferDeps, + source_codes: list[str] | None = None, + recover_history: bool = True, + sender: WeComSender | None = None, + recipients: list[str] | None = None) -> AutoTransferOutcome: + """执行一次自动调拨排程。 + + Args: + business_date: 业务日期。 + deps: 注入依赖。 + source_codes: 来源实例列表(缺省全部启用来源)。 + recover_history: 是否执行历史恢复。 + sender / recipients: 企微通知(None 则跳过通知)。 + Returns: + AutoTransferOutcome。 + """ + outcome = AutoTransferOutcome() + if recover_history: + try: + outcome.recovery = run_daily_recovery(business_date=business_date, deps=deps) + except Exception as exc: # noqa: BLE001 + outcome.errors.append(f"recovery_failed: {exc}") + try: + summary = create_precheck( + source_codes=source_codes or [], + business_date=business_date, + deps=deps, + ) + executed = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + outcome.run_no = executed.run_no + outcome.run_status = executed.status + except Exception as exc: # noqa: BLE001 + outcome.errors.append(f"auto_transfer_failed: {exc}") + if sender is not None and outcome.run_no: + try: + notice = notify_run_summary(run_no=outcome.run_no, sender=sender, recipients=recipients or []) + outcome.notification_status = notice.get("notification_status") + except Exception as exc: # noqa: BLE001 + outcome.errors.append(f"notification_failed: {exc}") + return outcome diff --git a/backend/app/services/in_transit_transfer/backlog_service.py b/backend/app/services/in_transit_transfer/backlog_service.py new file mode 100644 index 00000000..4a9371e2 --- /dev/null +++ b/backend/app/services/in_transit_transfer/backlog_service.py @@ -0,0 +1,141 @@ +"""在途调拨历史待处理池与老化分级。 + +用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项, + 按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。 +依赖:models、status。 +逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读; + manually_closed / success / duplicate_success 永久排除。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +from typing import Optional + +from app.models import TransferAttempt, TransferInvoiceItem +from app.services.in_transit_transfer.status import TransferStatus + +AGING_NORMAL = "normal" +AGING_WARN_3D = "warn_3d" +AGING_ESCALATE_5D = "escalate_5d" +AGING_CRITICAL_7D = "critical_7d" +AGING_UNKNOWN = "result_unknown" +AGING_CLOSED = "closed" + +_BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value + + +@dataclass(frozen=True) +class BacklogItemDTO: + """待处理池单项。""" + + item_id: int + source_code: str + invoice_no: str + material_no: str + status: str + reason: str + age_days: int + aging_level: str + last_attempt_at: Optional[str] = None + + +@dataclass +class BacklogSummaryDTO: + """待处理池汇总(含老化分级计数)。""" + + recoverable_count: int = 0 + closed_count: int = 0 + unknown_count: int = 0 + warn_3d: int = 0 + escalate_5d: int = 0 + critical_7d: int = 0 + + +def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str: + """按积压天数计算老化等级(0-2 普通 / 3 预警 / 5 升级 / 7+ 严重)。""" + if age_days >= critical: + return AGING_CRITICAL_7D + if age_days >= escalate: + return AGING_ESCALATE_5D + if age_days >= warn: + return AGING_WARN_3D + return AGING_NORMAL + + +def _latest_attempt(item: TransferInvoiceItem) -> Optional[TransferAttempt]: + """返回明细最近一次 Attempt(无则 None)。""" + return TransferAttempt.query.filter_by(item_id=item.id).order_by( + TransferAttempt.created_at.desc(), + ).first() + + +def _item_age_days(item: TransferInvoiceItem, now: datetime) -> int: + """按最近 Attempt 或明细更新时间计算积压天数。""" + latest = _latest_attempt(item) + base = latest.created_at if latest is not None else item.updated_at + return max(0, int((now - base).total_seconds() // 86400)) + + +def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]: + """列出待处理池项(可恢复 + 已关闭 + 结果未知)。 + + Args: + now: 判定时刻(默认当前时间)。 + source_code: 可选来源过滤。 + Returns: + BacklogItemDTO 列表。 + """ + current = now or datetime.utcnow() + query = TransferInvoiceItem.query.filter( + TransferInvoiceItem.status.in_([ + _BACKLOG_RECOVERABLE, + TransferStatus.RESULT_UNKNOWN.value, + TransferStatus.MANUALLY_CLOSED.value, + ]), + ) + if source_code: + query = query.filter_by(source_code=source_code) + output: list[BacklogItemDTO] = [] + for item in query.order_by(TransferInvoiceItem.updated_at.asc()).all(): + age = _item_age_days(item, current) + latest = _latest_attempt(item) + if item.status == TransferStatus.RESULT_UNKNOWN.value: + level = AGING_UNKNOWN + elif item.status == TransferStatus.MANUALLY_CLOSED.value: + level = AGING_CLOSED + else: + level = aging_level_for(age) + output.append(BacklogItemDTO( + item_id=item.id, + source_code=item.source_code, + invoice_no=item.invoice_no, + material_no=item.material_no, + status=item.status, + reason=item.result_message or item.result_code or "", + age_days=age, + aging_level=level, + last_attempt_at=latest.created_at.isoformat() if latest is not None else None, + )) + return output + + +def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO: + """计算待处理池汇总计数与老化分级。""" + items = list_backlog(now=now) + summary = BacklogSummaryDTO() + for item in items: + if item.status == TransferStatus.MANUALLY_CLOSED.value: + summary.closed_count += 1 + elif item.status == TransferStatus.RESULT_UNKNOWN.value: + summary.unknown_count += 1 + else: + summary.recoverable_count += 1 + if item.aging_level == AGING_WARN_3D: + summary.warn_3d += 1 + elif item.aging_level == AGING_ESCALATE_5D: + summary.escalate_5d += 1 + elif item.aging_level == AGING_CRITICAL_7D: + summary.critical_7d += 1 + return summary diff --git a/backend/app/services/in_transit_transfer/cancellation.py b/backend/app/services/in_transit_transfer/cancellation.py new file mode 100644 index 00000000..984549e3 --- /dev/null +++ b/backend/app/services/in_transit_transfer/cancellation.py @@ -0,0 +1,65 @@ +"""在途调拨请求停止(取消剩余任务)。 + +用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销; + 原因必填;取消前后状态进入审计。 +依赖:models、status、core.errors。 +逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer import status as status_machine + + +def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict: + """请求停止剩余任务。 + + Args: + run_no: Run 编号。 + reason: 取消原因(必填)。 + actor_id / request_id: 审计上下文。 + Returns: + {"run_no": ..., "cancelled_count": ...}。 + Raises: + ValidationError: 原因为空。 + NotFoundError: Run 不存在。 + ConflictError: Run 已终态不可取消。 + """ + reason_value = str(reason or "").strip() + if not reason_value: + raise ValidationError("reason is required") + run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + if run.status in { + status_machine.TransferRunStatus.SUCCESS.value, + status_machine.TransferRunStatus.FAILED.value, + status_machine.TransferRunStatus.CANCELLED.value, + }: + raise ConflictError("run is already terminal", code="TRANSFER.RUN_NOT_CANCELLABLE") + + cancelled = 0 + for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all(): + if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no: + item.status = status_machine.TransferStatus.CANCELLED.value + item.result_code = "cancelled" + item.result_message = reason_value + cancelled += 1 + + active = db.session.query(TransferInvoiceItem).filter( + TransferInvoiceItem.run_id == run.id, + TransferInvoiceItem.status.in_([ + status_machine.TransferStatus.EXECUTING.value, + status_machine.TransferStatus.READY_TO_EXECUTE.value, + ]), + ).count() + if active == 0: + run.status = status_machine.TransferRunStatus.CANCELLED.value + run.completed_at = run.completed_at or datetime.utcnow() + db.session.commit() + return {"run_no": run.run_no, "cancelled_count": cancelled} diff --git a/backend/app/services/in_transit_transfer/chat_actions.py b/backend/app/services/in_transit_transfer/chat_actions.py new file mode 100644 index 00000000..f3034c2d --- /dev/null +++ b/backend/app/services/in_transit_transfer/chat_actions.py @@ -0,0 +1,100 @@ +"""在途调拨 Chat Action Handler。 + +用途:通过 Chat Turn Action 触发预检/执行,并输出结构化卡片事件 + (message_type=transfer-precheck / transfer-result),供前端 TransferMessageView 渲染。 +依赖:action_registry、action_schema.TurnEvent、precheck_service、execution_service、deps、serializers。 +逻辑:Dify 只产生受限候选 Action;真实预检/执行由本确定性 Handler 执行并流式输出卡片。 +""" + +from __future__ import annotations + +from typing import Any, Iterator + +from app.services.chat.action_registry import register_action_handler +from app.services.chat.action_schema import TurnEvent +from app.services.chat.turn_context import TurnContext +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.execution_service import execute_precheck, get_run +from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck +from app.services.in_transit_transfer.serializers import serialize_precheck_detail + +ACTION_TRANSFER_PRECHECK = "transfer.precheck" +ACTION_TRANSFER_EXECUTE = "transfer.execute" + + +def _message(content: str, message_type: str, payload: dict[str, Any]) -> TurnEvent: + """构造结构化消息完成事件。""" + return TurnEvent(event="message.completed", data={ + "content": content, + "message_type": message_type, + "payload": payload, + }) + + +@register_action_handler +class TransferPrecheckAction: + """预检 Action:创建(或恢复)预检并输出预检卡。""" + + action_type = ACTION_TRANSFER_PRECHECK + + def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: + """执行只读预检并输出 transfer-precheck 卡片。 + + 【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发; + 只读,不写 ERP。 + """ + payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {} + source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])] + business_date = str(payload.get("business_date") or business_date_now()) + deps = transfer_deps.get_transfer_dependencies() + summary = create_precheck( + source_codes=source_codes, + business_date=business_date, + deps=deps, + ) + detail = restore_precheck(summary.precheck_id) + yield _message( + content="调拨预检完成", + message_type="transfer-precheck", + payload={"kind": "precheck", **serialize_precheck_detail(detail)}, + ) + + +@register_action_handler +class TransferExecuteAction: + """执行 Action:确认选择范围并直接生成执行 Run,输出结果卡。""" + + action_type = ACTION_TRANSFER_EXECUTE + + def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: + """执行勾选范围并输出 transfer-result 卡片。 + + 【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发; + 后台确定性服务完成写前复查与 ERP 原子写入。 + """ + payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {} + precheck_id = str(payload.get("precheck_id") or "").strip() + invoice_nos = payload.get("invoice_nos") + invoice_nos = [str(item).strip() for item in invoice_nos] if isinstance(invoice_nos, list) else None + deps = transfer_deps.get_transfer_dependencies() + outcome = execute_precheck( + precheck_id=precheck_id, + deps=deps, + selected_invoice_nos=invoice_nos, + ) + run_view = get_run(outcome.run_no) + yield _message( + content=f"调拨执行完成:{outcome.run_no}", + message_type="transfer-result", + payload={ + "kind": "result", + "run_no": outcome.run_no, + "status": outcome.status, + "run": { + "run_no": outcome.run_no, + "status": outcome.status, + "result": run_view["result"], + }, + }, + ) diff --git a/backend/app/services/in_transit_transfer/concurrency.py b/backend/app/services/in_transit_transfer/concurrency.py new file mode 100644 index 00000000..09438f5c --- /dev/null +++ b/backend/app/services/in_transit_transfer/concurrency.py @@ -0,0 +1,25 @@ +"""在途调拨并发参数与单写者约束。 + +用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值; + ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。 +依赖:无(纯常量)。 +逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。 +""" + +from __future__ import annotations + +# 一期冻结并发参数(与规格 §10 一致)。 +SOURCE_CONCURRENCY = 2 +ERP_QUERY_CONCURRENCY = 2 +ERP_WRITE_CONCURRENCY = 1 + + +def assert_single_writer(run_count: int) -> None: + """同预检最多一个执行 Run。 + + Args: + run_count: 已存在的执行 Run 数。 + Raises: + AssertionError: run_count > 1(一期硬约束)。 + """ + assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck" diff --git a/backend/app/services/in_transit_transfer/contracts.py b/backend/app/services/in_transit_transfer/contracts.py new file mode 100644 index 00000000..2c9ad2e5 --- /dev/null +++ b/backend/app/services/in_transit_transfer/contracts.py @@ -0,0 +1,200 @@ +"""在途调拨 DTO 与稳定错误码契约。 + +用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码, + 保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。 +依赖:标准库 dataclasses / decimal。 +逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页 + (决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from decimal import Decimal +from typing import Iterable + +# ---- 一期冻结错误码(TDD §7.3)------------------------------------------- +TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED" +TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED" +TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY" +TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID" +TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT" +TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH" +TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND" +TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED" +TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED" +TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED" +TRANSFER_RESULT_UNKNOWN = "TRANSFER_RESULT_UNKNOWN" +TRANSFER_MANUAL_CLOSE_REASON_REQUIRED = "TRANSFER_MANUAL_CLOSE_REASON_REQUIRED" +TRANSFER_CONFIG_PUBLISH_BLOCKED = "TRANSFER_CONFIG_PUBLISH_BLOCKED" +TRANSFER_SECRET_NOT_EXPOSED = "TRANSFER_SECRET_NOT_EXPOSED" +TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED" + +KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({ + TRANSFER_PERMISSION_DENIED, + TRANSFER_RECEIPT_NOT_MATURED, + TRANSFER_FILE_NOT_READY, + TRANSFER_FILE_SCHEMA_INVALID, + TRANSFER_INVOICE_CONFLICT, + TRANSFER_QUANTITY_MISMATCH, + TRANSFER_ERP_INVENTORY_NOT_FOUND, + TRANSFER_PRECHECK_EXPIRED, + TRANSFER_CONFIRMATION_REQUIRED, + TRANSFER_DUPLICATE_NOT_VERIFIED, + TRANSFER_RESULT_UNKNOWN, + TRANSFER_MANUAL_CLOSE_REASON_REQUIRED, + TRANSFER_CONFIG_PUBLISH_BLOCKED, + TRANSFER_SECRET_NOT_EXPOSED, + TRANSFER_NOTIFICATION_FAILED, +}) + + +def require_known_error_code(code: str) -> None: + """校验错误码属于一期冻结集合。 + + Args: + code: 错误码。 + Raises: + ValueError: 未知错误码。 + """ + if str(code or "").strip() not in KNOWN_TRANSFER_ERROR_CODES: + raise ValueError(f"unknown transfer error code: {code}") + + +# ---- 预检 DTO ------------------------------------------------------------- +@dataclass(frozen=True) +class PrecheckCountsDTO: + """预检计数。""" + + file_invoice_count: int = 0 + not_matured_count: int = 0 + prechecked_count: int = 0 + executable_count: int = 0 + blocked_count: int = 0 + + +@dataclass(frozen=True) +class RawLineRefDTO: + """原始文件行追溯(Sheet/行号/文件版本)。""" + + sheet: str + row_no: int + file_version: str + + +@dataclass(frozen=True) +class PrecheckInvoiceItemDTO: + """预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。""" + + source_code: str + material_no: str + material_name: str + specification: str + invoice_no: str + from_warehouse: str + from_quantity: Decimal | None + to_warehouse: str + to_quantity: Decimal + result: str + receipt_date: str | None = None + reason: str = "" + erp_document_no: str | None = None + raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple) + + +@dataclass(frozen=True) +class PrecheckSummaryDTO: + """预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。""" + + precheck_id: str + status: str + business_date: str + eligible_receipt_date_to: str + expires_at: str + counts: PrecheckCountsDTO + estimated_transfer_quantity: str + estimated_erp_write_count: int + precheck_hash: str + + +# ---- 结果页 DTO(决策 20)-------------------------------------------------- +@dataclass(frozen=True) +class ErpDocumentLineDTO: + """ERP 单据内物料明细。""" + + material_no: str + material_name: str + specification: str + invoice_no: str + quantity: Decimal + + +@dataclass(frozen=True) +class ErpDocumentDTO: + """按 ERP 单号聚合的结果项。""" + + document_no: str + from_warehouse: str + to_warehouse: str + material_count: int + total_quantity: Decimal + posting_status: str + lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple) + + +@dataclass(frozen=True) +class TransferExceptionDTO: + """未生成 ERP 单据的异常项(单独展示)。""" + + source_code: str + invoice_no: str + material_no: str + reason: str + facts: str + + +@dataclass(frozen=True) +class RunResultDTO: + """Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。""" + + run_no: str + status: str + erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple) + exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple) + + +def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]: + """按 ERP 单号聚合成功项,产出结果页文档视图。 + + Args: + items: 预检明细项(含 erp_document_no 与 result)。 + Returns: + 按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。 + """ + grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {} + for item in items: + if item.erp_document_no and item.result in {"success", "duplicate_success"}: + grouped.setdefault(item.erp_document_no, []).append(item) + documents: list[ErpDocumentDTO] = [] + for document_no in sorted(grouped): + rows = sorted(grouped[document_no], key=lambda row: row.invoice_no) + lines = tuple( + ErpDocumentLineDTO( + material_no=row.material_no, + material_name=row.material_name, + specification=row.specification, + invoice_no=row.invoice_no, + quantity=row.to_quantity, + ) + for row in rows + ) + documents.append(ErpDocumentDTO( + document_no=document_no, + from_warehouse=rows[0].from_warehouse, + to_warehouse=rows[0].to_warehouse, + material_count=len(rows), + total_quantity=sum((row.to_quantity for row in rows), Decimal("0")), + posting_status="posted", + lines=lines, + )) + return tuple(documents) diff --git a/backend/app/services/in_transit_transfer/date_policy.py b/backend/app/services/in_transit_transfer/date_policy.py new file mode 100644 index 00000000..25c225a0 --- /dev/null +++ b/backend/app/services/in_transit_transfer/date_policy.py @@ -0,0 +1,81 @@ +"""在途调拨业务日期与成熟度策略。 + +用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured, + 昨天及更早可预检,未来日期阻断)。 +依赖:标准库 zoneinfo / datetime。 +逻辑:所有日期判定集中在本模块,供 precheck_service / recovery_service 复用, + 避免各服务各自计算导致口径漂移。 +""" + +from __future__ import annotations + +from datetime import date, datetime, timedelta +from zoneinfo import ZoneInfo + +SHANGHAI_TZ = ZoneInfo("Asia/Shanghai") + +# 成熟度结果 +MATURITY_ELIGIBLE = "eligible" +MATURITY_NOT_MATURED = "not_matured" +MATURITY_FUTURE = "future" + + +def parse_date(value: date | str) -> date: + """将 date 或 'YYYY-MM-DD' 字符串归一化为 date。 + + Args: + value: date 对象或 ISO 日期字符串。 + Returns: + 归一化后的 date。 + Raises: + ValueError: 字符串不是合法 ISO 日期。 + """ + if isinstance(value, date): + return value + return date.fromisoformat(str(value).strip()) + + +def business_date_now(moment: datetime | None = None) -> date: + """计算 Asia/Shanghai 业务日期。 + + Args: + moment: 可选时刻;带时区则转换到上海,naive 按 UTC 兼容处理(与 + shipping_notice.business_numbering_service 口径一致)。 + Returns: + Asia/Shanghai 口径的日期。 + """ + if moment is None: + return datetime.now(SHANGHAI_TZ).date() + if moment.tzinfo is None: + moment = moment.replace(tzinfo=ZoneInfo("UTC")) + return moment.astimezone(SHANGHAI_TZ).date() + + +def maturity_status(receipt_date: date | str, business_date: date | str) -> str: + """按 D+1 规则判定收料日期成熟度。 + + Args: + receipt_date: 收料日期。 + business_date: 当前业务日期 T。 + Returns: + 'eligible'(receipt_date < T)、'not_matured'(receipt_date == T)或 + 'future'(receipt_date > T,结构化阻断)。 + """ + receipt = parse_date(receipt_date) + business = parse_date(business_date) + if receipt == business: + return MATURITY_NOT_MATURED + if receipt > business: + return MATURITY_FUTURE + return MATURITY_ELIGIBLE + + +def eligible_receipt_date_to(business_date: date | str) -> date: + """返回可进入预检的收料截止日期(业务日期 T - 1 天)。 + + Args: + business_date: 当前业务日期。 + Returns: + T - 1 天。 + """ + return parse_date(business_date) - timedelta(days=1) diff --git a/backend/app/services/in_transit_transfer/deps.py b/backend/app/services/in_transit_transfer/deps.py new file mode 100644 index 00000000..98054dba --- /dev/null +++ b/backend/app/services/in_transit_transfer/deps.py @@ -0,0 +1,118 @@ +"""在途调拨依赖装配(Dependencies)。 + +用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。 +依赖:file_preparation / erp_adapter / precheck_service / models。 +逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属 + (Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。 +""" + +from __future__ import annotations + +from typing import Any + +from app.core.errors import AppError +from app.models import ShippingInventoryExternalMapping, ShippingInventorySource +from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository +from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter +from app.services.in_transit_transfer.precheck_service import ( + RouteMapping, + RouteNotResolvedError, + RouteResolver, + TransferDeps, +) + +RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN" + + +class ReceiptRowsNotFrozenError(AppError): + """收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。""" + + def __init__(self, message: str = "receipt file row contract not frozen"): + super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False) + + +class ShippingReceiptFileRepository: + """默认收料 ready 文件仓库(只读复用 shipping 收料归档)。 + + 行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。 + """ + + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + """返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。""" + raise ReceiptRowsNotFrozenError( + "receipt file rows unfrozen: sample/sheet contract required (Q3)" + ) + + +class DefaultRouteResolver: + """默认路由解析:来源固定仓 + 外部系统仓库映射。 + + 路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。 + """ + + def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping: + """按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。""" + source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + raise RouteNotResolvedError(source_code=source_code) + mapping = ShippingInventoryExternalMapping.query.filter_by( + inventory_source_id=source.id, enabled=True, + ).first() + if mapping is None or not mapping.external_organization_code: + raise RouteNotResolvedError(source_code=source_code) + return RouteMapping( + erp_org=mapping.external_organization_code, + from_warehouse=source.fixed_warehouse_id or "", + to_warehouse=mapping.external_warehouse_code, + ) + + +def _build_erp_adapter() -> CapabilityErpAdapter: + """装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。 + + P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射) + 承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。 + """ + return CapabilityErpAdapter() + + +_override: TransferDeps | None = None + + +def set_transfer_dependencies(deps: TransferDeps | None) -> None: + """测试注入点:设置/清除 TransferDeps 覆盖。""" + global _override # noqa: PLW0603 + _override = deps + + +def get_transfer_dependencies() -> TransferDeps: + """返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。""" + if _override is not None: + return _override + return TransferDeps( + file_repository=ShippingReceiptFileRepository(), + rpa_trigger=_DefaultRpaTrigger(), + route_resolver=DefaultRouteResolver(), + erp=_build_erp_adapter(), + ) + + +class _DefaultRpaTrigger: + """默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。 + + 依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或 + trigger 目录未配置时返回失败(fail-closed),不伪造等待。 + """ + + def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: + from flask import current_app + + trigger_dir = str( + current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or "" + ).strip() + if not trigger_dir: + return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"} + source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"} + return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"} diff --git a/backend/app/services/in_transit_transfer/erp_adapter.py b/backend/app/services/in_transit_transfer/erp_adapter.py new file mode 100644 index 00000000..25d697e0 --- /dev/null +++ b/backend/app/services/in_transit_transfer/erp_adapter.py @@ -0,0 +1,295 @@ +"""在途调拨 ERP 访问统一边界(Adapter)。 + +用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。 + Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer / + verify_duplicate / 结果分类。 +依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。 +逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no / + erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试; + SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from decimal import Decimal +from typing import Any, Protocol + +from app.core.errors import AppError + +ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN" +ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT" +ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN" + + +@dataclass(frozen=True) +class InventoryQuery: + """ERP 账面库存查询结果。""" + + found: bool + quantity: Decimal | None = None + document_no: str | None = None + + +class ErpNotFrozenError(AppError): + """ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。""" + + def __init__(self, message: str = "ERP contract not frozen"): + super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False) + + +class ErpQueryTimeoutError(AppError): + """ERP 查询超时(只读路径,允许上层重试)。""" + + def __init__(self, message: str = "ERP query timeout"): + super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True) + + +class ErpResultUnknownError(AppError): + """ERP 写结果无法确认(Phase 2 使用);禁止自动重试。""" + + def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None): + details = {"operation_id": operation_id} if operation_id else {} + super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details) + + +class ErpWriteTimeoutError(TimeoutError): + """ERP 写超时;committed 表达是否可证明已落单。""" + + def __init__( + self, + message: str, + *, + committed: bool | None, + document_no: str | None = None, + operation_id: str | None = None, + ) -> None: + super().__init__(message) + self.committed = committed + self.document_no = document_no + self.operation_id = operation_id + + +@dataclass(frozen=True) +class TransferWriteResult: + """ERP 原子建单/审核/过账结果分类。""" + + status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown + document_no: str | None = None + verified_posted: bool | None = None + error_code: str | None = None + error_message: str | None = None + + +class ErpTransport(Protocol): + """ERP 传输层协议(SOAP 或测试替身)。""" + + def query_inventory(self, **kwargs: Any) -> dict[str, Any]: + """按 Invoice 查询账面库存。""" + + def create_transfer(self, **kwargs: Any) -> dict[str, Any]: + """原子建单/审核/过账(Phase 2)。""" + + def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]: + """核实重复 Invoice 原单是否已审核过账。""" + + +class SoapErpTransport: + """真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。 + + Args: + config: 来自 Flask config 或环境变量(endpoint/username/password 等)。 + """ + + def __init__(self, config: dict[str, Any] | None = None) -> None: + self._config = config or {} + + def _require_frozen(self, operation: str) -> None: + """WSDL/endpoint 未冻结前任何调用直接拒绝。""" + if not str(self._config.get("endpoint") or "").strip(): + raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)") + + def query_inventory(self, **kwargs: Any) -> dict[str, Any]: + """SOAP 查询账面库存(实现待 WSDL 冻结后落地)。""" + self._require_frozen("query_inventory") + raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL") + + def create_transfer(self, **kwargs: Any) -> dict[str, Any]: + """SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。""" + self._require_frozen("create_transfer") + raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL") + + def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]: + """SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。""" + self._require_frozen("verify_duplicate") + raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL") + + +class ErpAdapter: + """ERP 唯一访问入口;组装统一请求并分类结果。""" + + def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None: + self._transport = transport + self._default_org = default_org + + def query_inventory( + self, + *, + operation_id: str, + run_no: str, + attempt_no: int, + invoice_no: str, + erp_org: str | None = None, + from_warehouse: str, + to_warehouse: str, + quantity: Decimal, + ) -> InventoryQuery: + """查询 ERP 账面库存并分类结果。 + + Args: + operation_id / run_no / attempt_no / invoice_no / erp_org / + from_warehouse / to_warehouse / quantity: 请求强制追踪字段。 + Returns: + InventoryQuery。 + Raises: + ErpQueryTimeoutError: 查询超时(可重试)。 + ErpNotFrozenError: ERP 契约未冻结。 + """ + request = { + "operation_id": operation_id, + "run_no": run_no, + "attempt_no": attempt_no, + "invoice_no": invoice_no, + "erp_org": erp_org or self._default_org, + "from_warehouse": from_warehouse, + "to_warehouse": to_warehouse, + "quantity": quantity, + } + try: + response = self._transport.query_inventory(**request) + except ErpNotFrozenError: + raise + except TimeoutError as exc: + raise ErpQueryTimeoutError() from exc + response = response if isinstance(response, dict) else {} + if response.get("found"): + return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0"))) + return InventoryQuery(found=False) + + def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org, + from_warehouse, to_warehouse, quantity) -> dict[str, Any]: + """组装携带全部强制追踪字段的 ERP 请求。""" + return { + "operation_id": operation_id, + "run_no": run_no, + "attempt_no": attempt_no, + "invoice_no": invoice_no, + "erp_org": erp_org or self._default_org, + "from_warehouse": from_warehouse, + "to_warehouse": to_warehouse, + "quantity": quantity, + } + + def create_transfer( + self, + *, + operation_id: str, + run_no: str, + attempt_no: int, + invoice_no: str, + erp_org: str | None = None, + from_warehouse: str, + to_warehouse: str, + quantity: Decimal, + ) -> TransferWriteResult: + """ERP 原子建单/审核/过账并按结果分类。 + + Returns: + TransferWriteResult:success / duplicate_success / duplicate_unverified / + business_failed / technical_failed / result_unknown。 + Raises: + ErpNotFrozenError: ERP 契约未冻结。 + """ + request = self._build_request( + operation_id=operation_id, run_no=run_no, attempt_no=attempt_no, + invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse, + to_warehouse=to_warehouse, quantity=quantity, + ) + try: + response = self._transport.create_transfer(**request) + except ErpNotFrozenError: + raise + except ErpWriteTimeoutError as exc: + if exc.committed is False: + # 可证明未落单 → 明确技术失败(不产生单据)。 + return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT") + return TransferWriteResult( + status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT", + document_no=exc.document_no, + ) + except TimeoutError: + # 无法区分是否落单 → result_unknown,禁止自动重试。 + return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN") + return _classify_write_response(response) + + def verify_duplicate( + self, + *, + operation_id: str, + run_no: str, + attempt_no: int, + invoice_no: str, + erp_org: str | None = None, + from_warehouse: str, + to_warehouse: str, + quantity: Decimal, + ) -> TransferWriteResult: + """核实重复 Invoice 原单是否已审核过账(幂等确认)。 + + Returns: + duplicate_success(已过账,含原单号)或 duplicate_unverified。 + """ + request = self._build_request( + operation_id=operation_id, run_no=run_no, attempt_no=attempt_no, + invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse, + to_warehouse=to_warehouse, quantity=quantity, + ) + try: + response = self._transport.verify_duplicate(**request) + except ErpNotFrozenError: + raise + except (TimeoutError, ErpWriteTimeoutError): + return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN") + response = response if isinstance(response, dict) else {} + status = str(response.get("status") or "") + document_no = response.get("document_no") + posted = bool(response.get("verified_posted")) + if status == "duplicate_success" and posted: + return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True) + return TransferWriteResult( + status="duplicate_unverified", document_no=document_no, verified_posted=posted, + error_code="TRANSFER_DUPLICATE_NOT_VERIFIED", + ) + + +def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult: + """按 ERP 写响应原文分类业务结果。""" + status = str(response.get("status") or "") + document_no = response.get("document_no") + if status == "success": + return TransferWriteResult(status="success", document_no=document_no) + if status == "duplicate_success": + posted = bool(response.get("verified_posted")) + if posted: + return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True) + return TransferWriteResult( + status="duplicate_unverified", document_no=document_no, verified_posted=False, + error_code="TRANSFER_DUPLICATE_NOT_VERIFIED", + ) + if status == "business_failed": + return TransferWriteResult( + status="business_failed", + error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"), + error_message=str(response.get("message") or ""), + ) + return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE") diff --git a/backend/app/services/in_transit_transfer/excel_export.py b/backend/app/services/in_transit_transfer/excel_export.py new file mode 100644 index 00000000..e8a95311 --- /dev/null +++ b/backend/app/services/in_transit_transfer/excel_export.py @@ -0,0 +1,125 @@ +"""在途调拨七 Sheet 异常 Excel 导出。 + +用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/ + ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。 +依赖:openpyxl、models、execution_service。 +逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本; + Secret 明文永不写入单元格(仅输出业务字段)。 +""" + +from __future__ import annotations + +import io +from typing import Any + +from openpyxl import Workbook + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.core.errors import NotFoundError + +EXCEL_SHEET_NAMES = [ + "执行汇总", + "数量不一致", + "ERP无库存", + "ERP技术失败", + "ERP结果未知", + "通知失败", + "原始文件追溯", +] + +_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + + +def build_exceptions_workbook(run_no: str) -> bytes: + """生成 Run 的七 Sheet 异常 Excel 字节。 + + Args: + run_no: Run 编号。 + Returns: + xlsx 字节。 + Raises: + NotFoundError: Run 不存在。 + """ + run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).order_by( + TransferInvoiceItem.invoice_no, + ).all() + + workbook = Workbook() + workbook.remove(workbook.active) + + _sheet_summary(workbook, run, items) + _sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"}) + _sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"}) + _sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"}) + _sheet_unknown(workbook, items) + _sheet_notification(workbook, run) + _sheet_raw_trace(workbook, items) + + buffer = io.BytesIO() + workbook.save(buffer) + return buffer.getvalue() + + +def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInvoiceItem]) -> None: + """执行汇总 Sheet。""" + sheet = workbook.create_sheet("执行汇总") + sheet.append(["Run", run.run_no]) + sheet.append(["Run 状态", run.status]) + sheet.append(["通知状态", run.notification_status]) + sheet.append([]) + sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"]) + for item in items: + sheet.append([ + item.invoice_no, item.source_code, item.material_no, + item.result_code or item.status, item.erp_document_no or "", + ]) + + +def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None: + """按阻断原因归类 Sheet。""" + sheet = workbook.create_sheet(sheet_name) + sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"]) + for item in items: + if (item.result_code or "") in codes or item.status in codes: + sheet.append([ + item.invoice_no, item.source_code, item.material_no, + item.receipt_quantity, item.erp_quantity or "", + item.result_message or item.result_code or item.status, + ]) + + +def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None: + """ERP 结果未知 Sheet(只读提示,含 Operation 关联)。""" + sheet = workbook.create_sheet("ERP结果未知") + sheet.append(["Invoice", "来源", "料号", "说明"]) + sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""]) + for item in items: + if item.status == "result_unknown" or (item.result_code or "") == "result_unknown": + sheet.append([item.invoice_no, item.source_code, item.material_no, item.result_message or ""]) + + +def _sheet_notification(workbook: Workbook, run: TransferRun) -> None: + """通知失败 Sheet。""" + sheet = workbook.create_sheet("通知失败") + sheet.append(["Run", "通知状态", "错误码"]) + if run.notification_status == "failed": + sheet.append([run.run_no, run.notification_status, run.notification_error_code or ""]) + + +def _sheet_raw_trace(workbook: Workbook, items: list[TransferInvoiceItem]) -> None: + """原始文件追溯 Sheet(决策 11:Sheet/行号/文件版本)。""" + sheet = workbook.create_sheet("原始文件追溯") + sheet.append(["Invoice", "Sheet", "原始行号", "文件版本", "来源"]) + for item in items: + for line in (item.raw_lines_json or []): + sheet.append([ + item.invoice_no, + str(line.get("sheet") or ""), + int(line.get("row_no") or 0), + str(line.get("file_version") or ""), + item.source_code, + ]) diff --git a/backend/app/services/in_transit_transfer/execution_service.py b/backend/app/services/in_transit_transfer/execution_service.py new file mode 100644 index 00000000..8fd6be83 --- /dev/null +++ b/backend/app/services/in_transit_transfer/execution_service.py @@ -0,0 +1,399 @@ +"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。 + +用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run → + 逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。 +依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。 +逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0; + 每个 Invoice 独立写入,单项失败/结果未知不阻断其他项; + result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。 +""" + +from __future__ import annotations + +import uuid +from dataclasses import dataclass +from datetime import datetime +from decimal import Decimal +from typing import Any + +from app import db +from app.core.errors import AppError, NotFoundError, ValidationError +from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.contracts import ( + TRANSFER_CONFIRMATION_REQUIRED, + TRANSFER_PRECHECK_EXPIRED, + ErpDocumentDTO, + PrecheckInvoiceItemDTO, + RunResultDTO, + TransferExceptionDTO, + aggregate_erp_documents, +) +from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run +from app.services.in_transit_transfer.precheck_service import ( + RESULT_EXECUTABLE, + RouteNotResolvedError, + TransferDeps, +) +from app.services.in_transit_transfer.quantity import classify_quantity_match + +PRECHECK_EXPIRED_RESULT = "precheck_expired" +ITEM_EXECUTION_ERROR_RESULT = "item_execution_error" + + +@dataclass(frozen=True) +class ExecuteOutcome: + """一次执行的结果摘要。""" + + run_no: str + status: str + result: RunResultDTO + + +def _item_result_of(item: TransferInvoiceItem) -> str: + """从持久化状态还原明细结果值(与预检快照口径一致)。""" + if item.result_code: + return item.result_code + if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value: + return RESULT_EXECUTABLE + return item.status + + +def recompute_precheck_hash(precheck: TransferPrecheck) -> str: + """由存储明细复算预检 Hash(写前快照校验口径)。""" + from app.services.in_transit_transfer.audit import canonical_hash + + counts = precheck.counts_json if isinstance(precheck.counts_json, dict) else {} + items = [ + { + "source_code": item.source_code, + "invoice_no": item.invoice_no, + "from_warehouse": item.from_warehouse, + "to_warehouse": item.to_warehouse, + "receipt_quantity": item.receipt_quantity, + "erp_quantity": item.erp_quantity, + "result": _item_result_of(item), + } + for item in sorted(precheck.items, key=lambda row: row.id) + ] + snapshot = { + "scope": sorted(precheck.scope_json.get("source_codes") or []), + "business_date": precheck.business_date, + "file_snapshot": precheck.file_snapshot_json if isinstance(precheck.file_snapshot_json, dict) else {}, + "counts": { + key: int(counts.get(key, 0)) + for key in ("file_invoice_count", "not_matured_count", "prechecked_count", + "executable_count", "blocked_count") + }, + "items": items, + } + return f"sha256:{canonical_hash(snapshot)}" + + +def _expire(precheck: TransferPrecheck) -> None: + """将预检置为过期(fail-closed 落位)。""" + precheck.status = "expired" + db.session.flush() + + +def execute_precheck( + *, + precheck_id: str, + deps: TransferDeps, + selected_invoice_nos: list[str] | None = None, + actor_id: int | None = None, + request_id: str | None = None, +) -> ExecuteOutcome: + """执行一次已确认的预检(手工或自动触发共用)。 + + Args: + precheck_id: 预检编号。 + deps: 注入依赖。 + selected_invoice_nos: 选择范围(仅可执行项);缺省执行全部可执行项。 + actor_id / request_id: 审计上下文。 + Returns: + ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。 + Raises: + NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。 + ConflictError: 重复执行。 + """ + precheck = db.session.query(TransferPrecheck).filter_by( + precheck_no=str(precheck_id).strip(), + ).first() + if precheck is None: + raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND") + if precheck.confirmed_at is not None: + from app.core.errors import ConflictError + + raise ConflictError("precheck already executed", code="TRANSFER.PRECHECK_ALREADY_EXECUTED") + if precheck.status != status_machine.TransferStatus.READY_TO_EXECUTE.value: + raise AppError( + code=TRANSFER_CONFIRMATION_REQUIRED, + message="precheck is not confirmed for execution", + http_status=400, + ) + if precheck.expires_at is not None and precheck.expires_at <= datetime.utcnow(): + _expire(precheck) + db.session.commit() + raise AppError( + code=TRANSFER_PRECHECK_EXPIRED, message="precheck confirmation expired", + http_status=409, + ) + if recompute_precheck_hash(precheck) != precheck.precheck_hash: + _expire(precheck) + db.session.commit() + raise AppError( + code=TRANSFER_PRECHECK_EXPIRED, + message="precheck snapshot changed since confirmation", + http_status=409, + ) + + executable = [item for item in precheck.items if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value] + if selected_invoice_nos is not None: + selected_set = {str(item).strip() for item in selected_invoice_nos} + available = {item.invoice_no for item in executable} + invalid = selected_set - available + if invalid: + raise ValidationError( + f"invoices not executable: {sorted(invalid)}", + code="TRANSFER.SELECTION_INVALID", + ) + selected = [item for item in executable if item.invoice_no in selected_set] + else: + selected = list(executable) + if not selected: + raise ValidationError("no executable invoices selected", code=TRANSFER_CONFIRMATION_REQUIRED) + + run = create_execution_run( + precheck, deps=deps, actor_id=actor_id, + selected_invoice_nos={item.invoice_no for item in selected}, + ) + for item in selected: + try: + _write_item(item, deps=deps, run_no=run.run_no, request_id=request_id) + except Exception as exc: # noqa: BLE001 —— 单项失败不阻断其他项 + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = ITEM_EXECUTION_ERROR_RESULT + item.result_message = str(exc) + db.session.flush() + db.session.flush() + run_items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + finalize_run(run, run_items) + db.session.commit() + return ExecuteOutcome(run_no=run.run_no, status=run.status, result=_build_run_result(run)) + + +def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None: + """写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。""" + route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no) + if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse: + _mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck") + return + receipt_qty = Decimal(item.receipt_quantity) + operation_id = f"op-{uuid.uuid4().hex[:12]}" + # [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。 + try: + query = deps.erp.query_inventory( + operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no, + invoice_no=item.invoice_no, erp_org=route.erp_org, + from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse, + quantity=receipt_qty, + ) + except RouteNotResolvedError: + raise + if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE: + _mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck") + return + + # [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。 + attempt = TransferAttempt( + item_id=item.id, attempt_no=item.attempt_no, kind="erp_write", + status="running", operation_id=operation_id, + request_snapshot_json={ + "run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org, + "from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse, + "quantity": str(receipt_qty), + }, + ) + db.session.add(attempt) + db.session.flush() + result = deps.erp.create_transfer( + operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no, + invoice_no=item.invoice_no, erp_org=route.erp_org, + from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse, + quantity=receipt_qty, + ) + before_status = item.status + _apply_write_result(item, attempt, result) + _audit_item_write(item, run_no, request_id, operation_id, before_status) + + +def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None: + """写前复查失败:fail-closed,不写 ERP。""" + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = result + item.result_message = message + db.session.flush() + + +def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None: + """按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。""" + attempt.response_summary_json = { + "status": result.status, + "document_no": result.document_no, + "verified_posted": result.verified_posted, + "error_code": result.error_code, + } + if result.status == "success": + item.status = status_machine.TransferStatus.SUCCESS.value + item.erp_document_no = result.document_no + item.result_code = None + attempt.status = "success" + elif result.status == "duplicate_success": + item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value + item.erp_document_no = result.document_no + item.result_code = None + attempt.status = "success" + elif result.status == "result_unknown": + # 终态:禁止自动重试,等待人工核实 SOP。 + item.status = status_machine.TransferStatus.RESULT_UNKNOWN.value + item.result_code = "result_unknown" + attempt.status = "result_unknown" + else: + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = result.status + item.result_message = result.error_message or result.error_code or "" + attempt.status = "failed" + attempt.error_code = result.error_code + attempt.completed_at = datetime.utcnow() + + +def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None: + """为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。""" + event = build_transfer_audit_event( + event_type="TRANSFER_ITEM_EXECUTED", + aggregate_type="transfer_item", + aggregate_id=str(item.id), + run_no=run_no, + invoice_no=item.invoice_no, + item_id=str(item.id), + attempt_no=item.attempt_no, + actor_type="worker", + request_id=request_id, + operation_id=operation_id, + result="success" if item.status in {"success", "duplicate_success"} else "failure", + before={"status": before_status}, + after={"status": item.status, "erp_document_no": item.erp_document_no}, + ) + db.session.add(event) + + +def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = None) -> str: + """单 Invoice 执行入口(Item Job Handler 使用)。 + + Args: + item_id: TransferInvoiceItem.id。 + deps: 注入依赖。 + Returns: + 写入后的 item 状态。 + Raises: + NotFoundError / RuntimeError: item 不存在或未关联执行 Run。 + """ + item = db.session.get(TransferInvoiceItem, item_id) + if item is None: + raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND") + if item.run_id is None: + raise RuntimeError("item not linked to execution run") + run_no = item.run.run_no if item.run else "RUN-PENDING" + _write_item(item, deps=deps, run_no=run_no, request_id=request_id) + db.session.commit() + return item.status + + +def get_run(run_no: str) -> dict[str, Any]: + """按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。""" + run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + return { + "run_no": run.run_no, + "status": run.status, + "result": serialize_run_result(_build_run_result(run)), + } + + +def _build_run_result(run: TransferRun) -> RunResultDTO: + """由 Run 明细构建结果投影。""" + item_dtos: list[PrecheckInvoiceItemDTO] = [] + exceptions: list[TransferExceptionDTO] = [] + for item in sorted(run.items, key=lambda row: row.invoice_no): + result = _item_result_of(item) + item_dtos.append(PrecheckInvoiceItemDTO( + source_code=item.source_code, + material_no=item.material_no, + material_name=item.material_name, + specification=item.specification, + invoice_no=item.invoice_no, + receipt_date=item.receipt_date, + from_warehouse=item.from_warehouse, + from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None, + to_warehouse=item.to_warehouse, + to_quantity=Decimal(item.receipt_quantity), + result=result, + reason=item.result_message or "", + erp_document_no=item.erp_document_no, + )) + if result not in {"success", "duplicate_success"}: + exceptions.append(TransferExceptionDTO( + source_code=item.source_code, + invoice_no=item.invoice_no, + material_no=item.material_no, + reason=result, + facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""), + )) + return RunResultDTO( + run_no=run.run_no, + status=run.status, + erp_documents=aggregate_erp_documents(item_dtos), + exceptions=tuple(exceptions), + ) + + +def serialize_run_result(result: RunResultDTO) -> dict[str, Any]: + """结果投影序列化(前端结果页 DTO)。""" + return { + "run_no": result.run_no, + "status": result.status, + "erp_documents": [ + { + "document_no": document.document_no, + "from_warehouse": document.from_warehouse, + "to_warehouse": document.to_warehouse, + "material_count": document.material_count, + "total_quantity": str(document.total_quantity), + "posting_status": document.posting_status, + "lines": [ + { + "material_no": line.material_no, + "material_name": line.material_name, + "specification": line.specification, + "invoice_no": line.invoice_no, + "quantity": str(line.quantity), + } + for line in document.lines + ], + } + for document in result.erp_documents + ], + "exceptions": [ + { + "source_code": exc.source_code, + "invoice_no": exc.invoice_no, + "material_no": exc.material_no, + "reason": exc.reason, + "facts": exc.facts, + } + for exc in result.exceptions + ], + } diff --git a/backend/app/services/in_transit_transfer/file_parser.py b/backend/app/services/in_transit_transfer/file_parser.py new file mode 100644 index 00000000..a1eb299a --- /dev/null +++ b/backend/app/services/in_transit_transfer/file_parser.py @@ -0,0 +1,179 @@ +"""在途调拨收料文件字段/结构校验。 + +用途:校验收料文件必填列(Invoice No/料号/收料日期/收料数量)、数量与日期合法性、 + 来源身份一致性,输出 ParsedReceiptRow 供 Invoice 汇总。 +依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_receipt_quantity。 +逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date +from decimal import Decimal +from typing import Any, Iterable, Mapping + +from app.core.errors import AppError +from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID +from app.services.in_transit_transfer.date_policy import parse_date +from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_receipt_quantity + +REQUIRED_FIELDS = ("sheet", "row_no", "invoice_no", "material_no", "receipt_date", "receipt_quantity") + + +@dataclass(frozen=True) +class ParsedReceiptRow: + """单行已校验收料记录。""" + + source_code: str + sheet: str + row_no: int + invoice_no: str + material_no: str + material_name: str + specification: str + receipt_date: date + receipt_quantity: Decimal + + +class ReceiptFileSchemaError(AppError): + """收料文件结构/字段校验失败(整行阻断)。""" + + def __init__(self, message: str = "receipt file schema invalid", *, rows: list[dict[str, Any]] | None = None): + super().__init__( + code=TRANSFER_FILE_SCHEMA_INVALID, + message=message, + http_status=422, + details={"rows": rows or []}, + ) + + +def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None: + """累积式抛出首个行级错误(携带行号与原因)。""" + rows.append({"row_no": row_no, "reason": reason}) + + +def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]: + """把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。 + + 字段契约(领域定死)见 movement_contract.MOVEMENT_FIELDS;映射关系: + doc_no → invoice_no(幂等/汇总键) + quantity → receipt_quantity(严格数量匹配) + movement_date → receipt_date(成熟过滤) + 其余字段(material_code→material_no、material_name、warehouse_code、storage_code、 + lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。 + + Args: + source_code: 任务来源实例(行内来源身份一致性校验)。 + rows: 通用异动原始行 dict。 + Returns: + 已校验的 ParsedReceiptRow 列表。 + Raises: + ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 + """ + return _parse_rows( + source_code=source_code, + rows=rows, + projection={ + "invoice_no": "doc_no", + "material_no": "material_code", + "receipt_quantity": "quantity", + "receipt_date": "movement_date", + }, + ) + + +def parse_receipt_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]: + """校验并解析收料文件行。 + + Args: + source_code: 任务来源实例(用于校验行内来源身份一致性)。 + rows: 原始文件行 dict。 + Returns: + 已校验的 ParsedReceiptRow 列表。 + Raises: + ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 + """ + return _parse_rows( + source_code=source_code, + rows=rows, + projection={ + "invoice_no": "invoice_no", + "material_no": "material_no", + "receipt_quantity": "receipt_quantity", + "receipt_date": "receipt_date", + }, + ) + + +def _parse_rows( + *, + source_code: str, + rows: Iterable[Mapping[str, Any]], + projection: Mapping[str, str], +) -> list[ParsedReceiptRow]: + """按字段名投影校验并解析原始行。 + + Args: + source_code: 任务来源实例(行内来源身份一致性校验)。 + rows: 原始文件行 dict。 + projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date) + 到原始行字段名的映射(如 {invoice_no: doc_no})。 + Returns: + 已校验的 ParsedReceiptRow 列表。 + Raises: + ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 + """ + invoice_key = str(projection.get("invoice_no") or "invoice_no") + material_key = str(projection.get("material_no") or "material_no") + quantity_key = str(projection.get("receipt_quantity") or "receipt_quantity") + date_key = str(projection.get("receipt_date") or "receipt_date") + + errors: list[dict[str, Any]] = [] + parsed: list[ParsedReceiptRow] = [] + for raw in rows: + row = raw if isinstance(raw, Mapping) else {} + row_no = row.get("row_no") + invoice_no = str(row.get(invoice_key) or "").strip() + material_no = str(row.get(material_key) or "").strip() + sheet = str(row.get("sheet") or "").strip() + receipt_date_raw = str(row.get(date_key) or "").strip() + quantity_raw = row.get(quantity_key) + + if not sheet or not row_no: + _fail(errors, row_no=row_no, reason="missing_sheet_or_row_no") + continue + if not invoice_no: + _fail(errors, row_no=row_no, reason="missing_invoice_no") + continue + if not material_no: + _fail(errors, row_no=row_no, reason="missing_material_no") + continue + row_source = str(row.get("source_code") or "").strip() + if row_source and row_source.upper() != str(source_code).upper(): + _fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}") + continue + try: + receipt_date = parse_date(receipt_date_raw) + except ValueError: + _fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}") + continue + try: + quantity = validate_receipt_quantity(quantity_raw) + except QuantityValidationError as exc: + _fail(errors, row_no=row_no, reason=str(exc)) + continue + parsed.append(ParsedReceiptRow( + source_code=str(source_code), + sheet=sheet, + row_no=int(row_no), + invoice_no=invoice_no, + material_no=material_no, + material_name=str(row.get("material_name") or "").strip(), + specification=str(row.get("specification") or "").strip(), + receipt_date=receipt_date, + receipt_quantity=quantity, + )) + if errors: + raise ReceiptFileSchemaError(rows=errors) + return parsed diff --git a/backend/app/services/in_transit_transfer/file_preparation.py b/backend/app/services/in_transit_transfer/file_preparation.py new file mode 100644 index 00000000..ddeb0bfa --- /dev/null +++ b/backend/app/services/in_transit_transfer/file_preparation.py @@ -0,0 +1,96 @@ +"""在途调拨收料文件 Ready 复用与来源级 RPA 触发。 + +用途:按 (source_code, business_date, purpose=receipt) 检查最新 ready 文件; + 存在则复用,不存在则按来源实例触发一次收料 RPA;存在活动 Source Job + 时绑定已有任务,保证并发请求只触发一次抓取。 +依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。 +逻辑:文件仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身; + 任何触发失败 fail-closed 进入 failed,绝不误报 file_ready。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Protocol + +STAGE_FILE_READY = "file_ready" +STAGE_WAITING_RPA = "waiting_rpa_callback" +STAGE_FAILED = "failed" + + +@dataclass(frozen=True) +class ReadyReceiptFile: + """当日最新 ready 收料文件快照(含已提取行,供解析)。""" + + source_code: str + business_date: str + file_no: str + file_version: str + checksum: str + rows: tuple[dict[str, Any], ...] = () + + +@dataclass(frozen=True) +class FilePreparationResult: + """来源级文件准备结果。""" + + stage: str + file: ReadyReceiptFile | None = None + error_code: str | None = None + error_message: str | None = None + + +class ReceiptFileRepository(Protocol): + """收料 ready 文件仓库协议。""" + + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + """返回该来源当日最新 ready 文件;不存在返回 None。""" + + +class RpaTrigger(Protocol): + """收料 RPA 触发协议(DBS/Crane 共用)。""" + + def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: + """触发一次收料抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。""" + + +def ensure_receipt_file_ready( + *, + source_code: str, + business_date: str, + repository: ReceiptFileRepository, + rpa_trigger: RpaTrigger, + active_source_job_key: str | None = None, +) -> FilePreparationResult: + """确保来源当日 ready 文件可用。 + + Args: + source_code: 来源实例编码。 + business_date: 业务日期(YYYY-MM-DD)。 + repository: ready 文件仓库。 + rpa_trigger: RPA 触发器。 + active_source_job_key: 活动 Source Job 键;非空时绑定已有任务不重复触发。 + Returns: + FilePreparationResult(file_ready / waiting_rpa_callback / failed)。 + """ + ready = repository.latest_ready_file(source_code=source_code, business_date=business_date) + if ready is not None: + return FilePreparationResult(stage=STAGE_FILE_READY, file=ready) + + if active_source_job_key is not None: + # 已有活动抓取任务:绑定等待,不重复触发。 + return FilePreparationResult(stage=STAGE_WAITING_RPA) + + outcome = rpa_trigger.trigger( + source_code=source_code, + business_date=business_date, + reason="precheck_missing_ready_file", + ) + outcome = outcome if isinstance(outcome, dict) else {} + if outcome.get("ok"): + return FilePreparationResult(stage=STAGE_WAITING_RPA) + return FilePreparationResult( + stage=STAGE_FAILED, + error_code=str(outcome.get("error_code") or "RPA_TRIGGER_FAILED"), + error_message=str(outcome.get("error_message") or "rpa trigger failed"), + ) diff --git a/backend/app/services/in_transit_transfer/gateway_adapter.py b/backend/app/services/in_transit_transfer/gateway_adapter.py new file mode 100644 index 00000000..5e5c5d10 --- /dev/null +++ b/backend/app/services/in_transit_transfer/gateway_adapter.py @@ -0,0 +1,80 @@ +"""services/in_transit_transfer/gateway_adapter.py + +用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用 + (query_inventory 是首个配置绑定消费者)。 +依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。 +逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer / + verify_duplicate 留待调拨执行阶段(Phase 2)接线。 +""" + +from __future__ import annotations + +from decimal import Decimal +from typing import Any + +from app.core.errors import AppError +from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery + +QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory" + + +class CapabilityErpAdapter: + """把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。 + + Args: + gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。 + """ + + def __init__(self, gateway: Any | None = None) -> None: + self._gateway = gateway + + def _gateway_or_default(self): + if self._gateway is not None: + return self._gateway + from app.services.integration_connector.gateway import get_capability_gateway + + return get_capability_gateway() + + def query_inventory( + self, + *, + operation_id: str, + run_no: str, + attempt_no: int, + invoice_no: str, + erp_org: str, + from_warehouse: str, + to_warehouse: str, + quantity: Decimal, + ) -> InventoryQuery: + """查询外部系统库存(经连接器框架)。 + + Args/Raises: + 与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError; + 写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={}); + 来源专属绑定待 P2/P3。 + """ + result = self._gateway_or_default().call( + capability=QUERY_INVENTORY_CAPABILITY, + context={}, + params={ + "invoice_no": invoice_no, + "from_warehouse": from_warehouse, + "to_warehouse": to_warehouse, + "quantity": quantity, + }, + operation_id=operation_id, + ) + if result.status == "timeout": + raise ErpQueryTimeoutError() + if result.status != "success": + raise AppError( + code=result.error_code or "INTEGRATION.CALL_FAILED", + message=result.error_message or "query_inventory failed", + http_status=503, + retryable=False, + ) + data = result.data or {} + found = bool(data.get("found")) + qty = data.get("quantity") + return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None) diff --git a/backend/app/services/in_transit_transfer/invoice_aggregator.py b/backend/app/services/in_transit_transfer/invoice_aggregator.py new file mode 100644 index 00000000..472b9808 --- /dev/null +++ b/backend/app/services/in_transit_transfer/invoice_aggregator.py @@ -0,0 +1,91 @@ +"""在途调拨 Invoice 多行汇总与冲突阻断。 + +用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本; + 同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。 +依赖:app.core.errors.AppError、contracts.RawLineRefDTO。 +逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date +from decimal import Decimal +from typing import Iterable + +from app.core.errors import AppError +from app.services.in_transit_transfer.contracts import TRANSFER_INVOICE_CONFLICT, RawLineRefDTO +from app.services.in_transit_transfer.file_parser import ParsedReceiptRow + + +@dataclass(frozen=True) +class AggregatedInvoice: + """单 Invoice 汇总结果(含原始行追溯)。""" + + source_code: str + invoice_no: str + material_no: str + material_name: str + specification: str + receipt_date: date + receipt_quantity: Decimal + raw_lines: tuple[RawLineRefDTO, ...] + + +class InvoiceConflictError(AppError): + """同一 Invoice 出现冲突(多料号/多收料日期),整单阻断。""" + + def __init__(self, message: str = "invoice conflict", *, invoice_no: str, conflict: str): + super().__init__( + code=TRANSFER_INVOICE_CONFLICT, + message=message, + http_status=422, + details={"invoice_no": invoice_no, "conflict": conflict}, + ) + + +def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]: + """按 Invoice 汇总收料数量并保留原始行证据。 + + Args: + rows: 已校验的解析行。 + file_version: 当前文件版本(写入原始行追溯)。 + Returns: + 汇总后的 Invoice 列表(按 Invoice 排序)。 + Raises: + InvoiceConflictError: 同一 Invoice 多料号或多收料日期。 + """ + grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {} + for row in rows: + grouped.setdefault((row.source_code, row.invoice_no), []).append(row) + + invoices: list[AggregatedInvoice] = [] + for (source_code, invoice_no), group in sorted(grouped.items()): + material_nos = {row.material_no for row in group} + dates = {row.receipt_date for row in group} + if len(material_nos) > 1: + raise InvoiceConflictError( + invoice_no=invoice_no, + conflict=f"multiple_material_no: {sorted(material_nos)}", + ) + if len(dates) > 1: + raise InvoiceConflictError( + invoice_no=invoice_no, + conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}", + ) + first = group[0] + raw_lines = tuple( + RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version) + for row in group + ) + invoices.append(AggregatedInvoice( + source_code=source_code, + invoice_no=invoice_no, + material_no=first.material_no, + material_name=first.material_name, + specification=first.specification, + receipt_date=first.receipt_date, + receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")), + raw_lines=raw_lines, + )) + return invoices diff --git a/backend/app/services/in_transit_transfer/manual_close_service.py b/backend/app/services/in_transit_transfer/manual_close_service.py new file mode 100644 index 00000000..2f6e9dfb --- /dev/null +++ b/backend/app/services/in_transit_transfer/manual_close_service.py @@ -0,0 +1,66 @@ +"""在途调拨人工关闭服务。 + +用途:将异常项标记为 manually_closed(原因必填、永久排除、历史保留)。 +依赖:models、status、audit、contracts。 +逻辑:result_unknown / success / duplicate_success / manually_closed 禁止关闭。 +""" + +from __future__ import annotations + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.contracts import TRANSFER_MANUAL_CLOSE_REASON_REQUIRED + + +def manual_close_item(*, item_id: int, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict: + """人工关闭一个异常 Invoice。 + + Args: + item_id: TransferInvoiceItem.id。 + reason: 关闭原因(必填)。 + actor_id / request_id: 审计上下文。 + Returns: + {"item_id": ..., "status": "manually_closed"}。 + Raises: + ValidationError: 原因缺失或状态不可关闭。 + NotFoundError: item 不存在。 + """ + reason_value = str(reason or "").strip() + if not reason_value: + raise ValidationError("manual close reason is required", code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED) + item = db.session.get(TransferInvoiceItem, item_id) + if item is None: + raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND") + if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: + raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN") + if item.status in { + status_machine.TransferStatus.SUCCESS.value, + status_machine.TransferStatus.DUPLICATE_SUCCESS.value, + status_machine.TransferStatus.MANUALLY_CLOSED.value, + }: + raise ValidationError(f"item status {item.status} is not closeable", code="TRANSFER.MANUAL_CLOSE_NOT_ALLOWED") + + before_status = item.status + item.status = status_machine.TransferStatus.MANUALLY_CLOSED.value + item.result_code = "manually_closed" + item.result_message = reason_value + item.manually_closed_reason = reason_value + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_ITEM_MANUALLY_CLOSED", + aggregate_type="transfer_item", + aggregate_id=str(item.id), + run_no=item.run.run_no if item.run else None, + invoice_no=item.invoice_no, + item_id=str(item.id), + actor_type="user", + actor_id=str(actor_id) if actor_id is not None else None, + request_id=request_id, + result="success", + before={"status": before_status}, + after={"status": item.status, "reason": reason_value}, + )) + db.session.commit() + return {"item_id": item.id, "status": item.status} diff --git a/backend/app/services/in_transit_transfer/metrics.py b/backend/app/services/in_transit_transfer/metrics.py new file mode 100644 index 00000000..453a63c1 --- /dev/null +++ b/backend/app/services/in_transit_transfer/metrics.py @@ -0,0 +1,56 @@ +"""在途调拨运营指标。 + +用途:从数据库现状投影成功率、失败类型、待处理老化与通知失败等指标, + 供运营看板与告警使用。 +依赖:models、backlog_service。 +逻辑:指标只读,不触发任何外部调用。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.backlog_service import backlog_summary +from app.services.in_transit_transfer.status import TransferNotificationStatus + + +def collect_metrics(*, now: datetime | None = None) -> dict[str, Any]: + """采集调拨域指标。 + + Args: + now: 判定时刻(老化计算用)。 + Returns: + {"runs": {...}, "items": {...}, "backlog": {...}}。 + """ + runs_by_status: dict[str, int] = {} + for (status,) in db.session.query(TransferRun.status).all(): + runs_by_status[str(status)] = runs_by_status.get(str(status), 0) + 1 + notification_failed_runs = TransferRun.query.filter_by( + notification_status=TransferNotificationStatus.FAILED.value, + ).count() + + items_by_status: dict[str, int] = {} + for (status,) in db.session.query(TransferInvoiceItem.status).all(): + items_by_status[str(status)] = items_by_status.get(str(status), 0) + 1 + + backlog = backlog_summary(now=now) + return { + "runs": { + **runs_by_status, + "notification_failed_runs": notification_failed_runs, + }, + "items": items_by_status, + "backlog": { + "recoverable": backlog.recoverable_count, + "closed": backlog.closed_count, + "unknown": backlog.unknown_count, + "aging": { + "warn_3d": backlog.warn_3d, + "escalate_5d": backlog.escalate_5d, + "critical_7d": backlog.critical_7d, + }, + }, + } diff --git a/backend/app/services/in_transit_transfer/movement_contract.py b/backend/app/services/in_transit_transfer/movement_contract.py new file mode 100644 index 00000000..d4328a3b --- /dev/null +++ b/backend/app/services/in_transit_transfer/movement_contract.py @@ -0,0 +1,75 @@ +"""在途调拨通用异动/移动表领域字段契约。 + +用途:定义调拨消费的异动(入库/出库/收料/出货)文件领域字段——业务定死、不配置化。 + 未来出货/入库 Excel 复用同一套字段,靠 in_out_flag 区分方向。 +依赖:标准库 dataclasses / enum。 +逻辑:字段清单是 immutable 常量;幂等键为 doc_no,严格数量字段为 quantity, + 成熟过滤字段为 movement_date;字段映射由 movement_parser 完成。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import StrEnum + + +class MovementFieldValueType(StrEnum): + """领域字段值类型(校验与展示共用)。""" + + TEXT = "text" + DECIMAL = "decimal" + DATE = "date" + + +@dataclass(frozen=True) +class MovementField: + """单个定死异动字段契约。 + + Args: + code: 稳定字段名(运行时契约)。 + label: 业务中文名。 + value_type: 值类型(text / decimal / date)。 + is_identity: 是否参与幂等/匹配键。 + required: 是否必填(缺省阻断)。 + """ + + code: str + label: str + value_type: MovementFieldValueType + is_identity: bool = False + required: bool = False + + +# 定死的 10 个通用异动字段(领域契约,不配置化)。 +MOVEMENT_FIELDS: tuple[MovementField, ...] = ( + MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True), + MovementField("line_no", "项次", MovementFieldValueType.TEXT), + MovementField("in_out_flag", "进出库别", MovementFieldValueType.TEXT), + MovementField("material_code", "料号", MovementFieldValueType.TEXT, is_identity=True, required=True), + MovementField("material_name", "品名", MovementFieldValueType.TEXT), + MovementField("warehouse_code", "仓库", MovementFieldValueType.TEXT), + MovementField("storage_code", "储位", MovementFieldValueType.TEXT), + MovementField("lot_no", "批号", MovementFieldValueType.TEXT), + MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True), + MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True), +) + + +def movement_match_key() -> str: + """调拨幂等/汇总键:单号 doc_no。""" + return "doc_no" + + +def movement_quantity_field() -> str: + """严格数量匹配字段:数量 quantity。""" + return "quantity" + + +def movement_identity_fields() -> set[str]: + """参与幂等/匹配判定的字段集(doc_no / material_code / movement_date)。""" + return {field.code for field in MOVEMENT_FIELDS if field.is_identity} + + +def movement_field_codes() -> set[str]: + """全部定死字段名集合。""" + return {field.code for field in MOVEMENT_FIELDS} diff --git a/backend/app/services/in_transit_transfer/movement_file_repository.py b/backend/app/services/in_transit_transfer/movement_file_repository.py new file mode 100644 index 00000000..da2f36ed --- /dev/null +++ b/backend/app/services/in_transit_transfer/movement_file_repository.py @@ -0,0 +1,125 @@ +"""在途调拨真实异动(收料/出货)文件仓库。 + +用途:读取货代收料链路已落库的 ShippingReceiptReportFile(对象存储原始 xlsx), + 用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死 + 领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。 +依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、 + movement_contract、openpyxl。 +逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时 + 返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。 +""" + +from __future__ import annotations + +from io import BytesIO +from typing import Any, Mapping + +from app.services.file_assets.storage import file_asset_storage +from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile + + +class ShippingReceiptFileRepository: + """真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。""" + + def __init__(self) -> None: + self._storage = file_asset_storage + + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + """返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。 + + Args: + source_code: 来源实例编码。 + business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。 + Returns: + ReadyReceiptFile(rows 为领域字段名 dict)或 None。 + """ + from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile + + source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + return None + config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first() + if config is None or config.parsing_profile_id is None: + return None + profile = config.parsing_profile + if profile is None or profile.status != 'published' or profile.purpose != 'movement': + return None + + report = ( + ShippingReceiptReportFile.query + .join(ShippingReceiptReportFile.unit_run) + .filter( + ShippingReceiptReportFile.unit_run.has(source_code=source_code), + ShippingReceiptReportFile.archive_deleted_at.is_(None), + ) + .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) + .first() + ) + if report is None: + return None + + data = self._storage.get_bytes(report.storage_key) + rows = _extract_movement_rows( + data, + field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}), + sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None, + header_row_index=(profile.definition_json or {}).get('header_row_index'), + ) + return ReadyReceiptFile( + source_code=source_code, + business_date=business_date, + file_no=report.original_filename or str(report.id), + file_version=f"sha256:{report.sha256}"[:64], + checksum=report.sha256, + rows=tuple(rows), + ) + + +def _extract_movement_rows( + data: bytes, + *, + field_mapping: Mapping[str, str], + sheet_name: str | None = None, + header_row_index: int | None = None, +) -> list[dict[str, Any]]: + """从 xlsx 字节按 movement field_mapping 提取领域行 dict。 + + field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。 + 输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。 + """ + from openpyxl import load_workbook + from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index + + wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True) + try: + if sheet_name and sheet_name in wb.sheetnames: + ws = wb[sheet_name] + else: + ws = wb.active + raw_rows: list[list[Any]] = [list(row) for row in ws.iter_rows(values_only=True)] + finally: + wb.close() + if not raw_rows: + return [] + header_idx: int | None = None + if header_row_index is not None: + idx = int(header_row_index) - 1 + if 0 <= idx < len(raw_rows): + header_idx = idx + if header_idx is None: + header_idx = find_inventory_header_row_index(raw_rows) + headers = [str(c or '').strip() for c in raw_rows[header_idx]] + data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r] + + header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()} + return [_map_header_row(headers, row, header_to_code) for row in data_rows] + + +def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]: + """把一行原始单元格按表头别名映射为定死领域字段 dict。""" + output: dict[str, Any] = {} + for index, header in enumerate(headers): + code = header_to_code.get(header) + if code and index < len(row): + output[code] = row[index] + return output diff --git a/backend/app/services/in_transit_transfer/notification.py b/backend/app/services/in_transit_transfer/notification.py new file mode 100644 index 00000000..411d879c --- /dev/null +++ b/backend/app/services/in_transit_transfer/notification.py @@ -0,0 +1,84 @@ +"""在途调拨企业微信汇总通知。 + +用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录 + notification_failed 且不改变 ERP 业务结果(run.status 保持)。 +依赖:models、audit、typing.Protocol。 +逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。 +""" + +from __future__ import annotations + +from typing import Any, Protocol + +from app import db +from app.core.errors import NotFoundError +from app.models import TransferRun +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.status import TransferNotificationStatus + + +class WeComSender(Protocol): + """企业微信汇总通知协议(测试注入 FakeWeCom)。""" + + def send_summary(self, *, run_no: str, summary: dict[str, Any], + recipients: list[str], excel_path: str | None = None) -> dict[str, Any]: + """发送一次汇总通知。""" + + +def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str] | None = None, + excel_path: str | None = None) -> dict[str, Any]: + """为 Run 发送一条汇总通知(幂等)。 + + Args: + run_no: Run 编号。 + sender: 企微发送器。 + recipients: 接收人列表(缺省空)。 + excel_path: 异常 Excel 附件路径(可空)。 + Returns: + {"run_no", "notification_status", "delivered"};空数据返回 skipped。 + Raises: + NotFoundError: Run 不存在。 + """ + run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() + if run is None: + raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") + if not run.items: + # 空数据 Run:不通知(产品决策 C5:仅非空 Run 通知)。 + return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False, "skipped": "no_data"} + if run.notification_status == TransferNotificationStatus.SUCCESS.value: + # 已成功投递:幂等跳过,保证每个 Run 恰好一条。 + return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False} + + summary = { + "run_no": run.run_no, + "status": run.status, + "business_date": run.business_date, + "counts": dict(run.counts_json or {}), + "result_summary": dict(run.result_summary_json or {}), + } + outcome = sender.send_summary( + run_no=run.run_no, summary=summary, recipients=list(recipients or []), excel_path=excel_path, + ) + outcome = outcome if isinstance(outcome, dict) else {} + failed = str(outcome.get("status") or "success") != "success" + run.notification_status = TransferNotificationStatus.FAILED.value if failed else TransferNotificationStatus.SUCCESS.value + if failed: + run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED") + run.notification_error_message = str(outcome.get("error_message") or "") + # 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。 + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_NOTIFICATION", + aggregate_type="transfer_run", + aggregate_id=run.run_no, + run_no=run.run_no, + actor_type="worker", + result="failure" if failed else "success", + before={"status": run.status, "notification_status": "pending"}, + after={"status": run.status, "notification_status": run.notification_status}, + )) + db.session.commit() + return { + "run_no": run.run_no, + "notification_status": run.notification_status, + "delivered": True, + } diff --git a/backend/app/services/in_transit_transfer/orchestrator.py b/backend/app/services/in_transit_transfer/orchestrator.py new file mode 100644 index 00000000..ba3918c4 --- /dev/null +++ b/backend/app/services/in_transit_transfer/orchestrator.py @@ -0,0 +1,83 @@ +"""在途调拨执行编排(Run 生命周期辅助)。 + +用途:创建执行 Run(关联预检与可执行明细、置 executing、记录确认)、 + 按明细终态收尾 Run(success / partial_failed)。 +依赖:models、status、precheck_service.TransferDeps。 +逻辑:同一预检只允许创建一个执行 Run(confirmed_at 防重复);重复创建 409。 +""" + +from __future__ import annotations + +import uuid +from datetime import datetime + +from app import db +from app.core.errors import ConflictError +from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.precheck_service import TransferDeps + +EXECUTION_CONFLICT_CODE = "TRANSFER.PRECHECK_ALREADY_EXECUTED" + + +def create_execution_run( + precheck: TransferPrecheck, + *, + deps: TransferDeps, # noqa: ARG001 —— 预留并发/锁参数扩展 + actor_id: int | None = None, + selected_invoice_nos: set[str] | None = None, +) -> TransferRun: + """为已就绪预检创建执行 Run 并关联选中的可执行明细。 + + Args: + precheck: 已预检(ready_to_execute)对象。 + deps: 依赖集合(预留)。 + actor_id: 确认操作者。 + selected_invoice_nos: 选择范围(缺省关联全部可执行项)。 + Returns: + 状态为 executing 的 TransferRun。 + Raises: + ConflictError: 预检已确认(重复执行)。 + """ + if precheck.confirmed_at is not None: + raise ConflictError( + "precheck already executed", code=EXECUTION_CONFLICT_CODE, + ) + run_no = f"RUN-{str(precheck.business_date).replace('-', '')}-{uuid.uuid4().hex[:6].upper()}" + run = TransferRun( + run_no=run_no, + trigger_type="manual", + business_date=precheck.business_date, + status=status_machine.TransferRunStatus.EXECUTING.value, + source_codes_json=list(precheck.scope_json.get("source_codes") or []), + counts_json=dict(precheck.counts_json or {}), + ) + db.session.add(run) + db.session.flush() + + precheck.run_id = run.id + precheck.status = status_machine.TransferRunStatus.EXECUTING.value + precheck.confirmed_at = datetime.utcnow() + precheck.confirmed_by = actor_id + + for item in precheck.items: + if item.status != status_machine.TransferStatus.READY_TO_EXECUTE.value or item.run_id is not None: + continue + if selected_invoice_nos is not None and item.invoice_no not in selected_invoice_nos: + continue + item.run_id = run.id + item.status = status_machine.TransferStatus.EXECUTING.value + item.attempt_no += 1 + db.session.flush() + return run + + +def finalize_run(run: TransferRun, items: list[TransferInvoiceItem]) -> None: + """按明细终态汇总 Run 状态(全部 success/duplicate_success → success,否则 partial_failed)。""" + statuses = {str(item.status) for item in items} + terminal_ok = {status_machine.TransferStatus.SUCCESS.value, status_machine.TransferStatus.DUPLICATE_SUCCESS.value} + if statuses and statuses <= terminal_ok: + run.status = status_machine.TransferRunStatus.SUCCESS.value + else: + run.status = status_machine.TransferRunStatus.PARTIAL_FAILED.value + run.completed_at = datetime.utcnow() diff --git a/backend/app/services/in_transit_transfer/precheck_service.py b/backend/app/services/in_transit_transfer/precheck_service.py new file mode 100644 index 00000000..b336c028 --- /dev/null +++ b/backend/app/services/in_transit_transfer/precheck_service.py @@ -0,0 +1,578 @@ +"""在途调拨预检服务。 + +用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 → + 严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。 +依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter / + date_policy / quantity / contracts / audit / models。 +逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP; + 预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。 +""" + +from __future__ import annotations + +import uuid +from dataclasses import asdict, dataclass, field +from datetime import date, datetime, timedelta +from decimal import Decimal +from typing import Any, Protocol + +from app import db +from app.core.errors import AppError, NotFoundError, ValidationError +from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.audit import canonical_hash +from app.services.in_transit_transfer.contracts import ( + PrecheckCountsDTO, + PrecheckInvoiceItemDTO, + PrecheckSummaryDTO, + RawLineRefDTO, +) +from app.services.in_transit_transfer.date_policy import ( + MATURITY_ELIGIBLE, + MATURITY_FUTURE, + MATURITY_NOT_MATURED, + maturity_status, +) +from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError +from app.services.in_transit_transfer.file_parser import ( + ParsedReceiptRow, + ReceiptFileSchemaError, + parse_receipt_rows, +) +from app.services.in_transit_transfer.file_preparation import ( + ReadyReceiptFile, + ReceiptFileRepository, + RpaTrigger, + ensure_receipt_file_ready, +) +from app.services.in_transit_transfer.invoice_aggregator import ( + InvoiceConflictError, + aggregate_invoices, +) +from app.services.in_transit_transfer.quantity import classify_quantity_match +from app.services.in_transit_transfer.strategy import ( + TransferStrategyPolicy, + default_strategy, +) + +ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED" + +# 明细结果值(对应 Invoice 项状态) +RESULT_EXECUTABLE = "executable" +RESULT_NOT_MATURED = "not_matured" +RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch" +RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found" +RESULT_FUTURE_DATE = "blocked_future_date" +RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout" + + +@dataclass(frozen=True) +class RouteMapping: + """来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。""" + + erp_org: str + from_warehouse: str + to_warehouse: str + + +class RouteNotResolvedError(AppError): + """来源实例缺少路由归属映射(fail-closed)。""" + + def __init__(self, *, source_code: str): + super().__init__( + code=ROUTE_NOT_RESOLVED_CODE, + message=f"route not resolved for source {source_code}", + http_status=422, + details={"source_code": source_code}, + ) + + +class RouteResolver(Protocol): + """来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。""" + + def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping: + """返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。""" + + +@dataclass(frozen=True) +class SourceProgressDTO: + """来源实例级进度(决策 18:来源隔离展示)。""" + + source_code: str + stage: str + file_no: str | None = None + file_version: str | None = None + checksum: str | None = None + error_code: str | None = None + error_message: str | None = None + + +@dataclass(frozen=True) +class PrecheckRunResult: + """一次预检运行的完整结果。""" + + summary: PrecheckSummaryDTO + items: tuple[PrecheckInvoiceItemDTO, ...] + sources: tuple[SourceProgressDTO, ...] + + +@dataclass(frozen=True) +class TransferDeps: + """预检/执行依赖集合(测试注入 Fake 替身)。""" + + file_repository: ReceiptFileRepository + rpa_trigger: RpaTrigger + route_resolver: RouteResolver + erp: Any + strategy: TransferStrategyPolicy = field(default_factory=default_strategy) + + +def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCountsDTO) -> str: + """预检状态:存在未完成来源 → file_pending;否则按可执行数定。""" + if any(source.stage not in {"file_ready"} for source in sources): + return "file_pending" + if counts.executable_count > 0: + return "ready_to_execute" + return "success" + + +def run_precheck( + *, + source_codes: list[str], + business_date: str, + deps: TransferDeps, + active_source_job_key: str | None = None, + run_no: str = "RUN-PENDING", +) -> PrecheckRunResult: + """执行一次只读预检(不写 ERP)。 + + Args: + source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。 + business_date: 业务日期 T(YYYY-MM-DD)。 + deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。 + active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。 + run_no: Run 编号(创建 Run 前可为占位)。 + Returns: + PrecheckRunResult(摘要 + 明细 + 来源进度)。 + Raises: + ValidationError: source_codes 为空。 + """ + if not source_codes: + raise ValidationError("source_codes is required") + validate_strategy = deps.strategy + + sources: list[SourceProgressDTO] = [] + items: list[PrecheckInvoiceItemDTO] = [] + file_snapshot: dict[str, Any] = {} + for source_code in source_codes: + source_stage: SourceProgressDTO + try: + prepared = ensure_receipt_file_ready( + source_code=source_code, + business_date=business_date, + repository=deps.file_repository, + rpa_trigger=deps.rpa_trigger, + active_source_job_key=active_source_job_key, + ) + if prepared.stage != "file_ready" or prepared.file is None: + sources.append(SourceProgressDTO( + source_code=source_code, + stage=prepared.stage, + error_code=prepared.error_code, + error_message=prepared.error_message, + )) + continue + ready_file = prepared.file + file_snapshot[source_code] = { + "file_no": ready_file.file_no, + "file_version": ready_file.file_version, + "checksum": ready_file.checksum, + } + parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows) + invoices = aggregate_invoices(parsed, file_version=ready_file.file_version) + source_items = _precheck_invoices( + invoices=invoices, + source_code=source_code, + business_date=business_date, + ready_file=ready_file, + deps=deps, + run_no=run_no, + ) + items.extend(source_items) + sources.append(SourceProgressDTO( + source_code=source_code, + stage="file_ready", + file_no=ready_file.file_no, + file_version=ready_file.file_version, + checksum=ready_file.checksum, + )) + except (ReceiptFileSchemaError, InvoiceConflictError) as exc: + sources.append(SourceProgressDTO( + source_code=source_code, stage="failed", + error_code=exc.code, error_message=exc.message, + )) + except RouteNotResolvedError as exc: + sources.append(SourceProgressDTO( + source_code=source_code, stage="failed", + error_code=exc.code, error_message=exc.message, + )) + except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源 + sources.append(SourceProgressDTO( + source_code=source_code, stage="failed", + error_code="TRANSFER.SOURCE_PRECheck_ERROR", + error_message=str(exc), + )) + + counts = PrecheckCountsDTO( + file_invoice_count=sum( + 1 for item in items + ), + not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED), + prechecked_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED), + executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE), + blocked_count=sum(1 for item in items if item.result.startswith("blocked_")), + ) + estimated_quantity = sum( + (item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0") + ) + snapshot = { + "scope": sorted(set(source_codes)), + "business_date": business_date, + "file_snapshot": file_snapshot, + "counts": { + "file_invoice_count": counts.file_invoice_count, + "not_matured_count": counts.not_matured_count, + "prechecked_count": counts.prechecked_count, + "executable_count": counts.executable_count, + "blocked_count": counts.blocked_count, + }, + "items": [ + { + "source_code": item.source_code, + "invoice_no": item.invoice_no, + "from_warehouse": item.from_warehouse, + "to_warehouse": item.to_warehouse, + "receipt_quantity": str(item.to_quantity), + "erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None, + "result": item.result, + } + for item in items + ], + } + precheck_hash = f"sha256:{canonical_hash(snapshot)}" + sources_tuple = tuple(sources) + summary = PrecheckSummaryDTO( + precheck_id="", # 落库时回填 + status=_summary_status(sources_tuple, counts), + business_date=business_date, + eligible_receipt_date_to=str( + (date.fromisoformat(business_date) - timedelta(days=1)) + ), + expires_at="", + counts=counts, + estimated_transfer_quantity=str(estimated_quantity), + estimated_erp_write_count=counts.executable_count, + precheck_hash=precheck_hash, + ) + return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple) + + +def _precheck_invoices( + *, + invoices: list, + source_code: str, + business_date: str, + ready_file: ReadyReceiptFile, + deps: TransferDeps, + run_no: str, +) -> list[PrecheckInvoiceItemDTO]: + """对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。""" + output: list[PrecheckInvoiceItemDTO] = [] + for invoice in invoices: + maturity = maturity_status(invoice.receipt_date, business_date) + raw = tuple( + RawLineRefDTO(sheet=line.sheet, row_no=line.row_no, file_version=line.file_version) + for line in invoice.raw_lines + ) + receipt_date_iso = invoice.receipt_date.isoformat() + if maturity == MATURITY_NOT_MATURED: + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse="", from_quantity=None, + to_warehouse="", to_quantity=invoice.receipt_quantity, + result=RESULT_NOT_MATURED, reason="receipt not matured until next business day", + raw_lines=raw, + )) + continue + if maturity == MATURITY_FUTURE: + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse="", from_quantity=None, + to_warehouse="", to_quantity=invoice.receipt_quantity, + result=RESULT_FUTURE_DATE, reason="future receipt date", + raw_lines=raw, + )) + continue + route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no) + operation_id = f"op-{uuid.uuid4().hex[:12]}" + try: + query = deps.erp.query_inventory( + operation_id=operation_id, + run_no=run_no, + attempt_no=1, + invoice_no=invoice.invoice_no, + erp_org=route.erp_org, + from_warehouse=route.from_warehouse, + to_warehouse=route.to_warehouse, + quantity=invoice.receipt_quantity, + ) + except ErpQueryTimeoutError: + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse=route.from_warehouse, + from_quantity=None, to_warehouse=route.to_warehouse, + to_quantity=invoice.receipt_quantity, + result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout", + raw_lines=raw, + )) + continue + if not query.found: + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse=route.from_warehouse, + from_quantity=None, to_warehouse=route.to_warehouse, + to_quantity=invoice.receipt_quantity, + result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found", + raw_lines=raw, + )) + continue + match = classify_quantity_match(invoice.receipt_quantity, query.quantity) + output.append(PrecheckInvoiceItemDTO( + source_code=source_code, material_no=invoice.material_no, + material_name=invoice.material_name, specification=invoice.specification, + invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso, + from_warehouse=route.from_warehouse, + from_quantity=query.quantity, to_warehouse=route.to_warehouse, + to_quantity=invoice.receipt_quantity, + result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch", + raw_lines=raw, + )) + return output + + +def _item_status(result: str) -> str: + """明细结果 → Invoice 项状态。""" + mapping = { + RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value, + RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value, + RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + } + return mapping.get(result, status_machine.TransferStatus.BLOCKED_RECOVERABLE.value) + + +def _generate_no(prefix: str, business_date: str) -> str: + """生成稳定业务编号(TPC-YYYYMMDD-XXXX / RUN-...)。""" + compact = str(business_date).replace("-", "") + return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}" + + +def create_precheck( + *, + source_codes: list[str], + business_date: str, + deps: TransferDeps, + active_source_job_key: str | None = None, +) -> PrecheckSummaryDTO: + """运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。 + + Args: + source_codes / business_date / deps: 同 run_precheck。 + Returns: + 预检摘要(precheck_id 已回填)。 + """ + run_no = _generate_no("RUN", business_date) + result = run_precheck( + source_codes=source_codes, + business_date=business_date, + deps=deps, + active_source_job_key=active_source_job_key, + run_no=run_no, + ) + now = datetime.utcnow() + run = TransferRun( + run_no=run_no, + trigger_type="manual", + business_date=business_date, + status="prechecking", + source_codes_json=list(source_codes), + counts_json=asdict(result.summary.counts), + ) + db.session.add(run) + db.session.flush() + + # 来源级状态真相源:按 run 内每来源建一条 job((run_id, source_code) 唯一)。 + # 来源准备流程阶段(file_ready/waiting_rpa_callback/failed 等)与 job 状态集已对齐。 + from app.services.in_transit_transfer.source_job_service import create_source_job + + _valid_job_statuses = { + 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', + 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', + } + for job_source in result.sources: + create_source_job( + run_id=run.id, + source_code=job_source.source_code, + status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending', + ) + + precheck_no = _generate_no("TPC", business_date) + precheck = TransferPrecheck( + precheck_no=precheck_no, + run_id=run.id, + business_date=business_date, + status=result.summary.status, + scope_json={"source_codes": list(source_codes)}, + file_snapshot_json={ + stage.source_code: { + "file_no": stage.file_no, + "file_version": stage.file_version, + "checksum": stage.checksum, + } + for stage in result.sources + if stage.file_no + }, + mapping_version="v0", + strategy_version="v0", + counts_json=asdict(result.summary.counts), + estimated_transfer_quantity=result.summary.estimated_transfer_quantity, + estimated_erp_write_count=result.summary.estimated_erp_write_count, + precheck_hash=result.summary.precheck_hash, + expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds), + ) + db.session.add(precheck) + db.session.flush() + + for item in result.items: + db.session.add(TransferInvoiceItem( + precheck_id=precheck.id, + # 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。 + source_code=item.source_code, + invoice_no=item.invoice_no, + material_no=item.material_no, + material_name=item.material_name, + specification=item.specification, + receipt_date=item.receipt_date, + from_warehouse=item.from_warehouse or "", + to_warehouse=item.to_warehouse or "", + receipt_quantity=str(item.to_quantity), + erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None, + status=_item_status(item.result), + result_code=item.result if item.result != RESULT_EXECUTABLE else None, + result_message=item.reason or None, + raw_lines_json=[ + {"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version} + for line in item.raw_lines + ], + )) + db.session.commit() + + summary = PrecheckSummaryDTO( + precheck_id=precheck_no, + status=precheck.status, + business_date=precheck.business_date, + eligible_receipt_date_to=result.summary.eligible_receipt_date_to, + expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "", + counts=result.summary.counts, + estimated_transfer_quantity=result.summary.estimated_transfer_quantity, + estimated_erp_write_count=result.summary.estimated_erp_write_count, + precheck_hash=result.summary.precheck_hash, + ) + return summary + + +def restore_precheck(precheck_id: str) -> dict[str, Any]: + """按 precheck_no 恢复预检进度与明细(页面刷新/会话恢复)。 + + Args: + precheck_id: 预检编号(TPC-...)。 + Returns: + {"summary": {...}, "items": [...], "sources": [...]}。 + Raises: + NotFoundError: 预检不存在。 + """ + precheck = db.session.query(TransferPrecheck).filter_by( + precheck_no=str(precheck_id).strip() + ).first() + if precheck is None: + raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND") + counts = PrecheckCountsDTO(**{ + key: int(precheck.counts_json.get(key, 0)) + for key in ("file_invoice_count", "not_matured_count", "prechecked_count", + "executable_count", "blocked_count") + }) + summary = PrecheckSummaryDTO( + precheck_id=precheck.precheck_no, + status=precheck.status, + business_date=precheck.business_date, + eligible_receipt_date_to=str( + date.fromisoformat(precheck.business_date) - timedelta(days=1) + ), + expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "", + counts=counts, + estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0", + estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0), + precheck_hash=precheck.precheck_hash, + ) + items = [] + for item in sorted(precheck.items, key=lambda row: row.invoice_no): + items.append(PrecheckInvoiceItemDTO( + source_code=item.source_code, + material_no=item.material_no, + material_name=item.material_name, + specification=item.specification, + invoice_no=item.invoice_no, + from_warehouse=item.from_warehouse, + from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None, + to_warehouse=item.to_warehouse, + to_quantity=Decimal(item.receipt_quantity), + result=item.result_code or ( + RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status + ), + raw_lines=tuple( + RawLineRefDTO( + sheet=line.get("sheet", ""), + row_no=int(line.get("row_no", 0)), + file_version=line.get("file_version", ""), + ) + for line in (item.raw_lines_json or []) + ), + )) + sources = [ + SourceProgressDTO( + source_code=job.source_code, + stage=job.status, + file_no=job.file_no, + file_version=None, + checksum=job.file_sha256, + ) + for job in (precheck.run.source_jobs if precheck.run else []) + ] or [ + SourceProgressDTO(source_code=code, stage="file_ready") + for code in (precheck.scope_json.get("source_codes") or []) + ] + return { + "summary": summary, + "items": items, + "sources": sources, + } diff --git a/backend/app/services/in_transit_transfer/quantity.py b/backend/app/services/in_transit_transfer/quantity.py new file mode 100644 index 00000000..4abbe52b --- /dev/null +++ b/backend/app/services/in_transit_transfer/quantity.py @@ -0,0 +1,61 @@ +"""在途调拨严格数量门禁。 + +用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则, + 禁止部分调拨、数量容差与隐式截断。 +依赖:标准库 decimal。 +逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。 +""" + +from __future__ import annotations + +from decimal import Decimal, InvalidOperation +from typing import Any + +# 匹配结果 +MATCH_EXECUTABLE = "executable" +MATCH_QUANTITY_MISMATCH = "blocked_quantity_mismatch" +MATCH_INVENTORY_NOT_FOUND = "blocked_inventory_not_found" + + +class QuantityValidationError(ValueError): + """收料数量非法(0、负数、非数字)。""" + + +def validate_receipt_quantity(value: Any) -> Decimal: + """校验并归一化收料数量。 + + Args: + value: 数字或数字字符串。 + Returns: + 归一化后的 Decimal。 + Raises: + QuantityValidationError: 非数字、0 或负数。 + """ + try: + quantity = Decimal(str(value)) + except (InvalidOperation, ValueError) as exc: + raise QuantityValidationError(f"invalid receipt quantity: {value!r}") from exc + if quantity <= 0: + raise QuantityValidationError(f"receipt quantity must be positive: {value!r}") + return quantity + + +def strict_quantities_equal(left: Any, right: Any) -> bool: + """Decimal 精确相等比较(1.0 == 1.00)。""" + return Decimal(str(left)) == Decimal(str(right)) + + +def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str: + """按严格相等规则分类数量匹配结果。 + + Args: + receipt_quantity: 收料数量。 + erp_quantity: ERP 账面库存;None 表示无库存。 + Returns: + 'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。 + """ + if erp_quantity is None: + return MATCH_INVENTORY_NOT_FOUND + if strict_quantities_equal(receipt_quantity, erp_quantity): + return MATCH_EXECUTABLE + return MATCH_QUANTITY_MISMATCH diff --git a/backend/app/services/in_transit_transfer/receipt_callback_bridge.py b/backend/app/services/in_transit_transfer/receipt_callback_bridge.py new file mode 100644 index 00000000..4b3e0554 --- /dev/null +++ b/backend/app/services/in_transit_transfer/receipt_callback_bridge.py @@ -0,0 +1,57 @@ +"""在途调拨收料回调桥。 + +用途:货代收料 RPA 回调落文件后,按来源推进调拨等待中的 TransferSourceJob: + success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。 +依赖:models(TransferSourceJob)、datetime。 +逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作, + 避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.models import TransferSourceJob + +_FILE_READY = 'file_ready' +_WAITING_RPA_CALLBACK = 'waiting_rpa_callback' +_FAILED = 'failed' + + +def advance_source_job_from_receipt_callback( + *, source_code: str, file_no: str | None = None, file_sha256: str | None = None, + callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None, +) -> TransferSourceJob | None: + """按来源推进最新等待回调的调拨来源任务。 + + Args: + source_code: 回调所属来源实例。 + file_no: 收料文件号(success 时)。 + file_sha256: 收料文件 sha256(success 时)。 + callback_ok / error_code / error_message: 回调终态。 + Returns: + 被推进的任务;无等待任务或已终态时返回 None。 + """ + job = ( + TransferSourceJob.query + .filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK) + .order_by(TransferSourceJob.id.desc()) + .first() + ) + if job is None: + return None + if callback_ok and file_no: + job.status = _FILE_READY + job.file_no = file_no + job.file_sha256 = file_sha256 + job.error_code = None + job.error_message = None + job.finished_at = datetime.utcnow() + else: + job.status = _FAILED + job.error_code = error_code or 'RPA_RECEIPT_CALLBACK_FAILED' + job.error_message = error_message or 'receipt rpa callback failed' + job.finished_at = datetime.utcnow() + db.session.flush() + return job diff --git a/backend/app/services/in_transit_transfer/receipt_trigger_service.py b/backend/app/services/in_transit_transfer/receipt_trigger_service.py new file mode 100644 index 00000000..2440487a --- /dev/null +++ b/backend/app/services/in_transit_transfer/receipt_trigger_service.py @@ -0,0 +1,101 @@ +"""在途调拨真实收料 RPA 触发服务。 + +用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。 + 按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile, + 装配收料 trigger unit,调用 write_receipt_export_batch_trigger 原子写 trigger。 +依赖:write_receipt_export_batch_trigger(默认 writer)、models。 +逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待; + 写 trigger writer 可注入替身(测试)。 +""" + +from __future__ import annotations + +import uuid +from typing import Any, Callable + +from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger + +RouteTriggerWriter = Callable[..., str | None] + + +def _build_trigger_unit( + *, source_code: str, business_date: str, reason: str, +) -> dict[str, Any]: + """装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。""" + from app.models import ShippingInventorySource, ShippingReceiptReportConfig + + source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + raise RuntimeError(f'source not enabled: {source_code}') + config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first() + if config is None: + raise RuntimeError(f'receipt config missing: {source_code}') + profile = source.rpa_profile + if profile is None or not profile.enabled: + raise RuntimeError(f'receipt source profile unavailable: {source_code}') + warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None] + warehouse_id = str(warehouses[0]) if warehouses else None + snapshot = { + 'config_id': config.id, 'config_version': config.config_version, + 'connector_type': source.connector_type, + 'report_path_json': config.report_path_json or {}, + 'query_parameters_json': config.query_parameters_json or [], + 'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id, + } + return { + 'unit_run_id': 0, + 'callback_id': f'receipt:{uuid.uuid4().hex}', + 'source_code': source.source_code, + 'connector_type': source.connector_type, + 'warehouse_id': warehouse_id, + 'rpa_profile_id': profile.id, + 'rpa_profile_code': profile.profile_code, + 'login_url': profile.login_url, + 'login_config': dict(profile.login_config_json or {}), + 'credential_envelope': { + 'username_ciphertext': profile.username_ciphertext, + 'password_ciphertext': profile.password_ciphertext, + }, + 'report_path_json': dict(snapshot.get('report_path_json') or {}), + 'query_parameters_json': list(snapshot.get('query_parameters_json') or []), + 'config_snapshot': snapshot, + 'business_date': business_date, + 'reason': reason, + } + + +def trigger_receipt_rpa( + *, + source_code: str, + business_date: str, + reason: str = 'transfer_retry_receipt', + writer: RouteTriggerWriter | None = None, +) -> dict[str, Any]: + """触发一次来源收料 RPA 抓取。 + + Args: + source_code: 来源实例编码。 + business_date: 业务日期。 + reason: 触发原因(写入 trigger)。 + writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。 + Returns: + {"ok": True, "callback_id": ..., "trigger_path": ...} 或 + {"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。 + """ + try: + unit = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason) + except RuntimeError as exc: + return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)} + + run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}" + writer_fn = writer or write_receipt_export_batch_trigger + path = writer_fn(run_no, [unit], payload={ + 'schema_version': 'shipping_receipt_rpa.v1', + 'action': 'receipt_export_batch', + 'source_code': source_code, + 'business_date': business_date, + 'reason': reason, + }) + if not path: + return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"} + return {"ok": True, "callback_id": unit['callback_id'], "trigger_path": path} diff --git a/backend/app/services/in_transit_transfer/recovery.py b/backend/app/services/in_transit_transfer/recovery.py new file mode 100644 index 00000000..2eafd737 --- /dev/null +++ b/backend/app/services/in_transit_transfer/recovery.py @@ -0,0 +1,87 @@ +"""在途调拨 Worker 崩溃/陈旧执行恢复(区别于 recovery_service 的每日历史复核)。 + +用途:回收租约过期的 executing 项(重新写前复查 + 幂等写入,不重复建单), + 并将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。 +依赖:execution_service._write_item、orchestrator.finalize_run、status。 +逻辑:恢复依赖 Invoice 幂等(重复返回原单号 duplicate_success); + result_unknown 绝不自动重试。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.execution_service import _write_item +from app.services.in_transit_transfer.orchestrator import finalize_run +from app.services.in_transit_transfer.precheck_service import TransferDeps + +STALE_EXECUTION_THRESHOLD_SECONDS = 3600 + +_TERMINAL_ITEM_STATUSES = { + status_machine.TransferStatus.SUCCESS.value, + status_machine.TransferStatus.DUPLICATE_SUCCESS.value, + status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + status_machine.TransferStatus.RESULT_UNKNOWN.value, + status_machine.TransferStatus.MANUALLY_CLOSED.value, + status_machine.TransferStatus.CANCELLED.value, +} + + +def recover_stale_execution_items(*, deps: TransferDeps, now: datetime | None = None, + request_id: str | None = None) -> dict: + """回收租约过期的执行中明细。 + + Args: + deps: 注入依赖。 + now: 判定时刻。 + request_id: 审计上下文。 + Returns: + {"recovered": n, "skipped_result_unknown": n, "failed": n}。 + """ + current = now or datetime.utcnow() + threshold = current - timedelta(seconds=STALE_EXECUTION_THRESHOLD_SECONDS) + items = TransferInvoiceItem.query.filter( + TransferInvoiceItem.status == status_machine.TransferStatus.EXECUTING.value, + TransferInvoiceItem.updated_at <= threshold, + ).all() + recovered = skipped_unknown = failed = 0 + for item in items: + if (item.result_code or "") == "result_unknown" or item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: + skipped_unknown += 1 + continue + run_no = item.run.run_no if item.run else "RUN-PENDING" + try: + _write_item(item, deps=deps, run_no=run_no, request_id=request_id) + recovered += 1 + except Exception: # noqa: BLE001 —— 单项恢复失败不阻断其他项 + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = "recovery_failed" + failed += 1 + db.session.flush() + db.session.commit() + return {"recovered": recovered, "skipped_result_unknown": skipped_unknown, "failed": failed} + + +def finalize_stale_runs(*, now: datetime | None = None) -> list[int]: + """将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。 + + Args: + now: 判定时刻(保留参数)。 + Returns: + 已收尾的 Run id 列表。 + """ + finalized: list[int] = [] + runs = TransferRun.query.filter_by( + status=status_machine.TransferRunStatus.EXECUTING.value, + ).all() + for run in runs: + items = list(run.items) + if items and all(item.status in _TERMINAL_ITEM_STATUSES for item in items): + finalize_run(run, items) + finalized.append(run.id) + db.session.flush() + db.session.commit() + return finalized diff --git a/backend/app/services/in_transit_transfer/recovery_service.py b/backend/app/services/in_transit_transfer/recovery_service.py new file mode 100644 index 00000000..f810ad62 --- /dev/null +++ b/backend/app/services/in_transit_transfer/recovery_service.py @@ -0,0 +1,66 @@ +"""在途调拨每日历史恢复(自动复核待处理池)。 + +用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt; + result_unknown / manually_closed / success 不自动写入。 +依赖:models、retry_service._recheck_item、TransferDeps。 +逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。 +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.precheck_service import TransferDeps +from app.services.in_transit_transfer.retry_service import _recheck_item + + +@dataclass +class RecoveryOutcome: + """每日恢复结果汇总。""" + + recovered_count: int = 0 + still_blocked_count: int = 0 + skipped_result_unknown: int = 0 + skipped_manually_closed: int = 0 + attempts_created: int = 0 + + +def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOutcome: + """对可恢复异常执行每日自动复核。 + + Args: + business_date: 业务日期(仅用于审计上下文)。 + deps: 注入依赖。 + Returns: + RecoveryOutcome。 + """ + outcome = RecoveryOutcome() + items = TransferInvoiceItem.query.filter( + TransferInvoiceItem.status.in_([ + status_machine.TransferStatus.BLOCKED_RECOVERABLE.value, + status_machine.TransferStatus.RESULT_UNKNOWN.value, + status_machine.TransferStatus.MANUALLY_CLOSED.value, + ]), + ).all() + for item in items: + if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: + # 只读隔离:不查询、不写入、不创建 Attempt。 + outcome.skipped_result_unknown += 1 + continue + if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value: + # 永久排除。 + outcome.skipped_manually_closed += 1 + continue + before_attempt = item.attempt_no + new_status = _recheck_item(item, deps=deps, request_id=None) + if new_status == status_machine.TransferStatus.READY_TO_EXECUTE.value: + outcome.recovered_count += 1 + else: + outcome.still_blocked_count += 1 + if item.attempt_no > before_attempt: + outcome.attempts_created += 1 + db.session.commit() + return outcome diff --git a/backend/app/services/in_transit_transfer/retry_service.py b/backend/app/services/in_transit_transfer/retry_service.py new file mode 100644 index 00000000..2cbd7609 --- /dev/null +++ b/backend/app/services/in_transit_transfer/retry_service.py @@ -0,0 +1,120 @@ +"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。 + +用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP; + Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。 +依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。 +逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。 +""" + +from __future__ import annotations + +import uuid +from datetime import datetime +from decimal import Decimal + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import TransferAttempt, TransferInvoiceItem +from app.services.in_transit_transfer import status as status_machine +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.precheck_service import RESULT_EXECUTABLE, TransferDeps +from app.services.in_transit_transfer.quantity import classify_quantity_match + +RETRY_KIND_ERP_RECHECK = "erp_recheck" +RETRY_KIND_RPA_REFETCH = "rpa_refetch" + + +def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str: + """对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。 + + Returns: + 重检后的 item 状态。 + """ + route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no) + operation_id = f"op-{uuid.uuid4().hex[:12]}" + receipt_qty = Decimal(item.receipt_quantity) + query = deps.erp.query_inventory( + operation_id=operation_id, + run_no=item.run.run_no if item.run else "RUN-PENDING", + attempt_no=item.attempt_no + 1, + invoice_no=item.invoice_no, + erp_org=route.erp_org, + from_warehouse=route.from_warehouse, + to_warehouse=route.to_warehouse, + quantity=receipt_qty, + ) + item.attempt_no += 1 + before_status = item.status + attempt = TransferAttempt( + item_id=item.id, attempt_no=item.attempt_no, kind="erp_query", + status="running", operation_id=operation_id, + request_snapshot_json={ + "invoice_no": item.invoice_no, "erp_org": route.erp_org, + "from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse, + "quantity": str(receipt_qty), + }, + ) + db.session.add(attempt) + db.session.flush() + if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE: + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch" + item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch" + attempt.status = "failed" + else: + item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value + item.result_code = None + item.result_message = None + item.erp_quantity = str(query.quantity) + attempt.status = "success" + attempt.completed_at = datetime.utcnow() + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_ITEM_RECHECKED", + aggregate_type="transfer_item", + aggregate_id=str(item.id), + run_no=item.run.run_no if item.run else None, + invoice_no=item.invoice_no, + item_id=str(item.id), + attempt_no=item.attempt_no, + actor_type="worker", + request_id=request_id, + operation_id=operation_id, + result="success" if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value else "failure", + before={"status": before_status}, + after={"status": item.status, "attempt_no": item.attempt_no}, + )) + db.session.flush() + return item.status + + +def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK, + actor_id: int | None = None, request_id: str | None = None) -> dict: + """人工重试异常项。 + + Args: + item_id: TransferInvoiceItem.id。 + deps: 注入依赖。 + kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。 + actor_id / request_id: 审计上下文。 + Returns: + {"item_id": ..., "status": ..., "attempt_no": ...}。 + Raises: + ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读。 + NotFoundError: item 不存在。 + """ + kind_value = str(kind or "").strip() + if kind_value == RETRY_KIND_RPA_REFETCH: + raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED") + if kind_value != RETRY_KIND_ERP_RECHECK: + raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID") + item = db.session.get(TransferInvoiceItem, item_id) + if item is None: + raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND") + if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: + raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN") + if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}: + raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED") + + status = _recheck_item(item, deps=deps, request_id=request_id) + db.session.commit() + return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no} diff --git a/backend/app/services/in_transit_transfer/serializers.py b/backend/app/services/in_transit_transfer/serializers.py new file mode 100644 index 00000000..9d08e68d --- /dev/null +++ b/backend/app/services/in_transit_transfer/serializers.py @@ -0,0 +1,77 @@ +"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。 + +用途:将领域 DTO 转为前端稳定 JSON(预检摘要/明细/来源进度/执行结果)。 +依赖:contracts、execution_service。 +逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.in_transit_transfer.execution_service import serialize_run_result + + +def serialize_summary(summary) -> dict[str, Any]: + """预检摘要序列化。""" + return { + "precheck_id": summary.precheck_id, + "status": summary.status, + "business_date": summary.business_date, + "eligible_receipt_date_to": summary.eligible_receipt_date_to, + "expires_at": summary.expires_at, + "counts": { + "file_invoice_count": summary.counts.file_invoice_count, + "not_matured_count": summary.counts.not_matured_count, + "prechecked_count": summary.counts.prechecked_count, + "executable_count": summary.counts.executable_count, + "blocked_count": summary.counts.blocked_count, + }, + "estimated_transfer_quantity": summary.estimated_transfer_quantity, + "estimated_erp_write_count": summary.estimated_erp_write_count, + "precheck_hash": summary.precheck_hash, + } + + +def serialize_item(item) -> dict[str, Any]: + """明细项序列化(决策 6 十列字段)。""" + return { + "source_code": item.source_code, + "material_no": item.material_no, + "material_name": item.material_name, + "specification": item.specification, + "invoice_no": item.invoice_no, + "receipt_date": item.receipt_date, + "from_warehouse": item.from_warehouse, + "from_quantity": str(item.from_quantity) if item.from_quantity is not None else None, + "to_warehouse": item.to_warehouse, + "to_quantity": str(item.to_quantity), + "result": item.result, + "reason": item.reason, + "raw_lines": [ + {"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version} + for line in item.raw_lines + ], + } + + +def serialize_source(source) -> dict[str, Any]: + """来源进度序列化。""" + return { + "source_code": source.source_code, + "stage": source.stage, + "file_no": source.file_no, + "file_version": source.file_version, + "checksum": source.checksum, + "error_code": source.error_code, + "error_message": source.error_message, + } + + +def serialize_precheck_detail(detail: dict[str, Any]) -> dict[str, Any]: + """预检恢复详情(summary + items + sources)。""" + return { + "summary": serialize_summary(detail["summary"]), + "items": [serialize_item(item) for item in detail["items"]], + "sources": [serialize_source(source) for source in detail["sources"]], + } diff --git a/backend/app/services/in_transit_transfer/source_file_status.py b/backend/app/services/in_transit_transfer/source_file_status.py new file mode 100644 index 00000000..13f68e30 --- /dev/null +++ b/backend/app/services/in_transit_transfer/source_file_status.py @@ -0,0 +1,63 @@ +"""在途调拨来源收料文件状态投影服务。 + +用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile), + 按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发", + 供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。 +依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。 +逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching; + 最新单元为失败终态 → failed;否则 → none。 +""" + +from __future__ import annotations + +from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun + +RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing') +FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled') + + +def resolve_source_file_status(*, source_code: str) -> dict: + """返回某来源的收料文件状态投影。 + + Returns: + {"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...}, + file_status ∈ {'ready', 'fetching', 'failed', 'none'}。 + """ + report = ( + ShippingReceiptReportFile.query + .join(ShippingReceiptReportFile.unit_run) + .filter( + ShippingReceiptReportFile.unit_run.has(source_code=source_code), + ShippingReceiptReportFile.archive_deleted_at.is_(None), + ) + .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) + .first() + ) + if report is not None: + return { + 'file_status': 'ready', + 'has_ready_file': True, + 'file_no': report.original_filename or str(report.id), + 'file_sha256': report.sha256, + } + + active_unit = ( + ShippingReceiptRpaUnitRun.query + .filter_by(source_code=source_code) + .filter(ShippingReceiptRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES)) + .order_by(ShippingReceiptRpaUnitRun.id.desc()) + .first() + ) + if active_unit is not None: + return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} + + latest_unit = ( + ShippingReceiptRpaUnitRun.query + .filter_by(source_code=source_code) + .order_by(ShippingReceiptRpaUnitRun.id.desc()) + .first() + ) + if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES: + return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} + + return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} diff --git a/backend/app/services/in_transit_transfer/source_job_service.py b/backend/app/services/in_transit_transfer/source_job_service.py new file mode 100644 index 00000000..8626bb3f --- /dev/null +++ b/backend/app/services/in_transit_transfer/source_job_service.py @@ -0,0 +1,70 @@ +"""在途调拨来源级状态服务(唯一推进入口)。 + +用途:统一创建/推进 TransferSourceJob(run 内来源级状态真相源), + 让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。 +依赖:models(TransferSourceJob)、status_machine。 +逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束; + 不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.models import TransferSourceJob + +SOURCE_JOB_STATUSES = ( + 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', + 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', +) + + +def create_source_job(*, run_id: int, source_code: str, status: str = 'pending') -> TransferSourceJob: + """为一次 run 创建一条来源级 job;(run_id, source_code) 唯一由模型约束。 + + Args: + run_id: 所属 TransferRun.id。 + source_code: 来源实例编码。 + status: 初始状态。 + Returns: + 新建(或复用已存在同 run 同来源)的 TransferSourceJob。 + """ + existing = ( + TransferSourceJob.query.filter_by(run_id=run_id, source_code=source_code).order_by(TransferSourceJob.id.desc()).first() + ) + if existing is not None: + return existing + job = TransferSourceJob(run_id=run_id, source_code=source_code, status=status) + db.session.add(job) + db.session.flush() + return job + + +def advance_source_job(*, job: TransferSourceJob, status: str, **fields: Any) -> TransferSourceJob: + """推进单条来源 job 状态并写入来源级事实字段。 + + Args: + job: 目标 TransferSourceJob。 + status: 目标状态(须在 SOURCE_JOB_STATUSES 内,模型 CheckConstraint 兜底)。 + fields: 其余来源级字段(file_no/file_sha256/error_code/error_message/lease_until 等), + 可选 finished_at 被重置为当前时间。 + Returns: + 更新后的 job。 + """ + job.status = status + for key, value in fields.items(): + if hasattr(job, key): + setattr(job, key, value) + if status in ('success', 'partial_failed', 'failed', 'cancelled'): + job.finished_at = datetime.utcnow() + if status == 'pending': + job.started_at = datetime.utcnow() + db.session.flush() + return job + + +def source_jobs_for_run(run_id: int) -> list[TransferSourceJob]: + """读取某次 run 的全部来源级 job(供 restore/投影)。""" + return TransferSourceJob.query.filter_by(run_id=run_id).order_by(TransferSourceJob.source_code).all() diff --git a/backend/app/services/in_transit_transfer/status.py b/backend/app/services/in_transit_transfer/status.py new file mode 100644 index 00000000..193f0b71 --- /dev/null +++ b/backend/app/services/in_transit_transfer/status.py @@ -0,0 +1,217 @@ +"""在途调拨状态机与转换门禁。 + +用途:定义提示词冻结的 13 个业务状态(TransferStatus)、Run 生命周期 + (TransferRunStatus)与通知状态(TransferNotificationStatus), + 并强制所有状态转换走服务端门禁。 +依赖:app.core.errors.AppError。 +逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError; + result_unknown / manually_closed / success / duplicate_success / + not_matured / cancelled 为无出边终态; + 通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。 +""" + +from __future__ import annotations + +from enum import StrEnum +from typing import Mapping + +from app.core.errors import AppError + +INVALID_STATE_TRANSITION_CODE = "TRANSFER.INVALID_STATE_TRANSITION" + + +class TransferStatus(StrEnum): + """Invoice 项业务状态(含提示词冻结的全部 13 个状态)。""" + + FILE_PENDING = "file_pending" + FILE_READY = "file_ready" + PRECHECKING = "prechecking" + READY_TO_EXECUTE = "ready_to_execute" + EXECUTING = "executing" + SUCCESS = "success" + DUPLICATE_SUCCESS = "duplicate_success" + BLOCKED_RECOVERABLE = "blocked_recoverable" + NOT_MATURED = "not_matured" + RESULT_UNKNOWN = "result_unknown" + MANUALLY_CLOSED = "manually_closed" + CANCELLED = "cancelled" + NOTIFICATION_FAILED = "notification_failed" + + +class TransferRunStatus(StrEnum): + """Run 级生命周期;ERP 结果与通知结果分离。""" + + QUEUED = "queued" + PREPARING_FILES = "preparing_files" + PRECHECKING = "prechecking" + READY_TO_EXECUTE = "ready_to_execute" + EXECUTING = "executing" + SUCCESS = "success" + PARTIAL_FAILED = "partial_failed" + FAILED = "failed" + CANCELLED = "cancelled" + + +class TransferNotificationStatus(StrEnum): + """通知投递状态;failed 即提示词中 notification_failed 的语义。""" + + PENDING = "pending" + SUCCESS = "success" + FAILED = "failed" + + +# 无出边终态:这些状态不得再触发任何自动或手工迁移。 +TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({ + TransferStatus.SUCCESS.value, + TransferStatus.DUPLICATE_SUCCESS.value, + TransferStatus.RESULT_UNKNOWN.value, + TransferStatus.MANUALLY_CLOSED.value, + TransferStatus.CANCELLED.value, + TransferStatus.NOT_MATURED.value, + TransferStatus.NOTIFICATION_FAILED.value, +}) + +# Invoice 项转换白名单:key=当前状态,value=允许的目标状态集合。 +ITEM_TRANSITIONS: dict[str, frozenset[str]] = { + TransferStatus.FILE_PENDING.value: frozenset({ + TransferStatus.FILE_READY.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + }), + TransferStatus.FILE_READY.value: frozenset({ + TransferStatus.PRECHECKING.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + }), + TransferStatus.PRECHECKING.value: frozenset({ + TransferStatus.READY_TO_EXECUTE.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + TransferStatus.NOT_MATURED.value, + TransferStatus.CANCELLED.value, + }), + TransferStatus.READY_TO_EXECUTE.value: frozenset({ + TransferStatus.PRECHECKING.value, # 确认失效/库存变化 → 新 Attempt 重新预检 + TransferStatus.EXECUTING.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + TransferStatus.CANCELLED.value, + }), + TransferStatus.EXECUTING.value: frozenset({ + TransferStatus.SUCCESS.value, + TransferStatus.DUPLICATE_SUCCESS.value, + TransferStatus.BLOCKED_RECOVERABLE.value, + TransferStatus.RESULT_UNKNOWN.value, + TransferStatus.CANCELLED.value, + }), + TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({ + TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt + TransferStatus.MANUALLY_CLOSED.value, + TransferStatus.CANCELLED.value, + }), + TransferStatus.NOT_MATURED.value: frozenset(), + TransferStatus.SUCCESS.value: frozenset(), + TransferStatus.DUPLICATE_SUCCESS.value: frozenset(), + TransferStatus.RESULT_UNKNOWN.value: frozenset(), + TransferStatus.MANUALLY_CLOSED.value: frozenset(), + TransferStatus.CANCELLED.value: frozenset(), + TransferStatus.NOTIFICATION_FAILED.value: frozenset(), +} + +# Run 级转换白名单。 +RUN_TRANSITIONS: dict[str, frozenset[str]] = { + TransferRunStatus.QUEUED.value: frozenset({ + TransferRunStatus.PREPARING_FILES.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.PREPARING_FILES.value: frozenset({ + TransferRunStatus.PRECHECKING.value, + TransferRunStatus.FAILED.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.PRECHECKING.value: frozenset({ + TransferRunStatus.READY_TO_EXECUTE.value, + TransferRunStatus.FAILED.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.READY_TO_EXECUTE.value: frozenset({ + TransferRunStatus.EXECUTING.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.EXECUTING.value: frozenset({ + TransferRunStatus.SUCCESS.value, + TransferRunStatus.PARTIAL_FAILED.value, + TransferRunStatus.FAILED.value, + TransferRunStatus.CANCELLED.value, + }), + TransferRunStatus.SUCCESS.value: frozenset(), + TransferRunStatus.PARTIAL_FAILED.value: frozenset(), + TransferRunStatus.FAILED.value: frozenset(), + TransferRunStatus.CANCELLED.value: frozenset(), +} + + +class TransferStateError(AppError): + """非法状态转换领域错误。""" + + def __init__( + self, + message: str = "Invalid state transition", + *, + current: str | None = None, + target: str | None = None, + ): + details: dict[str, str] = {} + if current is not None: + details["current"] = current + if target is not None: + details["target"] = target + super().__init__( + code=INVALID_STATE_TRANSITION_CODE, + message=message, + http_status=409, + details=details, + ) + + +def assert_transition_allowed( + current: str, + target: str, + *, + transitions: Mapping[str, frozenset[str]] = ITEM_TRANSITIONS, +) -> None: + """服务端状态转换门禁。 + + Args: + current: 当前状态。 + target: 目标状态。 + transitions: 转换白名单(默认 Invoice 项表)。 + Raises: + TransferStateError: 当前状态未知或目标不在允许集合内。 + """ + current_value = str(current or "").strip() + target_value = str(target or "").strip() + allowed = transitions.get(current_value) + if allowed is None: + raise TransferStateError("unknown current status", current=current_value) + if target_value not in allowed: + raise TransferStateError( + "status transition not allowed", + current=current_value, + target=target_value, + ) + + +def apply_notification_failure(run_status: str) -> str: + """通知失败不改变 ERP 结果。 + + Args: + run_status: Run 的 ERP 业务终态。 + Returns: + 原 run_status(保持不变)。 + Raises: + TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。 + """ + status = str(run_status or "").strip() + if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}: + raise TransferStateError( + "notification failure only allowed after ERP terminal status", + current=status, + ) + return status diff --git a/backend/app/services/in_transit_transfer/strategy.py b/backend/app/services/in_transit_transfer/strategy.py new file mode 100644 index 00000000..6a3dcb43 --- /dev/null +++ b/backend/app/services/in_transit_transfer/strategy.py @@ -0,0 +1,61 @@ +"""在途调拨策略硬门禁。 + +用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试, + 强制默认 10 分钟确认有效期。 +依赖:app.core.errors.AppError、standard decimal。 +逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError, + 阻止发布/执行(fail-closed)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from decimal import Decimal + +from app.core.errors import AppError + +STRATEGY_VIOLATION_CODE = "TRANSFER.STRATEGY_VIOLATION" +DEFAULT_CONFIRM_TTL_SECONDS = 600 # 10 分钟 + + +@dataclass(frozen=True) +class TransferStrategyPolicy: + """调拨策略冻结快照;三项禁令默认关闭。""" + + allow_partial: bool = False + quantity_tolerance: Decimal = Decimal("0") + allow_erp_auto_retry: bool = False + confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS + + +class StrategyViolationError(AppError): + """策略触碰一期禁令。""" + + def __init__(self, message: str, *, reason: str): + super().__init__( + code=STRATEGY_VIOLATION_CODE, + message=message, + http_status=409, + details={"reason": reason}, + ) + + +def validate_strategy(strategy: TransferStrategyPolicy) -> None: + """校验策略是否违反一期硬门禁。 + + Args: + strategy: 待校验策略。 + Raises: + StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。 + """ + if strategy.allow_partial: + raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial") + if strategy.quantity_tolerance != Decimal("0"): + raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance") + if strategy.allow_erp_auto_retry: + raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry") + + +def default_strategy() -> TransferStrategyPolicy: + """返回一期默认策略(全部禁令关闭,确认有效期 600 秒)。""" + return TransferStrategyPolicy() diff --git a/backend/app/services/integration_connector/__init__.py b/backend/app/services/integration_connector/__init__.py new file mode 100644 index 00000000..7c704afc --- /dev/null +++ b/backend/app/services/integration_connector/__init__.py @@ -0,0 +1,7 @@ +"""services/integration_connector/__init__.py + +Integration Connector(外部系统连接器框架):能力契约、绑定解析、REST/SOAP 传输、 +声明式映射、凭据引用与调用引擎(CapabilityGateway)。 +""" + +from __future__ import annotations diff --git a/backend/app/services/integration_connector/binding.py b/backend/app/services/integration_connector/binding.py new file mode 100644 index 00000000..d1364959 --- /dev/null +++ b/backend/app/services/integration_connector/binding.py @@ -0,0 +1,105 @@ +"""services/integration_connector/binding.py + +用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到 + (客户端 + 接口 + 映射版本),并冻结调用期配置快照。 +依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。 +逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集; + 同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timezone + +from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition +from app.services.integration_connector.errors import BindingNotFoundError + + +@dataclass(frozen=True) +class BindingSnapshot: + """一次调用冻结的绑定快照:调用期配置 + 版本号(非活表引用)。""" + + capability: str + context_selector: dict + client_code: str + interface_code: str + connector_type: str + interface_version: int + mapping_version: int + credential_ref_code: str | None + config: dict + request_spec: dict + response_mapping: dict + output_schema: dict + + +def _to_naive(dt: datetime | None) -> datetime | None: + if dt is None: + return None + if dt.tzinfo is not None: + return dt.astimezone(timezone.utc).replace(tzinfo=None) + return dt + + +def _within_window(binding: IntegrationBinding, now: datetime) -> bool: + effective_from = _to_naive(binding.effective_from) + effective_to = _to_naive(binding.effective_to) + if effective_from is not None and now < effective_from: + return False + if effective_to is not None and now > effective_to: + return False + return True + + +def _is_subset(selector: dict, context: dict) -> bool: + """selector 的键值须全部存在于 context(空 selector 恒命中)。""" + return all(context.get(k) == v for k, v in selector.items()) + + +def resolve_binding(capability: str, context: dict, environment: str, *, now: datetime | None = None) -> BindingSnapshot: + """解析最佳绑定并冻结调用期快照。 + + Args: + capability: 能力名(如 in_transit_transfer.query_inventory)。 + context: 路由上下文(来源/组织/租户等),如 {"source_code": "DBS-AWSBI"}。 + environment: 环境(prod/test/dev)。 + now: 可选时钟(测试注入);缺省用 utcnow。 + Returns: + BindingSnapshot。 + Raises: + BindingNotFoundError: 无可用绑定(fail-closed)。 + """ + base_now = now or datetime.utcnow() + rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all() + candidates: list[tuple[IntegrationBinding, dict]] = [] + for row in rows: + if not _within_window(row, base_now): + continue + selector = row.context_selector_json or {} + if not _is_subset(selector, context or {}): + continue + candidates.append((row, selector)) + if not candidates: + raise BindingNotFoundError(capability=capability) + candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True) + row, selector = candidates[0] + + client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first() + iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first() + if client is None or iface is None: + raise BindingNotFoundError(capability=capability) + return BindingSnapshot( + capability=row.capability, + context_selector=selector, + client_code=client.code, + interface_code=iface.code, + connector_type=client.connector_type, + interface_version=iface.version, + mapping_version=row.mapping_version, + credential_ref_code=client.credential_ref_code, + config=client.config_json or {}, + request_spec=iface.request_spec_json or {}, + response_mapping=iface.response_mapping_json or {}, + output_schema=iface.output_schema_json or {}, + ) diff --git a/backend/app/services/integration_connector/capability.py b/backend/app/services/integration_connector/capability.py new file mode 100644 index 00000000..560ce700 --- /dev/null +++ b/backend/app/services/integration_connector/capability.py @@ -0,0 +1,125 @@ +"""services/integration_connector/capability.py + +用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。 +依赖:app.core.errors、errors.py;纯代码,不依赖 DB。 +逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。 +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from app.core.errors import ValidationError +from app.services.integration_connector.errors import CapabilityNotFoundError + +# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。 +_QUERY_INPUT_SCHEMA: dict = { + "type": "object", + "required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"], + "properties": { + "invoice_no": {"type": "string"}, + "from_warehouse": {"type": "string"}, + "to_warehouse": {"type": "string"}, + "quantity": {"type": "number"}, + }, +} +_QUERY_OUTPUT_SCHEMA: dict = { + "type": "object", + "properties": { + "found": {"type": "boolean"}, + "quantity": {"type": ["number", "null"]}, + }, +} +_WRITE_OUTPUT_SCHEMA: dict = { + "type": "object", + "required": ["status"], + "properties": { + "status": { + "type": "string", + "enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"], + }, + "document_no": {"type": ["string", "null"]}, + "verified_posted": {"type": ["boolean", "null"]}, + }, +} + + +@dataclass(frozen=True) +class CapabilitySpec: + """强类型能力契约(由代码注册)。""" + + name: str + input_schema: dict + output_schema: dict + idempotency: str + write: bool + + +_CAPABILITIES: dict[str, CapabilitySpec] = {} +_LOADED = False + + +def register_capability(spec: CapabilitySpec) -> CapabilitySpec: + """注册能力;同名重复注册抛 ValidationError。""" + if spec.name in _CAPABILITIES: + raise ValidationError( + f"capability already registered: {spec.name}", + code="INTEGRATION.CAPABILITY_DUPLICATE", + details={"name": spec.name}, + ) + _CAPABILITIES[spec.name] = spec + return spec + + +def get_capability(name: str) -> CapabilitySpec: + """按名查询能力;未注册抛 CapabilityNotFoundError(fail-closed)。""" + spec = _CAPABILITIES.get(name) + if spec is None: + raise CapabilityNotFoundError(name=name) + return spec + + +def list_capabilities() -> list[CapabilitySpec]: + """返回全部已注册能力(按名排序)。""" + return sorted(_CAPABILITIES.values(), key=lambda s: s.name) + + +def ensure_capabilities_loaded() -> None: + """惰性注册内置能力(幂等);由网关/API 在解析前调用。""" + global _LOADED # noqa: PLW0603 + if _LOADED: + return + _LOADED = True + _register_transfer_capabilities() + + +def _register_transfer_capabilities() -> None: + """注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。""" + register_capability(CapabilitySpec( + name="in_transit_transfer.query_inventory", + input_schema=_QUERY_INPUT_SCHEMA, + output_schema=_QUERY_OUTPUT_SCHEMA, + idempotency="none", + write=False, + )) + register_capability(CapabilitySpec( + name="in_transit_transfer.create_transfer", + input_schema=_QUERY_INPUT_SCHEMA, + output_schema=_WRITE_OUTPUT_SCHEMA, + idempotency="invoice", + write=True, + )) + register_capability(CapabilitySpec( + name="in_transit_transfer.verify_duplicate", + input_schema=_QUERY_INPUT_SCHEMA, + output_schema=_WRITE_OUTPUT_SCHEMA, + idempotency="invoice", + write=False, + )) + + +def reset_capability_registry_for_tests() -> None: + """单测隔离:清空注册表并重置加载标记。""" + global _LOADED # noqa: PLW0603 + _CAPABILITIES.clear() + _LOADED = False diff --git a/backend/app/services/integration_connector/engine.py b/backend/app/services/integration_connector/engine.py new file mode 100644 index 00000000..0701f370 --- /dev/null +++ b/backend/app/services/integration_connector/engine.py @@ -0,0 +1,153 @@ +"""services/integration_connector/engine.py + +用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。 +依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。 +逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout; + 入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。 +""" + +from __future__ import annotations + +import time +import uuid +from dataclasses import replace + +from app import db +from app.services.integration_connector.binding import BindingSnapshot, resolve_binding +from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability +from app.services.integration_connector.errors import CallFailedError, InputInvalidError +from app.services.integration_connector.mapping import map_response, schema_errors +from app.services.integration_connector.security import sanitize +from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response +from app.models import IntegrationCall + + +def build_request(request_spec: dict, config: dict, params: dict) -> dict: + """按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。""" + request_spec = request_spec or {} + spec_path = str(request_spec.get('path') or '') + try: + path = spec_path.format(**params) + except (KeyError, IndexError, ValueError): + path = spec_path + headers = dict(config.get('headers') or {}) + spec_params = list(request_spec.get('params') or []) + selected = {k: params[k] for k in spec_params if k in params} or params + template = request_spec.get('template') + if isinstance(template, dict): + body = _fill_template(template, params) + else: + body = selected + return {'path': path, 'params': selected, 'body': body, 'headers': headers} + + +def _fill_template(template: dict, params: dict) -> dict: + """填充模板 dict 中的 {placeholder} 占位符。""" + filled: dict = {} + for key, value in template.items(): + if isinstance(value, str) and '{' in value: + try: + filled[key] = value.format(**params) + except (KeyError, IndexError, ValueError): + filled[key] = value + else: + filled[key] = value + return filled + + +def _environment() -> str: + """从 Flask 配置推导环境(dev/test/prod),缺省 prod。""" + try: + from flask import current_app, has_app_context + if has_app_context(): + value = str(current_app.config.get('ENV_NAME') or '').strip().lower() + if value in {'dev', 'test', 'prod'}: + return value + except Exception: + pass + return 'prod' + + +class CapabilityGateway: + """能力调用引擎;transports 为 {connector_type: Transport} 可注入。""" + + def __init__(self, transports: dict[str, Transport] | None = None) -> None: + self.transports = dict(transports or {}) + + def call( + self, + *, + capability: str, + context: dict, + params: dict, + operation_id: str, + idempotency_key: str | None = None, + environment: str | None = None, + transports: dict[str, Transport] | None = None, + ) -> IntegrationCallResult: + ensure_capabilities_loaded() + spec = get_capability(capability) + input_errors = schema_errors(params, spec.input_schema) + if input_errors: + raise InputInvalidError(details={'errors': input_errors}) + + env = environment or _environment() + snapshot = resolve_binding(capability, context, env) + transport = (transports or self.transports).get(snapshot.connector_type) + if transport is None: + raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'}) + + request = build_request(snapshot.request_spec, snapshot.config, params) + trace_id = f'ic-{uuid.uuid4().hex}' + start_ms = int(time.time() * 1000) + try: + raw = transport.call( + client={'config_json': snapshot.config, 'credential': {}}, + interface={'request_spec_json': snapshot.request_spec}, + request=request, + ) + except TimeoutError: + result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id) + _record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id) + return result + + result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success') + if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'): + data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema) + result = replace(result, data=data) + result = replace(result, trace_id=trace_id) + _record_call(operation_id, capability, snapshot, params, raw, result, start_ms, trace_id) + return result + + +def _record_call( + operation_id: str, + capability: str, + snapshot: BindingSnapshot, + params: dict, + raw: dict | None, + result: IntegrationCallResult, + start_ms: int, + trace_id: str, +) -> None: + """落 IntegrationCall(冻结绑定版本 + 脱敏请求/响应摘要)。""" + elapsed_ms = int(time.time() * 1000) - start_ms + call = IntegrationCall( + operation_id=operation_id, + capability=capability, + binding_snapshot_json={ + 'client_code': snapshot.client_code, + 'interface_code': snapshot.interface_code, + 'connector_type': snapshot.connector_type, + 'interface_version': snapshot.interface_version, + 'mapping_version': snapshot.mapping_version, + 'credential_ref_code': snapshot.credential_ref_code, + }, + request_summary_json=sanitize(params), + response_summary_json=sanitize(raw or {}), + status=result.status, + elapsed_ms=elapsed_ms, + trace_id=trace_id, + ) + db.session.add(call) + db.session.commit() diff --git a/backend/app/services/integration_connector/errors.py b/backend/app/services/integration_connector/errors.py new file mode 100644 index 00000000..d90e83f6 --- /dev/null +++ b/backend/app/services/integration_connector/errors.py @@ -0,0 +1,104 @@ +"""services/integration_connector/errors.py + +用途:Integration Connector 框架统一业务异常类(INTEGRATION.* 错误码)。 +依赖:app.core.errors.AppError。 +逻辑:fail-closed —— 缺绑定/缺凭据/映射不合法/契约未冻结均抛出,绝不猜测。 +""" + +from __future__ import annotations + +from typing import Any + +from app.core.errors import AppError + +INTEGRATION_CAPABILITY_NOT_FOUND = "INTEGRATION.CAPABILITY_NOT_FOUND" +INTEGRATION_INPUT_INVALID = "INTEGRATION.INPUT_INVALID" +INTEGRATION_BINDING_NOT_FOUND = "INTEGRATION.BINDING_NOT_FOUND" +INTEGRATION_TRANSPORT_NOT_FROZEN = "INTEGRATION.TRANSPORT_NOT_FROZEN" +INTEGRATION_MAPPING_INVALID = "INTEGRATION.MAPPING_INVALID" +INTEGRATION_CREDENTIAL_UNRESOLVED = "INTEGRATION.CREDENTIAL_UNRESOLVED" +INTEGRATION_RESULT_UNKNOWN = "INTEGRATION.RESULT_UNKNOWN" +INTEGRATION_CALL_FAILED = "INTEGRATION.CALL_FAILED" + + +class CapabilityNotFoundError(AppError): + """能力未注册(fail-closed)。""" + + def __init__(self, message: str = "capability not registered", *, name: str | None = None): + details = {"name": name} if name else {} + super().__init__( + code=INTEGRATION_CAPABILITY_NOT_FOUND, message=message, http_status=404, details=details, + retryable=False, + ) + + +class InputInvalidError(AppError): + """入参不合能力输入 Schema。""" + + def __init__(self, message: str = "input invalid", *, details: dict[str, Any] | None = None): + super().__init__( + code=INTEGRATION_INPUT_INVALID, message=message, http_status=400, details=details or {}, + retryable=False, + ) + + +class BindingNotFoundError(AppError): + """无可用绑定(fail-closed)。""" + + def __init__(self, message: str = "no binding for capability", *, capability: str | None = None): + details = {"capability": capability} if capability else {} + super().__init__( + code=INTEGRATION_BINDING_NOT_FOUND, message=message, http_status=503, details=details, + retryable=False, + ) + + +class TransportNotFrozenError(AppError): + """传输契约未冻结(缺 endpoint/wsdl)。""" + + def __init__(self, message: str = "transport not frozen"): + super().__init__( + code=INTEGRATION_TRANSPORT_NOT_FROZEN, message=message, http_status=503, retryable=False, + ) + + +class MappingInvalidError(AppError): + """映射结果不合输出 Schema(fail-closed)。""" + + def __init__(self, message: str = "mapping invalid", *, details: dict[str, Any] | None = None): + super().__init__( + code=INTEGRATION_MAPPING_INVALID, message=message, http_status=503, details=details or {}, + retryable=False, + ) + + +class CredentialUnresolvedError(AppError): + """凭据无法解析(fail-closed)。""" + + def __init__(self, message: str = "credential unresolved", *, ref: str | None = None): + details = {"secret_ref": ref} if ref else {} + super().__init__( + code=INTEGRATION_CREDENTIAL_UNRESOLVED, message=message, http_status=503, details=details, + retryable=False, + ) + + +class ResultUnknownError(AppError): + """写结果无法确认;禁止自动重试。""" + + def __init__(self, message: str = "result unknown", *, operation_id: str | None = None): + details = {"operation_id": operation_id} if operation_id else {} + super().__init__( + code=INTEGRATION_RESULT_UNKNOWN, message=message, http_status=503, details=details, + retryable=False, + ) + + +class CallFailedError(AppError): + """调用技术失败(非业务失败)。""" + + def __init__(self, message: str = "call failed", *, details: dict[str, Any] | None = None): + super().__init__( + code=INTEGRATION_CALL_FAILED, message=message, http_status=502, details=details or {}, + retryable=False, + ) diff --git a/backend/app/services/integration_connector/gateway.py b/backend/app/services/integration_connector/gateway.py new file mode 100644 index 00000000..3785c80d --- /dev/null +++ b/backend/app/services/integration_connector/gateway.py @@ -0,0 +1,27 @@ +"""services/integration_connector/gateway.py + +用途:模块级 CapabilityGateway 装配与测试注入点。 +依赖:engine.CapabilityGateway、transports.rest/soap。 +逻辑:生产用 REST/SOAP 传输;测试通过 set_capability_gateway 注入替身。 +""" + +from __future__ import annotations + +from app.services.integration_connector.engine import CapabilityGateway +from app.services.integration_connector.transports.rest import RestTransport +from app.services.integration_connector.transports.soap import SoapTransport + +_override: CapabilityGateway | None = None + + +def set_capability_gateway(gateway: CapabilityGateway | None) -> None: + """测试注入点:设置/清除 CapabilityGateway 覆盖。""" + global _override # noqa: PLW0603 + _override = gateway + + +def get_capability_gateway() -> CapabilityGateway: + """返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP)。""" + if _override is not None: + return _override + return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport()}) diff --git a/backend/app/services/integration_connector/mapping.py b/backend/app/services/integration_connector/mapping.py new file mode 100644 index 00000000..51973652 --- /dev/null +++ b/backend/app/services/integration_connector/mapping.py @@ -0,0 +1,210 @@ +"""services/integration_connector/mapping.py + +用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。 +依赖:decimal、errors.py;纯函数,无 IO/网络/DB。 +逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL; + 缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。 +""" + +from __future__ import annotations + +from decimal import Decimal +from typing import Any + +from app.services.integration_connector.errors import MappingInvalidError + +# 表达式安全边界:路径长度/深度上限(失败即 fail-closed)。 +MAX_PATH_LENGTH = 256 +MAX_DEPTH = 8 + +# 缺字段哨兵:与合法值 None 区分。 +MISSING = object() + + +def _tokenize(path: str) -> list[str]: + """把点路径 + 数组下标拆成 token 序列,如 a.b[0].c -> ['a','b','0','c']。""" + tokens: list[str] = [] + current = "" + i = 0 + n = len(path) + while i < n: + c = path[i] + if c == "[": + if current: + tokens.append(current) + current = "" + j = path.index("]", i) + tokens.append(path[i + 1:j]) + i = j + 1 + elif c == ".": + if current: + tokens.append(current) + current = "" + i += 1 + else: + current += c + i += 1 + if current: + tokens.append(current) + return tokens + + +def extract_path(obj: Any, path: str) -> Any: + """按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。""" + path = str(path or "") + if len(path) > MAX_PATH_LENGTH: + raise MappingInvalidError(details={"reason": "path_too_long"}) + tokens = _tokenize(path) + if len(tokens) > MAX_DEPTH: + raise MappingInvalidError(details={"reason": "path_too_deep"}) + cur = obj + for tok in tokens: + if isinstance(cur, list) and tok.isdigit(): + idx = int(tok) + if idx >= len(cur): + return MISSING + cur = cur[idx] + elif isinstance(cur, dict) and tok in cur: + cur = cur[tok] + else: + return MISSING + return cur + + +# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ---- + +def _default(value: Any, default: Any) -> Any: + return default if value is MISSING else value + + +def _fallback(value: Any, fallback: Any) -> Any: + return fallback if value is MISSING or value in (None, "") else value + + +def _decimal(value: Any) -> Any: + if value is MISSING: + return MISSING + return Decimal(str(value)) + + +def _cast(value: Any, to: str) -> Any: + if value is MISSING or value is None: + return MISSING + if to == "int": + return int(value) + if to == "float": + return float(value) + if to == "str": + return str(value) + if to == "bool": + return bool(value) + return value + + +def _enum_map(value: Any, mapping: dict[str, str]) -> Any: + if value is MISSING: + return MISSING + return mapping.get(str(value), value) + + +def _list_map(value: Any, mapping: dict[str, str]) -> list[Any]: + if value is MISSING: + return MISSING + return [mapping.get(str(item), item) for item in (value or [])] + + +def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any: + if value is MISSING: + return MISSING + return then if condition == "truthy" and bool(value) else else_ + + +TRANSFORMS: dict[str, Any] = { + "default": _default, + "fallback": _fallback, + "decimal": _decimal, + "cast": _cast, + "enum-map": _enum_map, + "list-map": _list_map, + "if-else": _if_else, +} + + +# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)---- + +def _matches_type(value: Any, type_spec: Any) -> bool: + if isinstance(type_spec, list): + return any(_matches_type(value, t) for t in type_spec) + if type_spec == "object": + return isinstance(value, dict) + if type_spec == "array": + return isinstance(value, (list, tuple)) + if type_spec == "string": + return isinstance(value, str) + if type_spec == "number": + return isinstance(value, (int, float, Decimal)) and not isinstance(value, bool) + if type_spec == "integer": + return isinstance(value, int) and not isinstance(value, bool) + if type_spec == "boolean": + return isinstance(value, bool) + if type_spec == "null": + return value is None + return True + + +def _validate_against_schema(value: Any, schema: dict, path: str = "") -> list[tuple[str, str]]: + """返回不合规项 [(字段路径, 原因)];空列表表示合规。""" + if not isinstance(schema, dict): + return [] + errors: list[tuple[str, str]] = [] + if "enum" in schema and value not in schema["enum"]: + errors.append((path, f"not in enum: {value!r}")) + if "type" in schema and not _matches_type(value, schema["type"]): + errors.append((path, f"expected {schema['type']}, got {type(value).__name__}")) + if isinstance(value, dict): + for req in schema.get("required") or []: + if req not in value: + errors.append((f"{path}.{req}" if path else req, "required missing")) + for key, sub in (schema.get("properties") or {}).items(): + if key in value: + errors.extend(_validate_against_schema(value[key], sub, f"{path}.{key}" if path else key)) + elif isinstance(value, list) and "items" in schema: + for i, item in enumerate(value): + errors.extend(_validate_against_schema(item, schema["items"], f"{path}[{i}]")) + return errors + + +def schema_errors(value: Any, schema: dict) -> list[tuple[str, str]]: + """对 value 做最小 Schema 校验,返回不合规项 [(字段路径, 原因)];空列表表示合规。""" + return _validate_against_schema(value, schema or {}) + + +def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict: + """按 mapping 从 raw 提取并转换字段,组装 result 后经 output_schema 校验。 + + Raises: + MappingInvalidError: 未知转换函数 / 缺必需字段 / 类型或枚举不合。 + """ + mapping = mapping or {} + result: dict[str, Any] = {} + for field, spec in mapping.items(): + if not isinstance(spec, dict): + raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"}) + if "default" in spec: + value = spec["default"] + else: + expr = spec.get("expr") + value = extract_path(raw, expr) if expr is not None else MISSING + transform = spec.get("transform") + if transform: + fn = TRANSFORMS.get(transform) + if fn is None: + raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"}) + value = fn(value, **(spec.get("args") or {})) + if value is not MISSING: + result[field] = value + + errors = _validate_against_schema(result, output_schema or {}) + if errors: + raise MappingInvalidError(details={"errors": errors}) + return result diff --git a/backend/app/services/integration_connector/security.py b/backend/app/services/integration_connector/security.py new file mode 100644 index 00000000..865bc948 --- /dev/null +++ b/backend/app/services/integration_connector/security.py @@ -0,0 +1,83 @@ +"""services/integration_connector/security.py + +用途:凭据引用解析(fail-closed)与敏感字段脱敏。 +依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。 +逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError; + sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import IntegrationCredentialReference +from app.services.integration_connector.errors import CredentialUnresolvedError + +DEFAULT_SENSITIVE_KEYS = frozenset({ + 'password', 'token', 'secret', 'authorization', 'cookie', 'access_key', + 'secret_key', 'credential', 'api_key', 'apikey', 'credentials', +}) + + +def resolve_credential(credential_ref_code: str) -> dict[str, Any]: + """按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。 + + Raises: + CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。 + """ + from flask import current_app + + cred = IntegrationCredentialReference.query.filter_by( + code=credential_ref_code, status='active', + ).first() + if cred is None: + raise CredentialUnresolvedError(ref=credential_ref_code) + secret_ref = cred.secret_ref + value = current_app.config.get(secret_ref) if has_app_ctx() else None + if value is None or value == '': + raise CredentialUnresolvedError(ref=secret_ref) + if isinstance(value, dict): + return dict(value) + return {'value': value} + + +def has_app_ctx() -> bool: + """当前是否处于 Flask app 上下文(无则返回 False)。""" + try: + from flask import has_app_context + return has_app_context() + except Exception: + return False + + +def sanitize(obj: Any, sensitive_keys: set[str] | None = None) -> Any: + """递归脱敏:把敏感键对应的值替换为 ***;保留原始结构。 + + Args: + obj: 待脱敏对象(dict/list/标量)。 + sensitive_keys: 附加敏感键集合;缺省用 DEFAULT_SENSITIVE_KEYS。 + Returns: + 脱敏后的新对象(不修改入参)。 + """ + keys = DEFAULT_SENSITIVE_KEYS | (sensitive_keys or set()) + if isinstance(obj, dict): + return { + key: ('***' if str(key).lower() in keys else sanitize(value, sensitive_keys)) + for key, value in obj.items() + } + if isinstance(obj, (list, tuple)): + return [sanitize(item, sensitive_keys) for item in obj] + return obj + + +def credential_summary(cred: IntegrationCredentialReference) -> dict[str, Any]: + """只回凭据元数据,绝不含解析出的明文。""" + return { + 'code': cred.code, + 'secret_ref': cred.secret_ref, + 'secret_provider': cred.secret_provider, + 'credential_type': cred.credential_type, + 'version': cred.version, + 'status': cred.status, + 'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None, + } diff --git a/backend/app/services/integration_connector/transports/__init__.py b/backend/app/services/integration_connector/transports/__init__.py new file mode 100644 index 00000000..be8b4ce2 --- /dev/null +++ b/backend/app/services/integration_connector/transports/__init__.py @@ -0,0 +1,18 @@ +"""services/integration_connector/transports/__init__.py + +集成连接器传输层:base(契约+分类)、rest、soap。后续扩展 rpa/sql/file。 +""" + +from __future__ import annotations + +from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response +from app.services.integration_connector.transports.rest import RestTransport +from app.services.integration_connector.transports.soap import SoapTransport + +__all__ = [ + 'IntegrationCallResult', + 'Transport', + 'classify_transport_response', + 'RestTransport', + 'SoapTransport', +] diff --git a/backend/app/services/integration_connector/transports/base.py b/backend/app/services/integration_connector/transports/base.py new file mode 100644 index 00000000..17f6a680 --- /dev/null +++ b/backend/app/services/integration_connector/transports/base.py @@ -0,0 +1,73 @@ +"""services/integration_connector/transports/base.py + +用途:Transport 统一契约 + 结果分类(IntegrationCallResult)。 +依赖:typing.Protocol、dataclass;无 Flask/DB。 +逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为 + IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Protocol + +# 结果状态集(与在途调拨写入结果分类一致):success / duplicate_success / +# duplicate_unverified / business_failed / technical_failed / timeout / result_unknown +RESULT_STATUSES = ( + 'success', 'duplicate_success', 'duplicate_unverified', 'business_failed', + 'technical_failed', 'timeout', 'result_unknown', +) + + +@dataclass(frozen=True) +class IntegrationCallResult: + """一次调用归一后的结果对象。""" + + status: str + data: dict[str, Any] | None = None + error_code: str | None = None + error_message: str | None = None + document_no: str | None = None + trace_id: str | None = None + + +class Transport(Protocol): + """传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。""" + + connector_type: str + + def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: + ... + + +def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult: + """按原始响应文本归一化结果分类(复用调拨六态分类语义)。 + + Args: + raw: 原始响应 dict,含 status/document_no/verified_posted/code/message。 + Returns: + IntegrationCallResult。 + """ + status = str(raw.get('status') or 'technical_failed') + document_no = raw.get('document_no') + if status == 'success': + return IntegrationCallResult(status='success', data=raw, document_no=document_no) + if status == 'duplicate_success': + posted = bool(raw.get('verified_posted')) + if posted: + return IntegrationCallResult(status='duplicate_success', data=raw, document_no=document_no) + return IntegrationCallResult( + status='duplicate_unverified', data=raw, document_no=document_no, + error_code='INTEGRATION_DUPLICATE_NOT_VERIFIED', + ) + if status == 'business_failed': + return IntegrationCallResult( + status='business_failed', data=raw, + error_code=str(raw.get('code') or 'ERP_BUSINESS_REJECT'), + error_message=str(raw.get('message') or ''), + ) + if status == 'timeout': + return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN') + if status == 'result_unknown': + return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no) + return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE') diff --git a/backend/app/services/integration_connector/transports/rest.py b/backend/app/services/integration_connector/transports/rest.py new file mode 100644 index 00000000..081ad309 --- /dev/null +++ b/backend/app/services/integration_connector/transports/rest.py @@ -0,0 +1,62 @@ +"""services/integration_connector/transports/rest.py + +用途:REST Transport——按 client 配置与 interface 请求规格构造 HTTP 请求并返回原始 dict。 +依赖:requests(默认注入),可注入 http_request 供测试替身。 +逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为 + business_failed dict;非 JSON 响应映射为 technical_failed。 +""" + +from __future__ import annotations + +from typing import Any, Callable + +import requests + +from app.services.integration_connector.errors import TransportNotFrozenError + +HttpRequest = Callable[..., Any] + + +class RestTransport: + """REST 传输;http_request 可注入以便单元测试(默认 requests.request)。""" + + connector_type = 'rest' + + def __init__(self, http_request: HttpRequest | None = None) -> None: + self._http_request = http_request or requests.request + + def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: + config = client.get('config_json') or {} + endpoint = str(config.get('endpoint') or '').strip() + if not endpoint: + raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)') + + spec = interface.get('request_spec_json') or {} + method = str(spec.get('method') or 'GET').upper() + path = str(spec.get('path') or '').strip() + url = endpoint.rstrip('/') + '/' + path.lstrip('/') + headers = {**(config.get('headers') or {}), **(request.get('headers') or {})} + timeout = int(config.get('timeout_seconds') or 60) + + response = self._http_request( + method, + url, + params=request.get('params'), + json=request.get('body'), + headers=headers, + timeout=timeout, + ) + if int(getattr(response, 'status_code', 0)) >= 400: + return { + 'status': 'business_failed', + 'code': f"HTTP_{int(response.status_code)}", + 'message': str(getattr(response, 'text', ''))[:500], + } + try: + return response.json() + except Exception: + return { + 'status': 'technical_failed', + 'code': 'NON_JSON', + 'message': str(getattr(response, 'text', ''))[:500], + } diff --git a/backend/app/services/integration_connector/transports/soap.py b/backend/app/services/integration_connector/transports/soap.py new file mode 100644 index 00000000..3c14b73e --- /dev/null +++ b/backend/app/services/integration_connector/transports/soap.py @@ -0,0 +1,28 @@ +"""services/integration_connector/transports/soap.py + +用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。 +依赖:zeep(延时导入);errors.py。 +逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.integration_connector.errors import TransportNotFrozenError + + +class SoapTransport: + """SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。""" + + connector_type = 'soap' + + def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: + config = client.get('config_json') or {} + endpoint = str(config.get('endpoint') or '').strip() + wsdl = str(config.get('wsdl') or '').strip() + if not endpoint or not wsdl: + raise TransportNotFrozenError('SOAP contract not frozen (missing endpoint/wsdl)') + + # 真实 SOAP 调用(zeep.Client(action=...,构造请求体、解析响应))待 WSDL 冻结后落地。 + raise NotImplementedError('SOAP implementation pending frozen WSDL') diff --git a/backend/app/services/schedule/in_transit_receipt_file_job.py b/backend/app/services/schedule/in_transit_receipt_file_job.py new file mode 100644 index 00000000..48e17521 --- /dev/null +++ b/backend/app/services/schedule/in_transit_receipt_file_job.py @@ -0,0 +1,57 @@ +"""独立收料文件抓取排程(08:00)。 + +用途:为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。 +依赖:schedule.job_registry 的 ScheduleExecuteResult、transfer deps、file_preparation。 +逻辑:与 09:00 自动调拨解耦;自动调拨仍会调用统一文件准备服务,不假设本排程成功。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ScheduleRun, ScheduleTask +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.file_preparation import ensure_receipt_file_ready +from app.services.schedule.job_registry import ScheduleExecuteResult + + +def _wanted_sources(task: ScheduleTask) -> list[str]: + """提取结构化 source_codes;留空代表全部启用来源。""" + params = task.job_params if isinstance(task.job_params, dict) else {} + values = params.get("source_codes") or [] + if isinstance(values, str): + values = [values] + return [str(item).strip() for item in values if str(item).strip()] + + +def run_in_transit_receipt_file_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """08:00 收料文件抓取;按来源实例独立执行。""" + deps = transfer_deps.get_transfer_dependencies() + sources = _wanted_sources(task) or [] + business_date = str(business_date_now()) + total = success = failed = empty = 0 + results: list[dict[str, Any]] = [] + warnings: list[str] = [] + errors: list[str] = [] + for source_code in sources: + total += 1 + try: + prepared = ensure_receipt_file_ready( + source_code=source_code, + business_date=business_date, + repository=deps.file_repository, + rpa_trigger=deps.rpa_trigger, + ) + results.append({"source_code": source_code, "stage": prepared.stage}) + if prepared.stage == "file_ready": + success += 1 + elif prepared.stage == "waiting_rpa_callback": + empty += 1 + else: + failed += 1 + errors.append(f"{source_code}: {prepared.error_code or 'file_prep_failed'}") + except Exception as exc: # noqa: BLE001 —— 来源隔离 + failed += 1 + errors.append(f"{source_code}: {exc}") + return (total, success, failed, empty, results, warnings, errors) diff --git a/backend/app/services/schedule/in_transit_transfer_job.py b/backend/app/services/schedule/in_transit_transfer_job.py new file mode 100644 index 00000000..460540c3 --- /dev/null +++ b/backend/app/services/schedule/in_transit_transfer_job.py @@ -0,0 +1,59 @@ +"""自动调拨排程(09:00)。 + +用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。 +依赖:auto_transfer、transfer deps、ScheduleExecuteResult。 +逻辑:复用统一文件准备服务,不假设 08:00 排程成功;来源实例独立执行。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ScheduleRun, ScheduleTask +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.auto_transfer import run_auto_transfer +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.schedule.job_registry import ScheduleExecuteResult + + +def _task_params(task: ScheduleTask) -> dict[str, Any]: + return task.job_params if isinstance(task.job_params, dict) else {} + + +def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """09:00 自动调拨:恢复 + 预检 + 执行 + 通知。""" + params = _task_params(task) + source_codes = params.get("source_codes") or [] + if isinstance(source_codes, str): + source_codes = [source_codes] + recover_history = bool(params.get("recover_history", True)) + recipients = params.get("notify_user_ids") or [] + + deps = transfer_deps.get_transfer_dependencies() + outcome = run_auto_transfer( + business_date=str(business_date_now()), + deps=deps, + source_codes=[str(item).strip() for item in source_codes], + recover_history=recover_history, + sender=None, # 企微发送器在 deps/运维接线处注入(本期先记录阶段结果) + recipients=[str(item) for item in recipients], + ) + results: list[dict[str, Any]] = [] + errors: list[str] = list(outcome.errors) + if outcome.run_no: + results.append({ + "run_no": outcome.run_no, + "status": outcome.run_status, + "notification_status": outcome.notification_status, + }) + recovery = outcome.recovery + success = 1 if outcome.run_status in {"success", "partial_failed"} else 0 + return ( + success + recovery.recovered_count, + success, + recovery.still_blocked_count, + 0, + results, + [f"recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}"], + errors, + ) diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index becd2776..187fbce1 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -141,6 +141,8 @@ def _register_builtin_platform_jobs() -> None: ) from app.services.schedule.voucher_check_job import run_voucher_check_schedule from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES + from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule + from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule register_platform_job(PlatformJobDefinition( key="shipping-order-extraction-progress-cleanup", @@ -366,6 +368,67 @@ def _register_builtin_platform_jobs() -> None: ), defaults=dict(DEFAULT_JOB_PARAMS), )) + register_platform_job(PlatformJobDefinition( + key="in-transit-receipt-file", + label="在途收料文件抓取", + handler=run_in_transit_receipt_file_schedule, + description=( + "每日 08:00 为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。" + "09:00 自动调拨仍会调用统一文件准备服务,不假设本排程成功。" + ), + category="platform", + params_schema=( + { + "key": "source_codes", + "type": "multi_select", + "label": "来源实例", + "label_key": "admin.schedule.form.transferSourceCodes", + "required": False, + "default": [], + "options_source": "shipping_inventory_sources", + }, + ), + defaults={"source_codes": []}, + )) + register_platform_job(PlatformJobDefinition( + key="in-transit-transfer", + label="在途自动调拨", + handler=run_in_transit_transfer_schedule, + description=( + "每日 09:00 自动处理新增可调拨项与历史可恢复异常;" + "每非空 Run 发送一条企微汇总通知;通知失败不改变 ERP 结果。" + ), + category="platform", + params_schema=( + { + "key": "source_codes", + "type": "multi_select", + "label": "来源实例", + "label_key": "admin.schedule.form.transferSourceCodes", + "required": False, + "default": [], + "options_source": "shipping_inventory_sources", + }, + { + "key": "recover_history", + "type": "boolean", + "label": "历史可恢复异常复核", + "label_key": "admin.schedule.form.transferRecoverHistory", + "required": False, + "default": True, + }, + { + "key": "notify_user_ids", + "type": "multi_select", + "label": "通知人", + "label_key": "admin.schedule.form.transferNotifyUsers", + "required": False, + "default": [], + "options_source": "users", + }, + ), + defaults={"source_codes": [], "recover_history": True, "notify_user_ids": []}, + )) _register_builtin_platform_jobs() diff --git a/backend/app/services/shipping_notice/inventory_parsing_profile.py b/backend/app/services/shipping_notice/inventory_parsing_profile.py index c7124551..f36fe1ca 100644 --- a/backend/app/services/shipping_notice/inventory_parsing_profile.py +++ b/backend/app/services/shipping_notice/inventory_parsing_profile.py @@ -56,8 +56,37 @@ def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> se return match_ids | quantity_ids -def _validate_definition(raw: Any) -> dict[str, Any]: - """校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。""" +# 异动(movement)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。 +def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]: + """校验 movement 用途的解析定义只引用定死领域字段,且必需字段齐全。""" + from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS + + movement_codes = {field.code for field in MOVEMENT_FIELDS} + mapping = definition.get('field_mapping') or {} + mapped_codes = {str(code) for code in mapping.keys() if str(code).strip()} + unknown = mapped_codes - movement_codes + if unknown: + raise ValidationError( + f'Movement parsing profile references unknown field: {sorted(unknown)}', + code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + ) + missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes} + if missing: + raise ValidationError( + f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}', + code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + ) + return mapped_codes + + +def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, Any]: + """校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。 + + Args: + raw: 解析定义对象。 + purpose: 'inventory'(沿用库存字段目录与 match_keys)或 + 'movement'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。 + """ if not isinstance(raw, dict): raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') field_mapping = raw.get('field_mapping') @@ -65,6 +94,19 @@ def _validate_definition(raw: Any) -> dict[str, Any]: raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') if any(not str(value or '').strip() for value in field_mapping.values()): raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + header_row_index = raw.get('header_row_index') + if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1): + raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + + if purpose == 'movement': + _required_movement_field_ids(raw) + return { + 'sheet_name': str(raw.get('sheet_name') or '').strip() or None, + 'header_row_index': header_row_index, + 'field_mapping': {str(key).strip(): str(value).strip() for key, value in field_mapping.items()}, + 'match_keys': [], + } + catalog_fields = _catalog_fields(field_mapping) _required_catalog_field_ids(catalog_fields) match_keys = raw.get('match_keys') @@ -87,9 +129,6 @@ def _validate_definition(raw: Any) -> dict[str, Any]: seen_order_fields.add(field.id) seen_inventory_fields.add(inventory_field) normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field}) - header_row_index = raw.get('header_row_index') - if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1): - raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') return { 'sheet_name': str(raw.get('sheet_name') or '').strip() or None, 'header_row_index': header_row_index, @@ -151,7 +190,7 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]: sample_analysis = profile.sample_analysis return { 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, - 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format, + 'purpose': profile.purpose, 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format, 'definition': profile.definition_json or {}, 'checksum': profile.checksum, 'published_at': profile.published_at.isoformat() if profile.published_at else None, 'source_count': len(profile.sources), @@ -193,6 +232,15 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1 profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id) db.session.add(profile) + purpose = str(data.get('purpose') or profile.purpose or 'inventory').strip().lower() + if purpose not in {'inventory', 'movement'}: + raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + if profile_id and purpose != profile.purpose: + raise ValidationError( + 'Draft parsing profile purpose is immutable', + code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + ) + profile.purpose = purpose profile.display_name = str(data.get('display_name') or code).strip() requested_file_format = str(data.get('file_format') or 'xlsx').lower() if requested_file_format not in {'xls', 'xlsx', 'csv'}: @@ -203,7 +251,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', ) profile.file_format = requested_file_format - definition = _validate_definition(data.get('definition')) + definition = _validate_definition(data.get('definition'), purpose=purpose) if profile.file_format == 'csv' and definition.get('sheet_name'): raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') sample_analysis = _require_sample_evidence( diff --git a/backend/migrations/versions/ic1a2b3c4d5f_add_integration_connector.py b/backend/migrations/versions/ic1a2b3c4d5f_add_integration_connector.py new file mode 100644 index 00000000..e0b15aa8 --- /dev/null +++ b/backend/migrations/versions/ic1a2b3c4d5f_add_integration_connector.py @@ -0,0 +1,157 @@ +"""add integration connector tables + +Revision ID: ic1a2b3c4d5f +Revises: it1a2b3c4d5e +Create Date: 2026-08-27 21:00:00.000000 + +用途:Integration Connector(外部系统连接器框架)P1 配置与运行模型建表: + CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。 +依赖:integration_* 全部新表;不依赖既有 shipping/transfer 表。 +逻辑:配置层实体维护版本与状态;IntegrationCall 记录一次技术调用(冻结绑定版本 + 脱敏摘要)。 + 连接器类型(rest/soap)与状态用 CheckConstraint 兜底;fail-closed 语义在服务层。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'ic1a2b3c4d5f' +down_revision = 'it1a2b3c4d5e' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建 5 张连接器框架表(先建凭据/客户端,再建接口/绑定,最后调用记录)。""" + op.create_table( + 'integration_credential_references', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('code', sa.String(length=64), nullable=False), + sa.Column('secret_ref', sa.String(length=128), nullable=False), + sa.Column('secret_provider', sa.String(length=32), nullable=False, server_default='env'), + sa.Column('credential_type', sa.String(length=32), nullable=False, server_default='password'), + sa.Column('version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('status', sa.String(length=16), nullable=False, server_default='active'), + sa.Column('last_verified_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('code', name='uq_integration_credential_references_code'), + sa.CheckConstraint( + "status IN ('active', 'rotating', 'retired')", + name='ck_integration_credential_references_status', + ), + ) + + op.create_table( + 'integration_client_instances', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('code', sa.String(length=64), nullable=False), + sa.Column('name', sa.String(length=128), nullable=False), + sa.Column('connector_type', sa.String(length=16), nullable=False), + sa.Column('environment', sa.String(length=16), nullable=False, server_default='prod'), + sa.Column('config_json', sa.JSON(), nullable=False), + sa.Column('credential_ref_code', sa.String(length=64), sa.ForeignKey('integration_credential_references.code'), nullable=True), + sa.Column('enabled', sa.Boolean(), nullable=False, server_default='true'), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('code', name='uq_integration_client_instances_code'), + sa.CheckConstraint( + "connector_type IN ('rest', 'soap')", + name='ck_integration_client_instances_connector_type', + ), + ) + op.create_index( + 'ix_integration_client_instances_type_env', + 'integration_client_instances', ['connector_type', 'environment'], + ) + + op.create_table( + 'integration_interface_definitions', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('code', sa.String(length=64), nullable=False), + sa.Column('name', sa.String(length=128), nullable=False), + sa.Column('client_instance_code', sa.String(length=64), sa.ForeignKey('integration_client_instances.code'), nullable=False), + sa.Column('connector_type', sa.String(length=16), nullable=False), + sa.Column('request_spec_json', sa.JSON(), nullable=False), + sa.Column('input_schema_json', sa.JSON(), nullable=False), + sa.Column('response_mapping_json', sa.JSON(), nullable=False), + sa.Column('output_schema_json', sa.JSON(), nullable=False), + sa.Column('version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'), + sa.Column('enabled', sa.Boolean(), nullable=False, server_default='true'), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('code', name='uq_integration_interface_definitions_code'), + sa.CheckConstraint( + "connector_type IN ('rest', 'soap')", + name='ck_integration_interface_definitions_connector_type', + ), + sa.CheckConstraint( + "status IN ('draft', 'published', 'retired')", + name='ck_integration_interface_definitions_status', + ), + ) + op.create_index( + 'ix_integration_interface_definitions_client', + 'integration_interface_definitions', ['client_instance_code'], + ) + + op.create_table( + 'integration_bindings', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('capability', sa.String(length=128), nullable=False), + sa.Column('context_selector_json', sa.JSON().with_variant(sa.dialects.postgresql.JSONB(), 'postgresql'), nullable=False), + sa.Column('client_instance_code', sa.String(length=64), sa.ForeignKey('integration_client_instances.code'), nullable=False), + sa.Column('interface_definition_code', sa.String(length=64), sa.ForeignKey('integration_interface_definitions.code'), nullable=False), + sa.Column('mapping_version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('priority', sa.Integer(), nullable=False, server_default='0'), + sa.Column('environment', sa.String(length=16), nullable=False, server_default='prod'), + sa.Column('effective_from', sa.DateTime(), nullable=True), + sa.Column('effective_to', sa.DateTime(), nullable=True), + sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint( + 'capability', 'environment', 'context_selector_json', name='uq_integration_bindings_cap_env_ctx', + ), + sa.CheckConstraint( + "status IN ('draft', 'published', 'retired')", + name='ck_integration_bindings_status', + ), + sa.CheckConstraint('priority >= 0', name='ck_integration_bindings_priority'), + ) + op.create_index( + 'ix_integration_bindings_cap_env_status', + 'integration_bindings', ['capability', 'environment', 'status'], + ) + + op.create_table( + 'integration_calls', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('operation_id', sa.String(length=128), nullable=False), + sa.Column('capability', sa.String(length=128), nullable=False), + sa.Column('binding_snapshot_json', sa.JSON(), nullable=False), + sa.Column('request_summary_json', sa.JSON(), nullable=False), + sa.Column('response_summary_json', sa.JSON(), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False), + sa.Column('elapsed_ms', sa.Integer(), nullable=False, server_default='0'), + sa.Column('trace_id', sa.String(length=64), nullable=False, server_default=''), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'), + ) + op.create_index('ix_integration_calls_capability_created', 'integration_calls', ['capability', 'created_at']) + op.create_index('ix_integration_calls_trace_id', 'integration_calls', ['trace_id']) + + +def downgrade() -> None: + """回滚:按外键依赖逆序删除连接器表。""" + op.drop_index('ix_integration_calls_trace_id', table_name='integration_calls') + op.drop_index('ix_integration_calls_capability_created', table_name='integration_calls') + op.drop_table('integration_calls') + op.drop_index('ix_integration_bindings_cap_env_status', table_name='integration_bindings') + op.drop_table('integration_bindings') + op.drop_index('ix_integration_interface_definitions_client', table_name='integration_interface_definitions') + op.drop_table('integration_interface_definitions') + op.drop_index('ix_integration_client_instances_type_env', table_name='integration_client_instances') + op.drop_table('integration_client_instances') + op.drop_table('integration_credential_references') diff --git a/backend/migrations/versions/if1b2c3d4e5g_add_purpose_to_inventory_parsing_profiles.py b/backend/migrations/versions/if1b2c3d4e5g_add_purpose_to_inventory_parsing_profiles.py new file mode 100644 index 00000000..1eb84658 --- /dev/null +++ b/backend/migrations/versions/if1b2c3d4e5g_add_purpose_to_inventory_parsing_profiles.py @@ -0,0 +1,45 @@ +"""add purpose to inventory parsing profiles + +Revision ID: if1b2c3d4e5g +Revises: ic1a2b3c4d5f +Create Date: 2026-08-28 10:30:00.000000 + +用途:把库存解析规则泛化为通用文件解析规则——为 shipping_inventory_parsing_profiles + 增 purpose 列(inventory / movement)。inventory 沿用库存字段目录;movement + 端点用定死领域字段(MOVEMENT_FIELDS),供收料/异动文件映射。既有行默认 inventory, + 不改变既有库存语义。 +依赖:shipping_inventory_parsing_profiles 表。 +逻辑:仅加列 + CheckConstraint,无数据回填(默认 inventory)。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'if1b2c3d4e5g' +down_revision = 'ic1a2b3c4d5f' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增 purpose 列并加 CheckConstraint(inventory / movement)。""" + op.add_column( + 'shipping_inventory_parsing_profiles', + sa.Column('purpose', sa.String(length=16), nullable=False, server_default='inventory'), + ) + op.create_check_constraint( + 'ck_shipping_inventory_parsing_profiles_purpose', + 'shipping_inventory_parsing_profiles', + "purpose IN ('inventory', 'movement')", + ) + + +def downgrade() -> None: + """移除 purpose 约束与列。""" + op.drop_constraint( + 'ck_shipping_inventory_parsing_profiles_purpose', + 'shipping_inventory_parsing_profiles', + type_='check', + ) + op.drop_column('shipping_inventory_parsing_profiles', 'purpose') diff --git a/backend/migrations/versions/if1b2c3d4e5h_add_parsing_profile_id_to_receipt_configs.py b/backend/migrations/versions/if1b2c3d4e5h_add_parsing_profile_id_to_receipt_configs.py new file mode 100644 index 00000000..d8f09309 --- /dev/null +++ b/backend/migrations/versions/if1b2c3d4e5h_add_parsing_profile_id_to_receipt_configs.py @@ -0,0 +1,53 @@ +"""add parsing_profile_id to shipping_receipt_report_configs + +Revision ID: if1b2c3d4e5h +Revises: if1b2c3d4e5g +Create Date: 2026-08-28 10:45:00.000000 + +用途:收料报表配置绑定其收料文件解析规则(purpose='movement')。空则无法解析收料文件。 +依赖:shipping_receipt_report_configs 表 + shipping_inventory_parsing_profiles 表。 +逻辑:仅新增可空外键列,无数据回填。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'if1b2c3d4e5h' +down_revision = 'if1b2c3d4e5g' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增 parsing_profile_id 外键列。""" + op.add_column( + 'shipping_receipt_report_configs', + sa.Column('parsing_profile_id', sa.Integer(), nullable=True), + ) + op.create_index( + 'ix_shipping_receipt_report_configs_parsing_profile', + 'shipping_receipt_report_configs', + ['parsing_profile_id'], + ) + op.create_foreign_key( + 'fk_shipping_receipt_report_configs_parsing_profile', + 'shipping_receipt_report_configs', + 'shipping_inventory_parsing_profiles', + ['parsing_profile_id'], + ['id'], + ) + + +def downgrade() -> None: + """移除外键、索引与列。""" + op.drop_constraint( + 'fk_shipping_receipt_report_configs_parsing_profile', + 'shipping_receipt_report_configs', + type_='foreignkey', + ) + op.drop_index( + 'ix_shipping_receipt_report_configs_parsing_profile', + table_name='shipping_receipt_report_configs', + ) + op.drop_column('shipping_receipt_report_configs', 'parsing_profile_id') diff --git a/backend/migrations/versions/if1b2c3d4e5i_add_file_ready_to_source_jobs_status.py b/backend/migrations/versions/if1b2c3d4e5i_add_file_ready_to_source_jobs_status.py new file mode 100644 index 00000000..37bcb33f --- /dev/null +++ b/backend/migrations/versions/if1b2c3d4e5i_add_file_ready_to_source_jobs_status.py @@ -0,0 +1,42 @@ +"""add file_ready to transfer_source_jobs status constraint + +Revision ID: if1b2c3d4e5i +Revises: if1b2c3d4e5h +Create Date: 2026-08-28 11:15:00.000000 + +用途:让 TransferSourceJob.status 状态集与来源准备流程阶段(file_ready)对齐。 + 原 CHECK 缺少 file_ready,导致来源文件就绪时 job 无法用 file_ready 表达 + (create_precheck 只能硬映射为 pending)。 +依赖:transfer_source_jobs 表。 +逻辑:drop 旧 CHECK → 重新 create(追加 file_ready),无数据回填。 +""" + +from alembic import op + + +revision = 'if1b2c3d4e5i' +down_revision = 'if1b2c3d4e5h' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """更新 status 检查约束,允许 file_ready。""" + op.drop_constraint('ck_transfer_source_jobs_status', 'transfer_source_jobs', type_='check') + op.create_check_constraint( + 'ck_transfer_source_jobs_status', + 'transfer_source_jobs', + "status IN ('pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', " + "'parsing', 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')", + ) + + +def downgrade() -> None: + """恢复原检查约束(不含 file_ready)。""" + op.drop_constraint('ck_transfer_source_jobs_status', 'transfer_source_jobs', type_='check') + op.create_check_constraint( + 'ck_transfer_source_jobs_status', + 'transfer_source_jobs', + "status IN ('pending', 'checking_file', 'waiting_rpa_callback', 'parsing', " + "'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')", + ) diff --git a/backend/migrations/versions/it1a2b3c4d5e_add_in_transit_transfer.py b/backend/migrations/versions/it1a2b3c4d5e_add_in_transit_transfer.py new file mode 100644 index 00000000..52ab6f28 --- /dev/null +++ b/backend/migrations/versions/it1a2b3c4d5e_add_in_transit_transfer.py @@ -0,0 +1,275 @@ +"""add in-transit transfer domain tables + +Revision ID: it1a2b3c4d5e +Revises: hw6x7y8z9a0b +Create Date: 2026-08-27 14:00:00.000000 + +用途:在途仓自动调拨 Agent 一期领域模型建表:Run、SourceJob、Precheck、 + InvoiceItem、Attempt、AuditEvent 与 Archive。 +依赖:transfer_* 全部新表;不依赖既有 shipping 表(来源配置在服务层只读复用)。 +逻辑:Run 为业务真相源;InvoiceItem 按 (precheck_id, invoice_no) 唯一; + AuditEvent 只追加;Archive 记录 MinIO 对象路径与 Hash。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'it1a2b3c4d5e' +down_revision = 'hw6x7y8z9a0b' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建 7 张调拨领域表。""" + op.create_table( + 'transfer_runs', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('run_no', sa.String(length=64), nullable=False), + sa.Column('trigger_type', sa.String(length=16), nullable=False, server_default='manual'), + sa.Column('business_date', sa.String(length=16), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'), + sa.Column('source_codes_json', sa.JSON(), nullable=False), + sa.Column('counts_json', sa.JSON(), nullable=False), + sa.Column('result_summary_json', sa.JSON(), nullable=False), + sa.Column('notification_status', sa.String(length=16), nullable=False, server_default='pending'), + sa.Column('notification_error_code', sa.String(length=64), nullable=True), + sa.Column('notification_error_message', sa.Text(), nullable=True), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('run_no', name='uq_transfer_runs_run_no'), + sa.CheckConstraint( + "status IN ('queued', 'preparing_files', 'prechecking', 'ready_to_execute', " + "'executing', 'success', 'partial_failed', 'failed', 'cancelled')", + name='ck_transfer_runs_status', + ), + sa.CheckConstraint( + "notification_status IN ('pending', 'success', 'failed')", + name='ck_transfer_runs_notification_status', + ), + sa.CheckConstraint( + "trigger_type IN ('manual', 'schedule')", + name='ck_transfer_runs_trigger_type', + ), + ) + op.create_index('ix_transfer_runs_status_created', 'transfer_runs', ['status', 'created_at']) + op.create_index('ix_transfer_runs_business_date', 'transfer_runs', ['business_date']) + + op.create_table( + 'transfer_source_jobs', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=False), + sa.Column('source_code', sa.String(length=64), nullable=False), + sa.Column('source_config_version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'), + sa.Column('file_no', sa.String(length=64), nullable=True), + sa.Column('file_sha256', sa.String(length=64), nullable=True), + sa.Column('error_code', sa.String(length=64), nullable=True), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('lease_until', sa.DateTime(), nullable=True), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('run_id', 'source_code', name='uq_transfer_source_jobs_run_source'), + sa.CheckConstraint( + "status IN ('pending', 'checking_file', 'waiting_rpa_callback', 'parsing', " + "'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled')", + name='ck_transfer_source_jobs_status', + ), + ) + op.create_index('ix_transfer_source_jobs_source_status', 'transfer_source_jobs', ['source_code', 'status']) + + op.create_table( + 'transfer_prechecks', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('precheck_no', sa.String(length=64), nullable=False), + sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=True), + sa.Column('business_date', sa.String(length=16), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='prechecking'), + sa.Column('scope_json', sa.JSON(), nullable=False), + sa.Column('file_snapshot_json', sa.JSON(), nullable=False), + sa.Column('mapping_version', sa.String(length=64), nullable=True), + sa.Column('strategy_version', sa.String(length=64), nullable=True), + sa.Column('counts_json', sa.JSON(), nullable=False), + sa.Column('estimated_transfer_quantity', sa.String(length=40), nullable=True), + sa.Column('estimated_erp_write_count', sa.Integer(), nullable=False, server_default='0'), + sa.Column('precheck_hash', sa.String(length=128), nullable=False), + sa.Column('expires_at', sa.DateTime(), nullable=True), + sa.Column('confirmed_at', sa.DateTime(), nullable=True), + sa.Column('confirmed_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'), + sa.CheckConstraint( + "status IN ('file_pending', 'file_ready', 'prechecking', 'ready_to_execute', " + "'executing', 'success', 'failed', 'cancelled', 'expired')", + name='ck_transfer_prechecks_status', + ), + ) + op.create_index('ix_transfer_prechecks_run_status', 'transfer_prechecks', ['run_id', 'status']) + op.create_index('ix_transfer_prechecks_business_date', 'transfer_prechecks', ['business_date']) + + op.create_table( + 'transfer_invoice_items', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('precheck_id', sa.Integer(), sa.ForeignKey('transfer_prechecks.id'), nullable=False), + sa.Column('run_id', sa.Integer(), sa.ForeignKey('transfer_runs.id'), nullable=True), + sa.Column('source_code', sa.String(length=64), nullable=False), + sa.Column('invoice_no', sa.String(length=64), nullable=False), + sa.Column('material_no', sa.String(length=64), nullable=False), + sa.Column('material_name', sa.String(length=200), nullable=False, server_default=''), + sa.Column('specification', sa.String(length=200), nullable=False, server_default=''), + sa.Column('receipt_date', sa.String(length=16), nullable=True), + sa.Column('from_warehouse', sa.String(length=64), nullable=False), + sa.Column('to_warehouse', sa.String(length=64), nullable=False), + sa.Column('receipt_quantity', sa.String(length=40), nullable=False), + sa.Column('erp_quantity', sa.String(length=40), nullable=True), + sa.Column('status', sa.String(length=32), nullable=False), + sa.Column('result_code', sa.String(length=64), nullable=True), + sa.Column('result_message', sa.Text(), nullable=True), + sa.Column('erp_document_no', sa.String(length=64), nullable=True), + sa.Column('raw_lines_json', sa.JSON(), nullable=False), + sa.Column('attempt_no', sa.Integer(), nullable=False, server_default='0'), + sa.Column('manually_closed_reason', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'), + sa.CheckConstraint( + "status IN ('file_pending', 'file_ready', 'prechecking', 'ready_to_execute', " + "'executing', 'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', " + "'result_unknown', 'manually_closed', 'cancelled', 'notification_failed')", + name='ck_transfer_invoice_items_status', + ), + ) + op.create_index( + 'ix_transfer_invoice_items_source_invoice_status', + 'transfer_invoice_items', ['source_code', 'invoice_no', 'status'], + ) + op.create_index('ix_transfer_invoice_items_run_id', 'transfer_invoice_items', ['run_id']) + op.create_index('ix_transfer_invoice_items_erp_document_no', 'transfer_invoice_items', ['erp_document_no']) + + op.create_table( + 'transfer_attempts', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('item_id', sa.Integer(), sa.ForeignKey('transfer_invoice_items.id'), nullable=False), + sa.Column('attempt_no', sa.Integer(), nullable=False), + sa.Column('kind', sa.String(length=16), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'), + sa.Column('request_snapshot_json', sa.JSON(), nullable=False), + sa.Column('response_summary_json', sa.JSON(), nullable=False), + sa.Column('operation_id', sa.String(length=128), nullable=True), + sa.Column('error_code', sa.String(length=64), nullable=True), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('item_id', 'attempt_no', name='uq_transfer_attempts_item_no'), + sa.CheckConstraint( + "kind IN ('precheck', 'rpa', 'erp_query', 'erp_write')", + name='ck_transfer_attempts_kind', + ), + sa.CheckConstraint( + "status IN ('queued', 'running', 'waiting_external', 'success', 'failed', " + "'result_unknown', 'superseded')", + name='ck_transfer_attempts_status', + ), + ) + op.create_index('ix_transfer_attempts_item_created', 'transfer_attempts', ['item_id', 'created_at']) + + op.create_table( + 'transfer_audit_events', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('event_type', sa.String(length=64), nullable=False), + sa.Column('aggregate_type', sa.String(length=64), nullable=False), + sa.Column('aggregate_id', sa.String(length=128), nullable=False), + sa.Column('run_no', sa.String(length=64), nullable=True), + sa.Column('precheck_no', sa.String(length=64), nullable=True), + sa.Column('invoice_no', sa.String(length=64), nullable=True), + sa.Column('item_id', sa.String(length=64), nullable=True), + sa.Column('attempt_no', sa.Integer(), nullable=True), + sa.Column('actor_type', sa.String(length=16), nullable=False, server_default='system'), + sa.Column('actor_id', sa.String(length=128), nullable=True), + sa.Column('actor_role', sa.String(length=64), nullable=True), + sa.Column('actor_display', sa.String(length=128), nullable=True), + sa.Column('request_id', sa.String(length=64), nullable=True), + sa.Column('operation_id', sa.String(length=64), nullable=True), + sa.Column('source', sa.String(length=32), nullable=True), + sa.Column('result', sa.String(length=16), nullable=True), + sa.Column('error_code', sa.String(length=64), nullable=True), + sa.Column('before_json', sa.JSON(), nullable=False), + sa.Column('after_json', sa.JSON(), nullable=False), + sa.Column('diff_json', sa.JSON(), nullable=False), + sa.Column('before_hash', sa.String(length=64), nullable=True), + sa.Column('after_hash', sa.String(length=64), nullable=True), + sa.Column('event_hash', sa.String(length=64), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.CheckConstraint( + "actor_type IN ('user', 'system', 'worker', 'admin', 'rpa', 'schedule')", + name='ck_transfer_audit_events_actor_type', + ), + sa.CheckConstraint( + "result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')", + name='ck_transfer_audit_events_result', + ), + ) + op.create_index( + 'ix_transfer_audit_events_aggregate_created', + 'transfer_audit_events', ['aggregate_type', 'aggregate_id', 'created_at'], + ) + op.create_index('ix_transfer_audit_events_run_created', 'transfer_audit_events', ['run_no', 'created_at']) + op.create_index('ix_transfer_audit_events_invoice_created', 'transfer_audit_events', ['invoice_no', 'created_at']) + op.create_index('ix_transfer_audit_events_operation_created', 'transfer_audit_events', ['operation_id', 'created_at']) + op.create_index('ix_transfer_audit_events_event_hash', 'transfer_audit_events', ['event_hash']) + + op.create_table( + 'transfer_archives', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('archive_no', sa.String(length=64), nullable=False), + sa.Column('object_type', sa.String(length=64), nullable=False), + sa.Column('object_id', sa.String(length=128), nullable=False), + sa.Column('storage_provider', sa.String(length=32), nullable=False), + sa.Column('storage_bucket', sa.String(length=128), nullable=False), + sa.Column('storage_key', sa.String(length=1024), nullable=False), + sa.Column('original_filename', sa.String(length=255), nullable=False), + sa.Column('content_type', sa.String(length=128), nullable=True), + sa.Column('file_size', sa.Integer(), nullable=False), + sa.Column('sha256', sa.String(length=64), nullable=False), + sa.Column('archive_expires_at', sa.DateTime(), nullable=True), + sa.Column('archive_deleted_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('archive_no', name='uq_transfer_archives_archive_no'), + sa.UniqueConstraint('object_type', 'object_id', 'sha256', name='uq_transfer_archives_object_sha'), + sa.CheckConstraint('file_size >= 0', name='ck_transfer_archives_file_size'), + ) + op.create_index('ix_transfer_archives_object', 'transfer_archives', ['object_type', 'object_id']) + + +def downgrade() -> None: + """回滚:按外键依赖逆序删除调拨表。""" + op.drop_index('ix_transfer_archives_object', table_name='transfer_archives') + op.drop_table('transfer_archives') + op.drop_index('ix_transfer_audit_events_event_hash', table_name='transfer_audit_events') + op.drop_index('ix_transfer_audit_events_operation_created', table_name='transfer_audit_events') + op.drop_index('ix_transfer_audit_events_invoice_created', table_name='transfer_audit_events') + op.drop_index('ix_transfer_audit_events_run_created', table_name='transfer_audit_events') + op.drop_index('ix_transfer_audit_events_aggregate_created', table_name='transfer_audit_events') + op.drop_table('transfer_audit_events') + op.drop_index('ix_transfer_attempts_item_created', table_name='transfer_attempts') + op.drop_table('transfer_attempts') + op.drop_index('ix_transfer_invoice_items_erp_document_no', table_name='transfer_invoice_items') + op.drop_index('ix_transfer_invoice_items_run_id', table_name='transfer_invoice_items') + op.drop_index('ix_transfer_invoice_items_source_invoice_status', table_name='transfer_invoice_items') + op.drop_table('transfer_invoice_items') + op.drop_index('ix_transfer_prechecks_business_date', table_name='transfer_prechecks') + op.drop_index('ix_transfer_prechecks_run_status', table_name='transfer_prechecks') + op.drop_table('transfer_prechecks') + op.drop_index('ix_transfer_source_jobs_source_status', table_name='transfer_source_jobs') + op.drop_table('transfer_source_jobs') + op.drop_index('ix_transfer_runs_business_date', table_name='transfer_runs') + op.drop_index('ix_transfer_runs_status_created', table_name='transfer_runs') + op.drop_table('transfer_runs') diff --git a/backend/tests/api/test_in_transit_transfer_api.py b/backend/tests/api/test_in_transit_transfer_api.py new file mode 100644 index 00000000..3bf190ef --- /dev/null +++ b/backend/tests/api/test_in_transit_transfer_api.py @@ -0,0 +1,448 @@ +"""在途调拨预检 API 契约测试(L2,Flask test client)。 + +用途:验证 POST /prechecks 创建(含 envelope/权限/参数校验)与 + GET /prechecks/{id} 进度恢复;无权限 403、未认证 401。 +依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。 +逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或 + in_transit_transfer Agent 授权校验。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.auth.jwt import issue_local_access_token +from app.models import Agent, User +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + +API_PREFIX = "/api/in-transit-transfer" + + +def _jwt_headers(user: User) -> dict: + """为指定用户签发 Bearer JWT 请求头。""" + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def transfer_deps(monkeypatch, dbs_ready_file): + """注入 Fake 预检依赖,并预置可执行库存。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + return deps + + +@pytest.fixture +def admin_headers(app): + """创建 admin 用户并返回 JWT 请求头(token 在 app context 内签发)。""" + with app.app_context(): + user = db.session.query(User).filter_by(username="admin").first() + if not user: + user = User(username="admin", email="admin@example.com", role="admin", status="active") + user.set_password("admin") + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def warehouse_headers(app): + """创建持有 in_transit_transfer Agent 权限的仓库管理员并返回 JWT 请求头。""" + with app.app_context(): + agent = Agent.query.filter_by(agent_code="in_transit_transfer").first() + if not agent: + agent = Agent(name="在途仓调拨", agent_code="in_transit_transfer", + type="api", is_active=True) + db.session.add(agent) + db.session.flush() + user = db.session.query(User).filter_by(username="warehouse").first() + if not user: + user = User(username="warehouse", email="warehouse@example.com", + role="user", status="active") + user.set_password("x") + db.session.add(user) + db.session.flush() + if agent not in user.agents: + user.agents.append(agent) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def unauthorized_headers(app): + """无 Agent 权限的普通用户 JWT 请求头。""" + with app.app_context(): + user = db.session.query(User).filter_by(username="no_perm").first() + if not user: + user = User(username="no_perm", email="no_perm@example.com", role="user", status="active") + user.set_password("x") + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_headers, transfer_deps): + """POST /prechecks → 201 envelope,data 含 precheck_id/hash/计数。""" + response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }) + assert response.status_code == 201 + body = response.get_json() + assert body["success"] is True + data = body["data"] + assert data["precheck_id"].startswith("TPC-") + assert data["precheck_hash"].startswith("sha256:") + assert data["estimated_erp_write_count"] == 2 + assert body.get("request_id") + + +def test_create_precheck_requires_authentication(client): + """未认证 → 401(envelope error)。""" + response = client.post(f"{API_PREFIX}/prechecks", json={"source_codes": ["DBS-AWSBI"]}) + assert response.status_code == 401 + assert response.get_json()["success"] is False + + +def test_create_precheck_forbidden_without_agent_permission(client, unauthorized_headers): + """无 in_transit_transfer Agent 权限 → 403。""" + response = client.post(f"{API_PREFIX}/prechecks", headers=unauthorized_headers, json={ + "source_codes": ["DBS-AWSBI"], + }) + assert response.status_code == 403 + assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN" + + +def test_create_precheck_warehouse_manager_allowed(app, client, warehouse_headers, transfer_deps): + """持有 Agent 权限的仓库管理员可创建预检。""" + response = client.post(f"{API_PREFIX}/prechecks", headers=warehouse_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }) + assert response.status_code == 201 + assert response.get_json()["data"]["precheck_id"] + + +def test_create_precheck_validates_source_codes(app, client, admin_headers, transfer_deps): + """缺少 source_codes → 400 参数错误。""" + response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={"business_date": "2026-08-06"}) + assert response.status_code == 400 + assert response.get_json()["success"] is False + + +def test_restore_precheck_progress(app, client, admin_headers, transfer_deps): + """GET /prechecks/{id} 恢复预检进度(Hash/明细一致)。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + restored = client.get(f"{API_PREFIX}/prechecks/{created['precheck_id']}", headers=admin_headers) + assert restored.status_code == 200 + body = restored.get_json()["data"] + assert body["summary"]["precheck_hash"] == created["precheck_hash"] + assert {item["invoice_no"] for item in body["items"]} == {"INV-001", "INV-002"} + + +def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps): + """未知 precheck → 404。""" + response = client.get(f"{API_PREFIX}/prechecks/TPC-NOT-EXIST", headers=admin_headers) + assert response.status_code == 404 + + +def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps): + """执行预检 → 201 run_no;GET run 返回 ERP 单号聚合结果。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + assert executed.status_code == 201 + run_no = executed.get_json()["data"]["run_no"] + assert run_no.startswith("RUN-") + + run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers) + assert run.status_code == 200 + result = run.get_json()["data"]["result"] + assert len(result["erp_documents"]) == 2 + assert result["exceptions"] == [] + + +def test_execute_unconfirmed_precheck_rejected(app, client, admin_headers, transfer_deps): + """预检未就绪时执行 → 400 领域错误,不产生 Run。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + with app.app_context(): + from app.models import TransferPrecheck + + precheck = TransferPrecheck.query.filter_by(precheck_no=created["precheck_id"]).first() + precheck.status = "prechecking" + db.session.commit() + response = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001"]}, + ) + assert response.status_code == 400 + assert response.get_json()["error"]["code"] == "TRANSFER_CONFIRMATION_REQUIRED" + + +def test_cancel_run_requires_reason(app, client, admin_headers, transfer_deps): + """取消缺少原因 → 400。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={}, + ) + run_no = executed.get_json()["data"]["run_no"] + response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={"reason": ""}) + assert response.status_code == 400 + + +def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transfer_deps): + """取消未开始项并保留成功单据。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + run_no = executed.get_json()["data"]["run_no"] + # 模拟执行中状态:Run 回退 executing,INV-002 尚未开始 + with app.app_context(): + from app.models import TransferInvoiceItem, TransferRun + + run = TransferRun.query.filter_by(run_no=run_no).first() + run.status = "executing" + item = TransferInvoiceItem.query.filter_by(run_id=run.id, invoice_no="INV-002").first() + item.status = "ready_to_execute" + item.erp_document_no = None + db.session.commit() + response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={ + "reason": "货源调整,停止剩余", + }) + assert response.status_code == 200 + assert response.get_json()["data"]["cancelled_count"] == 1 + + +def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_deps): + """人工关闭缺少原因 → 400。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + with app.app_context(): + from app.models import TransferInvoiceItem + + item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first() + item.status = "blocked_recoverable" + item.result_code = "blocked_quantity_mismatch" + db.session.commit() + item_id = item.id + response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={"reason": ""}) + assert response.status_code == 400 + + +def test_manual_close_item_success(app, client, admin_headers, transfer_deps): + """人工关闭成功 → 状态 manually_closed。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + with app.app_context(): + from app.models import TransferInvoiceItem + + item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first() + item.status = "blocked_recoverable" + item.result_code = "blocked_quantity_mismatch" + db.session.commit() + item_id = item.id + response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={ + "reason": "线下已处理", + }) + assert response.status_code == 200 + assert response.get_json()["data"]["status"] == "manually_closed" + + +def test_exceptions_excel_download(app, transfer_db, client, admin_headers, transfer_deps): + """下载异常 Excel → 200 xlsx,且记录访问审计。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + run_no = executed.get_json()["data"]["run_no"] + response = client.get(f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx", headers=admin_headers) + assert response.status_code == 200 + assert response.content_type.startswith("application/vnd.openxmlformats") + with app.app_context(): + from app.models import TransferAuditEvent + + audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EXCEL_DOWNLOADED").first() + assert audit is not None + assert audit.run_no == run_no + + +def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps): + """下载收料来源文件 → 200(zip),记录访问审计。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + run_no = executed.get_json()["data"]["run_no"] + response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers) + assert response.status_code == 200 + assert response.content_type.startswith("application/zip") + with app.app_context(): + from app.models import TransferAuditEvent + + audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED").first() + assert audit is not None + + +def test_erp_inventory_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps): + """下载预检冻结的 ERP 库存表 → 200(csv),记录访问审计。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]}, + ) + run_no = executed.get_json()["data"]["run_no"] + response = client.get(f"{API_PREFIX}/runs/{run_no}/erp-inventory", headers=admin_headers) + assert response.status_code == 200 + assert "csv" in response.content_type + assert b"INV-001" in response.data + with app.app_context(): + from app.models import TransferAuditEvent + + audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED").first() + assert audit is not None + + +def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_headers, unauthorized_headers, transfer_deps): + """无权限下载 → 403(越权检查)。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={}, + ) + run_no = executed.get_json()["data"]["run_no"] + for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files", + f"{API_PREFIX}/runs/{run_no}/erp-inventory", + f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"): + response = client.get(path, headers=unauthorized_headers) + assert response.status_code == 403, path + + +def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client, admin_headers, transfer_deps): + """前端伪造来源仓/目标仓/数量 → 服务端忽略,使用冻结快照值(防篡改)。""" + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + executed = client.post( + f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", + headers=admin_headers, json={ + "invoice_nos": ["INV-001"], + "from_warehouse": "FAKE-TRANSIT", + "to_warehouse": "FAKE-HUB", + "quantity": "1", + }, + ) + assert executed.status_code == 201 + run_no = executed.get_json()["data"]["run_no"] + run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers).get_json()["data"] + documents = run["result"]["erp_documents"] + assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非伪造值 + assert documents[0]["to_warehouse"] == "HUB-CN01" + assert documents[0]["total_quantity"] == "1200" + + +def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, transfer_deps): + """待处理异常列表/汇总 API:收纳 blocked 项、排除 success、含老化等级。""" + # 预检含 1 个数量不一致(blocked)项 + created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }).get_json()["data"] + with app.app_context(): + from app.models import TransferInvoiceItem + + item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first() + item.status = "blocked_recoverable" + item.result_code = "blocked_quantity_mismatch" + item.result_message = "收料 1200 / ERP 1000" + db.session.commit() + + listed = client.get(f"{API_PREFIX}/backlog", headers=admin_headers) + assert listed.status_code == 200 + invoice_set = {entry["invoice_no"] for entry in listed.get_json()["data"]} + assert "INV-001" in invoice_set + assert "INV-002" not in invoice_set # 可执行项不在待处理池 + assert listed.get_json()["data"][0]["aging_level"] in {"normal", "warn_3d", "escalate_5d", "critical_7d"} + + summary = client.get(f"{API_PREFIX}/backlog/summary", headers=admin_headers) + assert summary.status_code == 200 + assert summary.get_json()["data"]["recoverable"] >= 1 + + +def test_backlog_forbidden_without_permission(app, transfer_db, client, unauthorized_headers, transfer_deps): + """无权限访问待处理池 → 403(越权检查)。""" + response = client.get(f"{API_PREFIX}/backlog", headers=unauthorized_headers) + assert response.status_code == 403 + + +def test_list_transfer_sources(app, client, admin_headers): + """来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。""" + response = client.get(f"{API_PREFIX}/sources", headers=admin_headers) + assert response.status_code == 200 + sources = response.get_json()["data"] + assert isinstance(sources, list) + # 测试种子来源 DSV360_AWSDU(dbs)应在列表中 + assert any(item["source_code"] == "DSV360_AWSDU" for item in sources) + for item in sources: + assert item["source_code"] + assert item["platform"] in {"dbs", "crane"} + assert item["enabled"] is True + + +def test_list_transfer_sources_forbidden(app, client, unauthorized_headers): + """无权限查看来源实例 → 403。""" + response = client.get(f"{API_PREFIX}/sources", headers=unauthorized_headers) + assert response.status_code == 403 + + +def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps): + """运营指标端点:返回 Run/明细/待处理/通知失败结构。""" + response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers) + assert response.status_code == 200 + data = response.get_json()["data"] + assert "runs" in data and "items" in data and "backlog" in data + assert "notification_failed_runs" in data["runs"] diff --git a/backend/tests/api/test_integration_connector_api.py b/backend/tests/api/test_integration_connector_api.py new file mode 100644 index 00000000..18adf4e7 --- /dev/null +++ b/backend/tests/api/test_integration_connector_api.py @@ -0,0 +1,146 @@ +"""tests/api/test_integration_connector_api.py + +用途:Integration Connector Admin API 契约测试——能力清单、客户端 CRUD、能力调用、 + interface_id 拒绝、连接测试、鉴权(401/403)。依赖 Fake 网关注入。 +依赖:app fixture、client、issue_local_access_token、gateway 覆盖注入。 +逻辑:Admin API 全部 require_admin;能力调用只暴露 Capability,拒绝传 interface_id。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.auth.jwt import issue_local_access_token +from app.models import User +from app.services.integration_connector.transports.base import IntegrationCallResult +from app.services.integration_connector.gateway import set_capability_gateway + +API_PREFIX = "/api/integration-connector" + + +class FakeTransport: + connector_type = "rest" + + def call(self, *, client, interface, request): + return {"found": True, "quantity": "100"} + + +class _FakeGateway: + """纯替代网关:call 直接返回,不解析绑定;transports 供连接测试。""" + + def __init__(self): + self.transports = {"rest": FakeTransport()} + + def call(self, **kwargs): + return IntegrationCallResult(status="success", data={"found": True, "quantity": None}) + + +@pytest.fixture +def admin_headers(app): + with app.app_context(): + user = db.session.query(User).filter_by(username="admin").first() + if not user: + user = User(username="admin", email="admin@example.com", role="admin", status="active") + user.set_password("admin") + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def plain_headers(app): + with app.app_context(): + user = db.session.query(User).filter_by(username="plain").first() + if not user: + user = User(username="plain", email="plain@example.com", role="user", status="active") + user.set_password("x") + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +@pytest.fixture +def fake_gateway(): + gw = _FakeGateway() + set_capability_gateway(gw) + yield gw + set_capability_gateway(None) + + +def _params(): + return {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100} + + +def test_list_capabilities(app, client, admin_headers): + """GET /capabilities → 200,含 3 个在途调拨能力。""" + response = client.get(f"{API_PREFIX}/capabilities", headers=admin_headers) + assert response.status_code == 200 + names = {item["name"] for item in response.get_json()["data"]} + assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names) + + +def test_create_and_list_client_instance(app, client, admin_headers): + """POST /client-instances → 201;GET 列表可查。""" + created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "ERP-T100", "name": "T100 ERP", "connector_type": "soap", "environment": "prod", + "config_json": {"endpoint": "https://t100.invalid/ws"}, + }) + assert created.status_code == 201 + assert created.get_json()["data"]["code"] == "ERP-T100" + + listed = client.get(f"{API_PREFIX}/client-instances", headers=admin_headers) + assert listed.status_code == 200 + assert any(item["code"] == "ERP-T100" for item in listed.get_json()["data"]) + + +def test_client_instance_invalid_connector_type(app, client, admin_headers): + """非法 connector_type → 400。""" + response = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "X", "name": "x", "connector_type": "ftp", + }) + assert response.status_code == 400 + + +def test_call_capability_success(app, client, admin_headers, fake_gateway): + """POST /capabilities/ → 200 success。""" + response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory", + headers=admin_headers, json={"params": _params(), "context": {}}) + assert response.status_code == 200 + data = response.get_json()["data"] + assert data["status"] == "success" + assert data["data"]["found"] is True + + +def test_call_capability_rejects_interface_id(app, client, admin_headers, fake_gateway): + """body 携带 interface_id → 400(禁止覆盖 Binding)。""" + response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory", + headers=admin_headers, json={"params": _params(), "context": {}, "interface_id": "X"}) + assert response.status_code == 400 + assert response.get_json()["error"]["code"] == "INTEGRATION.INTERFACE_ID_NOT_ALLOWED" + + +def test_call_requires_authentication(client): + """未认证 → 401。""" + response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory", + json={"params": _params()}) + assert response.status_code == 401 + + +def test_admin_only_forbidden(app, client, plain_headers): + """普通用户访问 Admin API → 403。""" + response = client.get(f"{API_PREFIX}/client-instances", headers=plain_headers) + assert response.status_code == 403 + + +def test_client_instance_test_connection(app, client, admin_headers, fake_gateway): + """POST /client-instances//test → 200(用注入的 Fake transport)。""" + client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ + "code": "CLI-A", "name": "client", "connector_type": "rest", "environment": "prod", + "config_json": {"endpoint": "https://erp.invalid"}, + }) + response = client.post(f"{API_PREFIX}/client-instances/CLI-A/test", headers=admin_headers) + assert response.status_code == 200 + assert response.get_json()["data"]["ok"] is True diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 2fe061df..9f2a9960 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -651,6 +651,77 @@ def client(app): return app.test_client() +@pytest.fixture +def dbs_ready_file() -> dict: + """当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。""" + return { + "source_code": "DBS-AWSBI", + "business_date": "2026-08-06", + "file_purpose": "receipt", + "file_no": "REC-20260806-001", + "file_version": "v3", + "checksum": "d" * 64, + "status": "ready", + "rows": [ + {"sheet": "Receipt", "row_no": 10, "invoice_no": "INV-001", "material_no": "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", + "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", + "material_name": "控制器组件", "specification": "标准型 / 48V", + "receipt_date": "2026-08-05", "receipt_quantity": "1200", "source_code": "DBS-AWSBI"}, + ], + } + + +@pytest.fixture +def crane_ready_file() -> dict: + """当日 ready 收料全量文件(CRANE-SZ),独立来源。""" + return { + "source_code": "CRANE-SZ", + "business_date": "2026-08-06", + "file_purpose": "receipt", + "file_no": "REC-20260806-002", + "file_version": "v4", + "checksum": "c" * 64, + "status": "ready", + "rows": [ + {"sheet": "Inbound", "row_no": 5, "invoice_no": "INV-008", "material_no": "MAT-200", + "material_name": "传感器模组", "specification": "SZ-8 / IP67", + "receipt_date": "2026-08-05", "receipt_quantity": "600", "source_code": "CRANE-SZ"}, + ], + } + + +@pytest.fixture +def same_day_receipt_file() -> dict: + """含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。""" + return { + "source_code": "DBS-AWSSG", + "business_date": "2026-08-06", + "file_purpose": "receipt", + "file_no": "REC-20260806-003", + "file_version": "v2", + "checksum": "s" * 64, + "status": "ready", + "rows": [ + {"sheet": "Receipt", "row_no": 3, "invoice_no": "INV-041", "material_no": "MAT-041", + "material_name": "连接器组件", "specification": "C 型", + "receipt_date": "2026-08-06", "receipt_quantity": "400", "source_code": "DBS-AWSSG"}, + ], + } + + +@pytest.fixture +def transfer_db(app): + """请求 app 后返回 db 实例;表由 create_all/drop_all 随 app 生命周期隔离。""" + from app import db + + return db + + @pytest.fixture def admin_headers(): return { diff --git a/backend/tests/jobs/test_in_transit_transfer_jobs.py b/backend/tests/jobs/test_in_transit_transfer_jobs.py new file mode 100644 index 00000000..d4837588 --- /dev/null +++ b/backend/tests/jobs/test_in_transit_transfer_jobs.py @@ -0,0 +1,101 @@ +"""在途调拨预检 Job Handler 测试(L1)。 + +用途:验证 in_transit_transfer_precheck JobType 已注册、handler 能驱动 + precheck_service 落库更新预检状态;缺失 precheck 时报错。 +依赖:app fixture、transfer_db、fakes/repo_fakes、jobs.handlers。 +逻辑:直接调用 handler 函数(不经过 Worker 队列),payload 携带 precheck_id。 +""" + +from __future__ import annotations + +import app.jobs.handlers # noqa: F401 —— 触发 @register_handler 注册 +import pytest + +from app import db +from app.jobs.registry import get_handler +from app.jobs.types import JobType +from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +@pytest.fixture +def transfer_deps(monkeypatch, dbs_ready_file): + """注入 Fake 依赖并预置库存。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + return deps + + +def test_precheck_job_type_registered(): + """in_transit_transfer_precheck handler 必须注册于 JobType 注册表。""" + handler = get_handler(JobType.TRANSFER_PRECHECK) + assert handler is not None + + +def test_precheck_job_handler_runs_and_updates_precheck(transfer_db, dbs_ready_file, transfer_deps): + """handler 执行后预检状态进入 ready_to_execute,明细落库。""" + summary = create_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + ) + handler = get_handler(JobType.TRANSFER_PRECHECK) + handler(None, {"precheck_id": summary.precheck_id}) + + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + assert precheck is not None + assert precheck.status == "ready_to_execute" + assert precheck.precheck_hash.startswith("sha256:") + assert len(precheck.items) == 2 + + +def test_precheck_job_handler_missing_precheck_raises(transfer_db): + """缺失 precheck_id → handler 抛 RuntimeError(fail-closed)。""" + handler = get_handler(JobType.TRANSFER_PRECHECK) + with pytest.raises(RuntimeError): + handler(None, {"precheck_id": "TPC-NOT-EXIST"}) + + +def test_run_and_item_job_types_registered(): + """TRANSFER_RUN / TRANSFER_ITEM handler 必须注册。""" + assert get_handler(JobType.TRANSFER_RUN) is not None + assert get_handler(JobType.TRANSFER_ITEM) is not None + + +def test_run_job_handler_executes_precheck(transfer_db, dbs_ready_file, transfer_deps): + """run handler 执行预检并创建成功 Run。""" + summary = create_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + ) + handler = get_handler(JobType.TRANSFER_RUN) + handler(None, {"precheck_id": summary.precheck_id}) + + from app.models import TransferRun as RunModel + + run = db.session.query(RunModel).filter( + RunModel.status != "prechecking", + ).order_by(RunModel.id.desc()).first() + assert run is not None + assert run.status == "success" + + +def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, transfer_deps): + """item handler 执行单个 Invoice 写入并置 success。""" + summary = create_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + ) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + from app.services.in_transit_transfer.orchestrator import create_execution_run + + create_execution_run(precheck, deps=transfer_deps, actor_id=None) + item = db.session.query(TransferInvoiceItem).filter_by( + invoice_no="INV-001", + ).first() + handler = get_handler(JobType.TRANSFER_ITEM) + handler(None, {"item_id": item.id}) + + refreshed = db.session.get(TransferInvoiceItem, item.id) + assert refreshed.status == "success" + assert refreshed.erp_document_no + diff --git a/backend/tests/performance/test_in_transit_transfer.py b/backend/tests/performance/test_in_transit_transfer.py new file mode 100644 index 00000000..bbc11973 --- /dev/null +++ b/backend/tests/performance/test_in_transit_transfer.py @@ -0,0 +1,53 @@ +"""在途调拨性能与规模测试(Phase 4,L6 子集)。 + +用途:验证大批量 Invoice 预检可完成且不退化(O(n) 汇总),投影读取正常。 +依赖:transfer_db、precheck_service、repo_fakes。 +逻辑:300 行收料文件 → 预检 300 个 Invoice;仅断言正确性,耗时打印参考。 +""" + +from __future__ import annotations + +import time + +import pytest + +from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _bulk_file(count: int) -> dict: + """生成 count 行收料文件(每 Invoice 单行)。""" + rows = [] + for index in range(1, count + 1): + rows.append({ + "sheet": "Receipt", + "row_no": index, + "invoice_no": f"INV-BULK-{index:04d}", + "material_no": f"MAT-{index:04d}", + "material_name": "批量物料", + "specification": "T-100", + "receipt_date": "2026-08-05", + "receipt_quantity": "100", + "source_code": "DBS-AWSBI", + }) + return { + "source_code": "DBS-AWSBI", "business_date": "2026-08-06", + "file_no": "REC-BULK", "file_version": "v1", "checksum": "b" * 64, + "status": "ready", "rows": rows, + } + + +def test_bulk_precheck_300_invoices(transfer_db): + """300 Invoice 预检完成且数量正确;耗时打印参考(不设脆断言)。""" + deps, erp, _ = make_transfer_deps(_bulk_file(300)) + for index in range(1, 301): + erp.seed_inventory(f"INV-BULK-{index:04d}", "100") + + started = time.perf_counter() + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + elapsed = time.perf_counter() - started + assert summary.counts.executable_count == 300 + assert summary.counts.file_invoice_count == 300 + restored = restore_precheck(summary.precheck_id) + assert len(restored["items"]) == 300 + print(f"\n[perf] bulk precheck 300 invoices: {elapsed:.3f}s") diff --git a/backend/tests/services/in_transit_transfer/__init__.py b/backend/tests/services/in_transit_transfer/__init__.py new file mode 100644 index 00000000..1cd88f8f --- /dev/null +++ b/backend/tests/services/in_transit_transfer/__init__.py @@ -0,0 +1 @@ +"""在途仓自动调拨 Agent 领域测试包。""" diff --git a/backend/tests/services/in_transit_transfer/assertions.py b/backend/tests/services/in_transit_transfer/assertions.py new file mode 100644 index 00000000..e296add9 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/assertions.py @@ -0,0 +1,44 @@ +"""在途调拨测试断言辅助。 + +用途:统一断言外部调用次数、审计字段完整率与 Hash 可复算。 +依赖:fakes.ErpCallRecord。 +逻辑:所有副作用断言优先读 Fake 的 call log,不猜测实现内部状态。 +""" + +from __future__ import annotations + +from decimal import Decimal +from typing import Any + +from tests.services.in_transit_transfer.fakes import ErpCallRecord, FakeERP + + +def assert_erp_calls(erp: FakeERP, expected: int, *, invoice_no: str | None = None) -> None: + """断言 ERP 调用次数(可按 Invoice 过滤)。""" + calls = erp.calls(invoice_no=invoice_no) + assert len(calls) == expected, f"expected {expected} ERP calls, got {len(calls)}: {calls}" + + +def assert_erp_write_zero(erp: FakeERP) -> None: + """断言没有任何 ERP 写调用(fail-closed 场景通用断言)。""" + writes = erp.write_calls() + assert not writes, f"unexpected ERP write calls: {writes}" + + +def assert_call_fields(record: ErpCallRecord) -> None: + """断言单次 ERP 调用携带全部必需追踪字段。""" + assert record.operation_id + assert record.invoice_no + assert record.erp_org + assert record.from_warehouse + assert record.to_warehouse + assert isinstance(record.quantity, Decimal) + assert record.call_seq > 0 + assert record.returned_status + + +def assert_audit_complete(event: dict[str, Any]) -> None: + """断言一条审计事件字段完整(操作者、关联、前后快照、Hash)。""" + for key in ("event_type", "aggregate_type", "aggregate_id", "actor_type", "operation_id", + "request_id", "before_hash", "after_hash", "event_hash"): + assert event.get(key), f"audit event missing {key}: {event}" diff --git a/backend/tests/services/in_transit_transfer/conftest.py b/backend/tests/services/in_transit_transfer/conftest.py new file mode 100644 index 00000000..4bb86bd9 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/conftest.py @@ -0,0 +1,39 @@ +"""在途调拨测试固定夹具:时钟、收料文件样例、外部替身与数据库隔离。 + +用途:为 tests/services/in_transit_transfer 提供与 TDD 文档一致的固定输入 + (fixed_clock 默认 2026-08-06 09:00:00+08:00、dbs/crane ready 文件、 + same_day_receipt_file),并组装 FakeERP/FakeRPA/FakeWeCom。 +依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。 +逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB; + 请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。 +""" + +from __future__ import annotations + +import pytest + +from tests.services.in_transit_transfer.fakes import FakeClock, FakeERP, FakeRPA, FakeWeCom + + +@pytest.fixture +def fixed_clock() -> FakeClock: + """固定时钟:默认 2026-08-06 09:00:00+08:00(业务日 T=2026-08-06)。""" + return FakeClock() + + +@pytest.fixture +def erp_fake() -> FakeERP: + """FakeERP:账面库存与写响应全部可注入,调用记录可断言。""" + return FakeERP() + + +@pytest.fixture +def rpa_fake() -> FakeRPA: + """FakeRPA:按来源实例独立注入失败/延迟。""" + return FakeRPA() + + +@pytest.fixture +def wecom_fake() -> FakeWeCom: + """FakeWeCom:记录投递事实,可注入附件失败。""" + return FakeWeCom() diff --git a/backend/tests/services/in_transit_transfer/factories.py b/backend/tests/services/in_transit_transfer/factories.py new file mode 100644 index 00000000..e7281579 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/factories.py @@ -0,0 +1,63 @@ +"""在途调拨领域测试的对象工厂。 + +用途:集中构造合法 Invoice / 文件行 / 预检 DTO,避免各测试重复内联样板。 +依赖:标准库(dataclasses / decimal)。 +逻辑:工厂只生成业务合法的默认值;测试用 override 注入变体。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from decimal import Decimal +from typing import Any + + +@dataclass(frozen=True) +class ReceiptRow: + """单行收料文件记录(含 Sheet/行号追溯证据)。""" + + sheet: str = "Receipt" + row_no: int = 1 + invoice_no: str = "INV-001" + material_no: str = "MAT-001" + material_name: str = "连接器组件" + specification: str = "A 型 / 24PIN" + receipt_date: str = "2026-08-05" + receipt_quantity: str = "1200" + source_code: str = "DBS-AWSBI" + + def to_dict(self) -> dict[str, Any]: + """转 dict,供 parser/aggregator 输入。""" + return { + "sheet": self.sheet, + "row_no": self.row_no, + "invoice_no": self.invoice_no, + "material_no": self.material_no, + "material_name": self.material_name, + "specification": self.specification, + "receipt_date": self.receipt_date, + "receipt_quantity": self.receipt_quantity, + "source_code": self.source_code, + } + + +def make_invoice_item( + *, + invoice_no: str = "INV-001", + source_code: str = "DBS-AWSBI", + material_no: str = "MAT-001", + receipt_quantity: Decimal | str | int = "1200", + erp_quantity: Decimal | str | int | None = "1200", + receipt_date: str = "2026-08-05", +) -> dict[str, Any]: + """构造一条预检明细项(默认严格匹配、可执行)。""" + return { + "invoice_no": invoice_no, + "source_code": source_code, + "material_no": material_no, + "material_name": "连接器组件", + "specification": "A 型 / 24PIN", + "receipt_date": receipt_date, + "receipt_quantity": Decimal(str(receipt_quantity)), + "erp_quantity": None if erp_quantity is None else Decimal(str(erp_quantity)), + } diff --git a/backend/tests/services/in_transit_transfer/fakes.py b/backend/tests/services/in_transit_transfer/fakes.py new file mode 100644 index 00000000..dd070678 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/fakes.py @@ -0,0 +1,242 @@ +"""在途调拨测试的可控外部系统替身:FakeERP / FakeRPA / FakeWeCom / FakeClock。 + +用途:让 L0/L1 测试在不接触真实 RPA、ERP、企业微信的前提下覆盖全部业务分支, + 并把每一次外部调用完整记录到 call log,供断言副作用与调用次数。 +依赖:标准库(dataclasses / decimal / zoneinfo)。 +逻辑:FakeERP 以 invoice_no 为业务键维护账面库存与已生成单据; + create_transfer 按注入的 scenario 返回 success / duplicate_success / + business_failed / timeout_before_commit / timeout_after_commit; + 所有调用均追加一条 ErpCallRecord(operation_id、invoice_no、erp_org、 + 来源仓、目标仓、数量、调用序号、方法、返回状态、ERP 单号)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from decimal import Decimal +from typing import Any +from zoneinfo import ZoneInfo + +from app.services.in_transit_transfer.erp_adapter import ErpWriteTimeoutError + + +class FakeClock: + """固定时钟:默认 2026-08-06 09:00:00+08:00,可推进业务日。""" + + def __init__(self, iso: str = "2026-08-06T09:00:00+08:00") -> None: + self.now_value = datetime.fromisoformat(iso) + + def now(self) -> datetime: + """返回当前固定时刻(带 Asia/Shanghai 时区)。""" + return self.now_value + + def advance(self, *, seconds: int = 0, days: int = 0) -> None: + """按秒或天推进固定时钟(保持 Asia/Shanghai 时区)。""" + self.now_value = self.now_value.replace(tzinfo=ZoneInfo("Asia/Shanghai")) + if seconds: + self.now_value = self.now_value + timedelta(seconds=seconds) + if days: + self.now_value = self.now_value + timedelta(days=days) + + +@dataclass(frozen=True) +class ErpCallRecord: + """FakeERP 单次调用的事实记录;测试断言优先读取该记录。""" + + operation_id: str + invoice_no: str + erp_org: str + from_warehouse: str + to_warehouse: str + quantity: Decimal + call_seq: int + returned_status: str + method: str + document_no: str | None = None + + +class FakeERP: + """可注入账面库存与响应场景的 ERP 替身;每次调用写入 call log。""" + + def __init__(self) -> None: + self.inventory: dict[str, dict[str, Any]] = {} + self.documents: dict[str, str] = {} + self.verified_posted: dict[str, bool] = {} + self.query_scenario: str = "normal" + self.write_scenario: str = "success" + # 按 Invoice 覆盖写场景(Key=invoice_no);未配置时回落到 write_scenario。 + self.write_scenarios: dict[str, str] = {} + self.call_log: list[ErpCallRecord] = [] + self._seq = 0 + + # -- 控制注入 ---------------------------------------------------------- + def seed_inventory(self, invoice_no: str, quantity: str | int | Decimal) -> None: + """设置指定 Invoice 的账面库存。""" + self.inventory[str(invoice_no).strip()] = {"quantity": Decimal(str(quantity))} + + def seed_document(self, invoice_no: str, document_no: str, *, posted: bool = True) -> None: + """预置某 Invoice 已存在的 ERP 单据(幂等重复场景)。""" + self.documents[str(invoice_no).strip()] = document_no + self.verified_posted[str(invoice_no).strip()] = posted + + def set_query_scenario(self, scenario: str) -> None: + """normal | inventory_not_found | timeout。""" + self.query_scenario = scenario + + def set_write_scenario(self, scenario: str) -> None: + """success | duplicate_success | business_failed | timeout_before_commit | timeout_after_commit。""" + self.write_scenario = scenario + + # -- ERP 能力 ---------------------------------------------------------- + def query_inventory(self, *, operation_id: str, run_no: str, attempt_no: int, + invoice_no: str, erp_org: str, from_warehouse: str, + to_warehouse: str, quantity: Decimal) -> dict[str, Any]: + """按 Invoice 返回账面库存;timeout 场景抛超时异常。""" + self._seq += 1 + key = str(invoice_no).strip() + if self.query_scenario == "timeout": + raise TimeoutError(f"query timeout operation_id={operation_id}") + if self.query_scenario == "inventory_not_found" or key not in self.inventory: + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "inventory_not_found", "query_inventory") + self.call_log.append(record) + return {"found": False, "quantity": Decimal("0")} + qty = self.inventory[key]["quantity"] + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "success", "query_inventory") + self.call_log.append(record) + return {"found": True, "quantity": qty} + + def create_transfer(self, *, operation_id: str, run_no: str, attempt_no: int, + invoice_no: str, erp_org: str, from_warehouse: str, + to_warehouse: str, quantity: Decimal) -> dict[str, Any]: + """原子建单/审核/过账;按注入场景返回结果并记录调用。""" + self._seq += 1 + key = str(invoice_no).strip() + scenario = self.write_scenarios.get(key, self.write_scenario) + if scenario == "timeout_before_commit": + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "timeout_before_commit", "create_transfer") + self.call_log.append(record) + raise ErpWriteTimeoutError( + "write timeout before commit", committed=False, operation_id=operation_id, + ) + if self.write_scenario == "timeout_after_commit" or scenario == "timeout_after_commit": + # 已落单但无法确认:调用方必须投 result_unknown,禁止自动重试。 + self.documents.setdefault(key, f"TRF-{self._seq:05d}") + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "timeout_after_commit", "create_transfer", + self.documents[key]) + self.call_log.append(record) + raise ErpWriteTimeoutError( + "write timeout after commit", committed=True, + document_no=self.documents[key], operation_id=operation_id, + ) + if scenario == "business_failed" or self.write_scenario == "business_failed": + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "business_failed", "create_transfer") + self.call_log.append(record) + return {"status": "business_failed", "code": "ERP_BUSINESS_REJECT", "rolled_back": True} + if key in self.documents: + document_no = self.documents[key] + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "duplicate_success", "create_transfer", + document_no) + self.call_log.append(record) + return { + "status": "duplicate_success", + "document_no": document_no, + "verified_posted": self.verified_posted.get(key, False), + } + document_no = f"TRF-{self._seq:05d}" + self.documents[key] = document_no + self.verified_posted[key] = True + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "success", "create_transfer", document_no) + self.call_log.append(record) + return {"status": "success", "document_no": document_no, "posted": True} + + def verify_duplicate(self, *, operation_id: str, run_no: str, attempt_no: int, + invoice_no: str, erp_org: str, from_warehouse: str, + to_warehouse: str, quantity: Decimal) -> dict[str, Any]: + """核实重复 Invoice 原单状态(已审核过账/未确认)。""" + self._seq += 1 + key = str(invoice_no).strip() + if key not in self.documents: + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, "duplicate_unverified", "verify_duplicate") + self.call_log.append(record) + return {"status": "duplicate_unverified", "document_no": None, "verified_posted": False} + document_no = self.documents[key] + posted = self.verified_posted.get(key, False) + status = "duplicate_success" if posted else "duplicate_unverified" + record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse, + quantity, self._seq, status, "verify_duplicate", document_no) + self.call_log.append(record) + return {"status": status, "document_no": document_no, "verified_posted": posted} + + # -- 断言辅助 ---------------------------------------------------------- + def calls(self, *, invoice_no: str | None = None) -> list[ErpCallRecord]: + """按 Invoice 过滤调用记录(默认返回全部)。""" + if invoice_no is None: + return list(self.call_log) + return [record for record in self.call_log if record.invoice_no == str(invoice_no).strip()] + + def write_calls(self) -> list[ErpCallRecord]: + """仅返回 create_transfer 调用记录(写副作用断言)。""" + return [record for record in self.call_log if record.method == "create_transfer"] + + +class FakeRPA: + """可独立按来源注入失败/延迟的收料 RPA 替身。""" + + def __init__(self) -> None: + self.triggered: list[dict[str, Any]] = [] + self.fail_on: set[str] = set() + + def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: + """触发一次来源收料抓取并记录。""" + self.triggered.append({ + "source_code": source_code, + "business_date": business_date, + "reason": reason, + }) + if source_code in self.fail_on: + return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"} + return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"} + + +class FakeWeCom: + """企业微信通知替身;记录投递事实,可注入附件失败。""" + + def __init__(self) -> None: + self.deliveries: list[dict[str, Any]] = [] + self.attach_fail = False + + def send_summary(self, *, run_no: str, summary: dict[str, Any], + recipients: list[str], excel_path: str | None = None) -> dict[str, Any]: + """发送一次汇总通知;附件失败时返回 failed 但不抛异常。""" + if self.attach_fail and excel_path: + record = {"run_no": run_no, "status": "failed", "error_code": "WECOM_ATTACH_FAILED"} + self.deliveries.append(record) + return {"status": "failed", "error_code": "WECOM_ATTACH_FAILED"} + record = {"run_no": run_no, "status": "success", "recipients": recipients, "excel": excel_path} + self.deliveries.append(record) + return {"status": "success"} + + +@dataclass +class FakeAuditSink: + """审计落点替身;记录 before/after、Diff、Hash 与关联上下文。""" + + events: list[dict[str, Any]] = field(default_factory=list) + + def append(self, event: dict[str, Any]) -> None: + """追加一条审计事件 dict。""" + self.events.append(event) + + +def utc_now_iso() -> str: + """返回当前 UTC 时间的 ISO 字符串(测试断言用)。""" + return datetime.now(timezone.utc).isoformat() diff --git a/backend/tests/services/in_transit_transfer/repo_fakes.py b/backend/tests/services/in_transit_transfer/repo_fakes.py new file mode 100644 index 00000000..552731d1 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/repo_fakes.py @@ -0,0 +1,88 @@ +"""在途调拨测试的仓库/路由/依赖替身。 + +用途:为 file_preparation / precheck_service / API / Job 测试提供可注入的 + ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps。 +依赖:app.services.in_transit_transfer(仅类型)、fakes。 +逻辑:所有替身只返回测试注入的值,不触碰真实存储; + TransferDeps.erp 统一使用 ErpAdapter(FakeERP) 以匹配 Adapter 契约。 +""" + +from __future__ import annotations + +from app.services.in_transit_transfer.erp_adapter import ErpAdapter +from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile +from app.services.in_transit_transfer.precheck_service import RouteMapping, TransferDeps +from tests.services.in_transit_transfer.fakes import FakeERP, FakeRPA + + +class FakeReceiptFileRepository: + """按 (source_code, business_date) 返回可注入 ready 文件。""" + + def __init__(self, files: dict[tuple[str, str], ReadyReceiptFile] | None = None) -> None: + self.files = files or {} + self.lookups: list[tuple[str, str]] = [] + + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + """记录查询并返回匹配文件。""" + self.lookups.append((source_code, business_date)) + return self.files.get((source_code, business_date)) + + +def make_ready_repo(*files: dict) -> FakeReceiptFileRepository: + """由 fixture 文件 dict 构建仓库;rows 透传为 ReadyReceiptFile.rows。""" + repository = FakeReceiptFileRepository() + for item in files: + repository.files[(item["source_code"], item["business_date"])] = ReadyReceiptFile( + source_code=item["source_code"], + business_date=item["business_date"], + file_no=item["file_no"], + file_version=item["file_version"], + checksum=item["checksum"], + rows=tuple(item["rows"]), + ) + return repository + + +def make_transfer_deps( + *files: dict, + erp: FakeERP | None = None, + rpa: FakeRPA | None = None, + routes: dict[str, RouteMapping] | None = None, +) -> tuple[TransferDeps, FakeERP, FakeRPA]: + """组装注入 Fake 的 TransferDeps(erp 统一包装为 ErpAdapter)。 + + Returns: + (deps, erp_fake, rpa_fake) 元组。 + """ + erp = erp or FakeERP() + rpa = rpa or FakeRPA() + deps = TransferDeps( + file_repository=make_ready_repo(*files), + rpa_trigger=rpa, + route_resolver=FakeRouteResolver(routes=routes), + erp=ErpAdapter(transport=erp, default_org="HX-CN01"), + ) + return deps, erp, rpa + + +class FakeRouteResolver: + """按来源返回固定路由(ERP 组织/拨出仓/拨入仓)。""" + + def __init__(self, routes: dict[str, RouteMapping] | None = None) -> None: + self.routes = routes if routes is not None else { + "DBS-AWSBI": RouteMapping(erp_org="HX-CN01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01"), + "DBS-AWSSG": RouteMapping(erp_org="HX-CN01", from_warehouse="AWSSG-TRANSIT", to_warehouse="HUB-SG"), + "CRANE-SZ": RouteMapping(erp_org="HX-CN01", from_warehouse="CRANE-SZ-TRANSIT", to_warehouse="HUB-SZ"), + } + self.raised_on: set[str] = set() + + def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping: + """返回来源路由;未配置来源抛 RouteNotResolvedError。""" + if source_code in self.raised_on: + raise RuntimeError("route resolution failed") + mapping = self.routes.get(source_code) + if mapping is None: + from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError + + raise RouteNotResolvedError(source_code=source_code) + return mapping diff --git a/backend/tests/services/in_transit_transfer/test_archive.py b/backend/tests/services/in_transit_transfer/test_archive.py new file mode 100644 index 00000000..6a167f32 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_archive.py @@ -0,0 +1,97 @@ +"""在途调拨 MinIO 归档与 Hash 校验测试(Phase 4,L1)。 + +用途:验证归档对象写入 MinIO(Fake 替身)并持久化索引记录, + 归档 Hash 可复算,损坏数据复核失败。 +依赖:transfer_db、archive、FakeObjectStore。 +逻辑:归档记录含 provider/bucket/key/sha256;校验重新下载并复算。 +""" + +from __future__ import annotations + +import hashlib + +import pytest + +from app import db +from app.models import TransferArchive, TransferAuditEvent +from app.services.in_transit_transfer.archive import ( + archive_snapshot, + restore_archive_bytes, + verify_archive_hash, +) + + +class FakeObjectStore: + """内存对象存储替身(Key → bytes)。""" + + def __init__(self) -> None: + self.objects: dict[str, bytes] = {} + + def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str: + """保存对象并返回对象键。""" + self.objects[f"{bucket}/{key}"] = data + return key + + def get_bytes(self, *, bucket: str, key: str) -> bytes: + """读取对象字节。""" + return self.objects[f"{bucket}/{key}"] + + def delete_object(self, *, bucket: str, key: str) -> None: + """删除对象。""" + self.objects.pop(f"{bucket}/{key}", None) + + +def _sample_data() -> bytes: + return b"erp-inventory-snapshot,2026-08-06,INV-001,1200,1200,executable\n" + + +def test_archive_snapshot_persists_index_and_audit(transfer_db): + """归档后记录 TransferArchive(含 sha256)并写入审计。""" + store = FakeObjectStore() + data = _sample_data() + archive = archive_snapshot( + object_type="erp_inventory_snapshot", + object_id="TPC-20260806-001", + data=data, + original_filename="erp-inventory-20260806.csv", + content_type="text/csv", + object_store=store, + bucket="hxops-transfer", + ) + assert archive.sha256 == hashlib.sha256(data).hexdigest() + assert archive.storage_provider == "minio" + assert archive.object_type == "erp_inventory_snapshot" + assert store.objects # 对象已写入存储 + audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ARCHIVED").first() + assert audit is not None + assert audit.aggregate_id == "TPC-20260806-001" + + +def test_verify_archive_hash_ok_and_corruption_detected(transfer_db): + """Hash 复算一致;对象损坏 → 复核失败。""" + store = FakeObjectStore() + data = _sample_data() + archive = archive_snapshot( + object_type="erp_inventory_snapshot", object_id="OBJ-1", data=data, + original_filename="a.csv", content_type="text/csv", + object_store=store, bucket="hxops-transfer", + ) + assert verify_archive_hash(archive, object_store=store) is True + + # 篡改存储对象后复核必须失败 + key = f"{archive.storage_bucket}/{archive.storage_key}" + store.objects[key] = data + b"tampered" + assert verify_archive_hash(archive, object_store=store) is False + + +def test_restore_archive_bytes_roundtrip(transfer_db): + """归档对象可恢复为原始字节。""" + store = FakeObjectStore() + data = _sample_data() + archive = archive_snapshot( + object_type="erp_inventory_snapshot", object_id="OBJ-2", data=data, + original_filename="a.csv", content_type="text/csv", + object_store=store, bucket="hxops-transfer", + ) + restored = restore_archive_bytes(archive, object_store=store) + assert restored == data diff --git a/backend/tests/services/in_transit_transfer/test_audit.py b/backend/tests/services/in_transit_transfer/test_audit.py new file mode 100644 index 00000000..c32e8677 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_audit.py @@ -0,0 +1,145 @@ +"""在途调拨审计完整性测试(L0 纯单元 + 一次 DB 落库冒烟)。 + +用途:验证审计快照脱敏(Secret 不进快照/Hash)、Hash 可复算、Diff 语义正确, + 以及审计事件携带操作者、operation_id、request_id 等关联上下文。 +依赖:app.services.in_transit_transfer.audit(纯函数)+ transfer_db(模型冒烟)。 +逻辑:L0 部分不创建 Flask;模型冒烟用例请求 app fixture 验证落库字段。 +""" + +from __future__ import annotations + +import pytest + +from app.services.in_transit_transfer.audit import ( + canonical_hash, + build_transfer_audit_event, + compute_event_hash, + sanitize_snapshot, + snapshot_diff, +) + + +@pytest.mark.pure_unit +def test_canonical_hash_is_deterministic(): + """相同快照两次计算 Hash 必须一致(键排序 + 紧凑 JSON)。""" + snapshot = {"invoice_no": "INV-001", "quantity": "1200", "org": "HX-CN01"} + assert canonical_hash(snapshot) == canonical_hash(snapshot) + + +@pytest.mark.pure_unit +def test_hash_changes_when_snapshot_changes(): + """任一字段变化 Hash 必须变化。""" + before = {"invoice_no": "INV-001", "quantity": "1200"} + after = {"invoice_no": "INV-001", "quantity": "1201"} + assert canonical_hash(before) != canonical_hash(after) + + +@pytest.mark.pure_unit +def test_hash_ignores_key_order(): + """字段顺序不影响 Hash。""" + a = {"x": 1, "y": 2} + b = {"y": 2, "x": 1} + assert canonical_hash(a) == canonical_hash(b) + + +@pytest.mark.pure_unit +def test_sanitize_snapshot_strips_secrets(): + """快照必须剔除密码/Token/密钥等敏感字段,绝不进入 Hash。""" + snapshot = { + "invoice_no": "INV-001", + "password": "P@ssw0rd", + "credential": {"api_key": "sk-xxx", "username_ciphertext": "abc"}, + "webhook_url": "https://hooks.example/secret-token", + } + clean = sanitize_snapshot(snapshot) + serialized = str(clean) + assert "P@ssw0rd" not in serialized + assert "sk-xxx" not in serialized + assert "abc" not in serialized + assert "secret-token" not in serialized + assert clean["invoice_no"] == "INV-001" + + +@pytest.mark.pure_unit +def test_snapshot_diff_reports_added_removed_changed(): + """Diff 必须区分新增/删除/修改三类变化。""" + diff = snapshot_diff( + {"invoice_no": "INV-001", "quantity": "1200", "old_key": "x"}, + {"invoice_no": "INV-001", "quantity": "1100", "new_key": "y"}, + ) + assert diff["changed"]["quantity"] == ("1200", "1100") + assert diff["removed"] == {"old_key": "x"} + assert diff["added"] == {"new_key": "y"} + + +@pytest.mark.pure_unit +def test_build_event_carries_actor_and_correlation_ids(): + """审计事件必须包含 actor、operation_id、request_id 与前后快照 Hash。""" + event = build_transfer_audit_event( + event_type="TRANSFER_CONFIRMED", + aggregate_type="transfer_item", + aggregate_id="item-1", + run_no="RUN-20260806-001", + precheck_no="TPC-20260806-001", + invoice_no="INV-001", + actor_type="user", + actor_id="u-42", + actor_role="warehouse_manager", + actor_display="李仓储", + request_id="req_001", + operation_id="op_001", + result="success", + before={"status": "prechecking"}, + after={"status": "ready_to_execute"}, + ) + assert event.actor_id == "u-42" + assert event.operation_id == "op_001" + assert event.request_id == "req_001" + assert event.run_no == "RUN-20260806-001" + assert event.before_hash and event.after_hash and event.event_hash + + +@pytest.mark.pure_unit +def test_event_hash_recomputable_from_fields(): + """审计 Hash 必须可由存储字段复算(Phase 4 Hash 校验基础)。""" + event = build_transfer_audit_event( + event_type="TRANSFER_EXECUTED", + aggregate_type="transfer_item", + aggregate_id="item-2", + run_no="RUN-20260806-001", + invoice_no="INV-002", + actor_type="worker", + operation_id="op_002", + result="success", + after={"erp_document_no": "TRF-10001"}, + ) + assert compute_event_hash(event) == event.event_hash + + +def test_audit_event_persists_with_required_fields(transfer_db): + """DB 冒烟:审计事件可落库并回读(含 Hash 与关联字段)。""" + event = build_transfer_audit_event( + event_type="TRANSFER_CREATED", + aggregate_type="transfer_run", + aggregate_id="RUN-20260806-001", + run_no="RUN-20260806-001", + actor_type="user", + actor_id="u-1", + operation_id="op_003", + request_id="req_003", + result="success", + after={"status": "queued"}, + ) + transfer_db.session.add(event) + transfer_db.session.commit() + + from app.models import TransferAuditEvent + + loaded = transfer_db.session.get(TransferAuditEvent, event.id) + assert loaded is not None + assert loaded.run_no == "RUN-20260806-001" + assert loaded.operation_id == "op_003" + assert loaded.event_hash == event.event_hash + # 复算一致率 100% 的落库断言 + assert compute_event_hash(loaded) == loaded.event_hash + diff --git a/backend/tests/services/in_transit_transfer/test_backlog_service.py b/backend/tests/services/in_transit_transfer/test_backlog_service.py new file mode 100644 index 00000000..eab581dc --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_backlog_service.py @@ -0,0 +1,75 @@ +"""在途调拨历史待处理池与老化测试(Phase 3,L1)。 + +用途:验证待处理池只收纳可恢复/已关闭/结果未知项,并正确计算 3/5/7 天老化等级。 +依赖:transfer_db、precheck_service、backlog_service、repo_fakes。 +逻辑:老化按最近一次 Attempt 或明细更新时间计算;result_unknown 单独高风险展示。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer.backlog_service import ( + aging_level_for, + backlog_summary, + list_backlog, +) +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _blocked_precheck(dbs_ready_file): + """构造含数量不一致(blocked)项的预检。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") # 1200 ≠ 1000 → blocked + erp.seed_inventory("INV-002", "1200") # executable + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return summary + + +def test_aging_level_thresholds(): + """3/5/7 天老化阈值正确。""" + assert aging_level_for(0) == "normal" + assert aging_level_for(1) == "normal" + assert aging_level_for(2) == "normal" + assert aging_level_for(3) == "warn_3d" + assert aging_level_for(5) == "escalate_5d" + assert aging_level_for(7) == "critical_7d" + assert aging_level_for(10) == "critical_7d" + + +def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file): + """待处理池收纳 blocked_recoverable,排除 success / not_matured。""" + _blocked_precheck(dbs_ready_file) + items = list_backlog() + invoice_set = {item.invoice_no for item in items} + assert "INV-001" in invoice_set + assert "INV-002" not in invoice_set + + +def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file): + """老化等级按明细更新日期计算。""" + _blocked_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + item.updated_at = datetime.utcnow() - timedelta(days=6) + db.session.commit() + items = list_backlog(now=datetime.utcnow()) + target = next(item_dto for item_dto in items if item_dto.invoice_no == "INV-001") + assert target.age_days == 6 + assert target.aging_level == "escalate_5d" + + +def test_backlog_summary_counts_and_aging(transfer_db, dbs_ready_file): + """汇总包含可恢复/已关闭/未知计数与老化分级。""" + _blocked_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + item.status = "manually_closed" + item.manually_closed_reason = "线下处理" + db.session.commit() + summary = backlog_summary() + assert summary.closed_count == 1 + assert summary.recoverable_count == 0 diff --git a/backend/tests/services/in_transit_transfer/test_cancellation.py b/backend/tests/services/in_transit_transfer/test_cancellation.py new file mode 100644 index 00000000..58bd20c4 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_cancellation.py @@ -0,0 +1,59 @@ +"""在途调拨请求停止(取消)测试(Phase 2,L1)。 + +用途:验证停止剩余任务只取消未开始项、已成功单据保留、原因必填。 +依赖:transfer_db、execution_service、cancellation、repo_fakes。 +逻辑:取消前快照与原因写入审计;成功后不可取消。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.errors import ValidationError +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.cancellation import cancel_run +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _ready_precheck(dbs_ready_file): + erp = __import__("tests.services.in_transit_transfer.fakes", fromlist=["FakeERP"]).FakeERP() + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + deps, _, _ = make_transfer_deps(dbs_ready_file, erp=erp) + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return deps, summary + + +def test_cancel_requires_reason(transfer_db, dbs_ready_file): + """取消原因必填;无副作用(不创建执行 Run)。""" + deps, summary = _ready_precheck(dbs_ready_file) + with pytest.raises(ValidationError): + cancel_run(run_no="RUN-X", reason="") + # 仅存在预检关联 Run(prechecking),无执行 Run + runs = db.session.query(TransferRun).all() + assert len(runs) == 1 + assert runs[0].status != "executing" + + +def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file): + """取消只作用于未开始项;已成功单据保留。""" + deps, summary = _ready_precheck(dbs_ready_file) + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first() + # 模拟执行中状态:Run 回退到 executing,INV-002 尚未开始,INV-001 保持 success + run.status = "executing" + item = db.session.query(TransferInvoiceItem).filter_by( + run_id=run.id, invoice_no="INV-002", + ).first() + item.status = "ready_to_execute" + item.erp_document_no = None + db.session.commit() + + result = cancel_run(run_no=outcome.run_no, reason="业务原因") + items = {i.invoice_no: i for i in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()} + assert items["INV-001"].status == "success" # 已成功单据保留 + assert items["INV-002"].status == "cancelled" # 未开始项取消 + assert result["cancelled_count"] == 1 diff --git a/backend/tests/services/in_transit_transfer/test_chat_actions.py b/backend/tests/services/in_transit_transfer/test_chat_actions.py new file mode 100644 index 00000000..620bd07f --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_chat_actions.py @@ -0,0 +1,114 @@ +"""在途调拨 Chat Action 测试(L2 契约,SQLite 内存库)。 + +用途:验证 transfer.precheck / transfer.execute 已注册、agent 权限映射正确、 + stream 产出结构化卡片事件(transfer-precheck / transfer-result)。 +依赖:app fixture、transfer_db、repo_fakes、action_registry、chat_actions、turn_context。 +逻辑:直接构造 TurnContext 调用 handler.stream,断言事件载荷与卡片契约。 +""" + +from __future__ import annotations + +import pytest + +from app.core.errors import ForbiddenError +from app.services.chat.action_registry import ACTION_AGENT_CODES, ensure_handlers_loaded, resolve_action_handler +from app.services.chat.action_schema import TurnInput +from app.services.chat.turn_context import TurnContext +from app.services.in_transit_transfer.chat_actions import ( + ACTION_TRANSFER_EXECUTE, + ACTION_TRANSFER_PRECHECK, + TransferExecuteAction, + TransferPrecheckAction, +) +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +class _Agent: + """带 agent_code 的假 Agent。""" + + def __init__(self, agent_code: str) -> None: + self.agent_code = agent_code + self.id = 1 + self.name = "test-agent" + + +class _User: + id = 99 + + +def _ctx(agent_code: str, action_type: str, payload: dict) -> TurnContext: + return TurnContext( + turn_id="turn-1", + run_id="run-1", + session_id="session-1", + request_id="req-1", + user=_User(), + agent=_Agent(agent_code), + input=TurnInput(type="action", display_text="调拨预检", action_type=action_type, payload=payload), + refs={}, + ) + + +def test_transfer_actions_registered(): + """两个 transfer action 必须注册。""" + ensure_handlers_loaded() + assert "transfer." in ACTION_AGENT_CODES + assert ACTION_AGENT_CODES["transfer."] == ("in_transit_transfer",) + assert TransferPrecheckAction.action_type == ACTION_TRANSFER_PRECHECK + assert TransferExecuteAction.action_type == ACTION_TRANSFER_EXECUTE + + +def test_transfer_action_agent_permission_enforced(): + """transfer.* 仅允许 in_transit_transfer agent;其他 agent 拒绝。""" + ensure_handlers_loaded() + ctx = _ctx("generic", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]}) + with pytest.raises(ForbiddenError): + resolve_action_handler(ctx) + allowed = _ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]}) + assert resolve_action_handler(allowed).action_type == ACTION_TRANSFER_PRECHECK + + +def test_precheck_action_streams_card(transfer_db, dbs_ready_file, monkeypatch): + """transfer.precheck 流式产出 transfer-precheck 卡片(含明细与来源进度)。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + + events = list(TransferPrecheckAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, { + "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", + }))) + assert len(events) == 1 + event = events[0] + assert event.event == "message.completed" + assert event.data["message_type"] == "transfer-precheck" + payload = event.data["payload"] + assert payload["kind"] == "precheck" + assert payload["summary"]["estimated_erp_write_count"] == 2 + assert {item["invoice_no"] for item in payload["items"]} == {"INV-001", "INV-002"} + assert payload["sources"][0]["source_code"] == "DBS-AWSBI" + + +def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeypatch): + """transfer.execute 流式产出 transfer-result 卡片(按 ERP 单号聚合)。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + + # 先跑预检拿 precheck_id + precheck_events = list(TransferPrecheckAction().stream(_ctx( + "in_transit_transfer", ACTION_TRANSFER_PRECHECK, + {"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06"}, + ))) + precheck_id = precheck_events[0].data["payload"]["summary"]["precheck_id"] + + execute_events = list(TransferExecuteAction().stream(_ctx( + "in_transit_transfer", ACTION_TRANSFER_EXECUTE, + {"precheck_id": precheck_id, "invoice_nos": ["INV-001", "INV-002"]}, + ))) + assert len(execute_events) == 1 + payload = execute_events[0].data["payload"] + assert payload["kind"] == "result" + assert payload["status"] == "success" + assert len(payload["run"]["result"]["erp_documents"]) == 2 diff --git a/backend/tests/services/in_transit_transfer/test_contracts.py b/backend/tests/services/in_transit_transfer/test_contracts.py new file mode 100644 index 00000000..18181dee --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_contracts.py @@ -0,0 +1,145 @@ +"""在途调拨 DTO 与错误码契约测试(L0 纯单元)。 + +用途:验证预检 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、 + ERP 单据按单号聚合投影,以及一期冻结错误码完整且唯一。 +依赖:app.services.in_transit_transfer.contracts。 +逻辑:DTO 为 frozen dataclass,聚合函数按 ERP 单号分组并统计物料数/总数量。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.contracts import ( + KNOWN_TRANSFER_ERROR_CODES, + TRANSFER_PERMISSION_DENIED, + TRANSFER_PRECHECK_EXPIRED, + TRANSFER_QUANTITY_MISMATCH, + TRANSFER_RESULT_UNKNOWN, + PrecheckCountsDTO, + PrecheckInvoiceItemDTO, + PrecheckSummaryDTO, + aggregate_erp_documents, + require_known_error_code, +) + +pytestmark = pytest.mark.pure_unit + +EXPECTED_ERROR_CODES = { + "TRANSFER_PERMISSION_DENIED", + "TRANSFER_RECEIPT_NOT_MATURED", + "TRANSFER_FILE_NOT_READY", + "TRANSFER_FILE_SCHEMA_INVALID", + "TRANSFER_INVOICE_CONFLICT", + "TRANSFER_QUANTITY_MISMATCH", + "TRANSFER_ERP_INVENTORY_NOT_FOUND", + "TRANSFER_PRECHECK_EXPIRED", + "TRANSFER_CONFIRMATION_REQUIRED", + "TRANSFER_DUPLICATE_NOT_VERIFIED", + "TRANSFER_RESULT_UNKNOWN", + "TRANSFER_MANUAL_CLOSE_REASON_REQUIRED", + "TRANSFER_CONFIG_PUBLISH_BLOCKED", + "TRANSFER_SECRET_NOT_EXPOSED", + "TRANSFER_NOTIFICATION_FAILED", +} + + +def test_error_codes_match_tdd_frozen_list(): + """TDD §7.3 冻结的 15 个错误码必须全部存在且唯一。""" + assert EXPECTED_ERROR_CODES <= KNOWN_TRANSFER_ERROR_CODES + assert len(KNOWN_TRANSFER_ERROR_CODES) == len(EXPECTED_ERROR_CODES) + + +def test_require_known_error_code_accepts_frozen_codes(): + """冻结错误码可被契约校验接受。""" + require_known_error_code(TRANSFER_QUANTITY_MISMATCH) + require_known_error_code(TRANSFER_PRECHECK_EXPIRED) + require_known_error_code(TRANSFER_RESULT_UNKNOWN) + require_known_error_code(TRANSFER_PERMISSION_DENIED) + + +def test_require_known_error_code_rejects_unknown(): + """未知错误码必须抛 ValueError。""" + with pytest.raises(ValueError): + require_known_error_code("TRANSFER_NO_SUCH_CODE") + + +def test_precheck_counts_dto_fields(): + """预检计数 DTO 包含文件内/未成熟/已预检/可执行/阻断五类计数。""" + counts = PrecheckCountsDTO( + file_invoice_count=40, not_matured_count=8, prechecked_count=32, + executable_count=27, blocked_count=5, + ) + assert counts.executable_count == 27 + assert counts.not_matured_count == 8 + + +def test_precheck_summary_dto_carries_estimate_and_hash(): + """预检摘要 DTO 必须携带预计调拨数量、预计 ERP 写入数与预检 Hash。""" + summary = PrecheckSummaryDTO( + precheck_id="TPC-20260806-001", + status="ready_to_execute", + business_date="2026-08-06", + eligible_receipt_date_to="2026-08-05", + expires_at="2026-08-06T09:20:00+08:00", + counts=PrecheckCountsDTO(40, 8, 32, 27, 5), + estimated_transfer_quantity="18460", + estimated_erp_write_count=27, + precheck_hash="sha256:abc", + ) + assert summary.estimated_transfer_quantity == "18460" + assert summary.estimated_erp_write_count == 27 + assert summary.precheck_hash.startswith("sha256:") + + +def test_invoice_item_dto_carries_warehouse_and_quantity_pairs(): + """预检明细 DTO 必须包含拨出/拨入仓库与数量对(决策 6/7)。""" + item = PrecheckInvoiceItemDTO( + source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件", + specification="A 型 / 24PIN", invoice_no="INV-001", + from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"), + to_warehouse="HUB-CN01", to_quantity=Decimal("1200"), + result="executable", + ) + assert item.from_warehouse == "DBS-TRANSIT" + assert item.to_warehouse == "HUB-CN01" + assert item.from_quantity == item.to_quantity + + +def test_aggregate_erp_documents_groups_by_document_no(): + """结果页按 ERP 单号聚合:物料数、调拨总数量、拨出/拨入仓。""" + items = [ + PrecheckInvoiceItemDTO( + source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件", + specification="A 型 / 24PIN", invoice_no="INV-001", + from_warehouse="DBS-TRANSIT", from_quantity=Decimal("500"), + to_warehouse="HUB-CN01", to_quantity=Decimal("500"), + result="success", erp_document_no="TRF-10001", + ), + PrecheckInvoiceItemDTO( + source_code="DBS-AWSBI", material_no="MAT-002", material_name="控制器组件", + specification="标准型 / 48V", invoice_no="INV-002", + from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"), + to_warehouse="HUB-CN01", to_quantity=Decimal("1200"), + result="success", erp_document_no="TRF-10001", + ), + PrecheckInvoiceItemDTO( + source_code="CRANE-SZ", material_no="MAT-200", material_name="传感器模组", + specification="SZ-8 / IP67", invoice_no="INV-008", + from_warehouse="CRANE-TRANSIT", from_quantity=Decimal("600"), + to_warehouse="HUB-SH", to_quantity=Decimal("600"), + result="success", erp_document_no="TRF-10008", + ), + ] + documents = aggregate_erp_documents(items) + assert len(documents) == 2 + by_no = {document.document_no: document for document in documents} + first = by_no["TRF-10001"] + assert first.material_count == 2 + assert first.total_quantity == Decimal("1700") + assert first.from_warehouse == "DBS-TRANSIT" + assert first.to_warehouse == "HUB-CN01" + assert first.posting_status == "posted" + assert [line.invoice_no for line in first.lines] == ["INV-001", "INV-002"] diff --git a/backend/tests/services/in_transit_transfer/test_date_policy.py b/backend/tests/services/in_transit_transfer/test_date_policy.py new file mode 100644 index 00000000..d24e5dd5 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_date_policy.py @@ -0,0 +1,78 @@ +"""在途调拨日期成熟度策略测试(L0 纯单元)。 + +用途:验证 D+1 成熟规则、当天 not_matured、未来日期阻断与上海业务时区。 +依赖:app.services.in_transit_transfer.date_policy(纯函数)。 +逻辑:全部断言只依赖业务日期与收料日期,不接触 Flask/DB(pure_unit)。 +""" + +from __future__ import annotations + +from datetime import date, datetime, timezone +from zoneinfo import ZoneInfo + +import pytest + +from app.services.in_transit_transfer.date_policy import ( + business_date_now, + eligible_receipt_date_to, + maturity_status, +) + +pytestmark = pytest.mark.pure_unit + +BUSINESS_T = date(2026, 8, 6) + + +def test_same_day_receipt_is_not_matured(): + """当天收料必须返回 not_matured;成熟门禁不查询 ERP(调用次数由服务层保证为 0)。""" + assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured" + + +def test_yesterday_receipt_is_eligible(): + """昨天(T-1)收料进入预检。""" + assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "eligible" + + +def test_older_receipt_is_eligible(): + """更早收料同样可预检。""" + assert maturity_status(date(2026, 8, 1), BUSINESS_T) == "eligible" + + +def test_future_receipt_is_blocked(): + """未来日期收料返回结构化阻断值。""" + assert maturity_status(date(2026, 8, 7), BUSINESS_T) == "future" + + +def test_maturity_status_accepts_iso_strings(): + """字符串日期与 date 对象等价。""" + assert maturity_status("2026-08-05", "2026-08-06") == "eligible" + assert maturity_status("2026-08-06", "2026-08-06") == "not_matured" + + +def test_eligible_receipt_date_to_is_previous_day(): + """可调拨收料截止日期 = 业务日期 - 1 天。""" + assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 5) + + +def test_business_date_now_uses_shanghai_across_utc_midnight(): + """UTC 17:00(北京时间次日 01:00)业务日期不得漂移回 UTC 日期。""" + moment = datetime(2026, 8, 5, 17, 0, 0, tzinfo=timezone.utc) + assert business_date_now(moment) == date(2026, 8, 6) + + +def test_business_date_now_naive_moment_treated_as_utc(): + """naive 时刻按 UTC 兼容处理(与 business_numbering_service 口径一致)。""" + moment = datetime(2026, 8, 6, 0, 30, 0) + assert business_date_now(moment) == date(2026, 8, 6) + + +def test_business_date_now_defaults_to_shanghai_now(): + """无参调用返回 Asia/Shanghai 当前日期。""" + today = datetime.now(ZoneInfo("Asia/Shanghai")).date() + assert business_date_now() == today + + +def test_invalid_date_string_raises(): + """非法日期字符串必须抛 ValueError,不得静默解析。""" + with pytest.raises(ValueError): + maturity_status("2026/13/99", BUSINESS_T) diff --git a/backend/tests/services/in_transit_transfer/test_erp_adapter.py b/backend/tests/services/in_transit_transfer/test_erp_adapter.py new file mode 100644 index 00000000..bcce342d --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_erp_adapter.py @@ -0,0 +1,219 @@ +"""在途调拨 ERP Adapter 查询契约测试(L0 纯单元)。 + +用途:验证 query_inventory 请求携带全部必需追踪字段(operation_id/run_no/ + attempt_no/invoice_no/erp_org/拨出仓/拨入仓/数量),并正确分类 + 有库存/无库存/超时;SOAP 传输在 WSDL 未冻结前 fail-closed。 +依赖:app.services.in_transit_transfer.erp_adapter + fakes.FakeERP。 +逻辑:Adapter 是唯一 ERP 访问边界;测试注入 FakeERP 作为 transport。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.erp_adapter import ( + ErpAdapter, + ErpNotFrozenError, + ErpQueryTimeoutError, + ErpTransport, + ErpWriteTimeoutError, + InventoryQuery, + SoapErpTransport, + TransferWriteResult, +) +from tests.services.in_transit_transfer.assertions import assert_call_fields +from tests.services.in_transit_transfer.fakes import FakeERP + +pytestmark = pytest.mark.pure_unit + + +def _adapter(erp: FakeERP) -> ErpAdapter: + return ErpAdapter(transport=erp, default_org="HX-CN01") + + +def _query_kwargs(**overrides): + kwargs = { + "operation_id": "op-001", + "run_no": "RUN-20260806-001", + "attempt_no": 1, + "invoice_no": "INV-001", + "erp_org": "HX-CN01", + "from_warehouse": "DBS-TRANSIT", + "to_warehouse": "HUB-CN01", + "quantity": Decimal("1200"), + } + kwargs.update(overrides) + return kwargs + + +def test_query_inventory_found(): + """有库存 → InventoryQuery(found=True, quantity)。""" + erp = FakeERP() + erp.seed_inventory("INV-001", "1200") + adapter = _adapter(erp) + result = adapter.query_inventory(**_query_kwargs()) + assert isinstance(result, InventoryQuery) + assert result.found is True + assert result.quantity == Decimal("1200") + + +def test_query_inventory_not_found(): + """无库存 → found=False。""" + erp = FakeERP() + adapter = _adapter(erp) + result = adapter.query_inventory(**_query_kwargs()) + assert result.found is False + assert result.quantity is None + + +def test_query_request_carries_all_trace_fields(): + """调用记录包含全部追踪字段(提示词 §五 强制字段)。""" + erp = FakeERP() + erp.seed_inventory("INV-001", "1200") + adapter = _adapter(erp) + adapter.query_inventory(**_query_kwargs()) + records = erp.calls(invoice_no="INV-001") + assert len(records) == 1 + assert_call_fields(records[0]) + assert records[0].operation_id == "op-001" + assert records[0].erp_org == "HX-CN01" + assert records[0].from_warehouse == "DBS-TRANSIT" + assert records[0].to_warehouse == "HUB-CN01" + + +def test_query_timeout_classified_retryable(): + """查询超时 → ErpQueryTimeoutError(可重试,只读路径不落未知态)。""" + erp = FakeERP() + erp.set_query_scenario("timeout") + adapter = _adapter(erp) + with pytest.raises(ErpQueryTimeoutError) as excinfo: + adapter.query_inventory(**_query_kwargs()) + assert excinfo.value.retryable is True + + +def test_soap_transport_fails_closed_before_wsdl_frozen(): + """WSDL/endpoint 未冻结 → SoapErpTransport 调用必须抛 ErpNotFrozenError。""" + transport = SoapErpTransport(config={}) + adapter = ErpAdapter(transport=transport, default_org="HX-CN01") + with pytest.raises(ErpNotFrozenError): + adapter.query_inventory(**_query_kwargs()) + + +def test_soap_transport_refuses_without_frozen_config(): + """未配置 endpoint 的传输对象直接拒绝查询。""" + transport = SoapErpTransport(config={}) + with pytest.raises(ErpNotFrozenError): + transport.query_inventory(**_query_kwargs()) + + +def test_request_payload_never_contains_credentials(): + """Adapter 请求体不得携带任何凭据字段(Secret 边界)。""" + + class RecordingTransport: + def __init__(self) -> None: + self.seen: dict | None = None + + def query_inventory(self, **kwargs): + self.seen = kwargs + return {"found": True, "quantity": Decimal("1200")} + + def create_transfer(self, **kwargs): + self.seen = kwargs + return {"status": "success", "document_no": "TRF-1", "posted": True} + + def verify_duplicate(self, **kwargs): + return {"status": "duplicate_success", "document_no": "TRF-1", "verified_posted": True} + + transport = RecordingTransport() + adapter = ErpAdapter(transport=transport, default_org="HX-CN01") + adapter.query_inventory(**_query_kwargs()) + serialized = str(transport.seen) + for fragment in ("password", "secret", "token", "ciphertext", "credential", "api_key"): + assert fragment not in serialized.lower() + + +# ---- Phase 2:create_transfer / verify_duplicate --------------------------- + +def test_create_transfer_success(): + """成功写入 → TransferWriteResult(success, document_no)。""" + erp = FakeERP() + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert isinstance(result, TransferWriteResult) + assert result.status == "success" + assert result.document_no.startswith("TRF-") + + +def test_create_transfer_duplicate_success_when_posted(): + """重复 Invoice 且原单已审核过账 → duplicate_success(含原单号)。""" + erp = FakeERP() + erp.seed_document("INV-001", "TRF-00001", posted=True) + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "duplicate_success" + assert result.document_no == "TRF-00001" + assert result.verified_posted is True + + +def test_create_transfer_duplicate_unverified_blocks(): + """重复 Invoice 但无法证明原单已过账 → duplicate_unverified(阻断)。""" + erp = FakeERP() + erp.seed_document("INV-001", "TRF-00001", posted=False) + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "duplicate_unverified" + assert result.document_no == "TRF-00001" + assert result.verified_posted is False + + +def test_create_transfer_business_failed(): + """明确业务失败且原子回滚 → business_failed(不得产生单据)。""" + erp = FakeERP() + erp.set_write_scenario("business_failed") + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "business_failed" + assert result.error_code == "ERP_BUSINESS_REJECT" + assert result.document_no is None + + +def test_create_transfer_timeout_before_commit_is_technical_failed(): + """提交前超时(可证明未落单)→ technical_failed,非 result_unknown。""" + erp = FakeERP() + erp.set_write_scenario("timeout_before_commit") + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "technical_failed" + assert result.document_no is None + + +def test_create_transfer_timeout_after_commit_is_result_unknown(): + """提交后超时(无法确认是否落单)→ result_unknown,禁止自动重试。""" + erp = FakeERP() + erp.set_write_scenario("timeout_after_commit") + adapter = _adapter(erp) + result = adapter.create_transfer(**_query_kwargs()) + assert result.status == "result_unknown" + assert result.document_no is not None # Fake 已知落单,但业务层视为无法确认 + + +def test_verify_duplicate_returns_original_document(): + """verify_duplicate 获取原 ERP 单号并确认已过账。""" + erp = FakeERP() + erp.seed_document("INV-001", "TRF-OLD-1", posted=True) + adapter = _adapter(erp) + result = adapter.verify_duplicate(**_query_kwargs()) + assert result.status == "duplicate_success" + assert result.document_no == "TRF-OLD-1" + + +def test_verify_duplicate_unverified_when_not_posted(): + """原单未确认过账 → duplicate_unverified。""" + erp = FakeERP() + erp.seed_document("INV-001", "TRF-OLD-1", posted=False) + adapter = _adapter(erp) + result = adapter.verify_duplicate(**_query_kwargs()) + assert result.status == "duplicate_unverified" + assert result.verified_posted is False diff --git a/backend/tests/services/in_transit_transfer/test_excel_export.py b/backend/tests/services/in_transit_transfer/test_excel_export.py new file mode 100644 index 00000000..1a8e09d8 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_excel_export.py @@ -0,0 +1,79 @@ +"""在途调拨七 Sheet 异常 Excel 测试(Phase 3,L1)。 + +用途:验证异常 Excel 七 Sheet 齐全、内容按状态归类、原始行追溯存在、 + Secret 明文不出现(凭据不出现在 Excel)。 +依赖:transfer_db、execution_service、excel_export、openpyxl。 +逻辑:以真实 Run 数据生成 workbook 字节并回读断言。 +""" + +from __future__ import annotations + +import io + +import pytest +from openpyxl import load_workbook + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer.excel_export import EXCEL_SHEET_NAMES, build_exceptions_workbook +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _executed_run(dbs_ready_file): + """构造含 1 成功 + 1 业务失败(未生成单据)的 Run。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + erp.write_scenarios["INV-001"] = "business_failed" + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + return outcome.run_no, deps + + +def test_workbook_has_seven_sheets(transfer_db, dbs_ready_file): + """异常 Excel 必须包含规格定义的 7 个 Sheet。""" + run_no, _ = _executed_run(dbs_ready_file) + data = build_exceptions_workbook(run_no) + workbook = load_workbook(io.BytesIO(data)) + assert workbook.sheetnames == EXCEL_SHEET_NAMES + + +def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file): + """业务失败项进入失败 Sheet,成功项出现在汇总 Sheet。""" + run_no, _ = _executed_run(dbs_ready_file) + workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no))) + summary_sheet = workbook["执行汇总"] + summary_text = _sheet_text(summary_sheet) + assert "INV-002" in summary_text + failed_sheet = workbook["ERP技术失败"] + failed_text = _sheet_text(failed_sheet) + assert "INV-001" in failed_text + + +def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file): + """原始文件追溯 Sheet 保留 Sheet/行号(决策 11)。""" + run_no, _ = _executed_run(dbs_ready_file) + workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no))) + trace_sheet = workbook["原始文件追溯"] + text = _sheet_text(trace_sheet) + assert "Receipt" in text and "10" in text + + +def test_workbook_never_contains_secrets(transfer_db, dbs_ready_file): + """Secret 明文不得出现在 Excel(密码/Token/密文片段)。""" + run_no, _ = _executed_run(dbs_ready_file) + workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no))) + for sheet in workbook.worksheets: + text = _sheet_text(sheet).lower() + for fragment in ("password", "secret", "token", "ciphertext", "api_key", "webhook"): + assert fragment not in text + + +def _sheet_text(sheet) -> str: + """拼接 Sheet 全部单元格文本。""" + rows = [] + for row in sheet.iter_rows(values_only=True): + rows.append(" ".join(str(cell) for cell in row if cell is not None)) + return "\n".join(rows) diff --git a/backend/tests/services/in_transit_transfer/test_execution_service.py b/backend/tests/services/in_transit_transfer/test_execution_service.py new file mode 100644 index 00000000..a3ce8e25 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_execution_service.py @@ -0,0 +1,224 @@ +"""在途调拨执行服务测试(Phase 2 核心,L1,SQLite 内存库)。 + +用途:验证确认门禁(未确认/过期/快照变化均写入 0)、写前复查(库存变化阻断)、 + Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、 + 选择子集执行、重复点击防重与按 ERP 单号投影最终结果。 +依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service、execution_service。 +逻辑:全部经真实 ORM 落库;外部依赖注入 Fake 替身。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app import db +from app.core.errors import AppError +from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer.contracts import ( + TRANSFER_CONFIRMATION_REQUIRED, + TRANSFER_PRECHECK_EXPIRED, +) +from app.services.in_transit_transfer.execution_service import execute_precheck, get_run +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.fakes import FakeERP +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _ready_precheck(*files: dict, erp=None, source_codes=None) -> tuple: + """创建已预检(ready_to_execute)的 precheck 并返回 (deps, erp_fake, summary)。""" + deps, erp_fake, _ = make_transfer_deps(*files, erp=erp) + source_codes = source_codes or [files[0]["source_code"]] + summary = create_precheck(source_codes=source_codes, business_date="2026-08-06", deps=deps) + return deps, erp_fake, summary + + +def _erp_with_stock(dbs_ready_file, *seeds) -> FakeERP: + """按 Invoice 预置账面库存的 FakeERP。""" + erp = FakeERP() + for invoice_no, quantity in seeds: + erp.seed_inventory(invoice_no, quantity) + return erp + + +def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]: + run = db.session.query(TransferRun).filter_by(run_no=run_no).first() + return { + item.invoice_no: item + for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + } + + +def test_execute_happy_path(transfer_db, dbs_ready_file): + """两个可执行 Invoice → Run 成功,按 ERP 单号投影两张单据,Attempt 落库。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert outcome.status == "success" + assert outcome.run_no.startswith("RUN-") + assert len(outcome.result.erp_documents) == 2 + assert outcome.result.exceptions == () + + items = _load_items(outcome.run_no) + assert all(item.status == "success" for item in items.values()) + assert all(item.erp_document_no for item in items.values()) + run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first() + attempts = db.session.query(TransferAttempt).join(TransferInvoiceItem).filter( + TransferInvoiceItem.run_id == run.id, + ).all() + assert len([a for a in attempts if a.kind == "erp_write"]) == 2 + + +def test_execute_duplicate_invoice_maps_duplicate_success(transfer_db, dbs_ready_file): + """重复 Invoice(原单已过账)→ item duplicate_success + 原单号。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + erp.seed_document("INV-002", "TRF-OLD-002", posted=True) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert outcome.status == "success" + items = _load_items(outcome.run_no) + assert items["INV-002"].status == "duplicate_success" + assert items["INV-002"].erp_document_no == "TRF-OLD-002" + # 同 Invoice 不重复建单:每 Invoice 恰 1 次写调用 + assert len(erp.write_calls()) == 2 + + +def test_execute_business_failure_does_not_block_others(transfer_db, dbs_ready_file): + """单项明确业务失败 → 该项阻断,其余项成功,Run partial_failed。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + erp.write_scenarios["INV-001"] = "business_failed" + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert outcome.status == "partial_failed" + items = _load_items(outcome.run_no) + assert items["INV-001"].status == "blocked_recoverable" + assert items["INV-002"].status == "success" + # 异常项进入结果页"未生成单据"区 + assert any(exc.invoice_no == "INV-001" for exc in outcome.result.exceptions) + + +def test_execute_result_unknown_no_auto_retry(transfer_db, dbs_ready_file): + """result_unknown:状态终态、每 Invoice 写调用仅 1 次。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + erp.set_write_scenario("timeout_after_commit") + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert outcome.status == "partial_failed" + items = _load_items(outcome.run_no) + assert all(item.status == "result_unknown" for item in items.values()) + # 禁止自动重试:每个 Invoice 写调用恰 1 次 + assert len(erp.write_calls()) == 2 + + +def test_execute_unconfirmed_precheck_no_write(transfer_db, dbs_ready_file): + """预检未就绪(prechecking)→ 拒绝执行,ERP 写入为 0。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + precheck.status = "prechecking" + db.session.commit() + + with pytest.raises(AppError) as excinfo: + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert excinfo.value.code == TRANSFER_CONFIRMATION_REQUIRED + assert erp.write_calls() == [] + + +def test_execute_expired_precheck_no_write(transfer_db, dbs_ready_file): + """确认过期(超过 10 分钟)→ 拒绝执行,ERP 写入为 0。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + precheck.expires_at = datetime.utcnow() - timedelta(seconds=1) + db.session.commit() + + with pytest.raises(AppError) as excinfo: + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED + assert erp.write_calls() == [] + + +def test_execute_snapshot_change_blocks_write(transfer_db, dbs_ready_file): + """预检快照(数量)变化 → fail-closed,ERP 写入为 0。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + item = db.session.query(TransferInvoiceItem).filter_by(precheck_id=precheck.id).first() + item.receipt_quantity = "999" + db.session.commit() + + with pytest.raises(AppError) as excinfo: + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED + assert erp.write_calls() == [] + + +def test_execute_selected_subset_only(transfer_db, dbs_ready_file): + """仅选择 INV-001 → 只写入该 Invoice。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + outcome = execute_precheck( + precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-001"], + ) + assert outcome.status == "success" + assert len(outcome.result.erp_documents) == 1 + assert [record.invoice_no for record in erp.write_calls()] == ["INV-001"] + + +def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_file): + """勾选当天收料项 → 拒绝,ERP 写入为 0。""" + deps, erp_fake, summary = _ready_precheck(same_day_receipt_file, source_codes=["DBS-AWSSG"]) + with pytest.raises(AppError): + execute_precheck( + precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-041"], + ) + assert erp_fake.write_calls() == [] + + +def test_execute_double_click_rejected(transfer_db, dbs_ready_file): + """重复点击执行 → 第二次 409,不创建重复 Run。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + + first = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + with pytest.raises(AppError) as excinfo: + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + assert excinfo.value.http_status == 409 + # 只存在一个执行 Run(其余为预检关联 Run) + execution_runs = db.session.query(TransferRun).filter( + TransferRun.status != "prechecking", + ).count() + assert execution_runs == 1 + assert first.run_no + + +def test_execute_write_before_recheck_inventory_change_blocks(transfer_db, dbs_ready_file): + """写前复查发现 ERP 库存变化 → 该项阻断不写,其余项正常。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + erp.seed_inventory("INV-001", "999") # 预检后库存变化 + + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + items = _load_items(outcome.run_no) + assert items["INV-001"].status == "blocked_recoverable" + assert items["INV-002"].status == "success" + assert [record.invoice_no for record in erp.write_calls()] == ["INV-002"] + + +def test_get_run_restores_document_projection(transfer_db, dbs_ready_file): + """GET run → 按 ERP 单号聚合单据 + 未生成单据异常分开展示。""" + erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200")) + erp.write_scenarios["INV-001"] = "business_failed" + deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp) + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + + restored = get_run(outcome.run_no) + assert restored["run_no"] == outcome.run_no + assert len(restored["result"]["erp_documents"]) == 1 + assert any(exc["invoice_no"] == "INV-001" for exc in restored["result"]["exceptions"]) diff --git a/backend/tests/services/in_transit_transfer/test_file_preparation.py b/backend/tests/services/in_transit_transfer/test_file_preparation.py new file mode 100644 index 00000000..a48becc4 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_file_preparation.py @@ -0,0 +1,128 @@ +"""在途调拨文件 Ready 复用与 RPA 触发测试(L0 纯单元)。 + +用途:验证当日 ready 文件可复用(不触发 RPA)、缺文件时同一来源只触发一次 + RPA、存在活动 Source Job 时绑定已有任务、触发失败 fail-closed。 +依赖:app.services.in_transit_transfer.file_preparation + fakes。 +逻辑:仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身。 +""" + +from __future__ import annotations + +import pytest + +from app.services.in_transit_transfer.file_preparation import ( + FilePreparationResult, + ReadyReceiptFile, + ReceiptFileRepository, + ensure_receipt_file_ready, +) +from tests.services.in_transit_transfer.fakes import FakeRPA +from tests.services.in_transit_transfer.repo_fakes import FakeReceiptFileRepository + + +def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyReceiptFile: + return ReadyReceiptFile( + source_code=source_code, + business_date=business_date, + file_no=f"REC-{source_code}-001", + file_version="v3", + checksum="d" * 64, + rows=(), + ) + + +def test_ready_file_reused_without_rpa_trigger(): + """当日 ready 文件存在 → 复用(stage=file_ready),不触发 RPA。""" + repository = FakeReceiptFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()}) + rpa = FakeRPA() + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert result.stage == "file_ready" + assert result.file is not None + assert rpa.triggered == [] + + +def test_missing_file_triggers_rpa_once(): + """缺文件 → 触发 RPA 一次并进入 waiting_rpa_callback。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert result.stage == "waiting_rpa_callback" + assert result.file is None + assert len(rpa.triggered) == 1 + assert rpa.triggered[0]["source_code"] == "DBS-AWSBI" + + +def test_active_source_job_binds_existing_task_no_new_trigger(): + """存在活动 Source Job → 绑定已有任务,不重复触发 RPA。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI", + ) + assert result.stage == "waiting_rpa_callback" + assert rpa.triggered == [] + + +def test_concurrent_requests_share_one_trigger(): + """并发请求携带同一活动键 → 全部绑定已有任务,不重复触发 RPA。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + for _ in range(3): + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI", + ) + assert result.stage == "waiting_rpa_callback" + assert rpa.triggered == [] + + +def test_without_active_key_each_call_triggers_once(): + """无活动键时每次调用各触发一次;幂等由调用方 SourceJob 唯一键兜底。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert len(rpa.triggered) == 2 + + +def test_rpa_trigger_failure_is_fail_closed(): + """RPA 触发失败 → stage=failed 且带错误码,不误报 file_ready。""" + repository = FakeReceiptFileRepository() + rpa = FakeRPA() + rpa.fail_on.add("DBS-AWSBI") + result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert result.stage == "failed" + assert result.error_code == "RPA_TRIGGER_FAILED" + + +def test_dbs_and_crane_sources_isolated(): + """DBS 失败不影响 Crane 的文件准备(来源隔离)。""" + repository = FakeReceiptFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")}) + rpa = FakeRPA() + rpa.fail_on.add("DBS-AWSBI") + dbs_result = ensure_receipt_file_ready( + source_code="DBS-AWSBI", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + crane_result = ensure_receipt_file_ready( + source_code="CRANE-SZ", business_date="2026-08-06", + repository=repository, rpa_trigger=rpa, + ) + assert dbs_result.stage == "failed" + assert crane_result.stage == "file_ready" diff --git a/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py b/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py new file mode 100644 index 00000000..106624aa --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py @@ -0,0 +1,117 @@ +"""在途调拨 Invoice 多行汇总与冲突测试(L0 纯单元)。 + +用途:验证相同 Invoice 多行只汇总收料数量并永久保留原始行追溯; + 同一 Invoice 出现多料号/多收料日期时整单阻断(InvoiceConflictError)。 +依赖:app.services.in_transit_transfer.invoice_aggregator + file_parser。 +逻辑:汇总键为 (source_code, invoice_no);冲突判定基于料号与收料日期。 +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.file_parser import parse_receipt_rows +from app.services.in_transit_transfer.invoice_aggregator import ( + AggregatedInvoice, + InvoiceConflictError, + aggregate_invoices, +) + +pytestmark = pytest.mark.pure_unit + + +def _parsed(rows: list[dict]) -> list: + """将原始行解析为 ParsedReceiptRow。""" + return parse_receipt_rows(source_code="DBS-AWSBI", rows=rows) + + +def _row(invoice_no: str, *, material_no: str = "MAT-001", material_name: str = "连接器组件", + specification: str = "A 型 / 24PIN", receipt_date: str = "2026-08-05", + quantity: str = "500", row_no: int = 10, sheet: str = "Receipt") -> dict: + return { + "sheet": sheet, "row_no": row_no, "invoice_no": invoice_no, + "material_no": material_no, "material_name": material_name, + "specification": specification, "receipt_date": receipt_date, + "receipt_quantity": quantity, "source_code": "DBS-AWSBI", + } + + +def test_same_invoice_multiple_rows_sum_quantity(): + """同 Invoice 同料号两行 → 数量相加,保留两条原始行。""" + rows = [ + _row("INV-001", quantity="500", row_no=10), + _row("INV-001", quantity="700", row_no=11), + ] + invoices = aggregate_invoices(_parsed(rows)) + assert len(invoices) == 1 + invoice = invoices[0] + assert invoice.invoice_no == "INV-001" + assert invoice.receipt_quantity == Decimal("1200") + assert len(invoice.raw_lines) == 2 + assert invoice.raw_lines[0].row_no == 10 + assert invoice.raw_lines[1].row_no == 11 + assert all(line.sheet == "Receipt" for line in invoice.raw_lines) + + +def test_distinct_invoices_stay_separate_and_sorted(): + """不同 Invoice 保持独立并按 Invoice 排序。""" + rows = [ + _row("INV-002", row_no=5), + _row("INV-001", row_no=3), + ] + invoices = aggregate_invoices(_parsed(rows)) + assert [item.invoice_no for item in invoices] == ["INV-001", "INV-002"] + + +def test_multiple_material_no_conflict_blocks_invoice(): + """同一 Invoice 出现多个料号 → 整单阻断。""" + rows = [ + _row("INV-001", material_no="MAT-001", row_no=1), + _row("INV-001", material_no="MAT-002", row_no=2), + ] + with pytest.raises(InvoiceConflictError) as excinfo: + aggregate_invoices(_parsed(rows)) + assert excinfo.value.details.get("invoice_no") == "INV-001" + + +def test_multiple_receipt_date_conflict_blocks_invoice(): + """同一 Invoice 出现多个收料日期 → 整单阻断。""" + rows = [ + _row("INV-001", receipt_date="2026-08-05", row_no=1), + _row("INV-001", receipt_date="2026-08-06", row_no=2), + ] + with pytest.raises(InvoiceConflictError): + aggregate_invoices(_parsed(rows)) + + +def test_aggregated_invoice_keeps_material_identity(): + """汇总结果保留料号、品名、规格与收料日期。""" + rows = [ + _row("INV-001", material_no="MAT-001", material_name="连接器组件", + specification="A 型 / 24PIN", receipt_date="2026-08-05", row_no=1), + _row("INV-001", material_no="MAT-001", row_no=2), + ] + invoices = aggregate_invoices(_parsed(rows)) + invoice = invoices[0] + assert invoice.material_no == "MAT-001" + assert invoice.material_name == "连接器组件" + assert invoice.specification == "A 型 / 24PIN" + assert invoice.receipt_date == date(2026, 8, 5) + + +def test_raw_lines_carry_file_version(): + """原始行追溯包含文件版本(决策 11:来源证据)。""" + rows = [ + _row("INV-001", row_no=10), + _row("INV-001", row_no=11), + ] + invoices = aggregate_invoices(_parsed(rows), file_version="v3") + assert all(line.file_version == "v3" for line in invoices[0].raw_lines) + + +def test_empty_input_returns_empty(): + """空行输入返回空汇总。""" + assert aggregate_invoices([]) == [] diff --git a/backend/tests/services/in_transit_transfer/test_metrics.py b/backend/tests/services/in_transit_transfer/test_metrics.py new file mode 100644 index 00000000..00616c1f --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_metrics.py @@ -0,0 +1,46 @@ +"""在途调拨运营指标测试(Phase 4,L1)。 + +用途:验证指标聚合(Run/明细状态分布、待处理老化、通知失败数)正确。 +依赖:transfer_db、precheck/execution/metrics、repo_fakes。 +逻辑:指标由数据库现状投影,便于上线观察板使用。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.metrics import collect_metrics +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file): + """指标包含 Run 状态分布与明细状态分布。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + execute_precheck(precheck_id=summary.precheck_id, deps=deps) + + metrics = collect_metrics() + assert metrics["runs"]["success"] >= 1 + assert metrics["items"]["success"] >= 2 + + +def test_collect_metrics_backlog_and_notification_failure(transfer_db, dbs_ready_file): + """指标含待处理老化与通知失败计数。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") # mismatch → blocked + erp.seed_inventory("INV-002", "1200") + create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + item.updated_at = item.updated_at # 保持默认年龄 + db.session.commit() + + metrics = collect_metrics() + assert metrics["backlog"]["recoverable"] == 1 + assert "aging" in metrics["backlog"] + assert "notification_failed_runs" in metrics["runs"] diff --git a/backend/tests/services/in_transit_transfer/test_migration_execution.py b/backend/tests/services/in_transit_transfer/test_migration_execution.py new file mode 100644 index 00000000..2f1f4e5a --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_migration_execution.py @@ -0,0 +1,72 @@ +"""在途调拨迁移升级/回滚执行测试。 + +用途:在 SQLite 内存库上真实执行 it1a2b3c4d5e 迁移的 upgrade 与 downgrade, + 证明建表/回滚 DDL 可运行(Phase 0 验收:迁移 upgrade/downgrade 成功)。 +依赖:Alembic Operations、SQLAlchemy SQLite、it1a2b3c4d5e 迁移模块。 +逻辑:upgrade 后断言 7 张调拨表存在;downgrade 后断言全部删除。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + +pytestmark = pytest.mark.pure_unit + +EXPECTED_TABLES = { + "transfer_runs", + "transfer_source_jobs", + "transfer_prechecks", + "transfer_invoice_items", + "transfer_attempts", + "transfer_audit_events", + "transfer_archives", +} + + +def _load_migration(): + """加载新增调拨迁移模块。""" + path = Path(__file__).parents[3] / "migrations" / "versions" / "it1a2b3c4d5e_add_in_transit_transfer.py" + spec = importlib.util.spec_from_file_location("in_transit_transfer_migration", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_transfer_migration_upgrade_creates_all_tables(): + """升级必须创建全部 7 张调拨表。""" + engine = sa.create_engine("sqlite:///:memory:") + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + migration = _load_migration() + migration.op = operations + + migration.upgrade() + tables = set(sa.inspect(connection).get_table_names()) + assert EXPECTED_TABLES <= tables, f"missing tables: {EXPECTED_TABLES - tables}" + + # 关键约束抽查:Invoice 唯一键与状态检查约束落库 + columns = {item["name"] for item in sa.inspect(connection).get_columns("transfer_invoice_items")} + assert "invoice_no" in columns and "raw_lines_json" in columns + + +def test_transfer_migration_downgrade_drops_all_tables(): + """回滚必须删除全部调拨表且不残留索引。""" + engine = sa.create_engine("sqlite:///:memory:") + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + migration = _load_migration() + migration.op = operations + + migration.upgrade() + migration.downgrade() + tables = set(sa.inspect(connection).get_table_names()) + assert not (EXPECTED_TABLES & tables), f"leftover tables: {EXPECTED_TABLES & tables}" diff --git a/backend/tests/services/in_transit_transfer/test_migration_revision.py b/backend/tests/services/in_transit_transfer/test_migration_revision.py new file mode 100644 index 00000000..f9a64ba0 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_migration_revision.py @@ -0,0 +1,59 @@ +"""在途调拨数据库迁移链测试。 + +用途:验证新增迁移 revision 存在、正确挂在当前 head 之后,且不产生分叉。 +依赖:alembic 迁移脚本目录(backend/migrations/versions)。 +逻辑:读取版本文件头部 revision/down_revision 文本,不加载 Flask 应用。 +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions" +# 在途调拨迁移根:ic1a2b3c4d5f(Add integration connector)挂在其上。 +NEW_REVISION = "ic1a2b3c4d5f" +# ic1a2b3c4d5f 的直接 parent(仍是线性链,未被分叉)。 +CURRENT_HEAD = "it1a2b3c4d5e" + +pytestmark = pytest.mark.pure_unit + + +def _migration_file(revision: str) -> Path: + """按 revision 定位迁移文件(命名规则 _.py)。""" + for path in MIGRATIONS_DIR.glob("*.py"): + if path.name.startswith(f"{revision}_"): + return path + raise AssertionError(f"migration file for revision {revision} not found") + + +def test_migration_file_exists_and_chains_from_head(): + """新增迁移必须存在并挂在当前 head(it1a2b3c4d5e)之后。""" + path = _migration_file(NEW_REVISION) + text = path.read_text(encoding="utf-8") + assert f"revision = '{NEW_REVISION}'" in text or f'revision = "{NEW_REVISION}"' in text + assert f"down_revision = '{CURRENT_HEAD}'" in text or f'down_revision = "{CURRENT_HEAD}"' in text + + +def test_new_revision_is_not_referenced_as_parent(): + """没有歧义分叉:ic1a2b3c4d5f 后续仅允许线性延伸(if1b2c3d4e5g),禁止其余分支。""" + allowed_children = {"if1b2c3d4e5g"} + for path in MIGRATIONS_DIR.glob("*.py"): + if path.name.startswith(f"{NEW_REVISION}_"): + continue + text = path.read_text(encoding="utf-8", errors="ignore") + match = re.search(rf"down_revision\s*=\s*['\"]{NEW_REVISION}['\"]", text) + if match and path.name.split("_", 1)[0] not in allowed_children: + raise AssertionError(f"unexpected branch from {NEW_REVISION}: {path.name}") + + +def test_head_still_linear_after_new_migration(): + """当前 in_transit_transfer 链保持线性:it1a2b3c4d5e 之后仅 ic1a2b3c4d5f 一个后继。""" + allowed_children = {"ic1a2b3c4d5f"} + for path in MIGRATIONS_DIR.glob("*.py"): + text = path.read_text(encoding="utf-8", errors="ignore") + match = re.search(rf"down_revision\s*=\s*['\"]{CURRENT_HEAD}['\"]", text) + if match and path.name.split("_", 1)[0] not in allowed_children: + raise AssertionError(f"unexpected branch from head: {path.name}") diff --git a/backend/tests/services/in_transit_transfer/test_models.py b/backend/tests/services/in_transit_transfer/test_models.py new file mode 100644 index 00000000..304def6f --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_models.py @@ -0,0 +1,213 @@ +"""在途调拨领域模型测试(L1,使用 SQLite 内存库)。 + +用途:验证 7 个核心模型可建表、可持久化回读,唯一约束与状态约束生效, + 审计事件只追加不可改删。 +依赖:app fixture(create_all 自动建表)、models/in_transit_transfer。 +逻辑:全部走真实 ORM 落库,不 Mock 模型本身。 +""" + +from __future__ import annotations + +import pytest +from sqlalchemy.exc import IntegrityError +from sqlalchemy import inspect + +from app import db +from app.models import ( + TransferArchive, + TransferAttempt, + TransferAuditEvent, + TransferInvoiceItem, + TransferPrecheck, + TransferRun, + TransferSourceJob, +) + +TRANSFER_TABLES = { + "transfer_runs", "transfer_source_jobs", "transfer_prechecks", + "transfer_invoice_items", "transfer_attempts", "transfer_audit_events", + "transfer_archives", +} + + +def test_create_all_includes_transfer_tables(app): + """create_all 必须包含全部调拨表(迁移与测试建表同源)。""" + inspector = inspect(db.engine) + tables = set(inspector.get_table_names()) + assert TRANSFER_TABLES <= tables + + +def test_run_source_job_item_attempt_roundtrip(transfer_db): + """Run → SourceJob → InvoiceItem → Attempt 全链路持久化回读。""" + run = TransferRun( + run_no="RUN-20260806-001", + trigger_type="manual", + business_date="2026-08-06", + status="prechecking", + source_codes_json=["DBS-AWSBI"], + counts_json={"file_invoice_count": 3, "executable_count": 2}, + ) + transfer_db.session.add(run) + transfer_db.session.flush() + + source_job = TransferSourceJob( + run_id=run.id, + source_code="DBS-AWSBI", + source_config_version=5, + status="checking_file", + ) + precheck = TransferPrecheck( + precheck_no="TPC-20260806-001", + run_id=run.id, + business_date="2026-08-06", + status="ready_to_execute", + scope_json={"source_codes": ["DBS-AWSBI"]}, + counts_json={"executable_count": 1}, + precheck_hash="sha256:test", + ) + item = TransferInvoiceItem( + precheck=precheck, + run_id=run.id, + source_code="DBS-AWSBI", + invoice_no="INV-001", + material_no="MAT-001", + material_name="连接器组件", + specification="A 型 / 24PIN", + receipt_date="2026-08-05", + from_warehouse="DBS-TRANSIT", + to_warehouse="HUB-CN01", + receipt_quantity="1200", + erp_quantity="1200", + status="ready_to_execute", + raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}], + ) + transfer_db.session.add_all([source_job, precheck, item]) + transfer_db.session.flush() + + attempt = TransferAttempt( + item_id=item.id, + attempt_no=1, + kind="erp_query", + status="success", + request_snapshot_json={"invoice_no": "INV-001"}, + operation_id="op_001", + ) + transfer_db.session.add(attempt) + transfer_db.session.commit() + + loaded_run = transfer_db.session.get(TransferRun, run.id) + assert loaded_run.run_no == "RUN-20260806-001" + loaded_item = transfer_db.session.get(TransferInvoiceItem, item.id) + assert loaded_item.raw_lines_json[0]["row_no"] == 10 + loaded_attempt = transfer_db.session.get(TransferAttempt, attempt.id) + assert loaded_attempt.operation_id == "op_001" + assert loaded_attempt.attempt_no == 1 + + +def test_invoice_item_unique_per_precheck(transfer_db): + """同一预检内同一 Invoice 只能出现一次(防重复建单底座)。""" + precheck = TransferPrecheck( + precheck_no="TPC-20260806-002", + business_date="2026-08-06", + status="prechecking", + scope_json={}, + counts_json={}, + precheck_hash="sha256:test2", + ) + transfer_db.session.add(precheck) + transfer_db.session.flush() + + def _item(invoice_no: str) -> TransferInvoiceItem: + return TransferInvoiceItem( + precheck_id=precheck.id, + source_code="DBS-AWSBI", + invoice_no=invoice_no, + material_no="MAT-001", + receipt_date="2026-08-05", + from_warehouse="DBS-TRANSIT", + to_warehouse="HUB-CN01", + receipt_quantity="1200", + erp_quantity="1200", + status="ready_to_execute", + raw_lines_json=[], + ) + + transfer_db.session.add(_item("INV-001")) + transfer_db.session.flush() + transfer_db.session.add(_item("INV-001")) + with pytest.raises(IntegrityError): + transfer_db.session.flush() + transfer_db.session.rollback() + + +def test_run_no_unique(transfer_db): + """run_no 唯一约束生效。""" + transfer_db.session.add(TransferRun(run_no="RUN-UNIQUE-1", trigger_type="manual", + business_date="2026-08-06", status="queued")) + transfer_db.session.flush() + transfer_db.session.add(TransferRun(run_no="RUN-UNIQUE-1", trigger_type="manual", + business_date="2026-08-06", status="queued")) + with pytest.raises(IntegrityError): + transfer_db.session.flush() + transfer_db.session.rollback() + + +def test_invoice_item_status_check_constraint(transfer_db): + """Invoice 状态必须属于冻结枚举(数据库级门禁兜底)。""" + precheck = TransferPrecheck( + precheck_no="TPC-20260806-003", business_date="2026-08-06", + status="prechecking", scope_json={}, counts_json={}, precheck_hash="x", + ) + transfer_db.session.add(precheck) + transfer_db.session.flush() + transfer_db.session.add(TransferInvoiceItem( + precheck_id=precheck.id, source_code="DBS-AWSBI", invoice_no="INV-999", + material_no="MAT-9", receipt_date="2026-08-05", + from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", + receipt_quantity="1", erp_quantity="1", + status="no_such_status", raw_lines_json=[], + )) + with pytest.raises(IntegrityError): + transfer_db.session.flush() + transfer_db.session.rollback() + + +def test_audit_event_is_append_only(transfer_db): + """审计事件禁止更新与删除(ORM 门禁)。""" + event = TransferAuditEvent( + event_type="TRANSFER_READ", aggregate_type="transfer_run", + aggregate_id="RUN-X", run_no="RUN-X", actor_type="user", + actor_id="u-1", result="success", + ) + transfer_db.session.add(event) + transfer_db.session.commit() + + event.result = "failure" + with pytest.raises(Exception): + transfer_db.session.commit() + transfer_db.session.rollback() + + transfer_db.session.delete(event) + with pytest.raises(Exception): + transfer_db.session.commit() + transfer_db.session.rollback() + + +def test_archive_roundtrip(transfer_db): + """归档记录保存对象路径与 Hash,供 Phase 4 MinIO 归档校验。""" + archive = TransferArchive( + archive_no="ARC-20260806-001", + object_type="erp_inventory_snapshot", + object_id="TPC-20260806-001", + storage_provider="minio", + storage_bucket="hxops-transfer", + storage_key="transfer/20260806/snapshot.xlsx", + original_filename="erp-inventory-20260806.xlsx", + file_size=1024, + sha256="a" * 64, + ) + transfer_db.session.add(archive) + transfer_db.session.commit() + loaded = transfer_db.session.get(TransferArchive, archive.id) + assert loaded.sha256 == "a" * 64 + assert loaded.object_type == "erp_inventory_snapshot" diff --git a/backend/tests/services/in_transit_transfer/test_movement_contract.py b/backend/tests/services/in_transit_transfer/test_movement_contract.py new file mode 100644 index 00000000..bb41c93d --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_movement_contract.py @@ -0,0 +1,62 @@ +"""在途调拨通用异动表领域字段契约测试(L0 纯单元)。 + +用途:锁定调拨定死的 10 个通用异动/移动字段契约(领域定死、不配置化), + 以及通用异动解析器 parse_movement_rows 把字段映射到调拨 ParsedReceiptRow。 +依赖:app.services.in_transit_transfer.movement_contract + file_parser(纯函数)。 +逻辑:字段契约是 immutable 常量;解析只认契约字段,供未来出货/入库 Excel 复用。 +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.file_parser import ParsedReceiptRow +from app.services.in_transit_transfer.movement_contract import ( + MOVEMENT_FIELDS, + MovementField, + movement_match_key, + movement_quantity_field, + movement_identity_fields, +) + +pytestmark = pytest.mark.pure_unit + + +def test_movement_fields_contract_is_frozen_and_complete(): + """领域字段契约定死:10 个字段、名称唯一、不可变。""" + assert len(MOVEMENT_FIELDS) == 10 + codes = {field.code for field in MOVEMENT_FIELDS} + assert codes == { + "doc_no", "line_no", "in_out_flag", "material_code", "material_name", + "warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", + } + + +def test_movement_field_metadata(): + """每个字段携带中文名、类型与使用标记。""" + by_code = {field.code: field for field in MOVEMENT_FIELDS} + doc_no = by_code["doc_no"] + assert doc_no.label == "单号" + assert doc_no.value_type == "text" + assert doc_no.is_identity is True + assert by_code["quantity"].value_type == "decimal" + assert by_code["movement_date"].value_type == "date" + + +def test_match_key_is_doc_no(): + """调拨幂等/汇总键为 doc_no(单号)。""" + assert movement_match_key() == "doc_no" + + +def test_quantity_field_is_quantity(): + """数量严格匹配字段为 quantity。""" + assert movement_quantity_field() == "quantity" + + +def test_identity_fields_cover_match_predicates(): + """幂等/匹配字段集至少含 doc_no + material_code + movement_date。""" + ids = movement_identity_fields() + assert {"doc_no", "material_code", "movement_date"} <= ids diff --git a/backend/tests/services/in_transit_transfer/test_movement_file_repository.py b/backend/tests/services/in_transit_transfer/test_movement_file_repository.py new file mode 100644 index 00000000..b6bdd0d1 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_movement_file_repository.py @@ -0,0 +1,81 @@ +"""真实异动文件仓库的 xlsx→领域行解析测试。 + +用途:验证 _extract_movement_rows 用 movement field_mapping(定死领域字段 code→表头别名) + 把 xlsx 原始列映射为领域行 dict,供 parse_movement_rows 校验。纯单元(内存 xlsx)。 +依赖:openpyxl(构造内存工作簿)、movement_file_repository._extract_movement_rows。 +""" + +from __future__ import annotations + +from io import BytesIO + +import pytest +from openpyxl import Workbook + +from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows + +pytestmark = pytest.mark.pure_unit + +MOVEMENT_MAPPING = { + 'doc_no': '单据编号', + 'line_no': '项次', + 'in_out_flag': '进出库别', + 'material_code': '料号', + 'material_name': '品名', + 'warehouse_code': '仓库', + 'storage_code': '储位', + 'lot_no': '批号', + 'quantity': '数量', + 'movement_date': '异动日期', +} + + +def _movement_xlsx_bytes() -> bytes: + """构造含表头 + 两行数据的 xlsx。""" + wb = Workbook() + ws = wb.active + ws.title = 'Movement' + ws.append(['单据编号', '项次', '进出库别', '料号', '品名', '仓库', '储位', '批号', '数量', '异动日期']) + ws.append(['MOV-001', 1, 'I', 'MAT-001', '连接器', 'DBS-T', 'A-01', 'LOT-9', 500, '2026-08-05']) + ws.append(['MOV-001', 2, 'I', 'MAT-001', '连接器', 'DBS-T', 'A-01', 'LOT-9', 300, '2026-08-05']) + buf = BytesIO() + wb.save(buf) + return buf.getvalue() + + +def test_extract_movement_rows_maps_columns_to_domain_fields(): + """表头别名被映射为定死领域字段 code 的行字段。""" + rows = _extract_movement_rows( + _movement_xlsx_bytes(), + field_mapping=MOVEMENT_MAPPING, + sheet_name='Movement', + header_row_index=1, + ) + assert len(rows) == 2 + first = rows[0] + assert first['doc_no'] == 'MOV-001' + assert first['material_code'] == 'MAT-001' + assert first['quantity'] == 500 + assert str(first['movement_date']) == '2026-08-05' + second = rows[1] + assert second['quantity'] == 300 + + +def test_extract_movement_rows_skips_missing_alias_columns(): + """表头缺某别名列时,对应领域字段不输出(行仍保留其余字段)。""" + wb = Workbook() + ws = wb.active + ws.title = 'S' + ws.append(['单据编号', '料号', '数量']) + ws.append(['MOV-9', 'MAT-9', 120]) + buf = BytesIO() + wb.save(buf) + rows = _extract_movement_rows( + buf.getvalue(), + field_mapping={'doc_no': '单据编号', 'material_code': '料号', 'quantity': '数量', 'movement_date': '异动日期'}, + sheet_name='S', + header_row_index=1, + ) + assert rows[0]['doc_no'] == 'MOV-9' + assert rows[0]['quantity'] == 120 + assert 'movement_date' not in rows[0] diff --git a/backend/tests/services/in_transit_transfer/test_movement_parser.py b/backend/tests/services/in_transit_transfer/test_movement_parser.py new file mode 100644 index 00000000..8feadf30 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_movement_parser.py @@ -0,0 +1,94 @@ +"""通用异动表解析器测试(L0 纯单元)。 + +用途:验证 parse_movement_rows 把通用异动字段(doc_no/line_no/...)映射到 + 调拨 ParsedReceiptRow(invoice_no=doc_no, receipt_quantity=quantity, + receipt_date=movement_date),并保留既有校验(必填/非法值/来源一致)。 +依赖:app.services.in_transit_transfer.movement_parser(纯函数)。 +逻辑:字段映射后进入既有 file_parser 校验链路,保证下游 invoice_aggregator 不变。 +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.file_parser import ( + ParsedReceiptRow, + ReceiptFileSchemaError, + parse_movement_rows, +) + +pytestmark = pytest.mark.pure_unit + +VALID_MOVEMENT_ROW = { + "sheet": "Movement", + "row_no": 7, + "doc_no": "MOV-001", + "line_no": 1, + "in_out_flag": "I", + "material_code": "MAT-001", + "material_name": "连接器组件", + "warehouse_code": "DBS-TRANSIT", + "storage_code": "A-01", + "lot_no": "LOT-9", + "quantity": "500", + "movement_date": "2026-08-05", + "source_code": "DBS-AWSBI", +} + + +def _rows(**overrides) -> list[dict]: + base = dict(VALID_MOVEMENT_ROW) + base.update(overrides) + return [base] + + +def test_valid_movement_row_maps_to_parsed_rows(): + """通用字段映射为调拨行:doc_no→invoice_no、quantity→receipt_quantity、movement_date→receipt_date。""" + parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows()) + assert len(parsed) == 1 + row = parsed[0] + assert isinstance(row, ParsedReceiptRow) + assert row.invoice_no == "MOV-001" + assert row.material_no == "MAT-001" + assert row.material_name == "连接器组件" + assert row.receipt_date == date(2026, 8, 5) + assert row.receipt_quantity == Decimal("500") + assert row.sheet == "Movement" + assert row.row_no == 7 + + +def test_missing_doc_no_rejected(): + """单号缺失阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no="")) + + +def test_invalid_quantity_rejected(): + """非数字数量阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc")) + + +def test_invalid_movement_date_rejected(): + """非法异动日期阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99")) + + +def test_source_identity_mismatch_rejected(): + """来源身份漂移阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ")) + + +def test_optional_fields_default_empty(): + """品名/规格/仓库/储位/批号可缺省为空展示。""" + parsed = parse_movement_rows( + source_code="DBS-AWSBI", + rows=_rows(material_name="", warehouse_code="", storage_code="", lot_no=""), + ) + row = parsed[0] + assert row.material_name == "" diff --git a/backend/tests/services/in_transit_transfer/test_notification.py b/backend/tests/services/in_transit_transfer/test_notification.py new file mode 100644 index 00000000..74c1e7e2 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_notification.py @@ -0,0 +1,54 @@ +"""在途调拨企微汇总通知测试(Phase 3,L1)。 + +用途:验证每个非空 Run 恰好一条汇总通知、空数据不通知、 + 通知失败不改变 ERP 结果(run.status 保持)。 +依赖:transfer_db、execution_service、notification、fakes.FakeWeCom。 +逻辑:通知状态独立于 ERP 业务状态;失败记录 notification_failed。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import TransferRun +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.notification import notify_run_summary +from app.services.in_transit_transfer.precheck_service import create_precheck +from tests.services.in_transit_transfer.fakes import FakeWeCom +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _executed_run(dbs_ready_file): + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + return outcome.run_no + + +def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file): + """非空 Run → 恰好一条汇总通知;重复调用幂等。""" + run_no = _executed_run(dbs_ready_file) + wecom = FakeWeCom() + first = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1", "u-2"]) + assert first["notification_status"] == "success" + second = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1"]) + assert second["delivered"] is False # 已投递,幂等跳过 + assert len(wecom.deliveries) == 1 + run = db.session.query(TransferRun).filter_by(run_no=run_no).first() + assert run.notification_status == "success" + assert run.status == "success" # ERP 结果不受影响 + + +def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_file): + """通知失败 → notification_status=failed,run.status 保持 success。""" + run_no = _executed_run(dbs_ready_file) + wecom = FakeWeCom() + wecom.attach_fail = True + result = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1"], excel_path="x.xlsx") + assert result["notification_status"] == "failed" + run = db.session.query(TransferRun).filter_by(run_no=run_no).first() + assert run.notification_status == "failed" + assert run.status == "success" # 关键:通知失败不改变 ERP 业务结果 diff --git a/backend/tests/services/in_transit_transfer/test_orchestrator.py b/backend/tests/services/in_transit_transfer/test_orchestrator.py new file mode 100644 index 00000000..e8403c79 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_orchestrator.py @@ -0,0 +1,69 @@ +"""在途调拨 Run 编排测试(Phase 2,L1)。 + +用途:验证执行 Run 创建(执行中状态、关联预检与明细)、终态收尾与 + 重复创建防护。 +依赖:transfer_db、precheck_service、orchestrator、repo_fakes。 +逻辑:编排层复用 execution_service 落库流程,本文件聚焦 Run 生命周期辅助函数。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.errors import ConflictError +from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun +from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run +from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.status import TransferRunStatus +from tests.services.in_transit_transfer.fakes import FakeERP +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _ready_precheck(dbs_ready_file): + """创建已预检 precheck 并返回 (deps, summary)。""" + erp = FakeERP() + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + deps, _, _ = make_transfer_deps(dbs_ready_file, erp=erp) + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return deps, summary + + +def test_create_execution_run_links_items_and_sets_executing(transfer_db, dbs_ready_file): + """create_execution_run 创建 executing Run 并关联可执行明细。""" + deps, summary = _ready_precheck(dbs_ready_file) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + + run = create_execution_run(precheck, deps=deps, actor_id=None) + assert run.status == TransferRunStatus.EXECUTING.value + items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + assert len(items) == 2 + assert all(item.status == "executing" for item in items) + + +def test_finalize_run_sets_terminal_status(transfer_db, dbs_ready_file): + """finalize_run 按明细终态汇总 Run 状态。""" + deps, summary = _ready_precheck(dbs_ready_file) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + run = create_execution_run(precheck, deps=deps, actor_id=None) + + items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + for item in items: + item.status = "success" + finalize_run(run, items) + assert run.status == TransferRunStatus.SUCCESS.value + + for item in items: + item.status = "blocked_recoverable" + finalize_run(run, items) + assert run.status == TransferRunStatus.PARTIAL_FAILED.value + + +def test_create_execution_run_rejects_duplicate(transfer_db, dbs_ready_file): + """已确认的 precheck 不允许重复创建执行 Run。""" + deps, summary = _ready_precheck(dbs_ready_file) + precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() + create_execution_run(precheck, deps=deps, actor_id=None) + with pytest.raises(ConflictError): + create_execution_run(precheck, deps=deps, actor_id=None) diff --git a/backend/tests/services/in_transit_transfer/test_precheck_service.py b/backend/tests/services/in_transit_transfer/test_precheck_service.py new file mode 100644 index 00000000..fa0f66d6 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_precheck_service.py @@ -0,0 +1,164 @@ +"""在途调拨预检服务测试(L1,SQLite 内存库)。 + +用途:验证 D+1 过滤(当天收料 ERP 调用=0)、严格数量匹配、来源隔离、 + 预检快照 Hash 稳定、缺文件等待与进度恢复。 +依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service。 +逻辑:全部经真实 ORM 落库(create_precheck/restore_precheck), + 外部依赖注入 Fake 替身。 +""" + +from __future__ import annotations + +import pytest + +from app.services.in_transit_transfer.erp_adapter import ErpAdapter +from app.services.in_transit_transfer.precheck_service import ( + TransferDeps, + create_precheck, + restore_precheck, + run_precheck, +) +from tests.services.in_transit_transfer.assertions import assert_erp_calls +from tests.services.in_transit_transfer.fakes import FakeERP, FakeRPA +from tests.services.in_transit_transfer.repo_fakes import FakeRouteResolver, make_ready_repo, make_transfer_deps + + +def _deps(*files: dict, erp: FakeERP | None = None, rpa: FakeRPA | None = None) -> tuple[TransferDeps, FakeERP, FakeRPA]: + """构造注入 Fake 依赖的 TransferDeps。""" + return make_transfer_deps(*files, erp=erp, rpa=rpa) + + +def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file): + """两个来源全部严格匹配 → executable_count 正确,无阻断。""" + deps, erp, _ = _deps(dbs_ready_file, crane_ready_file) + for invoice, qty in [("INV-001", "1200"), ("INV-002", "1200"), ("INV-008", "600")]: + erp.seed_inventory(invoice, qty) + + result = run_precheck( + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, + ) + summary = result.summary + assert summary.counts.executable_count == 3 + assert summary.counts.not_matured_count == 0 + assert summary.counts.blocked_count == 0 + assert summary.status == "ready_to_execute" + assert summary.precheck_hash.startswith("sha256:") + assert summary.estimated_erp_write_count == 3 + # 明细 DTO 决策 6/7:拨出/拨入仓库与数量对 + items = {item.invoice_no: item for item in result.items} + assert items["INV-001"].from_warehouse == "DBS-TRANSIT" + assert items["INV-001"].to_warehouse == "HUB-CN01" + assert items["INV-001"].from_quantity == items["INV-001"].to_quantity == 1200 + assert len(items["INV-001"].raw_lines) == 2 # 多行汇总保留原始行 + + +def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file): + """当天收料 → not_matured,ERP 调用次数为 0。""" + deps, erp, _ = _deps(same_day_receipt_file) + result = run_precheck( + source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps, + ) + assert result.summary.counts.not_matured_count == 1 + assert result.summary.counts.executable_count == 0 + assert result.summary.estimated_erp_write_count == 0 + assert_erp_calls(erp, 0) + + +def test_quantity_mismatch_blocked_no_write(dbs_ready_file): + """收料 1200 vs ERP 1000 → blocked_recoverable;无任何写调用。""" + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") + erp.seed_inventory("INV-002", "1200") + result = run_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + items = {item.invoice_no: item for item in result.items} + assert items["INV-001"].result == "blocked_quantity_mismatch" + assert items["INV-002"].result == "executable" + assert result.summary.counts.blocked_count == 1 + assert erp.write_calls() == [] + + +def test_erp_inventory_not_found_blocked(dbs_ready_file): + """ERP 无库存 → blocked_inventory_not_found。""" + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") # INV-002 无库存 + result = run_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + items = {item.invoice_no: item for item in result.items} + assert items["INV-002"].result == "blocked_inventory_not_found" + + +def test_missing_file_waits_without_erp(): + """缺文件 → 来源阶段 waiting_rpa_callback,无 ERP 调用。""" + deps, erp, _ = _deps() + result = run_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + assert result.sources[0].stage == "waiting_rpa_callback" + assert result.summary.status == "file_pending" + assert_erp_calls(erp, 0) + + +def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file): + """DBS 缺文件且 RPA 触发失败不阻断 CRANE-SZ 预检(来源隔离)。""" + deps, erp, rpa = _deps(crane_ready_file) + rpa.fail_on.add("DBS-AWSBI") + erp.seed_inventory("INV-008", "600") + result = run_precheck( + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, + ) + by_source = {stage.source_code: stage for stage in result.sources} + assert by_source["DBS-AWSBI"].stage == "failed" + assert by_source["CRANE-SZ"].stage == "file_ready" + items = {item.invoice_no: item for item in result.items} + assert items["INV-008"].result == "executable" + + +def test_snapshot_hash_is_stable(dbs_ready_file): + """相同输入两次预检 → 预检 Hash 一致(可审计复算)。""" + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + first = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + second = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + assert first.summary.precheck_hash == second.summary.precheck_hash + + +def test_create_and_restore_precheck(transfer_db, dbs_ready_file): + """create_precheck 落库后 restore_precheck 可完整恢复进度与明细。""" + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + + summary = create_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + assert summary.precheck_id.startswith("TPC-") + restored = restore_precheck(summary.precheck_id) + assert restored["summary"].precheck_hash == summary.precheck_hash + assert restored["summary"].status == summary.status + restored_items = {item.invoice_no: item for item in restored["items"]} + assert set(restored_items) == {"INV-001", "INV-002"} + assert restored_items["INV-001"].result == "executable" + # 落库数量与 DTO 一致(Decimal 文本持久化) + assert str(restored_items["INV-001"].to_quantity) == "1200" + + +def test_route_not_resolved_marks_source_failed(dbs_ready_file): + """来源缺少路由映射 → 该来源阶段失败,其余来源继续(fail-closed)。""" + erp = FakeERP() + rpa = FakeRPA() + deps = TransferDeps( + file_repository=make_ready_repo(dbs_ready_file), + rpa_trigger=rpa, + route_resolver=FakeRouteResolver(routes={}), + erp=ErpAdapter(transport=erp, default_org="HX-CN01"), + ) + result = run_precheck( + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, + ) + 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" # 无文件 → 等待,不阻断 diff --git a/backend/tests/services/in_transit_transfer/test_quantity_match.py b/backend/tests/services/in_transit_transfer/test_quantity_match.py new file mode 100644 index 00000000..7a72de3d --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_quantity_match.py @@ -0,0 +1,76 @@ +"""在途调拨严格数量门禁测试(L0 纯单元)。 + +用途:验证"收料数量 == ERP 账面库存 才可执行",大于/小于/缺失均阻断, + 且不允许 0、负数、非数字与隐式截断。 +依赖:app.services.in_transit_transfer.quantity。 +逻辑:数量比较全部基于 Decimal 精确语义,杜绝浮点误差。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.quantity import ( + QuantityValidationError, + classify_quantity_match, + strict_quantities_equal, + validate_receipt_quantity, +) + +pytestmark = pytest.mark.pure_unit + + +def test_equal_quantities_are_executable(): + """收料数量等于账面库存 → executable。""" + assert classify_quantity_match(Decimal("1200"), Decimal("1200")) == "executable" + + +def test_erp_greater_than_receipt_is_blocked(): + """ERP 库存大于收料数量 → 阻断(不允许部分调拨)。""" + assert classify_quantity_match(Decimal("1200"), Decimal("1500")) == "blocked_quantity_mismatch" + + +def test_erp_less_than_receipt_is_blocked(): + """ERP 库存小于收料数量 → 阻断。""" + assert classify_quantity_match(Decimal("1200"), Decimal("800")) == "blocked_quantity_mismatch" + + +def test_erp_missing_is_blocked(): + """ERP 无库存(None)→ 阻断,与数量不一致分开归类。""" + assert classify_quantity_match(Decimal("1200"), None) == "blocked_inventory_not_found" + + +def test_decimal_scale_equality_is_exact(): + """1.0 与 1.00 数量相等(Decimal 精确语义)。""" + assert strict_quantities_equal(Decimal("1.0"), Decimal("1.00")) + + +def test_zero_receipt_quantity_rejected(): + """收料数量为 0 非法。""" + with pytest.raises(QuantityValidationError): + validate_receipt_quantity(Decimal("0")) + + +def test_negative_receipt_quantity_rejected(): + """收料数量为负数非法。""" + with pytest.raises(QuantityValidationError): + validate_receipt_quantity(Decimal("-5")) + + +def test_non_numeric_quantity_rejected(): + """非数字数量非法(解析层不得静默截断)。""" + with pytest.raises(QuantityValidationError): + validate_receipt_quantity("abc") + + +def test_string_numeric_quantity_normalized(): + """字符串数字归一化为 Decimal 后参与严格比较。""" + assert validate_receipt_quantity("1200") == Decimal("1200") + assert strict_quantities_equal("1200", Decimal("1200")) + + +def test_fractional_partial_quantity_rejected_by_policy(): + """策略层不允许部分数量:1.5 与 1 不相等即阻断。""" + assert classify_quantity_match(Decimal("1.5"), Decimal("1")) == "blocked_quantity_mismatch" diff --git a/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py b/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py new file mode 100644 index 00000000..3f8a05c2 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py @@ -0,0 +1,96 @@ +"""tests/services/in_transit_transfer/test_query_inventory_gateway.py + +用途:验证调拨 query_inventory 经 CapabilityGateway 接线(首个消费者)—— + 网关被调用、成熟过滤(当天收料不查)、fail-closed(无绑定来源失败但不阻断)。 +依赖:run_precheck、CapabilityErpAdapter、repo_fakes.make_transfer_deps、transports.base。 +逻辑:领域规则(严格数量匹配/D+1/来源隔离)仍在领域层;接口选择与调用由连接器框架承担。 +""" + +from __future__ import annotations + +from dataclasses import replace +from decimal import Decimal + +from app.core.errors import AppError +from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter +from app.services.in_transit_transfer.precheck_service import run_precheck +from app.services.integration_connector.errors import BindingNotFoundError +from app.services.integration_connector.transports.base import IntegrationCallResult +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +class FakeGateway: + """按 Invoice 返回库存结果的替代网关,并记录调用。""" + + def __init__(self, inventory: dict[str, str] | None = None, *, fail: bool = False) -> None: + self.inventory = inventory or {} + self.fail = fail + self.calls: list[tuple[str, dict, dict]] = [] + + def call(self, *, capability, context, params, operation_id, idempotency_key=None, environment=None, transports=None): + self.calls.append((capability, context, params)) + if self.fail: + raise BindingNotFoundError(capability=capability) + invoice_no = params["invoice_no"] + qty = self.inventory.get(invoice_no) + if qty is None: + return IntegrationCallResult(status="success", data={"found": False}) + return IntegrationCallResult(status="success", data={"found": True, "quantity": Decimal(qty)}) + + +def _cap_deps(file, gw): + deps, _, _ = make_transfer_deps(file) + return replace(deps, erp=CapabilityErpAdapter(gateway=gw)) + + +def test_query_inventory_routed_through_gateway(app, dbs_ready_file): + """成熟 Invoice 的库存查询经网关;严格数量匹配仍由领域控制。""" + gw = FakeGateway(inventory={"INV-001": "1200", "INV-002": "1200"}) + result = run_precheck( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", + deps=_cap_deps(dbs_ready_file, gw), run_no="RUN-T", + ) + # 网关被调用,且携带 query_inventory 能力名 + assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls) + # INV-001 汇总 1200 == ERP 1200 → executable + item = next(i for i in result.items if i.invoice_no == "INV-001") + assert item.result == "executable" + assert item.from_quantity == Decimal("1200") + + +def test_not_matured_not_queried(app, same_day_receipt_file): + """当天收料(not_matured)不查 ERP——网关零调用。""" + gw = FakeGateway(inventory={}) + result = run_precheck( + source_codes=["DBS-AWSSG"], business_date="2026-08-06", + deps=_cap_deps(same_day_receipt_file, gw), run_no="RUN-T", + ) + assert gw.calls == [] + assert result.items[0].result == "not_matured" + + +def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file): + """无绑定的来源(网关抛错)标记来源失败,不阻断整个预检。""" + class _SplitGateway: + """按 Invoice 区分失败来源:DBS(INV-001/002)失败,CRANE(INV-008)成功。""" + + def __init__(self): + self.calls = [] + + def call(self, **kwargs): + self.calls.append(kwargs) + invoice = kwargs["params"]["invoice_no"] + if invoice in {"INV-001", "INV-002"}: + raise BindingNotFoundError(capability="in_transit_transfer.query_inventory") + return IntegrationCallResult(status="success", data={"found": True, "quantity": Decimal("600")}) + + deps, _, _ = make_transfer_deps(dbs_ready_file, crane_ready_file) + deps = replace(deps, erp=CapabilityErpAdapter(gateway=_SplitGateway())) + result = run_precheck( + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", + deps=deps, run_no="RUN-T", + ) + dbs_source = next(s for s in result.sources if s.source_code == "DBS-AWSBI") + assert dbs_source.stage == "failed" + # CRANE 正常执行 → 出可执行项 + assert any(i.invoice_no == "INV-008" and i.result == "executable" for i in result.items) diff --git a/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py b/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py new file mode 100644 index 00000000..a09636fa --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py @@ -0,0 +1,123 @@ +"""在途调拨收料文件字段/结构校验测试(L0 纯单元)。 + +用途:验证必填列缺失、空值、非法数量(0/负数/非数字)、非法日期与 + 来源身份不一致均整行阻断并抛出 ReceiptFileSchemaError。 +依赖:app.services.in_transit_transfer.file_parser(纯函数)。 +逻辑:解析不接触文件存储;所有错误带行号细节,供预检页展示原因。 +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.file_parser import ( + ParsedReceiptRow, + ReceiptFileSchemaError, + parse_receipt_rows, +) + +pytestmark = pytest.mark.pure_unit + +VALID_ROW = { + "sheet": "Receipt", + "row_no": 10, + "invoice_no": "INV-001", + "material_no": "MAT-001", + "material_name": "连接器组件", + "specification": "A 型 / 24PIN", + "receipt_date": "2026-08-05", + "receipt_quantity": "500", + "source_code": "DBS-AWSBI", +} + + +def _rows(**overrides) -> list[dict]: + """以 VALID_ROW 为基底覆盖字段构造测试行。""" + base = dict(VALID_ROW) + base.update(overrides) + return [base] + + +def test_valid_rows_parse(): + """合法行解析出全部字段(数量 Decimal、日期 date)。""" + parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows()) + assert len(parsed) == 1 + row = parsed[0] + assert isinstance(row, ParsedReceiptRow) + assert row.invoice_no == "INV-001" + assert row.material_no == "MAT-001" + assert row.material_name == "连接器组件" + assert row.specification == "A 型 / 24PIN" + assert row.receipt_date == date(2026, 8, 5) + assert row.receipt_quantity == Decimal("500") + assert row.sheet == "Receipt" + assert row.row_no == 10 + + +def test_missing_invoice_no_rejected(): + """Invoice No 缺失必须整行阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(invoice_no="")) + + +def test_missing_material_no_rejected(): + """料号缺失必须整行阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(material_no="")) + + +def test_invalid_quantity_rejected(): + """非数字数量必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc")) + + +def test_zero_quantity_rejected(): + """0 数量必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0")) + + +def test_negative_quantity_rejected(): + """负数数量必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="-5")) + + +def test_invalid_date_rejected(): + """非法日期必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_date="2026/13/99")) + + +def test_source_identity_mismatch_rejected(): + """行内来源与任务来源不一致(Callback 身份漂移)必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ")) + + +def test_missing_sheet_or_row_no_rejected(): + """Sheet/原始行号缺失无法追溯,必须阻断。""" + with pytest.raises(ReceiptFileSchemaError): + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0)) + + +def test_material_name_and_specification_optional(): + """品名/规格允许为空(后续由明细 DTO 展示空值)。""" + parsed = parse_receipt_rows( + source_code="DBS-AWSBI", + rows=_rows(material_name="", specification=""), + ) + assert parsed[0].material_name == "" + assert parsed[0].specification == "" + + +def test_error_carries_row_details(): + """错误细节必须携带行号与原因,供页面定位。""" + with pytest.raises(ReceiptFileSchemaError) as excinfo: + parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc")) + details = excinfo.value.details + assert any(str(item.get("row_no")) == "77" for item in details.get("rows", [])) diff --git a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py new file mode 100644 index 00000000..7b7e4fbc --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py @@ -0,0 +1,72 @@ +"""真实收料 RPA 触发服务测试。 + +用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者; + 配置/来源/触发目录缺失时 fail-closed(ok=False)。 +依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、 + 既有测试种子(ShippingRpaProfile/ShippingInventorySource)。 +逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。 +""" + +from __future__ import annotations + +import pytest + +from app.models import ShippingInventorySource, ShippingReceiptReportConfig +from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa + + +@pytest.fixture +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, + report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, + query_parameters_json=[], warehouse_ids_json=[], + ) + from app import db + + db.session.add(config) + db.session.commit() + return source + + +def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source): + """来源有效 → 写入 trigger 并返回 callback_id / trigger_path。""" + calls = {} + + def fake_writer(run_no, units, payload=None): + calls['run_no'] = run_no + calls['units'] = units + calls['payload'] = payload or {} + return f'/tmp/trigger/{run_no}.json' + + result = trigger_receipt_rpa( + source_code='DSV360_AWSDU', business_date='2026-08-06', + reason='transfer_retry_receipt', writer=fake_writer, + ) + assert result['ok'] is True + assert result['callback_id'] + assert result['trigger_path'].endswith('.json') + assert calls['units'][0]['source_code'] == 'DSV360_AWSDU' + assert calls['units'][0]['credential_envelope'] + assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1' + + +def test_trigger_receipt_rpa_disabled_source_fails_closed(app): + """来源停用 → ok=False,不写 trigger。""" + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + source.enabled = False + from app import db + + db.session.commit() + result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') + assert result['ok'] is False + assert result['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING' + + +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 diff --git a/backend/tests/services/in_transit_transfer/test_recovery_service.py b/backend/tests/services/in_transit_transfer/test_recovery_service.py new file mode 100644 index 00000000..b76df3c4 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_recovery_service.py @@ -0,0 +1,76 @@ +"""在途调拨每日恢复(待处理池自动复核)测试(Phase 3,L1)。 + +用途:验证历史可恢复项下一排程重新预检并创建新 Attempt; + result_unknown / manually_closed / success 不自动写入。 +依赖:transfer_db、precheck_service、recovery_service、repo_fakes。 +逻辑:恢复 = 重新预检(仅查询/匹配),不写 ERP;每次恢复新 Attempt。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import TransferAttempt, TransferInvoiceItem +from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.recovery_service import run_daily_recovery +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _mixed_precheck(dbs_ready_file): + """构造 1 个数量不一致 + 1 个可执行的预检。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") # mismatch → blocked + erp.seed_inventory("INV-002", "1200") # executable + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return deps, erp, summary + + +def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_file): + """ERP 修正后恢复 → 项转 ready_to_execute,新 Attempt 落库。""" + deps, erp, summary = _mixed_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + assert item.status == "blocked_recoverable" + old_attempt_no = item.attempt_no + + erp.seed_inventory("INV-001", "1200") + outcome = run_daily_recovery(business_date="2026-08-06", deps=deps) + assert outcome.recovered_count == 1 + assert outcome.attempts_created == 1 + + refreshed = db.session.get(TransferInvoiceItem, item.id) + assert refreshed.status == "ready_to_execute" + assert refreshed.attempt_no == old_attempt_no + 1 + attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all() + assert len(attempts) == 1 and attempts[0].kind == "erp_query" + # 恢复仅预检,不写 ERP + assert erp.write_calls() == [] + + +def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file): + """result_unknown 不自动恢复,也不产生 ERP 调用。""" + deps, erp, summary = _mixed_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + item.status = "result_unknown" + db.session.commit() + + outcome = run_daily_recovery(business_date="2026-08-06", deps=deps) + assert outcome.skipped_result_unknown == 1 + assert outcome.recovered_count == 0 + assert erp.write_calls() == [] + + +def test_recovery_skips_manually_closed_and_success(transfer_db, dbs_ready_file): + """manually_closed / success 永久排除,不生成 Attempt。""" + deps, erp, summary = _mixed_precheck(dbs_ready_file) + blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first() + blocked.status = "manually_closed" + blocked.manually_closed_reason = "线下处理" + success = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-002").first() + success.status = "success" + db.session.commit() + + outcome = run_daily_recovery(business_date="2026-08-06", deps=deps) + assert outcome.skipped_manually_closed == 1 + assert outcome.recovered_count == 0 + assert outcome.attempts_created == 0 diff --git a/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py b/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py new file mode 100644 index 00000000..8b93f2ac --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py @@ -0,0 +1,117 @@ +"""在途调拨人工重试与人工关闭测试(Phase 3,L1)。 + +用途:验证人工重试只创建新 Attempt(重新查询 ERP,不重新抓 RPA、不写 ERP), + result_unknown 拒绝重试;人工关闭原因必填且永久排除。 +依赖:transfer_db、precheck_service、retry_service、manual_close_service、repo_fakes。 +逻辑:重试前冻结文件不变;每次重试 attempt_no 递增且旧 Attempt 保留。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.errors import ValidationError +from app.models import TransferAttempt, TransferInvoiceItem +from app.services.in_transit_transfer.manual_close_service import manual_close_item +from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.retry_service import retry_item +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _mismatch_precheck(dbs_ready_file): + """构造 INV-001 数量不一致的预检。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1000") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + return deps, erp, summary + + +def _item_by_invoice(invoice_no: str) -> TransferInvoiceItem: + return db.session.query(TransferInvoiceItem).filter_by(invoice_no=invoice_no).first() + + +def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file): + """ERP 修正后重试 → 新 Attempt,状态进入 ready_to_execute。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + assert item.status == "blocked_recoverable" + old_attempt_count = item.attempt_no + + erp.seed_inventory("INV-001", "1200") # 人工在 ERP 修正库存 + result = retry_item(item_id=item.id, deps=deps) + assert result["status"] == "ready_to_execute" + assert result["attempt_no"] == old_attempt_count + 1 + + refreshed = db.session.get(TransferInvoiceItem, item.id) + assert refreshed.status == "ready_to_execute" + assert refreshed.attempt_no == old_attempt_count + 1 + attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all() + assert len(attempts) == 1 + assert attempts[0].kind == "erp_query" + # 重试不写 ERP + assert erp.write_calls() == [] + + +def test_retry_still_mismatch_keeps_blocked(transfer_db, dbs_ready_file): + """重试后仍不匹配 → 保持 blocked_recoverable,attempt_no 递增。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + old = item.attempt_no + result = retry_item(item_id=item.id, deps=deps) + assert result["status"] == "blocked_recoverable" + assert result["attempt_no"] == old + 1 + + +def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file): + """result_unknown 只读:拒绝重试(禁止猜测性二次写入)。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + item.status = "result_unknown" + item.result_code = "result_unknown" + db.session.commit() + with pytest.raises(ValidationError): + retry_item(item_id=item.id, deps=deps) + assert erp.write_calls() == [] + + +def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file): + """Run 创建后禁止重新抓取 RPA(文件冻结)。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + with pytest.raises(ValidationError): + retry_item(item_id=item.id, deps=deps, kind="rpa_refetch") + + +def test_manual_close_requires_reason(transfer_db, dbs_ready_file): + """人工关闭原因必填。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + with pytest.raises(ValidationError): + manual_close_item(item_id=item.id, reason="") + + +def test_manual_close_marks_terminal(transfer_db, dbs_ready_file): + """人工关闭 → manually_closed(永久排除,后续排程不再处理)。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + result = manual_close_item(item_id=item.id, reason="货代确认无需调拨") + assert result["status"] == "manually_closed" + refreshed = db.session.get(TransferInvoiceItem, item.id) + assert refreshed.status == "manually_closed" + assert refreshed.manually_closed_reason == "货代确认无需调拨" + # 关闭后不再进入可恢复池(自动排程不再处理) + from app.services.in_transit_transfer.backlog_service import backlog_summary + + assert backlog_summary().recoverable_count == 0 + + +def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file): + """result_unknown 只读:禁止人工关闭(需按 SOP 核实)。""" + deps, erp, summary = _mismatch_precheck(dbs_ready_file) + item = _item_by_invoice("INV-001") + item.status = "result_unknown" + db.session.commit() + with pytest.raises(ValidationError): + manual_close_item(item_id=item.id, reason="尝试关闭未知项") diff --git a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py new file mode 100644 index 00000000..fa4df666 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py @@ -0,0 +1,46 @@ +"""在途调拨排程注册与执行测试(Phase 3)。 + +用途:验证 08:00 收料文件 / 09:00 自动调拨 platform job 已注册(含参数契约), + handler 返回标准 ScheduleExecuteResult(7 元组)。 +依赖:schedule.job_registry、schedule 两个 in_transit job 模块。 +逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。 +""" + +from __future__ import annotations + +import pytest + +from app.services.schedule.job_registry import get_platform_job, list_platform_jobs + + +def test_receipt_file_job_registered_with_schedule_defaults(): + """08:00 收料文件 job 注册且含 source_codes 参数契约。""" + job = get_platform_job("in-transit-receipt-file") + assert job is not None + assert job.enabled + keys = {field.get("key") for field in job.params_schema} + assert "source_codes" in keys + + +def test_transfer_job_registered_with_schedule_defaults(): + """09:00 自动调拨 job 注册且含并发/恢复参数契约。""" + 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"} <= keys + + +def test_schedule_handlers_return_seven_tuple(): + """两个排程 handler 返回标准 ScheduleExecuteResult(7 元组)。""" + from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule + from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule + + for handler in (run_in_transit_receipt_file_schedule, run_in_transit_transfer_schedule): + assert callable(handler) + + +def test_jobs_visible_in_platform_list(): + """platform job 列表包含两个调拨排程。""" + keys = {job.key for job in list_platform_jobs()} + assert {"in-transit-receipt-file", "in-transit-transfer"} <= keys diff --git a/backend/tests/services/in_transit_transfer/test_source_file_status.py b/backend/tests/services/in_transit_transfer/test_source_file_status.py new file mode 100644 index 00000000..b319fa7b --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_source_file_status.py @@ -0,0 +1,88 @@ +"""来源收料文件状态投影服务测试。 + +用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile), + 按来源投影 ready/fetching/failed/none。调拨不维护独立抓取状态表。 +依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。 +逻辑:有文件→ready;有进行中单元→fetching;最新单元失败终态→failed;否则→none。 +""" + +from __future__ import annotations + +import hashlib + +import pytest + +from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + +SOURCE_CODE = 'DSV360_AWSDU' + + +@pytest.fixture +def receipt_unit_run(): + """构造一条收料执行单元(含排程/来源上下文)。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun + + source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one() + task = ScheduleTask( + schedule_no='SCH-SOURCE-STATUS', name='Source status test', schedule_type='platform_job', + owner_user_id=1, cron_expr='0 8 * * *', job_params={}, + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun(run_no='RUN-SOURCE-STATUS', schedule_task_id=task.id, status='awaiting_callback') + db.session.add(run) + db.session.flush() + unit = ShippingReceiptRpaUnitRun( + schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, + connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-status-001', + status='awaiting_rpa', config_snapshot_json={}, + ) + db.session.add(unit) + db.session.commit() + return unit + + +def test_no_file_and_no_unit_is_none(app): + """无文件且无执行单元 → none(待触发)。""" + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status['file_status'] == 'none' + assert status['has_ready_file'] is False + + +def test_running_unit_is_fetching(app, receipt_unit_run): + """有进行中执行单元 → fetching。""" + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status['file_status'] == 'fetching' + assert status['has_ready_file'] is False + + +def test_failed_latest_unit_is_failed(app, receipt_unit_run): + """最新单元为失败终态且无文件 → failed。""" + from app import db + from app.models import ShippingReceiptRpaUnitRun + + receipt_unit_run.status = 'failed' + db.session.commit() + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status['file_status'] == 'failed' + + +def test_report_file_is_ready(app, receipt_unit_run): + """有收料归档文件 → ready,且带 file_no/sha256。""" + from app import db + from app.models import ShippingReceiptReportFile + + receipt_unit_run.status = 'success' + digest = hashlib.sha256(b'receipt workbook').hexdigest() + db.session.add(ShippingReceiptReportFile( + unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', + storage_key='shipping/receipt/test.xlsx', original_filename='receipt.xlsx', + file_size=16, sha256=digest, + )) + db.session.commit() + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status['file_status'] == 'ready' + assert status['has_ready_file'] is True + assert status['file_no'] == 'receipt.xlsx' + assert status['file_sha256'] == digest diff --git a/backend/tests/services/in_transit_transfer/test_source_job_service.py b/backend/tests/services/in_transit_transfer/test_source_job_service.py new file mode 100644 index 00000000..833adcbd --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_source_job_service.py @@ -0,0 +1,88 @@ +"""来源级状态服务测试。 + +用途:验证 create_source_job / advance_source_job / source_jobs_for_run 的职责—— + 一次 run 内每来源一条 job((run, source) 唯一),状态推进统一集中在此服务。 +依赖:app(SQLite)、models(TransferRun/TransferSourceJob)、source_job_service。 +逻辑:同 run 同来源复用(不重复建);终态自动写 finished_at。 +""" + +from __future__ import annotations + +import pytest + +from app.models import TransferRun, TransferSourceJob +from app.services.in_transit_transfer.source_job_service import ( + advance_source_job, + create_source_job, + source_jobs_for_run, +) + + +def _run() -> TransferRun: + from app import db + + run = TransferRun(run_no='RUN-SJOB', trigger_type='manual', business_date='2026-08-06', status='prechecking') + db.session.add(run) + db.session.flush() + return run + + +def test_create_source_job_per_run_source_unique(app): + """一次 run 内同来源只建一条 job。""" + run = _run() + job_a = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + job_b = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + from app import db + + db.session.commit() + assert job_a.id == job_b.id + + +def test_source_jobs_for_run_returns_ordered_sources(app): + """source_jobs_for_run 按来源排序。""" + run = _run() + create_source_job(run_id=run.id, source_code='CRANE-SZ') + create_source_job(run_id=run.id, source_code='DBS-AWSBI') + from app import db + + db.session.commit() + jobs = source_jobs_for_run(run.id) + assert [j.source_code for j in jobs] == ['CRANE-SZ', 'DBS-AWSBI'] + + +def test_advance_source_job_writes_status_and_fields(app): + """推进 job 写入状态与来源字段。""" + run = _run() + job = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + advance_source_job(job=job, status='waiting_rpa_callback', file_no='REC-1', file_sha256='hash') + from app import db + + db.session.commit() + assert job.status == 'waiting_rpa_callback' + assert job.file_no == 'REC-1' + assert job.file_sha256 == 'hash' + + +def test_terminal_status_sets_finished_at(app): + """到达终态自动写 finished_at。""" + run = _run() + job = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + advance_source_job(job=job, status='failed', error_code='ERR', error_message='boom') + from app import db + + db.session.commit() + assert job.status == 'failed' + assert job.finished_at is not None + assert job.error_code == 'ERR' + + +def test_file_ready_is_valid_source_job_status(app): + """file_ready 是合法来源 job 状态(来源准备流程阶段与 job 状态集对齐)。""" + run = _run() + job = create_source_job(run_id=run.id, source_code='DBS-AWSBI') + advance_source_job(job=job, status='file_ready', file_no='REC-1') + from app import db + + db.session.commit() + assert job.status == 'file_ready' + assert job.file_no == 'REC-1' diff --git a/backend/tests/services/in_transit_transfer/test_status_machine.py b/backend/tests/services/in_transit_transfer/test_status_machine.py new file mode 100644 index 00000000..deeddb51 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_status_machine.py @@ -0,0 +1,123 @@ +"""在途调拨状态机与转换门禁测试(L0 纯单元)。 + +用途:验证提示词冻结的 13 个状态全部存在、非法迁移被服务端拒绝、 + result_unknown / manually_closed / success 无出边、通知失败不改变 ERP 结果。 +依赖:app.services.in_transit_transfer.status。 +逻辑:所有转换必须显式声明于转换表;未声明迁移一律抛 TransferStateError。 +""" + +from __future__ import annotations + +import pytest + +from app.services.in_transit_transfer.status import ( + ITEM_TRANSITIONS, + RUN_TRANSITIONS, + TERMINAL_TRANSFER_STATUSES, + TransferNotificationStatus, + TransferRunStatus, + TransferStateError, + TransferStatus, + apply_notification_failure, + assert_transition_allowed, +) + +pytestmark = pytest.mark.pure_unit + +PROMPT_STATUSES = { + "file_pending", "file_ready", "prechecking", "ready_to_execute", "executing", + "success", "duplicate_success", "blocked_recoverable", "not_matured", + "result_unknown", "manually_closed", "cancelled", "notification_failed", +} + + +def test_all_prompt_statuses_covered(): + """提示词要求的 13 个状态必须全部存在。""" + actual = {status.value for status in TransferStatus} + assert PROMPT_STATUSES <= actual + + +def test_success_and_duplicate_success_are_terminal(): + """成功/重复成功为终态(幂等跳过)。""" + assert TransferStatus.SUCCESS in TERMINAL_TRANSFER_STATUSES + assert TransferStatus.DUPLICATE_SUCCESS in TERMINAL_TRANSFER_STATUSES + + +def test_result_unknown_is_terminal_without_outgoing_edges(): + """result_unknown 无出边:禁止自动重试、禁止手工猜测性操作。""" + assert TransferStatus.RESULT_UNKNOWN in TERMINAL_TRANSFER_STATUSES + assert ITEM_TRANSITIONS[TransferStatus.RESULT_UNKNOWN.value] == frozenset() + + +def test_manually_closed_is_terminal_without_outgoing_edges(): + """manually_closed 永久排除:不得再进入待处理池。""" + assert TransferStatus.MANUALLY_CLOSED in TERMINAL_TRANSFER_STATUSES + assert ITEM_TRANSITIONS[TransferStatus.MANUALLY_CLOSED.value] == frozenset() + + +def test_illegal_transition_rejected(): + """file_ready 直接跳 executing 必须抛领域错误。""" + with pytest.raises(TransferStateError): + assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.EXECUTING.value) + + +def test_legal_transition_accepted(): + """file_ready → prechecking 是合法迁移。""" + assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.PRECHECKING.value) + + +def test_executing_to_success_accepted(): + """executing → success 合法。""" + assert_transition_allowed(TransferStatus.EXECUTING.value, TransferStatus.SUCCESS.value) + + +def test_executing_to_result_unknown_accepted_but_no_auto_retry(): + """executing → result_unknown 合法(超时落位),但之后无任何出边。""" + assert_transition_allowed(TransferStatus.EXECUTING.value, TransferStatus.RESULT_UNKNOWN.value) + with pytest.raises(TransferStateError): + assert_transition_allowed(TransferStatus.RESULT_UNKNOWN.value, TransferStatus.EXECUTING.value) + with pytest.raises(TransferStateError): + assert_transition_allowed(TransferStatus.RESULT_UNKNOWN.value, TransferStatus.MANUALLY_CLOSED.value) + + +def test_blocked_recoverable_to_manual_close_and_recheck(): + """blocked_recoverable 可人工关闭或重新预检(新 Attempt)。""" + assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.MANUALLY_CLOSED.value) + assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.PRECHECKING.value) + + +def test_unknown_status_rejected(): + """未知状态字符串不得被门禁接受。""" + with pytest.raises(TransferStateError): + assert_transition_allowed("no_such_status", TransferStatus.SUCCESS.value) + + +def test_not_matured_has_no_outgoing_edges(): + """not_matured 无出边:当天不得查询 ERP、不得生成调拨单。""" + assert ITEM_TRANSITIONS[TransferStatus.NOT_MATURED.value] == frozenset() + + +def test_run_transition_queued_to_executing_path(): + """Run 生命周期:queued → preparing_files → prechecking → ready_to_execute → executing。""" + assert_transition_allowed(TransferRunStatus.QUEUED.value, TransferRunStatus.PREPARING_FILES.value, transitions=RUN_TRANSITIONS) + assert_transition_allowed(TransferRunStatus.PREPARING_FILES.value, TransferRunStatus.PRECHECKING.value, transitions=RUN_TRANSITIONS) + assert_transition_allowed(TransferRunStatus.PRECHECKING.value, TransferRunStatus.READY_TO_EXECUTE.value, transitions=RUN_TRANSITIONS) + assert_transition_allowed(TransferRunStatus.READY_TO_EXECUTE.value, TransferRunStatus.EXECUTING.value, transitions=RUN_TRANSITIONS) + + +def test_notification_failed_does_not_change_erp_result(): + """通知失败不改变 ERP 结果:apply_notification_failure 返回原 ERP 终态。""" + assert apply_notification_failure(TransferRunStatus.SUCCESS.value) == TransferRunStatus.SUCCESS.value + assert apply_notification_failure(TransferRunStatus.PARTIAL_FAILED.value) == TransferRunStatus.PARTIAL_FAILED.value + + +def test_notification_failed_rejected_on_non_terminal_run(): + """非终态 Run 不允许记录通知失败(必须先结束 ERP 阶段)。""" + with pytest.raises(TransferStateError): + apply_notification_failure(TransferRunStatus.EXECUTING.value) + + +def test_notification_status_enum(): + """通知状态枚举包含 pending/success/failed(failed 即 notification_failed 语义)。""" + assert TransferNotificationStatus.FAILED.value == "failed" + assert TransferNotificationStatus.SUCCESS.value == "success" diff --git a/backend/tests/services/in_transit_transfer/test_strategy_policy.py b/backend/tests/services/in_transit_transfer/test_strategy_policy.py new file mode 100644 index 00000000..2117734c --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_strategy_policy.py @@ -0,0 +1,63 @@ +"""在途调拨策略硬门禁测试(L0 纯单元)。 + +用途:验证一期策略禁止部分数量调拨、数量容差与 ERP 自动重试, + 并强制默认确认有效期(10 分钟)。 +依赖:app.services.in_transit_transfer.strategy。 +逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.strategy import ( + TransferStrategyPolicy, + StrategyViolationError, + default_strategy, + validate_strategy, +) + +pytestmark = pytest.mark.pure_unit + + +def test_default_strategy_is_valid(): + """默认策略(无部分调拨/无容差/无自动重试/10 分钟确认)合法。""" + strategy = default_strategy() + validate_strategy(strategy) + assert strategy.confirm_ttl_seconds == 600 + + +def test_partial_transfer_rejected(): + """开启部分数量调拨必须被发布门禁拒绝。""" + strategy = TransferStrategyPolicy(allow_partial=True) + with pytest.raises(StrategyViolationError) as excinfo: + validate_strategy(strategy) + assert "partial" in str(excinfo.value) + + +def test_quantity_tolerance_rejected(): + """任何非零数量容差必须被拒绝。""" + strategy = TransferStrategyPolicy(quantity_tolerance=Decimal("0.01")) + with pytest.raises(StrategyViolationError): + validate_strategy(strategy) + + +def test_erp_auto_retry_rejected(): + """开启 ERP 自动重试必须被拒绝(result_unknown 严禁自动重试)。""" + strategy = TransferStrategyPolicy(allow_erp_auto_retry=True) + with pytest.raises(StrategyViolationError): + validate_strategy(strategy) + + +def test_combined_violations_still_rejected(): + """多项禁令同时开启仍拒绝。""" + strategy = TransferStrategyPolicy(allow_partial=True, allow_erp_auto_retry=True) + with pytest.raises(StrategyViolationError): + validate_strategy(strategy) + + +def test_custom_ttl_allowed_but_default_ten_minutes(): + """确认有效期可配置,但默认必须是 600 秒(10 分钟)。""" + assert TransferStrategyPolicy().confirm_ttl_seconds == 600 diff --git a/backend/tests/services/in_transit_transfer/test_worker_recovery.py b/backend/tests/services/in_transit_transfer/test_worker_recovery.py new file mode 100644 index 00000000..9a02d13e --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_worker_recovery.py @@ -0,0 +1,84 @@ +"""在途调拨 Worker 崩溃/陈旧执行恢复测试(Phase 4,L1)。 + +用途:验证执行中(executing)且租约过期的项可恢复(依赖 Invoice 幂等,不重复建单)、 + 停滞 Run 可终态收尾、result_unknown 不被自动重试。 +依赖:transfer_db、precheck/execution/recovery、repo_fakes。 +逻辑:恢复 = 重新写前复查 + 幂等写入;已落单场景由 ERP 返回 duplicate_success。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app import db +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.execution_service import execute_precheck +from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.recovery import ( + finalize_stale_runs, + recover_stale_execution_items, +) +from app.services.in_transit_transfer.status import TransferStatus +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _executing_precheck(dbs_ready_file): + """构造已预检 precheck(不执行),并手动把明细置为 executing。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + for item in db.session.query(TransferInvoiceItem).all(): + item.status = "executing" + item.updated_at = datetime.utcnow() - timedelta(hours=2) # 租约已过期 + db.session.commit() + return deps, erp + + +def test_recover_stale_execution_items_completes_writes(transfer_db, dbs_ready_file): + """租约过期的 executing 项恢复后完成写入(幂等,无重复建单)。""" + deps, erp = _executing_precheck(dbs_ready_file) + result = recover_stale_execution_items(deps=deps) + assert result["recovered"] == 2 + items = db.session.query(TransferInvoiceItem).all() + assert all(item.status == "success" for item in items) + assert all(item.erp_document_no for item in items) + # 每 Invoice 恰 1 次写(恢复只写一次,不重复建单) + assert len(erp.write_calls()) == 2 + + +def test_recover_skips_result_unknown(transfer_db, dbs_ready_file): + """result_unknown 不自动重试(不触碰、不写 ERP)。""" + deps, erp = _executing_precheck(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).first() + item.status = "result_unknown" + db.session.commit() + result = recover_stale_execution_items(deps=deps) + assert result["recovered"] == 1 # 仅另一个 executing 项恢复 + db.session.refresh(item) + assert item.status == "result_unknown" # 未知项保持只读 + assert len(erp.write_calls()) == 1 # 未知项 0 写入 + + +def test_finalize_stale_runs_marks_terminal(transfer_db, dbs_ready_file): + """停滞 Run(全部明细已终态但 Run 仍 executing)→ 收尾为 success。""" + from app.models import TransferPrecheck + from app.services.in_transit_transfer.orchestrator import create_execution_run + + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_inventory("INV-001", "1200") + erp.seed_inventory("INV-002", "1200") + summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first() + run = create_execution_run(precheck, deps=deps, actor_id=None) + for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all(): + item.status = "success" + item.erp_document_no = "TRF-DONE" + db.session.commit() + + run_ids = finalize_stale_runs() + assert run.id in run_ids + db.session.refresh(run) + assert run.status == "success" \ No newline at end of file diff --git a/backend/tests/services/integration_connector/test_binding.py b/backend/tests/services/integration_connector/test_binding.py new file mode 100644 index 00000000..245b1ff8 --- /dev/null +++ b/backend/tests/services/integration_connector/test_binding.py @@ -0,0 +1,122 @@ +"""tests/services/integration_connector/test_binding.py + +用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。 +依赖:IntegrationBinding 等模型、binding.py、errors.py。 +逻辑:只匹配 published + environment + 生效区间 + context_selector 子集; + 无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +import pytest + +from app import db +from app.core.errors import AppError +from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition +from app.services.integration_connector.binding import BindingSnapshot, resolve_binding + + +def _client(code="CLI-A", **overrides): + values = {"name": f"client {code}", "connector_type": "soap", "environment": "prod", + "config_json": {"endpoint": "https://erp.invalid"}} + values.update(overrides) + return IntegrationClientInstance(code=code, **values) + + +def _interface(code="IFACE-Q", **overrides): + values = {"name": "查询库存", "client_instance_code": "CLI-A", "connector_type": "soap", + "request_spec_json": {"method": "GET", "path": "/stock"}, + "input_schema_json": {}, "response_mapping_json": {"qty": {"expr": "quantity", "transform": "decimal"}}, + "output_schema_json": {"type": "object", "properties": {"qty": {"type": "number"}}}, + "version": 3, "status": "published"} + values.update(overrides) + return IntegrationInterfaceDefinition(code=code, **values) + + +def _binding(capability="in_transit_transfer.query_inventory", **overrides): + values = {"capability": capability, "context_selector_json": {}, + "client_instance_code": "CLI-A", "interface_definition_code": "IFACE-Q", + "mapping_version": 2, "priority": 0, "environment": "prod", "status": "published"} + values.update(overrides) + return IntegrationBinding(**values) + + +def _seed_default(app): + db.session.add_all([_client(), _interface(), _binding()]) + db.session.commit() + + +def test_default_binding_matches_any_context(app): + """空 context_selector 的默认绑定命中(context 含额外键也可命中)。""" + _seed_default(app) + snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "DBS-AWSBI"}, "prod") + assert snap.client_code == "CLI-A" + assert snap.interface_code == "IFACE-Q" + assert snap.mapping_version == 2 + + +def test_context_specific_overrides_default(app): + """context_selector 匹配的来源专属绑定(更高优先级)覆盖默认绑定。""" + db.session.add_all([_client(), _interface()]) + db.session.add_all([ + _binding(), + _binding(context_selector_json={"source_code": "CRANE-SZ"}, priority=10), + ]) + db.session.commit() + snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "CRANE-SZ"}, "prod") + assert snap.context_selector == {"source_code": "CRANE-SZ"} + + +def test_higher_priority_wins_among_matching(app): + """同一 context 下、不同 context_selector 均命中时,priority 高者优先。""" + db.session.add_all([_client(), _interface()]) + db.session.add_all([ + _binding(context_selector_json={"source_code": "X", "region": "cn"}, priority=1), + _binding(context_selector_json={"source_code": "X"}, priority=5), + ]) + db.session.commit() + snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X", "region": "cn"}, "prod") + assert snap.context_selector == {"source_code": "X"} # priority 5 绑定胜出 + + +def test_expired_effective_window_not_matched(app): + """effective_to 已过期的绑定不命中,回落到默认。""" + past = datetime.now(timezone.utc) - timedelta(days=1) + db.session.add_all([_client(), _interface()]) + db.session.add_all([ + _binding(context_selector_json={"source_code": "X"}, effective_from=past, effective_to=past), + _binding(), + ]) + db.session.commit() + snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X"}, "prod") + assert snap.context_selector == {} + + +def test_draft_status_not_matched(app): + """status=draft 的绑定不命中;无默认时抛 BindingNotFoundError。""" + db.session.add_all([_client(), _interface(), _binding(status="draft")]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_no_match_raises(app): + """无任何可命中绑定抛 BindingNotFoundError(fail-closed)。""" + db.session.add_all([_client(), _interface(), _binding(capability="other.cap")]) + db.session.commit() + with pytest.raises(AppError) as exc: + resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_freeze_versions_in_snapshot(app): + """快照冻结 interface 版本与调用期配置(非活表)。""" + _seed_default(app) + snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod") + assert snap.interface_version == 3 + assert snap.credential_ref_code is None + assert snap.request_spec.get("path") == "/stock" + assert snap.config.get("endpoint") == "https://erp.invalid" diff --git a/backend/tests/services/integration_connector/test_capability.py b/backend/tests/services/integration_connector/test_capability.py new file mode 100644 index 00000000..8b0c3c8b --- /dev/null +++ b/backend/tests/services/integration_connector/test_capability.py @@ -0,0 +1,59 @@ +"""tests/services/integration_connector/test_capability.py + +用途:验证 Capability 强类型契约注册表:注册/查询/清单/重复/未注册。 +依赖:服务层 capability.py(纯代码,不依赖 DB);errors.py。 +逻辑:领域只能调用已注册的强类型能力;未注册 fail-closed 抛 INTEGRATION.CAPABILITY_NOT_FOUND。 +""" + +from __future__ import annotations + +import pytest + +from app.services.integration_connector.capability import ( + CapabilitySpec, + ensure_capabilities_loaded, + get_capability, + list_capabilities, + register_capability, + reset_capability_registry_for_tests, +) +from app.core.errors import AppError, ValidationError + + +@pytest.fixture(autouse=True) +def _fresh_registry(): + reset_capability_registry_for_tests() + yield + reset_capability_registry_for_tests() + + +def test_register_then_get_returns_same_spec(): + """注册后按名查询返回同一对象。""" + spec = CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False) + register_capability(spec) + assert get_capability("demo.echo") is spec + + +def test_duplicate_register_raises_validation(): + """同名能力重复注册抛 ValidationError。""" + register_capability(CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False)) + with pytest.raises(ValidationError): + register_capability(CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False)) + + +def test_get_unregistered_raises_not_found(): + """未注册能力抛 INTEGRATION.CAPABILITY_NOT_FOUND(fail-closed)。""" + with pytest.raises(AppError) as exc: + get_capability("in_transit_transfer.none") + assert exc.value.code == "INTEGRATION.CAPABILITY_NOT_FOUND" + assert exc.value.http_status == 404 + + +def test_ensure_loaded_registers_three_transfer_capabilities(): + """ensure_capabilities_loaded 后注册 3 个在途调拨能力,write 标志正确。""" + ensure_capabilities_loaded() + names = {spec.name for spec in list_capabilities()} + assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names) + assert get_capability("in_transit_transfer.create_transfer").write is True + assert get_capability("in_transit_transfer.query_inventory").write is False + assert get_capability("in_transit_transfer.verify_duplicate").write is False diff --git a/backend/tests/services/integration_connector/test_engine.py b/backend/tests/services/integration_connector/test_engine.py new file mode 100644 index 00000000..8cb22785 --- /dev/null +++ b/backend/tests/services/integration_connector/test_engine.py @@ -0,0 +1,162 @@ +"""tests/services/integration_connector/test_engine.py + +用途:验证 CapabilityGateway 调用引擎管线——resolve→validate→call→map→classify→落 IntegrationCall。 +依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。 +逻辑:读能力走 success(映射校验通过);写能力按原始 status 分类;超时→timeout; + 入参非法/无绑定/映射失败/result_unknown 均 fail-closed,且 result_unknown 不自动重试。 +""" + +from __future__ import annotations + +from datetime import datetime +from decimal import Decimal + +import pytest + +from app import db +from app.core.errors import AppError +from app.models import IntegrationBinding, IntegrationCall, IntegrationClientInstance, IntegrationInterfaceDefinition +from app.services.integration_connector.capability import ensure_capabilities_loaded +from app.services.integration_connector.engine import CapabilityGateway + + +class FakeTransport: + """可注入响应或异常的传输替身。""" + + connector_type = "rest" + + def __init__(self, response): + self._response = response + + def call(self, *, client, interface, request): + if isinstance(self._response, Exception): + raise self._response + return self._response + + +def _seed(capability, *, connector_type="rest", response_mapping=None, output_schema=None): + resp_map = response_mapping or {"found": {"expr": "found"}, "quantity": {"expr": "quantity", "transform": "decimal"}} + out_schema = output_schema or {"type": "object", "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}} + client = IntegrationClientInstance( + code="CLI-A", name="client", connector_type=connector_type, environment="prod", + config_json={"endpoint": "https://erp.invalid"}, + ) + iface = IntegrationInterfaceDefinition( + code="IFACE-Q", name="iface", client_instance_code="CLI-A", connector_type=connector_type, + request_spec_json={"method": "GET", "path": "/stock/{invoice_no}"}, + input_schema_json={}, response_mapping_json=resp_map, output_schema_json=out_schema, + version=3, status="published", + ) + db.session.add_all([client, iface]) + db.session.flush() + binding = IntegrationBinding( + capability=capability, context_selector_json={}, client_instance_code="CLI-A", + interface_definition_code="IFACE-Q", mapping_version=2, priority=0, environment="prod", + status="published", + ) + db.session.add(binding) + db.session.commit() + return connector_type + + +def _params(**overrides): + values = {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100} + values.update(overrides) + return values + + +def test_call_success_records_integration_call(app): + """读能力成功:status=success、data 含映射结果、落 IntegrationCall。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.query_inventory") + fake = FakeTransport({"found": True, "quantity": "100"}) + result = CapabilityGateway(transports={"rest": fake}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-1", environment="prod", + ) + assert result.status == "success" + assert result.data["quantity"] == Decimal("100") + call_row = IntegrationCall.query.filter_by(operation_id="OP-1").first() + assert call_row is not None + assert call_row.status == "success" + + +def test_call_input_invalid_raises(app): + """入参不合输入 Schema → INTEGRATION.INPUT_INVALID。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.query_inventory") + with pytest.raises(AppError) as exc: + CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call( + capability="in_transit_transfer.query_inventory", context={}, + params={}, operation_id="OP-2", environment="prod", + ) + assert exc.value.code == "INTEGRATION.INPUT_INVALID" + + +def test_call_no_binding_raises(app): + """无可用绑定 → INTEGRATION.BINDING_NOT_FOUND(fail-closed)。""" + ensure_capabilities_loaded() + with pytest.raises(AppError) as exc: + CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-3", environment="prod", + ) + assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND" + + +def test_call_write_business_failed(app): + """写能力按原始 status 分类 → business_failed。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.create_transfer") + fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"}) + result = CapabilityGateway(transports={"rest": fake}).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_params(), operation_id="OP-4", environment="prod", + ) + assert result.status == "business_failed" + assert result.error_code == "E1" + + +def test_call_transport_timeout_returns_timeout(app): + """传输超时 → status=timeout。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.query_inventory") + result = CapabilityGateway(transports={"rest": FakeTransport(TimeoutError())}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-5", environment="prod", + ) + assert result.status == "timeout" + + +def test_call_mapping_invalid_raises(app): + """输出不合输出 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.query_inventory", + output_schema={"type": "object", "required": ["found", "quantity"], + "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}}) + fake = FakeTransport({"found": True}) # 缺 quantity + with pytest.raises(AppError) as exc: + CapabilityGateway(transports={"rest": fake}).call( + capability="in_transit_transfer.query_inventory", context={}, + params=_params(), operation_id="OP-6", environment="prod", + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_call_result_unknown_no_auto_retry(app): + """result_unknown 不自动重试:transport 仅被调用一次。""" + ensure_capabilities_loaded() + _seed("in_transit_transfer.create_transfer") + calls = [] + + class _OneShot(FakeTransport): + def call(self, **kw): + calls.append(1) + return {"status": "result_unknown"} + + result = CapabilityGateway(transports={"rest": _OneShot(None)}).call( + capability="in_transit_transfer.create_transfer", context={}, + params=_params(), operation_id="OP-7", environment="prod", + ) + assert result.status == "result_unknown" + assert len(calls) == 1 diff --git a/backend/tests/services/integration_connector/test_mapping.py b/backend/tests/services/integration_connector/test_mapping.py new file mode 100644 index 00000000..e6548a2a --- /dev/null +++ b/backend/tests/services/integration_connector/test_mapping.py @@ -0,0 +1,96 @@ +"""tests/services/integration_connector/test_mapping.py + +用途:验证声明式映射引擎——点路径/数组下标提取、白名单转换函数、最小 Schema 校验。 +依赖:mapping.py(纯函数);errors.py。 +逻辑:缺字段且不可满足→MappingInvalidError;非法类型/枚举→MappingInvalidError; + 表达式超深/超长→MappingInvalidError(fail-closed)。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app.core.errors import AppError +from app.services.integration_connector.mapping import MISSING, extract_path, map_response + + +def test_extract_path_dot(): + assert extract_path({"a": {"b": 1}}, "a.b") == 1 + + +def test_extract_path_array_index(): + assert extract_path({"a": [10, 20]}, "a[1]") == 20 + + +def test_extract_path_missing_returns_sentinel(): + assert extract_path({"a": 1}, "a.b") is MISSING + assert extract_path({"a": [1]}, "a[9]") is MISSING + + +def test_extract_path_depth_limit(): + deep = {"a": {"b": {"c": {"d": {"e": {"f": {"g": {"h": {"i": 1}}}}}}}}} + with pytest.raises(AppError) as exc: + extract_path(deep, "a.b.c.d.e.f.g.h.i") + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_extract_path_length_limit(): + with pytest.raises(AppError) as exc: + extract_path({"a": 1}, "a." + "b" * 300) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_map_response_extract_and_decimal_transform(): + mapped = map_response( + {"qty": {"expr": "rows[0].qty", "transform": "decimal"}}, + {"rows": [{"qty": "100.5"}]}, + {"type": "object", "required": ["qty"], "properties": {"qty": {"type": "number"}}}, + ) + assert mapped["qty"] == Decimal("100.5") + + +def test_map_response_default_and_fallback(): + mapped = map_response( + { + "a": {"expr": "missing", "transform": "default", "args": {"default": 7}}, + "b": {"expr": "missing", "transform": "fallback", "args": {"fallback": "X"}}, + }, + {}, + {"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "string"}}}, + ) + assert mapped == {"a": 7, "b": "X"} + + +def test_map_response_missing_required_raises(): + with pytest.raises(AppError) as exc: + map_response( + {"a": {"expr": "missing"}}, + {}, + {"type": "object", "required": ["a"], "properties": {"a": {"type": "string"}}}, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_map_response_wrong_type_raises(): + with pytest.raises(AppError) as exc: + map_response( + {"a": {"expr": "x"}}, + {"x": "not-a-number"}, + {"type": "object", "required": ["a"], "properties": {"a": {"type": "number"}}}, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" + + +def test_map_response_enum_violation_raises(): + with pytest.raises(AppError) as exc: + map_response( + {"status": {"expr": "s"}}, + {"s": "banana"}, + { + "type": "object", "required": ["status"], + "properties": {"status": {"type": "string", "enum": ["ok", "bad"]}}, + }, + ) + assert exc.value.code == "INTEGRATION.MAPPING_INVALID" diff --git a/backend/tests/services/integration_connector/test_migration.py b/backend/tests/services/integration_connector/test_migration.py new file mode 100644 index 00000000..7aab261a --- /dev/null +++ b/backend/tests/services/integration_connector/test_migration.py @@ -0,0 +1,64 @@ +"""tests/services/integration_connector/test_migration.py + +用途:验证 Integration Connector 迁移可独立升级与回滚,且正确链在当前 head 之后。 +依赖:Alembic Operations、SQLAlchemy SQLite、ic1a2b3c4d5f 迁移。 +逻辑:空库升级后 5 张表(含索引/约束)存在;回滚后全部删除;down_revision 指向既有 head。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +EXPECTED_TABLES = { + 'integration_credential_references', + 'integration_client_instances', + 'integration_interface_definitions', + 'integration_bindings', + 'integration_calls', +} + + +def _load_migration(): + """加载连接器框架建表迁移。""" + path = Path(__file__).parents[3] / 'migrations' / 'versions' / 'ic1a2b3c4d5f_add_integration_connector.py' + spec = importlib.util.spec_from_file_location('integration_connector_migration', path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_migration_chains_after_head(): + """新迁移必须挂接在既有链 head it1a2b3c4d5e 之后。""" + migration = _load_migration() + assert migration.revision == 'ic1a2b3c4d5f' + assert migration.down_revision == 'it1a2b3c4d5e' + + +def test_integration_connector_migration_round_trip(): + """空库升级后 5 表存在;回滚后全部删除。""" + engine = sa.create_engine('sqlite:///:memory:') + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + migration = _load_migration() + migration.op = operations + + migration.upgrade() + tables = set(sa.inspect(connection).get_table_names()) + assert EXPECTED_TABLES.issubset(tables) + + inspector = sa.inspect(connection) + client_cols = {item['name'] for item in inspector.get_columns('integration_client_instances')} + assert 'credential_ref_code' in client_cols + binding_indexes = {item['name'] for item in inspector.get_indexes('integration_bindings')} + assert 'ix_integration_bindings_cap_env_status' in binding_indexes + + migration.downgrade() + assert EXPECTED_TABLES.isdisjoint(set(sa.inspect(connection).get_table_names())) diff --git a/backend/tests/services/integration_connector/test_models.py b/backend/tests/services/integration_connector/test_models.py new file mode 100644 index 00000000..25c4fedf --- /dev/null +++ b/backend/tests/services/integration_connector/test_models.py @@ -0,0 +1,119 @@ +"""tests/services/integration_connector/test_models.py + +用途:验证 Integration Connector 领域模型的可建表、唯一约束与状态/连接器类型约束。 +依赖:根 conftest 的 app fixture(SQLite 内存 + db.create_all())。 +逻辑:create_all 后各表可查询为空;code 唯一冲突抛 IntegrityError;非法 + connector_type / status 被 CheckConstraint 拒绝。 +""" + +from __future__ import annotations + +import pytest +from sqlalchemy.exc import IntegrityError + +from app import db +from app.models import ( + IntegrationBinding, + IntegrationCall, + IntegrationClientInstance, + IntegrationCredentialReference, + IntegrationInterfaceDefinition, +) + +CONNECTOR_MODELS = ( + IntegrationCredentialReference, + IntegrationClientInstance, + IntegrationInterfaceDefinition, + IntegrationBinding, + IntegrationCall, +) + + +def _client(**overrides): + values = { + "code": "ERP-T100", + "name": "T100 ERP", + "connector_type": "soap", + "environment": "prod", + "config_json": {"endpoint": "https://t100.invalid/ws", "timeout_seconds": 60}, + } + values.update(overrides) + return IntegrationClientInstance(**values) + + +def test_all_connector_tables_created_and_empty(app): + """create_all 已随 app fixture 执行,5 张连接器表均可插入且初始为空。""" + for model in CONNECTOR_MODELS: + assert model.query.count() == 0 + + +def test_client_instance_code_unique_conflict(app): + """同一 code 的第二条记录触发唯一约束。""" + db.session.add(_client()) + db.session.flush() + db.session.add(_client()) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_client_instance_connector_type_check(app): + """connector_type 不在白名单(rest/soap)时被 CheckConstraint 拒绝。""" + db.session.add(_client(connector_type="ftp")) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_interface_definition_status_check(app): + """InterfaceDefinition.status 非法值被 CheckConstraint 拒绝。""" + client = _client() + db.session.add(client) + db.session.flush() + iface = IntegrationInterfaceDefinition( + code="ERP-QUERY-STOCK", + name="查询库存", + client_instance_code=client.code, + connector_type="soap", + request_spec_json={"template": "{{invoice_no}}"}, + input_schema_json={}, + response_mapping_json={}, + output_schema_json={}, + version=1, + status="banana", + ) + db.session.add(iface) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_credential_reference_status_check(app): + """CredentialReference.status 非法值被 CheckConstraint 拒绝。""" + db.session.add(IntegrationCredentialReference( + code="ERP-CRED-01", + secret_ref="ERP_PASSWORD", + secret_provider="env", + credential_type="password", + version=1, + status="expired", + )) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_credential_reference_secret_ref_not_returned_in_summary_column(app): + """模型列本身不存明文;secret_ref 是引用键而非真实凭据。""" + cred = IntegrationCredentialReference( + code="ERP-CRED-01", + secret_ref="ERP_PASSWORD", + secret_provider="env", + credential_type="password", + version=1, + status="active", + ) + db.session.add(cred) + db.session.flush() + assert cred.secret_ref == "ERP_PASSWORD" + assert "password" not in cred.secret_ref.lower() or cred.secret_ref != "P@ssw0rd!" diff --git a/backend/tests/services/integration_connector/test_security.py b/backend/tests/services/integration_connector/test_security.py new file mode 100644 index 00000000..7f53ab69 --- /dev/null +++ b/backend/tests/services/integration_connector/test_security.py @@ -0,0 +1,73 @@ +"""tests/services/integration_connector/test_security.py + +用途:验证凭据引用解析(fail-closed)与敏感字段脱敏。 +依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。 +逻辑:secret_ref 指向缺失配置键→CredentialUnresolvedError;sanitize 脱敏敏感键; + credential_summary 只含元数据,绝不含明文。 +""" + +from __future__ import annotations + +import json + +import pytest + +from app import db +from app.core.errors import AppError +from app.models import IntegrationCredentialReference +from app.services.integration_connector.security import credential_summary, resolve_credential, sanitize + + +def _add_credential(code="ERP-CRED-01", secret_ref="ERP_TEST_CRED", **overrides): + cred = IntegrationCredentialReference( + code=code, secret_ref=secret_ref, secret_provider="env", + credential_type="password", version=1, status="active", **overrides, + ) + db.session.add(cred) + db.session.flush() + return cred + + +def test_resolve_credential_returns_secrets(app): + """secret_ref 指向存在的配置键时返回该字典。""" + app.config["ERP_TEST_CRED"] = {"username": "u", "password": "p", "endpoint": "https://erp.invalid"} + _add_credential() + creds = resolve_credential("ERP-CRED-01") + assert creds == {"username": "u", "password": "p", "endpoint": "https://erp.invalid"} + + +def test_resolve_credential_missing_secret_fail_closed(app): + """secret_ref 指向缺失/空配置键时抛 CredentialUnresolvedError。""" + _add_credential(secret_ref="MISSING_KEY") + with pytest.raises(AppError) as exc: + resolve_credential("ERP-CRED-01") + assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED" + + +def test_resolve_credential_unknown_ref_fail_closed(app): + """凭据引用不存在时抛 CredentialUnresolvedError。""" + with pytest.raises(AppError) as exc: + resolve_credential("NOPE") + assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED" + + +def test_sanitize_redacts_sensitive_keys(): + """sanitize 递归把 password/token/secret 等键替换为 ***。""" + data = {"outer": {"password": "s3cret", "keep": "ok"}, "token": "abc", "list": [{"secret": "x"}]} + out = sanitize(data) + assert out["outer"]["password"] == "***" + assert out["outer"]["keep"] == "ok" + assert out["token"] == "***" + assert out["list"][0]["secret"] == "***" + assert "s3cret" not in json.dumps(out) + + +def test_credential_summary_has_no_plaintext(app): + """credential_summary 只含元数据,不含解析出的明文。""" + app.config["ERP_TEST_CRED"] = {"username": "svc_user_erp", "password": "s3cretLY"} + cred = _add_credential() + resolve_credential("ERP-CRED-01") # 确保能解析 + summary = credential_summary(cred) + assert "s3cretLY" not in json.dumps(summary) + assert "svc_user_erp" not in json.dumps(summary) + assert summary["version"] == 1 diff --git a/backend/tests/services/integration_connector/test_transports.py b/backend/tests/services/integration_connector/test_transports.py new file mode 100644 index 00000000..6b2b80ee --- /dev/null +++ b/backend/tests/services/integration_connector/test_transports.py @@ -0,0 +1,104 @@ +"""tests/services/integration_connector/test_transports.py + +用途:验证 REST/SOAP Transport 的请求构造、业务错误映射与 fail-closed; + 以及结果分类(classify_transport_response)的六态语义。 +依赖:transports/base.py、transports/rest.py、transports/soap.py、errors.py。 +逻辑:Transport.call 返回原始 dict;分类器把 dict 归一为 IntegrationCallResult。 +""" + +from __future__ import annotations + +import pytest + +from app.services.integration_connector.errors import TransportNotFrozenError +from app.services.integration_connector.transports.base import IntegrationCallResult, classify_transport_response +from app.services.integration_connector.transports.rest import RestTransport +from app.services.integration_connector.transports.soap import SoapTransport + + +def _resp(status_code, payload=None, text=""): + class _Response: + def __init__(self): + self.status_code = status_code + self.text = text + self._payload = payload + + def json(self): + return self._payload + + return _Response() + + +def _client(**overrides): + cfg = {"endpoint": "https://erp.invalid", "timeout_seconds": 30} + cfg.update(overrides) + return {"config_json": cfg, "credential": {}} + + +def test_rest_builds_url_and_sends_request(): + """REST Transport 拼接 endpoint+path,按 method/params 发请求并返回 JSON。""" + captured = {} + + def fake_http(method, url, **kw): + captured.update(method=method, url=url, params=kw.get("params"), json=kw.get("json")) + return _resp(200, {"found": True, "quantity": "100"}) + + transport = RestTransport(http_request=fake_http) + result = transport.call( + client=_client(), + interface={"request_spec_json": {"method": "GET", "path": "/stock"}}, + request={"params": {"invoice_no": "INV-001"}}, + ) + assert captured["url"] == "https://erp.invalid/stock" + assert captured["method"] == "GET" + assert captured["params"] == {"invoice_no": "INV-001"} + assert result == {"found": True, "quantity": "100"} + + +def test_rest_business_error_maps_to_dict(): + """4xx 映射为 business_failed dict,供上层透传分类。""" + + def fake_http(method, url, **kw): + return _resp(404, text="not found") + + transport = RestTransport(http_request=fake_http) + result = transport.call( + client=_client(), + interface={"request_spec_json": {"method": "GET", "path": "/stock"}}, + request={}, + ) + assert result["status"] == "business_failed" + assert result["code"] == "HTTP_404" + assert "not found" in result["message"] + + +def test_rest_fail_closed_without_endpoint(): + """endpoint 未冻结时 fail-closed 抛 TransportNotFrozenError。""" + transport = RestTransport(http_request=lambda *a, **k: None) + with pytest.raises(TransportNotFrozenError): + transport.call( + client={"config_json": {}}, + interface={"request_spec_json": {"method": "GET", "path": "/stock"}}, + request={}, + ) + + +def test_soap_fail_closed_without_wsdl(): + """SOAP 无 wsdl/endpoint 时 fail-closed 抛 TransportNotFrozenError。""" + transport = SoapTransport() + with pytest.raises(TransportNotFrozenError): + transport.call( + client={"config_json": {}}, + interface={"request_spec_json": {"soap_action": "queryInventory"}}, + request={}, + ) + + +def test_classify_transport_response_states(): + """结果分类覆盖 success/duplicate_success/business_failed/technical_failed。""" + assert classify_transport_response({"status": "success", "document_no": "DOC-1"}).status == "success" + assert classify_transport_response({"status": "business_failed", "code": "E1", "message": "reject"}).status == "business_failed" + dup = classify_transport_response({"status": "duplicate_success", "verified_posted": True, "document_no": "DOC-9"}) + assert dup.status == "duplicate_success" + unknown = classify_transport_response({}) + assert unknown.status == "technical_failed" diff --git a/backend/tests/test_agent_registry_catalog.py b/backend/tests/test_agent_registry_catalog.py index 7d40baab..e1091da7 100644 --- a/backend/tests/test_agent_registry_catalog.py +++ b/backend/tests/test_agent_registry_catalog.py @@ -16,18 +16,22 @@ from app.services.agent_registry.catalog import ( def test_agent_type_catalog_contains_three_seed_types(): - """首批 Catalog 应包含 generic、shipping_notice、file_check 三类。""" - assert set(AGENT_TYPE_CATALOG.keys()) == {'generic', 'shipping_notice', 'file_check'} + """Catalog 应包含 generic、shipping_notice、file_check 等注册类型(含后续扩展)。""" + assert { + 'generic', 'shipping_notice', 'file_check', + 'procurement_contract_review', 'in_transit_transfer', + } <= set(AGENT_TYPE_CATALOG.keys()) def test_list_type_catalog_includes_agent_code_and_label(): """Admin 下拉列表每条须含 agent_code 与人类可读 label。""" catalog = list_type_catalog() - assert len(catalog) == 3 + assert len(catalog) >= 5 codes = {entry['agent_code'] for entry in catalog} - assert codes == {'generic', 'shipping_notice', 'file_check'} + assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer'} <= codes labels = {entry['label'] for entry in catalog} assert '通用问答 / 知识库' in labels + assert '在途仓自动调拨' in labels assert '货代发货通知' in labels assert '文件检核' in labels diff --git a/backend/tests/test_agent_registry_in_transit_transfer.py b/backend/tests/test_agent_registry_in_transit_transfer.py new file mode 100644 index 00000000..a6530647 --- /dev/null +++ b/backend/tests/test_agent_registry_in_transit_transfer.py @@ -0,0 +1,69 @@ +"""在途仓自动调拨 Agent 应用类型注册测试。 + +用途:验证 in_transit_transfer 已注册为 Agent 应用类型(catalog manifest + handler 绑定 + + HANDLER_REGISTRY),与既有 shipping_notice 注册链路一致。 +依赖:catalog_loader / catalog_bindings / handlers.bootstrap / resolver / catalog_validation。 +逻辑:只读断言注册契约;不创建 Flask 应用(避免对既有 catalog 单测造成影响)。 +""" + +from __future__ import annotations + +import pytest + +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.catalog_validation import ( + apply_catalog_capabilities, + normalize_handler_config, + validate_required_fields, +) +from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests +from app.services.agent_registry.handlers.base import AgentHandler +from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY + + +def test_in_transit_transfer_type_in_catalog(): + """catalog 必须包含 in_transit_transfer 应用类型及关键声明。""" + entry = get_catalog_entry('in_transit_transfer') + assert entry is not None + assert entry.get('label') == '在途仓自动调拨' + assert entry.get('runtime_provider_default') == 'hybrid' + progress = entry.get('progress_contract') or {} + assert progress.get('enabled') is True + assert progress.get('data_source', {}).get('domain') == 'in_transit_transfer' + + +def test_in_transit_transfer_bound_to_runtime_handler(): + """catalog_bindings 必须把 in_transit_transfer 绑定到同名 HANDLER_REGISTRY key。""" + assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['in_transit_transfer'] == 'in_transit_transfer' + + +def test_in_transit_transfer_handler_registered(): + """bootstrap 加载后 HANDLER_REGISTRY 包含 InTransitTransferHandler 实例。""" + reset_handlers_for_tests() + load_handlers() + handler = HANDLER_REGISTRY.get('in_transit_transfer') + assert handler is not None + assert isinstance(handler, AgentHandler) + assert handler.handler_key == 'in_transit_transfer' + reset_handlers_for_tests() + + +def test_in_transit_transfer_validation_compatible(): + """catalog_validation 对 in_transit_transfer 的强制能力/配置归一化/必填校验可执行。""" + from app.core.errors import ValidationError + + capabilities = apply_catalog_capabilities('in_transit_transfer', {'streaming': True}) + assert capabilities.get('human_confirm') is True + # 空 handler_config_schema:null 允许、任意字段拒绝(与既有类型一致)。 + assert normalize_handler_config('in_transit_transfer', None) is None + with pytest.raises(ValidationError): + normalize_handler_config('in_transit_transfer', {'poll_interval_seconds': '5'}) + validate_required_fields('in_transit_transfer', bound_schedule_task_id=None) + + +def test_in_transit_transfer_present_in_full_catalog(): + """完整 catalog 构建包含新类型(与既有类型共存)。""" + catalog = build_agent_type_catalog() + assert 'in_transit_transfer' in catalog + assert 'shipping_notice' in catalog diff --git a/backend/tests/test_parsing_profile_purpose.py b/backend/tests/test_parsing_profile_purpose.py new file mode 100644 index 00000000..5f3a3c84 --- /dev/null +++ b/backend/tests/test_parsing_profile_purpose.py @@ -0,0 +1,69 @@ +"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验)。 + +用途:验证 inventory_parsing_profile._validate_definition(purpose=...) 分支—— + movement 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、 + 不查库存字段目录、无 match_keys);inventory 维持既有 match_keys 校验。 + 并用 app fixture 校验模型 purpose 列默认 'inventory'。 +依赖:inventory_parsing_profile._validate_definition(纯)、app(SQLite)。 +逻辑:_required_movement_field_ids 纯函数校验;模型列默认值经 app fixture 校验。 +""" + +from __future__ import annotations + +import pytest + +from app.core.errors import ValidationError +from app.services.shipping_notice.inventory_parsing_profile import _validate_definition + +pytestmark = pytest.mark.pure_unit + + +def _movement_definition() -> dict: + return { + 'sheet_name': 'Movement', + 'header_row_index': 1, + 'field_mapping': { + 'doc_no': '单据编号', + 'line_no': '项次', + 'in_out_flag': '进出库别', + 'material_code': '料号', + 'material_name': '品名', + 'warehouse_code': '仓库', + 'storage_code': '储位', + 'lot_no': '批号', + 'quantity': '数量', + 'movement_date': '异动日期', + }, + } + + +def test_movement_definition_validates_fixed_fields(): + """movement 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。""" + definition = _validate_definition(_movement_definition(), purpose='movement') + assert definition['field_mapping']['doc_no'] == '单据编号' + assert definition['field_mapping']['quantity'] == '数量' + assert definition['match_keys'] == [] + + +def test_movement_definition_missing_fixed_field_rejected(): + """movement 缺 movement_date → 阻断。""" + raw = dict(_movement_definition()) + raw['field_mapping'] = {k: v for k, v in raw['field_mapping'].items() if k != 'movement_date'} + with pytest.raises(ValidationError): + _validate_definition(raw, purpose='movement') + + +def test_movement_definition_rejects_unknown_field(): + """movement 引用非定死领域字段 → 阻断。""" + raw = dict(_movement_definition()) + raw['field_mapping'] = {**raw['field_mapping'], 'free_text': '随意列'} + with pytest.raises(ValidationError): + _validate_definition(raw, purpose='movement') + + +def test_model_purpose_column_defaults_to_inventory(app): + """模型 purpose 列默认 'inventory'(既有行不回填)。""" + from app.models import ShippingInventoryParsingProfile + + existing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first() + assert existing is not None and existing.purpose == 'inventory' diff --git a/backend/tests/workers/test_in_transit_transfer_worker.py b/backend/tests/workers/test_in_transit_transfer_worker.py new file mode 100644 index 00000000..8b68b253 --- /dev/null +++ b/backend/tests/workers/test_in_transit_transfer_worker.py @@ -0,0 +1,23 @@ +"""在途调拨 transfer 队列 Worker 入口测试。 + +用途:验证 workers/worker_in_transit_transfer.py 可导入、目标队列为 transfer, + 且模块导入不触发主循环(__main__ 守卫)。 +依赖:workers.worker_in_transit_transfer(import 级验证,不启动进程)。 +""" + +from __future__ import annotations + +import importlib + + +def test_worker_module_imports_and_targets_transfer_queue(): + """worker 模块可导入并声明 transfer 队列。""" + module = importlib.import_module("workers.worker_in_transit_transfer") + assert module.QUEUES == ["transfer"] + + +def test_worker_main_guard_prevents_auto_start(): + """模块导入不执行 main(__main__ 守卫)。""" + module = importlib.import_module("workers.worker_in_transit_transfer") + assert hasattr(module, "main") + assert module.__name__ == "workers.worker_in_transit_transfer" diff --git a/backend/workers/worker_in_transit_transfer.py b/backend/workers/worker_in_transit_transfer.py new file mode 100644 index 00000000..1d5ace55 --- /dev/null +++ b/backend/workers/worker_in_transit_transfer.py @@ -0,0 +1,24 @@ +""" +backend/workers/worker_in_transit_transfer.py + +用途:在途仓自动调拨 transfer 队列 Worker Supervisor 兼容入口。 +依赖:backend/worker.py(通用领取/租约/回收)。 +逻辑:转调 backend/worker.py,仅消费 transfer 队列(预检/执行 Run/Item)。 +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +_backend_root = Path(__file__).resolve().parents[1] +if str(_backend_root) not in sys.path: + sys.path.insert(0, str(_backend_root)) + +from worker import main # noqa: E402 + +# transfer 队列消费类型:in_transit_transfer_precheck / in_transit_transfer_run / in_transit_transfer_item +QUEUES = ["transfer"] + +if __name__ == "__main__": + main(queues=QUEUES) diff --git a/docker-compose.yml b/docker-compose.yml index 2fadea96..f7847c2d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -243,6 +243,52 @@ services: networks: - ai-platform + # ============================================================================== + # hxops-transfer-worker: 在途仓自动调拨专用 worker(transfer 队列) + # ============================================================================== + hxops-transfer-worker: + image: ${BACKEND_IMAGE:-hxops-backend:local} + build: + context: . + dockerfile: backend/Dockerfile + args: + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim-bookworm} + PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} + PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} + container_name: hxops-transfer-worker + restart: always + command: ["python", "workers/worker_in_transit_transfer.py"] + depends_on: + - hxops-backend + env_file: + - ${COMPOSE_SHARED_ENV_BASENAME:-.env.shared} + - ${COMPOSE_ENV_BASENAME:-.env.dev} + environment: + - DATABASE_URL=${DATABASE_URL} + - SECRET_KEY=${SECRET_KEY} + - FLASK_APP=${FLASK_APP:-run.py} + - FLASK_ENV=${FLASK_ENV} + - REDIS_URL=${REDIS_URL:-redis://kb-redis:6379/0} + - SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=${SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR:-} + - IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=${IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY:-2} + - IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=${IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY:-2} + - IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=${IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY:-1} + - IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=${IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS:-60} + - IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=${IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS:-60} + - IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=${IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS:-600} + - IN_TRANSIT_TRANSFER_ERP_ENDPOINT=${IN_TRANSIT_TRANSFER_ERP_ENDPOINT:-} + - IN_TRANSIT_TRANSFER_ERP_USERNAME=${IN_TRANSIT_TRANSFER_ERP_USERNAME:-} + - IN_TRANSIT_TRANSFER_ERP_PASSWORD=${IN_TRANSIT_TRANSFER_ERP_PASSWORD:-} + - IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG=${IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG:-} + - IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=${IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET:-hxops-transfer} + extra_hosts: + - "host.docker.internal:host-gateway" + volumes: + - ./oracle_client:/app/oracle_client:ro + - hxops_runtime_data:/app/data + networks: + - ai-platform + # ============================================================================== # hxops-frontend: Vue 前端静态资源 + Nginx 反向代理 (端口: 80) # ============================================================================== diff --git a/docs/demand.md b/docs/demand.md index bdf845cc..85a7ad50 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -833,3 +833,10 @@ XFA 模板管理端暂不启用字段脱敏,树、拆分预览和样本验证 - Casdoor 登录到 HXOPS 本地用户以 `employee_id`(工号)为主映射键;当前用户名等于工号,仅保留用户名到本地工号/用户名的兼容回退。邮箱和手机号不参与认证映射;工号与用户名命中不同本地用户时拒绝登录。 --- + +## 在途仓自动调拨 Agent(2026-08) + +- 需求:仓库管理人员按收料来源实例(DBS-AWSBI / DBS-AWSSG / CRANE-SZ)核对收料文件与 ERP 账面库存后生成 ERP 调拨单;DBS/Crane 仅分组,来源实例为执行边界。 +- 手工两步:选择来源实例 → 预检明细核对后直接生成 ERP 调拨单(无独立确认页);当天收料不查询 ERP;数量严格相等才可执行;不支持部分调拨/容差/单位换算/批次拆分。 +- ERP 写入由后端确定性服务与 Worker 完成,Dify 不得直接调用 ERP;Invoice No 幂等;结果未知只读禁自动重试;通知失败不改变 ERP 结果。 +- 完整规格见 [features/in-transit-transfer/minimum-implementation-spec.md](features/in-transit-transfer/minimum-implementation-spec.md)。 diff --git a/docs/features/README.md b/docs/features/README.md index 562f488c..99088ef1 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -5,7 +5,7 @@ | 域 | 说明 | 入口 | | --- | --- | --- | | [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [客户识别规则改造方案](shipping-notice/customer_identity_rules_plan.md) | -| [in-transit-transfer](in-transit-transfer/) | 在途仓自动调拨 Agent | [开发部门需求与原型评审包](in-transit-transfer/mvp-requirements-and-prototype-review-pack.md) · [来源实例 Lean UX Canvas](in-transit-transfer/mvp-source-instance-lean-ux-canvas.md) · [可点击原型](../platform/in-transit-transfer-source-instance-mvp.html) · [PRD](in-transit-transfer/prd.md) · [路线图](in-transit-transfer/roadmap.md) · [完整规格](in-transit-transfer/minimum-implementation-spec.md) · [一期 TDD](in-transit-transfer/in-transit-transfer-tdd.md) | +| [in-transit-transfer](in-transit-transfer/) | 在途仓自动调拨 Agent | [开发部门需求与原型评审包](in-transit-transfer/mvp-requirements-and-prototype-review-pack.md) · [来源实例 Lean UX Canvas](in-transit-transfer/mvp-source-instance-lean-ux-canvas.md) · [可点击原型](../platform/in-transit-transfer-source-instance-mvp.html) · [PRD](in-transit-transfer/prd.md) · [路线图](in-transit-transfer/roadmap.md) · [完整规格](in-transit-transfer/minimum-implementation-spec.md) · [一期 TDD](in-transit-transfer/in-transit-transfer-tdd.md) · [运维手册](in-transit-transfer/technical.md) | | [auth](auth/README.md) | Casdoor 登录与产品内平级服务无感登录 | [hxops-peer-service-sso.md](auth/hxops-peer-service-sso.md) | | [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [原型](shipping-notice/shipping_notice_agent_prototype.md) | | [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) | diff --git a/docs/features/in-transit-transfer/technical.md b/docs/features/in-transit-transfer/technical.md new file mode 100644 index 00000000..8ee235be --- /dev/null +++ b/docs/features/in-transit-transfer/technical.md @@ -0,0 +1,95 @@ +# 在途仓自动调拨 Agent — 运行维护手册 + +> 状态:后端 Phase 0-4 已交付(领域/文件/预检/执行/排程/恢复/通知/归档/指标),前端实施中。 +> 关联规格:[minimum-implementation-spec.md](./minimum-implementation-spec.md) · [TDD](./in-transit-transfer-tdd.md) · [PRD](./prd.md) · [路线图](./roadmap.md) + +## 1. 架构概览 + +- **业务域**:`backend/app/services/in_transit_transfer/`(独立领域模块,不混入 shipping_notice 订单解析)。 +- **执行边界**:收料来源实例(如 DBS-AWSBI / DBS-AWSSG / CRANE-SZ);DBS/Crane 仅分组。 +- **真相源**:`TransferRun` / `TransferPrecheck` / `TransferInvoiceItem` / `TransferAttempt`(表:`transfer_*`,迁移 `it1a2b3c4d5e`)。 +- **ERP 访问唯一出口**:`erp_adapter.py`(query_inventory / create_transfer / verify_duplicate);SOAP 在 WSDL 冻结前 fail-closed(`ErpNotFrozenError`)。 +- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费预检/执行 Run/执行 Item 三类 Job。 +- **排程**:`in-transit-receipt-file`(08:00)与 `in-transit-transfer`(09:00)platform job(`schedule/job_registry.py`)。 + +## 2. 数据库 + +- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`)。 +- 部署:`cd backend && flask db upgrade`(PostgreSQL)。回滚:`flask db downgrade <上一revision>`。 +- 表:transfer_runs / transfer_source_jobs / transfer_prechecks / transfer_invoice_items / transfer_attempts / transfer_audit_events / transfer_archives。 +- 审计表只追加(ORM 门禁 + 前端禁止删除);大对象归档 MinIO(transfer_archives 记录 provider/bucket/key/sha256)。 + +## 3. 环境变量(⑨业务模块区;凭据只由环境/Secret 注入) + +| 变量 | 默认 | 说明 | +| --- | --- | --- | +| `IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY` | 2 | 来源并发 | +| `IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY` | 2 | ERP 查询并发 | +| `IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY` | 1 | ERP 写并发(一期恒 1,禁止提升) | +| `IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS` | 60 | 查询超时 | +| `IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS` | 60 | 写超时 | +| `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` | 600 | 确认有效期(10 分钟) | +| `IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS` | 3 | 老化预警阈值 | +| `IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS` | 5 | 老化升级阈值 | +| `IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS` | 7 | 老化严重阈值 | +| `IN_TRANSIT_TRANSFER_ERP_ENDPOINT` / `_USERNAME` / `_PASSWORD` / `_DEFAULT_ORG` | 空 | ERP SOAP 地址与凭据(WSDL 冻结前留空=fail-closed) | +| `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` | hxops-transfer | 归档 bucket | +| `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | MinIO 连接(复用既有变量) | +| `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` | 既有 | 收料 RPA trigger 目录(复用收料链路) | + +> 凭据纪律:ERP/MinIO 凭据只存在于环境/Secret;不得写入代码、日志、DOM、Excel 或 API 响应。 + +## 4. API(`/api/in-transit-transfer`,统一 envelope + requestJson) + +| Method | Path | 说明 | +| --- | --- | --- | +| POST | `/prechecks` | 创建预检(只读) | +| GET | `/prechecks/{id}` | 预检进度恢复 | +| POST | `/prechecks/{id}/execute` | 确认范围并直接生成执行 Run | +| GET | `/runs/{run_no}` | Run 结果(按 ERP 单号聚合 + 未生成单据异常) | +| POST | `/runs/{run_no}/cancel` | 请求停止剩余任务(原因必填) | +| POST | `/items/{id}/retry` | 人工重试(erp_recheck,新 Attempt) | +| POST | `/items/{id}/manual-close` | 人工关闭(原因必填) | +| GET | `/runs/{run_no}/exceptions.xlsx` | 七 Sheet 异常 Excel(下载留审计) | +| GET | `/runs/{run_no}/receipt-files` | 收料来源文件 zip(下载留审计) | +| GET | `/runs/{run_no}/erp-inventory` | 预检冻结 ERP 库存表 csv(下载留审计) | + +权限:admin 或持有 `in_transit_transfer` Agent 权限;无权限 403。 + +## 5. 部署 + +```bash +# 后端(迁移 + worker) +cd backend && flask db upgrade +# 新增 transfer worker 服务(docker-compose 增加 hxops-transfer-worker, +# command: python workers/worker_in_transit_transfer.py,环境同后端) +``` + +上线灰度顺序(路线图 §8.6):ERP 测试组织 UAT → 生产只读观察(预检、写=0)→ 小范围对话写入试点 → 正式对话写入 → 单来源自动排程 → 全部来源自动排程;每步留启用人/时间/配置版本/门禁结果/回退条件审计。 + +## 6. 告警与运维关注点 + +- `result_unknown` 项数量(只读隔离,等待人工核实 SOP;禁止自动重试)。 +- 待处理池 3/5/7 天老化计数(`metrics.collect_metrics()` / 待处理页)。 +- `notification_status=failed` 的 Run(ERP 结果不受影响,但通知缺失需人工补发)。 +- ERP 超时率与 `ErpNotFrozenError` 出现(说明契约/配置未冻结或 endpoint 缺失)。 +- 归档 Hash 复核(`verify_archive_hash`)与 MinIO 容量。 + +## 7. 归档与数据保留 + +- 大型快照/Excel/报文经 `archive.py` 归档 MinIO,`transfer_archives` 索引+Hash 留库;归档必须重算 Hash 并写审计。 +- 审计事件永久保留(到期清理需显式配置,参照既有 shipping 审计保留机制)。 + +## 8. 回退策略 + +- 停用 `in-transit-transfer` 自动排程(不删除历史 Run);保留对话只读预检与手工执行。 +- `result_unknown` 继续进入人工核实池;已成功 ERP 单据不自动撤销。 +- 回退配置走新发布版本 + Diff 审计,不直接改数据库。 + +## 9. E2E 与验收(前置:ERP 契约/路由归属/单据分组冻结 + 测试组织/白名单 + Secret 注入 + SOP 确认) + +- 后端专项:`cd backend; pytest -q tests/services/in_transit_transfer; pytest -q tests/api/test_in_transit_transfer_api.py; pytest -q tests/jobs/test_in_transit_transfer_jobs.py; pytest -q tests/workers/test_in_transit_transfer_worker.py` +- 性能:`pytest -q tests/performance/test_in_transit_transfer.py` +- 前端:`cd frontend; npm run test:unit -- src/features/chat; npm run build` +- 端到端场景清单(前端实施后落 Playwright/Vitest 契约):人工执行主路径、自动排程、异常恢复、刷新恢复、权限越权、ERP 沙箱真实单据(创建/审核/过账/作废)。 +- 上线门禁:P0/P1 缺陷 0;越权写 403 100%;当天收料 ERP 调用 0;审计 Hash 复算一致率 100%;Secret 明文暴露 0。 diff --git a/docs/funclist.md b/docs/funclist.md index 9a20ef75..ffb17f7c 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -696,3 +696,33 @@ 详细目标架构、接口契约、测试矩阵与验收标准见 [features/auth/hxops-peer-service-sso.md](features/auth/hxops-peer-service-sso.md)。 --- + +## 在途仓自动调拨 Agent + +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | ackend/app/models/in_transit_transfer.py(Run/SourceJob/Precheck/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e;13 状态服务端门禁(services/in_transit_transfer/status.py) | +| 收料文件准备与只读预检 | 后端已实现 | ready 复用/缺文件按来源触发收料 RPA/来源隔离/字段校验/D+1/Invoice 多行汇总+原始行追溯/ERP 库存查询/严格数量匹配/预检快照 Hash/进度恢复 | +| 确认与 ERP 原子调拨 | 后端已实现 | 直接生成执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按 ERP 单号聚合结果(ERP SOAP 实现在 WSDL 冻结前 fail-closed) | +| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) | +| 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md | +| 前端 Chat 卡片/结果页与四语言 | 实施中 | `frontend/src/features/chat/` 卡片(文件进度/预检/结果/待处理)与 admin 模块按计划实施 | + +--- + +## 外部系统连接器框架(Integration Connector) + +> 平台级外部系统集成抽象(连接器/能力契约/绑定/AI 工具暴露)。首个消费者为在途仓自动调拨的 `query_inventory`。设计文档 [docs/platform/integration-connector-framework-design.md](platform/integration-connector-framework-design.md);完整愿景见 [enterprise-integration-center-prototype.md](platform/enterprise-integration-center-prototype.md)。 + +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| 配置实体 + 迁移 | 后端已实现 | `models/integration_connector.py`(CredentialReference/ClientInstance/InterfaceDefinition/Binding/Call)+ 迁移 ic1a2b3c4d5f | +| Capability 强类型契约 | 后端已实现 | 代码注册(输入/输出 Schema/幂等语义/是否写);在途调拨 3 能力 query_inventory/create_transfer/verify_duplicate | +| REST/SOAP 传输 | 后端已实现 | `transports/`(fail-closed:缺 endpoint/wsdl 抛 INTEGRATION.TRANSPORT_NOT_FROZEN) | +| 声明式映射引擎 | 后端已实现 | 点路径/数组下标 + 白名单转换函数 + 最小 Schema 校验(禁任意 Python/JS/SQL) | +| 凭据引用 + 脱敏 | 后端已实现 | 只存 secret_ref 引用;sanitize 脱敏;credential_summary 不回显明文 | +| Binding 版本化解析 | 后端已实现 | (capability, context, environment) → 客户端+接口+映射版本;默认+来源覆盖+优先级+生效区间;冻结快照 | +| CapabilityGateway 引擎 | 后端已实现 | resolve→validate→build→call→map→classify→落 IntegrationCall;result_unknown 不自动重试 | +| Admin API | 后端已实现 | `/api/integration-connector/*`(配置 CRUD + 能力清单/调用 + 连接测试;拒绝 interface_id;require_admin) | +| 调拨 query_inventory 接线 | 后端已实现 | `services/in_transit_transfer/gateway_adapter.py` 把 ERP 访问收敛到 gateway(P1 用默认绑定,来源专属绑定待 P2/P3) | +| 配置作业 UI / MCP / Dify 暴露 / RPA/SQL 传输 | 待实施 | 属 P2/P3(AI 只暴露 Capability;RPA 为独立异步 Transport) | diff --git a/docs/platform/README.md b/docs/platform/README.md index 7f633316..cf45214b 100644 --- a/docs/platform/README.md +++ b/docs/platform/README.md @@ -10,3 +10,5 @@ | [agent_progress_prototype.md](agent_progress_prototype.md) | Agent 进度管理通用底座(`async_batch` 等) | | [agent_runtime_context_prototype.md](agent_runtime_context_prototype.md) | Runtime Context 协议原型 | | [progress_contract_platform_prototype.html](progress_contract_platform_prototype.html) | 进度契约平台 HTML 原型 | +| [enterprise-integration-center-prototype.md](enterprise-integration-center-prototype.md) | 企业集成中心蓝图(完整愿景,含 HTML 原型) | +| [integration-connector-framework-design.md](integration-connector-framework-design.md) | Integration Connector Framework 设计(首期最小可行收敛版) | diff --git a/docs/platform/integration-connector-framework-design.md b/docs/platform/integration-connector-framework-design.md new file mode 100644 index 00000000..f5576512 --- /dev/null +++ b/docs/platform/integration-connector-framework-design.md @@ -0,0 +1,385 @@ +# Integration Connector Framework:连接器、能力契约、绑定与 AI 工具暴露设计 + +| 项目 | 说明 | +| --- | --- | +| 文档版本 | v1.0(首期最小可行设计) | +| 日期 | 2026-08-27 | +| 状态 | 设计评审中(未实现) | +| 读者 | 平台研发、后端、前端、Agent/集成负责人、ERP/RPA 管理员 | +| 关联文档 | [企业集成中心蓝图(完整愿景)](enterprise-integration-center-prototype.md) | +| 首个消费者 | 在途仓自动调拨(`in_transit_transfer`) | + +> 本文是既有《HXOPS 企业集成中心与在途仓自动调拨原型设计》(`enterprise-integration-center-prototype.md`)的**首期收敛版**。蓝图描绘的是平台级完整愿景;本文只规定**先落地的那个最小闭环**,避免一次性建成完整 iPaaS 导致的过度设计。蓝图未在本文明示的能力(流程编排、Saga 补偿、Schema Registry、发布中心、Mock/契约测试、可观测、灾备等)一律视为**后续平台化能力**,不在首期范围。 + +--- + +## 0. 三条设计原则 + +1. **配置替换外部系统,不替代领域业务规则。** 连接器/接口/字段映射可配置;但"数量必须相等""当天收料不调拨""`result_unknown` 不得重试"等规则永远属于领域层,不允许管理员通过配置改变。 +2. **AI 调用业务能力,不调用原始接口。** 对 AI Agent 与外部应用只暴露治理过的 Capability(如 `query_inventory`),不暴露 ERP 地址、SOAP Action、凭据、请求模板或接口编号。 +3. **所有配置与调用均版本化、可测试、可审计、fail-closed。** 配置缺项即拒绝,不猜测;一次 Run 冻结全部相关版本;每次调用留痕。 + +--- + +## 1. 背景与问题 + +### 1.1 现状 + +在途仓自动调拨当前把 ERP 访问**写死**在代码里: + +- `app/services/in_transit_transfer/erp_adapter.py` 的 `SoapErpTransport` 是唯一传输层,`query_inventory` / `create_transfer` / `verify_duplicate` 三个操作硬编码; +- `app/services/in_transit_transfer/deps.py::_build_erp_adapter()` 固定读取 `IN_TRANSIT_TRANSFER_ERP_*` 配置键并固定构造 SOAP 传输; +- 没有"按来源/按操作选择哪个外部系统、哪个接口、哪种映射"的注册与路由机制。 + +### 1.2 目标 + +建设一个**系统无关**的连接器框架:同一业务能力(如"查库存")在不同外部系统(ERP / WMS / OA / PLM / HR / RPA 等)上,只通过配置切换客户端实例、接口定义与字段映射,业务代码零改动。同时把治理过的能力暴露给 AI Agent 与其他应用调用。 + +> 命名约定:框架不使用 `ErpAdapter` 之类 ERP 专属命名。ERP 只是框架接入的**一个外部系统示例**。通用抽象统一称为 **Connector / Transport / Capability / InterfaceDefinition / Binding**。 + +### 1.3 "零改代码"的边界 + +- **已注册的业务能力**更换外部系统、接口或字段映射时,业务代码零改动; +- **新增全新业务能力**仍需注册能力契约(输入/输出 Schema、幂等语义、是否写)并实现领域处理逻辑。 + +配置不能替代领域业务规则(见原则 1)。 + +--- + +## 2. 三层最小架构 + +```text +┌─────────────────────────────────────────────────────────┐ +│ 领域层(Domain) │ +│ 业务规则、状态机、幂等、写前复查、来源隔离、审计 │ +│ 只调用标准 Capability,不感知协议/地址/凭据/字段路径 │ +└────────────────────────┬────────────────────────────────┘ + │ CapabilityGateway.call(capability, ctx, params) +┌────────────────────────▼────────────────────────────────┐ +│ 连接器层(Connector) │ +│ Transport 实现(首期 REST / SOAP)+ 声明式请求/响应映射 │ +│ resolve → build → call → map → classify → audit │ +└────────────────────────┬────────────────────────────────┘ + │ Transport.call(interface, client, request) +┌────────────────────────▼────────────────────────────────┐ +│ 配置层(Configuration) │ +│ ClientInstance / InterfaceDefinition / Binding / 版本 │ +│ CredentialReference(Secret 引用,非明文) │ +└─────────────────────────────────────────────────────────┘ +``` + +--- + +## 3. 核心概念与实体 + +### 3.1 配置实体(6) + +| 实体 | 存哪 | 职责 | +| --- | --- | --- | +| **ConnectorType 连接器类型** | 代码 + 目录 | Transport 实现:首期 `REST`、`SOAP`;后置 `RPA`、`SQL`、`FILE` | +| **ClientInstance 客户端实例** | DB | 一份连接配置:连到哪、凭据引用、超时/TLS、默认 org/租户 | +| **InterfaceDefinition 接口定义** | DB | 一个可调操作:请求模板 + 参数 Schema + 返回值映射 + 成功/错误条件 | +| **Binding 绑定** | DB | `(Capability, context_selector) → (ClientInstance + InterfaceDefinition + mapping_version)`,含版本/生效区间/优先级/状态 | +| **CredentialReference 凭据引用** | DB | 仅存 `secret_ref` + 元数据;真实凭据由 Secret 服务注入,不回显 | +| **Capability 业务能力** | 代码注册 + DB 目录 | 强类型契约(见 §4) | + +### 3.2 运行时实体(2) + +| 实体 | 职责 | +| --- | --- | +| **IntegrationCall** | 一次调用实例:能力、绑定版本、请求摘要、响应摘要、状态、耗时、trace_id | +| **IntegrationAsyncTask** | RPA/Webhook/MQ 等异步任务的提交、等待、回调与恢复状态(后置) | + +> 审计事件可关联以上两个实体,但**审计表不承担运行状态**;运行状态归 IntegrationCall / IntegrationAsyncTask。 + +--- + +## 4. Capability 强类型契约 + +`Capability` **不能完全由数据库动态定义**,否则会退化为"管理员写业务逻辑"。 + +- **代码注册**:能力名称、输入 Schema、输出 Schema、幂等语义、是否允许写,由代码注册(如 `@register_capability`)。 +- **DB 只维护**:启用状态、版本、展示描述、绑定关系。 +- **领域只调标准能力**,例如: + +```text +query_inventory(input) -> InventoryResult +create_transfer(input) -> TransferResult +verify_duplicate(input) -> TransferResult +``` + +外部系统差异全部在 Connector 层(Transport + 映射)解决,不进入领域层。 + +> 能力命名规范:`.`,如 `in_transit_transfer.query_inventory`。本文其余处以短名 `query_inventory` 等指代,均属于 `in_transit_transfer` 域。 + +--- + +## 5. Binding 版本化与发布 + +Binding 至少包含: + +```text +capability +context_selector # 来源/组织/租户/环境等路由条件(含默认绑定) +client_instance # 版本引用 +interface_definition # 版本引用 +mapping_version +priority +environment +effective_from / effective_to +status # draft / published / retired +``` + +- 配置修改**不能影响运行中的任务**。 +- 一次 Run 创建时必须冻结:`ClientInstance 版本`、`InterfaceDefinition 版本`、`Binding 版本`、`Mapping 版本`、`Credential 引用版本`。 + +--- + +## 6. 表达式与映射限制 + +请求模板与返回映射**禁止**执行任意 Python / JavaScript / SQL。仅允许: + +- JSONPath / JMESPath(JSON) +- XPath(XML) +- SQL 命名参数(仅限预注册模板,见 §12) +- 白名单转换函数(`cast` / `decimal` / `date` / `default` / `fallback` / `enum-map` / `list-map` / `if-else`) +- 有限条件表达式 +- 变量占位符 + +所有表达式执行须有**超时、深度、长度、函数白名单**限制;输出经 JSON Schema 校验,不合法即 fail-closed 报错。 + +--- + +## 7. 运行时调用引擎(同步管线) + +``` +resolve(capability, context) → Binding → (client, interface, credential, mapping) +build_request(interface, params) → 该接口的原始请求 +transport.call(connector_type, client, request) → 原始响应 +map_response(mapping, raw) → 统一结果 DTO(经输出 Schema 校验) +classify(result) → success / business_failed / technical_failed / timeout / result_unknown +audit(IntegrationCall) +``` + +统一结果 DTO: + +```text +IntegrationCallResult(status, data, error_code, error_message, document_no?, trace_id) +``` + +首期 Transport 契约(同步): + +```text +rest.call(interface, client, request) -> raw_response +soap.call(interface, client, request) -> raw_response +``` + +--- + +## 8. RPA 与异步执行(后置,但契约先定) + +RPA **不是 FILE 的别名**,也不是普通同步调用。它必须拥有独立 Transport Contract: + +```text +submit_trigger # 写 trigger 文件/信号,原子提交 +callback_authentication # 回调签名/防重放 +heartbeat # Worker 心跳与能力声明 +timeout_recovery # 超时恢复与反查 +artifact_locator # 结果产物定位(文件/共享目录) +result_file_mapping # 结果文件 → 标准数据(复用 FILE 映射) +``` + +即:**RPA = 异步 Transport + 文件结果适配器**,不能只配置成"触发一个文件,然后按 FILE 读取"。 + +异步管线(预留): + +``` +resolve → submit(trigger) → 注册 IntegrationAsyncTask → 等待(心跳/回调) → 结果落盘 → map → classify → audit +``` + +首期**不实现** RPA 通用连接器内核;继续复用现有收料 RPA 能力(`shipping_notice/receipt_rpa.py` + `rpa_worker_heartbeat.py`)。待框架稳定后再将 RPA 接入为异步 Transport。 + +--- + +## 9. AI / 外部应用暴露面 + +### 9.1 只暴露 Capability,不暴露原始接口 + +AI 与其他应用只能看到: + +```text +query_inventory +create_transfer +verify_duplicate +get_transfer_status +download_receipt_file +``` + +不应知道:ERP 地址、SOAP Action、凭据、原始请求模板、外部系统接口编号、`interface_id`。 + +### 9.2 治理门禁 + +- 能力级 RBAC(复用 `app/core/decorators.py` + `action_registry.py` 的 `ACTION_AGENT_CODES` 模式) +- 租户 / 组织范围校验 +- 写操作确认门禁 +- 幂等键 +- 调用额度与超时 +- `result_unknown` 禁止自动重试 +- 高风险操作的人工确认或策略开关 + +### 9.3 通用 REST 网关(谨慎) + +`POST /api/integration/call` 灵活但风险高,约束如下: + +- 对外默认使用**能力白名单**; +- **不允许**客户端直接传 `interface_id` 覆盖 Binding; +- `interface_id` 仅作后台诊断参数,普通 Agent / 外部应用不可传; +- 推荐生成**能力专用端点**或统一工具名,例如: + +```text +POST /api/integration/capabilities/query_inventory +``` + +### 9.4 多面暴露(一次定义、多面复用) + +每个 InterfaceDefinition 自动生成**工具描述**(name / 描述 / 入参 Schema / 出参 Schema / 鉴权): + +1. **REST 网关**(其他应用) +2. **MCP Server**(对标 MCP 的 Agent,后置) +3. **Dify 自定义工具**(接入现有 `action_registry.py`) + +--- + +## 10. 凭据模型(引用 + Secret 元数据) + +DB **不保存真正凭据内容**,只保存: + +```text +secret_ref +secret_provider +credential_type +version +status +last_verified_at +``` + +- ClientInstance 引用 `secret_ref`; +- 切换凭据通过版本更新,**不能覆盖运行中的调用**; +- 凭据不回显、不写日志、不进配置快照(复用调拨 `sanitize_snapshot` 思路)。 + +--- + +## 11. 配置作业完整生命周期 + +客户端配置页不是简单 CRUD,而是: + +```text +草稿 +→ 参数校验 +→ 连接测试 +→ 接口试运行 +→ 返回映射预览 +→ 发布 +→ 生效 +→ 停用 +``` + +- 试运行必须使用**脱敏样本或测试环境**; +- "测试连接成功"不代表业务映射正确——试运行须同时校验成功响应与业务错误响应的映射结果。 + +--- + +## 12. SQL 连接器限制(后置) + +SQL 连接器除"默认只读"外,还须: + +- 只允许**预注册查询模板**; +- 禁止 AI 直接生成 SQL; +- 禁止多语句、DDL、DML、存储过程调用; +- 限制表、字段、行数、执行时长; +- 返回结果必须经输出 Schema 校验与脱敏。 + +--- + +## 13. 与在途调拨的接入(首个消费者) + +### 13.1 责任分层 + +| 层 | 负责 | 不负责 | +| --- | --- | --- | +| 领域层 | 数量严格匹配、D+1、幂等、写前复查、`result_unknown`、来源隔离、审计 | 协议、地址、凭据、字段路径 | +| 连接器层 | `query_inventory` / `create_transfer` / `verify_duplicate` 的请求/响应映射与 SOAP/REST 传输 | 是否该调拨、数量判定 | + +### 13.2 接入方式 + +- 领域代码改为通过 `CapabilityGateway` 调能力 `in_transit_transfer.query_inventory / create_transfer / verify_duplicate`; +- 现有 `RouteResolver`(按来源解析 org/仓库)**不替换**,其输出的来源上下文作为 `context_selector` 喂给 Binding; +- 预置绑定:`(query_inventory, DBS-AWSBI)` → 当前 ERP 客户端 + 查询接口;将来 `(query_inventory, CRANE-SZ)` → 新 WMS 客户端 + 接口,只加配置行; +- 移除 ERP 专属 `ErpAdapter` 作为通用层;ERP 仅作为框架接入的外部系统实例。 + +--- + +## 14. MVP 范围与分期 + +### 14.1 首期最小可行(MVP) + +实体:`Capability`、`ClientInstance`、`InterfaceDefinition`、`Binding`、`CredentialReference`、`IntegrationCall`。 + +Transport:仅 `REST`、`SOAP`。 + +能力:仅注册 3 个: + +```text +query_inventory # 查询外部系统库存 +create_transfer # 创建/审核/过账调拨单 +verify_duplicate # 确认重复 Invoice 对应原单 +``` + +### 14.2 分期 + +| 阶段 | 内容 | 明确不做 | +| --- | --- | --- | +| **P0** | 稳定现有调拨业务闭环;ERP 调用收敛为内部 Adapter | 通用配置页 | +| **P1** | 连接器内核:`CapabilityGateway` + REST/SOAP Transport + ClientInstance/InterfaceDefinition/Binding + 版本化配置 + Secret 引用 + 连接测试/接口试运行;`query_inventory` 首个配置绑定消费者 | 通用接口设计器、任意表达式编辑器、SQL/RPA/FILE | +| **P2** | 配置作业 UI(草稿→校验→测试→试运行→预览→发布→回滚/停用)+ AI 暴露(只暴露 3 能力) | interface_id 直传、原始接口暴露 | +| **P3** | 异步与更多协议:RPA / FILE / Webhook / MQ / MCP / SQL 只读查询 | 低代码编排、脚本转换 | + +--- + +## 15. 落地文件与数据迁移(P1 起) + +- 模型:`app/models/integration_connector.py`(ClientInstance / InterfaceDefinition / Binding / CredentialReference / IntegrationCall / IntegrationAsyncTask) +- 服务:`app/services/integration_connector/`(`capability.py` / `binding.py` / `engine.py` / `mapping.py` / `transports/rest.py` / `transports/soap.py` / `descriptors.py` / `security.py`) +- API:`app/api/integration_connector.py`(Admin CRUD + 能力调用端点 + 工具清单) +- Admin UI:`frontend/src/features/admin/modules/integration-connector/`(客户端配置作业) +- 迁移:Alembic 新迁移,挂在当前 head 后 + +--- + +## 16. 安全 / 审计 / fail-closed 总则 + +- 能力级 RBAC;SQL 默认只读、写操作须显式标记 + 强制审计; +- 凭据仅 Secret 引用,日志脱敏; +- 缺端点 / 缺凭据 / 映射不合法 → fail-closed 拒绝,绝不猜测; +- 每次调用落 `IntegrationCall`;配置创建/测试/发布/停用记前后快照审计; +- 写操作必须携带幂等键,`result_unknown` 禁止自动重试。 + +--- + +## 17. 首期验收标准 + +- 新增外部系统实例(换系统)无需修改调拨领域代码; +- 修改外部字段路径仅需发布新映射版本; +- 一次 Run 能追溯到冻结的全部配置版本; +- 原始 SOAP/REST 报文不进入调拨领域表; +- 凭据不回显、不写日志、不进快照; +- AI / 外部应用只能调用治理过的 Capability,无法传入 `interface_id` 或原始接口参数; +- 数量严格匹配、D+1、写前复查、`result_unknown` 禁重试等规则仍在领域层生效。 + +--- + +## 18. 相关文档 + +- [企业集成中心蓝图(完整愿景)](enterprise-integration-center-prototype.md) +- 在途仓自动调拨实现(Phase 0/1):`backend/app/services/in_transit_transfer/` +- Chat Action Registry(Agent 挂载点):`backend/app/services/chat/action_registry.py` diff --git a/docs/tec.md b/docs/tec.md index 9be52f84..fec019d8 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -1473,3 +1473,7 @@ RecoveryPlan → Gate Attempt → Job → Worker/RPA → 幂等回调 → `run_t `freight-receipt-rpa` 写入 `shipping_receipt_rpa.v1` trigger,仅由 `freight_receipt_rpa_worker.py` 消费。它使用专属 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` 和 `...RECEIPT_DROP_DIR`,不得与库存 Worker 共享目录或 callback。trigger 先写同目录临时文件、`fsync` 后以 `os.replace` 原子发布,避免 Worker 读取半截 JSON。Worker 在单次排程内按 `connector_type + rpa_profile_id + login_url` 分组并登录一次,串行导出;密文凭据仅在冻结 trigger 内传递并在 Worker 短暂解密。callback 仅允许读取 receipt drop 根内的 `.xlsx`,校验 SHA-256/大小后归档 MinIO。收料表与 `shipping_inventory_files` 无关联。 下载接口为 `GET /api/workspace/receipt-report-files/{file_id}/download`(管理员或排程接收人);`GET /api/workspace/receipt-report-files` 仅列出当前用户有权读取的脱敏归档元数据,并在授权过滤后施加 limit。管理员可通过 `GET /api/admin/receipt-rpa-units?status=failed` 定位失败单元,并以 `POST /api/admin/receipt-rpa-units/{unit_id}/retry`(必填原因)或 `POST /api/admin/receipt-report-files/{file_id}/resend` 补偿。运行等待 callback 超时会被 Worker 启动和周期扫描收口为失败,绝不自动重试;管理员补偿创建新单元,保留旧单元。管理员在既有库存站点抽屉通过独立 `GET/PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` 维护收料配置,不能改写库存 Source 字段:DBS 维护路径/条件/Warehouse,Crane 固定 `Inbound Details`,拒绝 Warehouse 和查询条件;Worker 无论 Profile 登录 URL 的原 hash 均强制进入 `#/inbound-details-query` 并直接使用页面默认条件。所有入口写含前后状态快照的 `ShippingAuditEvent`;三年期满仅删除对象、保留文件事实与审计。 + +# 在途仓自动调拨独立架构(2026-08) + +调拨业务域独立于 shipping_notice 订单解析:ackend/app/services/in_transit_transfer/ 承载状态机/DTO/审计/文件准备/预检/执行/恢复/通知/归档/指标,erp_adapter.py 为 ERP 唯一访问出口(SOAP 在 WSDL 冻结前 fail-closed,凭据仅来自环境/Secret)。数据落 ransfer_* 七表(迁移 it1a2b3c4d5e);异步走 ransfer 队列(workers/worker_in_transit_transfer.py);08:00/09:00 platform job 注册于 schedule。前端卡片在 rontend/src/features/chat/(TransferMessageView 自驱动),四语言文案齐备。运维手册见 [features/in-transit-transfer/technical.md](features/in-transit-transfer/technical.md)。 diff --git a/frontend/src/features/chat/api/transfer.api.spec.ts b/frontend/src/features/chat/api/transfer.api.spec.ts new file mode 100644 index 00000000..a2cc4564 --- /dev/null +++ b/frontend/src/features/chat/api/transfer.api.spec.ts @@ -0,0 +1,78 @@ +/** + * features/chat/api/transfer.api.spec.ts + * 用途:锁定在途仓自动调拨 JSON POST 请求头契约——必须携带 Content-Type: application/json, + * 否则后端 Flask request.get_json 解析不到 body,导致默认 source_codes=[] 返回 400。 + * 依赖:Vitest、vi.mock(@/shared/api/client)、transfer.api、getAuthHeaders。 + * 逻辑:POST(create/execute/cancel/retry/manual-close)断言 headers 含 application/json, + * 且 body 序列化正确;GET/blob 端点不强制 Content-Type。 + */ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const requestJson = vi.hoisted(() => vi.fn()); +const requestBlob = vi.hoisted(() => vi.fn()); + +vi.mock('@/shared/api/client', () => ({ + BusinessError: class BusinessError extends Error {}, + requestJson, + requestBlob, +})); + +vi.mock('@/shared/utils/auth', () => ({ + getAuthHeaders: () => ({ Authorization: 'Bearer TEST-TOKEN' }), +})); + +import { + cancelTransferRun, + createTransferPrecheck, + executeTransferPrecheck, + getTransferBacklogSummary, + getTransferPrecheck, + getTransferRun, + listTransferSources, + manualCloseTransferItem, + retryTransferItem, +} from './transfer.api'; + +describe('transfer.api JSON request contract', () => { + beforeEach(() => { + requestJson.mockReset(); + requestBlob.mockReset(); + }); + + it('创建预检 POST 带 Content-Type: application/json 与序列化 source_codes', () => { + createTransferPrecheck({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' }); + const [url, init] = requestJson.mock.calls[0] as [string, RequestInit]; + expect(url).toBe('/api/in-transit-transfer/prechecks'); + expect(init.method).toBe('POST'); + expect((init.headers as Record)['Content-Type']).toBe('application/json'); + expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' })); + }); + + it('直接生成调拨单 POST 带 application/json', () => { + executeTransferPrecheck('TPC-1', ['INV-001']); + const [, init] = requestJson.mock.calls[0] as [string, RequestInit]; + expect(init.method).toBe('POST'); + expect((init.headers as Record)['Content-Type']).toBe('application/json'); + expect(init.body).toBe(JSON.stringify({ invoice_nos: ['INV-001'] })); + }); + + it('重试/关闭/取消 POST 带 application/json', () => { + retryTransferItem(7); + manualCloseTransferItem(7, '线下已处理'); + cancelTransferRun('RUN-1', '紧急'); + for (const [, init] of requestJson.mock.calls as [string, RequestInit][]) { + expect(init.method).toBe('POST'); + expect((init.headers as Record)['Content-Type']).toBe('application/json'); + } + }); + + it('GET 端点只需鉴权头,不需要强制 Content-Type', () => { + getTransferPrecheck('TPC-1'); + getTransferRun('RUN-1'); + getTransferBacklogSummary(); + listTransferSources(); + for (const [, init] of requestJson.mock.calls as [string, RequestInit][]) { + expect(init.headers).toBeDefined(); + } + }); +}); diff --git a/frontend/src/features/chat/api/transfer.api.ts b/frontend/src/features/chat/api/transfer.api.ts new file mode 100644 index 00000000..14da6ff0 --- /dev/null +++ b/frontend/src/features/chat/api/transfer.api.ts @@ -0,0 +1,112 @@ +/** + * features/chat/api/transfer.api.ts + * 用途:在途仓自动调拨 API 客户端(统一 requestJson / requestBlob,不重复造客户端)。 + * 依赖:@/shared/api/client(requestJson / requestBlob / BusinessError)、getAuthHeaders。 + * 逻辑:薄封装后端 /api/in-transit-transfer 全部端点;二进制下载走 requestBlob。 + */ +import { requestBlob, requestJson } from '@/shared/api/client'; +import { getAuthHeaders } from '@/shared/utils/auth'; +import type { + TransferActionResult, + TransferBacklogItem, + TransferBacklogSummary, + TransferExecuteResponse, + TransferPrecheckDetail, + TransferPrecheckSummary, + TransferRunResult, + TransferSourceFileStatus, + TransferSourceOption, +} from '../types/transfer.types'; + +const BASE = '/api/in-transit-transfer'; + +/** JSON 请求头:除鉴权外必须带 Content-Type: application/json,否则 Flask request.get_json 解析不到 body。 */ +const jsonHeaders = () => ({ 'Content-Type': 'application/json', ...getAuthHeaders() }); + +export interface CreatePrecheckPayload { + source_codes: string[]; + business_date?: string; +} + +/** 创建预检(只读) */ +export const createTransferPrecheck = (payload: CreatePrecheckPayload) => + requestJson(BASE + '/prechecks', { + method: 'POST', + headers: jsonHeaders(), + body: JSON.stringify(payload), + }); + +/** 恢复预检进度与明细 */ +export const getTransferPrecheck = (precheckId: string) => + requestJson(`${BASE}/prechecks/${precheckId}`, { + headers: getAuthHeaders(), + }); + +/** 确认选择范围并直接生成执行 Run */ +export const executeTransferPrecheck = (precheckId: string, invoiceNos: string[]) => + requestJson(`${BASE}/prechecks/${precheckId}/execute`, { + method: 'POST', + headers: jsonHeaders(), + body: JSON.stringify({ invoice_nos: invoiceNos }), + }); + +/** 恢复 Run 最终结果 */ +export const getTransferRun = (runNo: string) => + requestJson(`${BASE}/runs/${runNo}`, { + headers: getAuthHeaders(), + }); + +/** 请求停止剩余任务 */ +export const cancelTransferRun = (runNo: string, reason: string) => + requestJson(`${BASE}/runs/${runNo}/cancel`, { + method: 'POST', + headers: jsonHeaders(), + body: JSON.stringify({ reason }), + }); + +/** 人工重试异常项(仅重新查询 ERP,新 Attempt) */ +export const retryTransferItem = (itemId: number) => + requestJson(`${BASE}/items/${itemId}/retry`, { + method: 'POST', + headers: jsonHeaders(), + body: JSON.stringify({ kind: 'erp_recheck' }), + }); + +/** 人工关闭异常项 */ +export const manualCloseTransferItem = (itemId: number, reason: string) => + requestJson(`${BASE}/items/${itemId}/manual-close`, { + method: 'POST', + headers: jsonHeaders(), + body: JSON.stringify({ reason }), + }); + +/** 下载收料来源文件(zip) */ +export const downloadTransferReceiptFiles = (runNo: string) => + requestBlob(`${BASE}/runs/${runNo}/receipt-files`, { headers: getAuthHeaders() }); + +/** 下载预检冻结的 ERP 库存表(csv) */ +export const downloadTransferErpInventory = (runNo: string) => + requestBlob(`${BASE}/runs/${runNo}/erp-inventory`, { headers: getAuthHeaders() }); + +/** 下载七 Sheet 异常 Excel */ +export const downloadTransferExceptions = (runNo: string) => + requestBlob(`${BASE}/runs/${runNo}/exceptions.xlsx`, { headers: getAuthHeaders() }); + +/** 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级) */ +export const listTransferBacklog = () => + requestJson(`${BASE}/backlog`, { headers: getAuthHeaders() }); + +/** 待处理异常汇总(含 3/5/7 天老化分级) */ +export const getTransferBacklogSummary = () => + requestJson(`${BASE}/backlog/summary`, { headers: getAuthHeaders() }); + +/** 来源实例列表(平台 DBS/Crane 仅分组,每来源附收料文件状态) */ +export const listTransferSources = () => + requestJson(`${BASE}/sources`, { headers: getAuthHeaders() }); + +/** 对指定来源重新触发一次收料 RPA 抓取 */ +export const retryTransferSourceRpa = (sourceCode: string) => + requestJson(`${BASE}/sources/${encodeURIComponent(sourceCode)}/retry-rpa`, { + method: 'POST', + headers: jsonHeaders(), + }); diff --git a/frontend/src/features/chat/components/ChatMessageList.vue b/frontend/src/features/chat/components/ChatMessageList.vue index 84eb6e3f..0c539166 100644 --- a/frontend/src/features/chat/components/ChatMessageList.vue +++ b/frontend/src/features/chat/components/ChatMessageList.vue @@ -7,6 +7,7 @@ import type { Ref } from 'vue'; import ChatWelcomePanel, { type WelcomeQuestionItem, type WelcomeQuestionSection } from './ChatWelcomePanel.vue'; import ChatThinkingBubble from './ChatThinkingBubble.vue'; import ChatMessageBubble, { type ChatMessageBubbleHandlers } from './messages/ChatMessageBubble.vue'; +import TransferHomePanel from './messages/TransferHomePanel.vue'; import ToolRunProgressCard from './ToolRunProgressCard.vue'; import type { LeaveMessageHandlers } from './messages/LeaveMessageBlock.vue'; import type { ShippingMessageHandlers } from './messages/shippingMessageHandlers'; @@ -45,6 +46,8 @@ const { toolRunProgressTitle: string; showScrollToBottom: boolean; hideWelcomePanel?: boolean; + /** 在途仓自动调拨 Agent:无消息时渲染专属首页入口区(替代通用欢迎面板)。 */ + isInTransitTransferAgent?: boolean; pinMessagesToBottom?: boolean; /** 供父级滚动逻辑绑定 main 元素 */ scrollContainerHolder: { el: Ref }; @@ -63,6 +66,8 @@ const emit = defineEmits<{ 'maintenance-view-record-history': [device: MaintenanceDevice]; 'maintenance-create-record-for-device': [device: MaintenanceDevice]; 'open-batch-workbench': []; + /** 在途仓自动调拨:业务流激活时向上冒泡,父级据此隐藏聊天输入框。 */ + 'transfer-flow-active': [active: boolean]; }>(); const bindScrollContainer = (node: unknown) => { @@ -144,7 +149,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => { >
{ @select-question="emit('select-question', $event)" /> + +