- 调度整合:退役 in_transit_receipt_file_job,收料归档收敛 shipping_receipt_rpa_archive,排程注册表统一 - 自动调拨 Job:调拨前确保各来源当日收料文件就绪(缺失自动触发收料 RPA),严格等量匹配后生成 ERP 调拨单 - worker 手动唤醒:排程工作台支持手动唤醒与 runs 透视,heartbeat 协议同步 - 收料缺失幸存 T2:parse_failed 状态落库(迁移 q4c5) - 来源错误分层与 stale 时钟换源:改挂 inventory_checked_at 库存查得时刻,展示阈值与执行门禁解耦(迁移 t5a6) - 新增 wecom_sender 企微通知:每非空 Run 汇总一条,通知失败不影响 ERP 结果 - 同步排程工作台/调拨卡片前端、chat/admin 文案四语言、RPA 脚本与测试全家
48 KiB
在途自动调拨排程接线与「在途收料文件抓取」下线 Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: 下线冗余的 in-transit-receipt-file 排程类型(职责本就在途自动调拨内建),并把 09:00 在途自动调拨排程补成"默认配置即可跑通":来源留空兜底、空数据日干净跳过、企微汇总通知真实接线、通知人下拉选项源修复、i18n 四语言补齐。
Architecture: 排程层只做参数解析与编排接线;文件就绪判定复用在途调拨域唯一的 latest_ready_file 谓词(movement_file_repository.py,来源启用+收料配置+已发布 movement 解析 Profile+当日可用文件);企微发送器实现域内既有 notification.WeComSender 协议,复用 schedule_completed 事件开关(不新增 WECOM_NOTIFY_EVENTS 事件名,不动 .env.*)。freight-receipt-rpa 及其测试零改动。
Tech Stack: Flask (Python 3.12) + SQLAlchemy 2.0 + pytest;前端 Vue3 i18n JSON(四语言)+ vite build。
Spec: 本计划实现 2026-09-28 会话中用户逐条批准的设计(bounded 路径,无独立 spec 文件);领域权威文档 docs/features/in-transit-transfer/technical.md。已冻结决策:
- D1:「在途收料文件抓取」整个类型删除,不设兼容层;已建过该类型排程的环境需删除重建。
- D2:「货代收料 RPA」零改动(无条件导出+归档+推送的报表通道);"就绪复用、缺失触发 RPA"是「在途自动调拨」的内建行为(代码已存在,本计划只改描述文案)。
- D3:任务描述不得出现硬编码时间(08:00/09:00 仅为历史文案,执行时间完全由排程 Cron 决定)。
- D4:通知方案=配了「通知人」发领域明细汇总卡并抑制框架通用排程卡(
domain_notification_managed,对齐立账凭证检核先例);未配则落回框架通用卡。 - D5:09:00 排程来源留空=全部启用且已配置收料报表的来源(与货代收料 RPA 排程同口径)。
Global Constraints
- 🔒 不提交任何密钥/密码/生产地址;不改
.env.*(本计划复用既有事件开关,无需新增环境变量)。 - 🌍 前端新增文案必须同时补齐
zh-CN / zh-TW / en / th四语言admin.json;zh-CN 值必须与job_registry.py中label兜底文案逐字一致。 - 📝 新建/调整代码必须满足 AGENTS.md §5:文件头三要素注释(后端模块 docstring:用途/依赖/逻辑)+ 每个函数 docstring(用途、Args/Returns、AI 触发时机如适用)。
- 🚫 禁止自动 commit(用户记忆红线):每个任务止步于
git add <具体文件>;提交由用户批准后进行。 - ➕ 不新增第三方依赖。
- 🧪 后端测试命令统一
cd backend && python -m pytest ...;前端验证cd frontend && npm run build。 - ⚠️
notify_run_summary的既有语义不得破坏:空数据 Run 不通知(C5)、已成功投递幂等跳过、通知失败不改run.status。
Task 1: 下线 in-transit-receipt-file 排程类型 + 在途自动调拨描述改写
Files:
- Modify:
backend/app/services/schedule/job_registry.py(删 import、删注册块、改 in-transit-transfer 描述) - Delete:
backend/app/services/schedule/in_transit_receipt_file_job.py - Test:
backend/tests/services/in_transit_transfer/test_schedule_jobs.py
Interfaces:
-
Produces: 注册表中不再存在 key
in-transit-receipt-file;in-transit-transfer注册保留(Task 2/5 继续改其 handler 所在模块)。后续任务依赖get_platform_job("in-transit-transfer")仍可解析。 -
Step 1: 改写测试(先失败)
将 backend/tests/services/in_transit_transfer/test_schedule_jobs.py 整体替换为:
"""在途调拨排程注册与执行测试。
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
依赖:schedule.job_registry。
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
"""
from __future__ import annotations
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
def test_receipt_file_job_deregistered():
"""in-transit-receipt-file 已下线:不再注册、不可创建。"""
assert get_platform_job("in-transit-receipt-file") is None
keys = {job.key for job in list_platform_jobs()}
assert "in-transit-receipt-file" not in keys
def test_transfer_job_registered_with_schedule_defaults():
"""自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。"""
import re
job = get_platform_job("in-transit-transfer")
assert job is not None
assert job.enabled
keys = {field.get("key") for field in job.params_schema}
assert {"source_codes", "recover_history"} <= keys
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
def test_schedule_handler_callable():
"""自动调拨 handler 可调用(返回 7 元组的契约由执行链路测试覆盖)。"""
from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule
assert callable(run_in_transit_transfer_schedule)
- Step 2: 运行测试确认失败
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q
Expected: test_receipt_file_job_deregistered FAIL(当前仍注册);test_transfer_job_registered_with_schedule_defaults FAIL(旧描述含 "09:00" 命中时刻正则);test_schedule_handler_callable PASS。
- Step 3: 删除注册与 import,改写描述
backend/app/services/schedule/job_registry.py:
(a) 删除这两行 import(原 196-197 行附近,保留 run_in_transit_transfer_schedule 那行):
from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule
(b) 整块删除 in-transit-receipt-file 注册(原 475-496 行):
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": []},
))
(c) 将 in-transit-transfer 注册的 description 由:
description=(
"每日 09:00 自动处理新增可调拨项与历史可恢复异常;"
"每非空 Run 发送一条企微汇总通知;通知失败不改变 ERP 结果。"
),
改为(去时间硬编码 + 写明内建文件就绪行为):
description=(
"自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪"
"(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;"
"每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。"
"执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。"
),
- Step 4: 删除模块文件
rm backend/app/services/schedule/in_transit_receipt_file_job.py
- Step 5: 运行测试确认通过
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q
Expected: 3 passed。
- Step 6: 全仓确认无残留引用
cd backend && grep -rn "in_transit_receipt_file_job\|in-transit-receipt-file" app/ tests/ --include="*.py"
Expected: 无输出(docs 的清理在 Task 7)。
- Step 7: Stage
git add backend/app/services/schedule/job_registry.py backend/app/services/schedule/in_transit_receipt_file_job.py backend/tests/services/in_transit_transfer/test_schedule_jobs.py
Task 2: list_receipt_capable_source_codes() 助手 + 09:00 来源留空兜底
Files:
- Modify:
backend/app/services/in_transit_transfer/receipt_trigger_service.py(新增函数) - Modify:
backend/app/services/schedule/in_transit_transfer_job.py(新增_wanted_source_codes并替换来源解析) - Test:
backend/tests/services/in_transit_transfer/test_schedule_jobs.py(追加)
Interfaces:
-
Produces:
receipt_trigger_service.list_receipt_capable_source_codes() -> list[str](enabled 库存源 ⨝ 收料报表配置,按 source_code 排序;无匹配返回空列表)。 -
Produces:
in_transit_transfer_job._wanted_source_codes(task: ScheduleTask) -> list[str](显式选择优先;留空调用上面的助手兜底)。Task 5 的最终版 handler 依赖它。 -
Step 1: 追加失败测试
向 backend/tests/services/in_transit_transfer/test_schedule_jobs.py 追加:
def _make_receipt_source(db, source_code: str, *, enabled: bool):
"""创建可参与收料的最小库存源(rpa_profile_id 非空,须先建 Profile)。"""
from app.models import ShippingInventorySource, ShippingRpaProfile
profile = ShippingRpaProfile(
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="crane",
login_url="https://test.invalid/login", login_config_json={"auth_mode": "password"},
)
db.session.add(profile)
db.session.flush()
source = ShippingInventorySource(
source_code=source_code, display_name=source_code, connector_type="crane",
rpa_profile_id=profile.id, warehouse_resolution_mode="fixed", enabled=enabled,
)
db.session.add(source)
return source
def test_list_receipt_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
"""缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。"""
from app.models import ShippingReceiptReportConfig
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True)
_make_receipt_source(transfer_db, "DBS_OFF", enabled=False)
_make_receipt_source(transfer_db, "CRANE_NOCONF", enabled=True)
transfer_db.session.flush()
transfer_db.session.add(ShippingReceiptReportConfig(
inventory_source_id=enabled.id, report_path_json={}, query_parameters_json=[],
))
transfer_db.session.commit()
result = list_receipt_capable_source_codes()
assert "CRANE_SGP" in result
assert "DBS_OFF" not in result
assert "CRANE_NOCONF" not in result
assert result == sorted(result)
def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
"""09:00 排程来源留空=全部启用收料来源;显式选择优先。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleTask
from app.services.schedule.in_transit_transfer_job import _wanted_source_codes
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP", "DBS_HUB"])
empty = ScheduleTask(job_params={"source_codes": []})
assert _wanted_source_codes(empty) == ["CRANE_SGP", "DBS_HUB"]
explicit = ScheduleTask(job_params={"source_codes": ["DBS_HUB"]})
assert _wanted_source_codes(explicit) == ["DBS_HUB"]
string_param = ScheduleTask(job_params={"source_codes": "DBS_HUB"})
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
- Step 2: 运行确认失败
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q
Expected: 新增两条 FAIL(ImportError/cannot import name '_wanted_source_codes' 等)。
- Step 3: 实现助手函数
backend/app/services/in_transit_transfer/receipt_trigger_service.py 在 trigger_receipt_rpa 定义之前加入:
def list_receipt_capable_source_codes() -> list[str]:
"""列出可产出收料文件的启用来源实例(enabled 库存源 + 已配置收料报表)。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——收料文件只能
来自已配置收料报表的站点,与货代收料 RPA 排程的站点口径保持一致。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
from app import db
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
rows = db.session.query(ShippingInventorySource.source_code).join(
ShippingReceiptReportConfig,
ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all()
return [str(code) for (code,) in rows]
- Step 4: 实现排程侧兜底解析
backend/app/services/schedule/in_transit_transfer_job.py:文件头 docstring 的"依赖"行补上 receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径);import 区新增:
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
并在 _task_params 之后新增:
def _wanted_source_codes(task: ScheduleTask) -> list[str]:
"""提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。"""
params = _task_params(task)
values = params.get("source_codes") or []
if isinstance(values, str):
values = [values]
codes = [str(item).strip() for item in values if str(item).strip()]
if not codes:
codes = list_receipt_capable_source_codes()
return codes
(run_in_transit_transfer_schedule 本任务暂不改动;其内部来源解析改用 _wanted_source_codes 在 Task 5 随通知接线一并落地。)
- Step 5: 运行测试确认通过
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q
Expected: 全部 passed。
- Step 6: Stage
git add backend/app/services/in_transit_transfer/receipt_trigger_service.py backend/app/services/schedule/in_transit_transfer_job.py backend/tests/services/in_transit_transfer/test_schedule_jobs.py
Task 3: run_auto_transfer 空数据日干净跳过
Files:
- Modify:
backend/app/services/in_transit_transfer/auto_transfer.py - Create:
backend/tests/services/in_transit_transfer/test_auto_transfer.py
Interfaces:
-
Consumes:
matching_service.create_matching(...) -> MatchingSummaryDTO(summary.counts.executable_count)。 -
Produces:
run_auto_transfer(...) -> AutoTransferOutcome新语义——executable_count == 0时直接返回(run_no=None、errors为空),不调用execute_matching_items、不通知。Task 5 的空日 warning 依赖该语义(run_no=None且errors空)。 -
Step 1: 写失败测试(新文件)
创建 backend/tests/services/in_transit_transfer/test_auto_transfer.py:
"""自动调拨编排(run_auto_transfer)测试:空数据日跳过与正常执行透传。
用途:锁定 09:00 自动排程编排的阶段语义——匹配后无可执行行(含恢复后仍为 0)
时不建票、不写 ERP、不通知、不记 error(产品决策 C5);有可执行行时把
执行结果透传给调用方。
依赖:auto_transfer(monkeypatch create_matching / execute_matching_items)。
逻辑:纯单元用例,不触库;恢复阶段用 recover_history=False 关闭。
"""
from __future__ import annotations
from types import SimpleNamespace
import app.services.in_transit_transfer.auto_transfer as at
from app.services.in_transit_transfer.contracts import MatchingCountsDTO, MatchingSummaryDTO
def _summary(executable_count: int) -> MatchingSummaryDTO:
return MatchingSummaryDTO(
matching_id="MTG-20260928-ABC123",
status="matched",
business_date="2026-09-28",
eligible_receipt_date_to="2026-09-27",
expires_at="2026-09-28T10:00:00",
counts=MatchingCountsDTO(executable_count=executable_count),
estimated_transfer_quantity="0",
estimated_external_write_count=executable_count,
matching_hash="hash-x",
)
def test_skips_execution_when_no_executable_items(monkeypatch):
"""空数据日:不执行、不通知、不记 error,clean no-op。"""
monkeypatch.setattr(at, "create_matching", lambda **kwargs: _summary(0))
def _must_not_execute(**kwargs):
raise AssertionError("execute_matching_items must not be called on empty day")
monkeypatch.setattr(at, "execute_matching_items", _must_not_execute)
outcome = at.run_auto_transfer(
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
)
assert outcome.run_no is None
assert outcome.run_status is None
assert outcome.errors == []
def test_executes_and_propagates_result_when_executable(monkeypatch):
"""有可执行行:按匹配执行并透传 run_no/status。"""
monkeypatch.setattr(at, "create_matching", lambda **kwargs: _summary(3))
captured = {}
def _fake_execute(**kwargs):
captured.update(kwargs)
return SimpleNamespace(run_no="RUN-20260928-XYZ789", status="success")
monkeypatch.setattr(at, "execute_matching_items", _fake_execute)
outcome = at.run_auto_transfer(
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
)
assert captured["matching_id"] == "MTG-20260928-ABC123"
assert outcome.run_no == "RUN-20260928-XYZ789"
assert outcome.run_status == "success"
assert outcome.errors == []
- Step 2: 运行确认失败
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_auto_transfer.py -q
Expected: test_skips_execution_when_no_executable_items FAIL(当前实现会调 execute → 门禁抛 item_ids is required 被记入 errors)。
- Step 3: 实现跳过分支
backend/app/services/in_transit_transfer/auto_transfer.py 中,将 create_matching(...) 与 execute_matching_items(...) 之间的段落改为:
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
if summary.counts.executable_count == 0:
return outcome
# [STEP 3] 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items
# (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)。
executed = execute_matching_items(matching_id=summary.matching_id, deps=deps)
outcome.run_no = executed.run_no
outcome.run_status = executed.status
(即删除原注释中"无可执行行时门禁抛错,与旧流程一致记入 errors 不阻断通知阶段"的旧语义,替换为上述显式跳过。)
- Step 4: 运行测试确认通过
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_auto_transfer.py -q
Expected: 2 passed。
- Step 5: Stage
git add backend/app/services/in_transit_transfer/auto_transfer.py backend/tests/services/in_transit_transfer/test_auto_transfer.py
Task 4: WecomSummarySender 企微汇总发送器
Files:
- Create:
backend/app/services/in_transit_transfer/wecom_sender.py - Create:
backend/tests/services/in_transit_transfer/test_wecom_sender.py
Interfaces:
-
Consumes:
integrations.wecom.notify.send_wecom_event_message(*, event_type, user, title, content, jump_path) -> dict(含ok键)。 -
Produces:
wecom_sender.WecomSummarySender().send_summary(*, run_no: str, summary: dict, recipients: list[str], excel_path: str | None = None) -> dict,返回{"status": "success", "delivered": n}或{"status": "failed", "error_code": "WECOM_SEND_FAILED", "error_message": str}——满足notification.WeComSender协议。Task 5 以此注入run_auto_transfer(sender=...)。 -
Step 1: 写失败测试(新文件)
创建 backend/tests/services/in_transit_transfer/test_wecom_sender.py:
"""企微汇总发送器(WecomSummarySender)测试。
用途:锁定 notify_run_summary 真实通道的投递语义——逐收件人解析 wecom_userid
后经 schedule_completed 事件开关发送;≥1 人送达即 success;无可用收件人
或全部失败为 failed(由 notify_run_summary 落库,不影响 ERP 结果)。
依赖:app fixture(SQLite)、User 行、monkeypatch send_wecom_event_message。
逻辑:纯单元用例;不发送真实企微消息。
"""
from __future__ import annotations
import pytest
import app.services.in_transit_transfer.wecom_sender as ws
@pytest.fixture
def wecom_user_ids(transfer_db):
"""两个用户:一个绑定企微、一个未绑定;返回 {角色: 用户id}。"""
from app.models import User
bound = User(username="u_bound", email="u_bound@test.dev", wecom_userid="wecom_bound")
loose = User(username="u_loose", email="u_loose@test.dev", wecom_userid=None)
transfer_db.session.add_all([bound, loose])
transfer_db.session.commit()
return {"bound": bound.id, "loose": loose.id}
def _summary() -> dict:
return {
"run_no": "RUN-20260928-XYZ789",
"status": "success",
"business_date": "2026-09-28",
"counts": {"file_invoice_count": 2, "matched_count": 2, "executable_count": 2},
}
def test_delivers_to_wecom_bound_user_only(monkeypatch, wecom_user_ids):
"""送达绑定用户计 delivered;未绑定用户跳过;≥1 送达即 success。"""
calls = []
def _fake(**kwargs):
calls.append(kwargs)
return {"ok": True, "trace_id": "t1"}
monkeypatch.setattr(ws, "send_wecom_event_message", _fake)
outcome = ws.WecomSummarySender().send_summary(
run_no="RUN-20260928-XYZ789", summary=_summary(),
recipients=[str(wecom_user_ids["bound"]), str(wecom_user_ids["loose"])],
)
assert outcome == {"status": "success", "delivered": 1}
assert len(calls) == 1
assert calls[0]["event_type"] == "schedule_completed"
assert calls[0]["user"].wecom_userid == "wecom_bound"
assert calls[0]["title"].startswith("在途自动调拨 RUN-")
def test_failed_when_all_sends_fail(monkeypatch, wecom_user_ids):
"""企微侧全部失败 → failed + WECOM_SEND_FAILED(交 notify_run_summary 落库)。"""
monkeypatch.setattr(ws, "send_wecom_event_message", lambda **kwargs: {"ok": False, "reason": "event_disabled"})
outcome = ws.WecomSummarySender().send_summary(
run_no="RUN-1", summary=_summary(), recipients=[str(wecom_user_ids["bound"])],
)
assert outcome["status"] == "failed"
assert outcome["error_code"] == "WECOM_SEND_FAILED"
assert outcome["error_message"] == "event_disabled"
def test_failed_when_no_wecom_bound_recipient(monkeypatch, wecom_user_ids):
"""收件人全部未绑定企微 → failed(no wecom-bound recipients),不调用发送。"""
sent = []
monkeypatch.setattr(ws, "send_wecom_event_message", lambda **kwargs: sent.append(kwargs))
outcome = ws.WecomSummarySender().send_summary(
run_no="RUN-1", summary=_summary(), recipients=[str(wecom_user_ids["loose"])],
)
assert outcome["status"] == "failed"
assert outcome["error_message"] == "no wecom-bound recipients"
assert sent == []
def test_non_digit_recipients_ignored(monkeypatch, wecom_user_ids):
"""非数字收件人(脏数据)直接忽略,不查询不发送。"""
monkeypatch.setattr(ws, "send_wecom_event_message", lambda **kwargs: {"ok": True})
outcome = ws.WecomSummarySender().send_summary(
run_no="RUN-1", summary=_summary(), recipients=["abc", ""],
)
assert outcome["status"] == "failed"
assert outcome["error_message"] == "no wecom-bound recipients"
- Step 2: 运行确认失败
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_wecom_sender.py -q
Expected: FAIL(ModuleNotFoundError: app.services.in_transit_transfer.wecom_sender)。
- Step 3: 实现发送器(新文件)
创建 backend/app/services/in_transit_transfer/wecom_sender.py(全文):
"""在途调拨企微汇总通知的真实通道适配(notification.WeComSender 协议实现)。
用途:把自动调拨 Run 汇总经企微 textcard 发给通知人,替代排程 handler 的
sender=None 占位;通知失败只落 run.notification_status,不影响 ERP 结果。
依赖:integrations.wecom.notify.send_wecom_event_message(事件门禁+审计)、models.User。
逻辑:逐收件人解析 wecom_userid 后发送;复用 schedule_completed 事件开关(与排程
通用通知同一启停入口,不新增 WECOM_NOTIFY_EVENTS 事件名);至少一人送达即
success,无可用收件人或全部失败为 failed,由 notify_run_summary 统一落库。
"""
from __future__ import annotations
from typing import Any
from app.services.integrations.wecom.notify import send_wecom_event_message
# 复用排程完成事件开关:运维通过 WECOM_NOTIFY_EVENTS 的 schedule_completed
# 统一启停排程类通知,本发送器不引入独立事件名(避免各环境事件表漂移)。
WECOM_EVENT_TYPE = "schedule_completed"
_STATUS_LABELS = {
"success": "全部成功",
"partial_failed": "部分失败",
"failed": "失败",
"matching": "匹配中",
}
class WecomSummarySender:
"""企微汇总通知发送器(协议见 notification.WeComSender)。
Args 约定:recipients 为 HXOPS 用户 id 列表(字符串/整数均可),由排程参数
notify_user_ids(options_source=users)下发;未绑定企微的用户跳过。
excel_path 为协议占位,当前不发送附件(异常明细以管理端已执行区块为准)。
"""
def send_summary(self, *, run_no: str, summary: dict[str, Any],
recipients: list[str], excel_path: str | None = None) -> dict[str, Any]:
"""向通知人逐一发送一条 Run 汇总 textcard。
Args:
run_no: 调拨 Run 编号(RUN-YYYYMMDD-XXXXXX)。
summary: notify_run_summary 组装的汇总(run_no/status/business_date/counts)。
recipients: 用户 id 列表。
excel_path: 协议占位;当前不发送附件。
Returns:
{"status": "success", "delivered": n} 或
{"status": "failed", "error_code": "WECOM_SEND_FAILED", "error_message": str};
由 notify_run_summary 写入 run.notification_* 字段。
"""
counts = summary.get("counts") if isinstance(summary.get("counts"), dict) else {}
status = str(summary.get("status") or "")
title = f"在途自动调拨 {run_no}"
content = "\n".join([
f"状态: {_STATUS_LABELS.get(status, status or '未知')}",
f"业务日期: {summary.get('business_date') or '-'}",
"文件票数: {tickets} 已匹配: {matched} 待查库存: {pending}".format(
tickets=counts.get("file_invoice_count", 0),
matched=counts.get("matched_count", 0),
pending=counts.get("pending_stock_check_count", 0),
),
"可执行: {executable} 数量不符: {blocked} 未成熟: {not_matured}".format(
executable=counts.get("executable_count", 0),
blocked=counts.get("blocked_count", 0),
not_matured=counts.get("not_matured_count", 0),
),
])
user_ids = [int(item) for item in (recipients or []) if str(item).strip().isdigit()]
users = []
if user_ids:
from app.models import User
users = User.query.filter(User.id.in_(user_ids)).all()
# [STEP 1] 逐收件人投递;send_wecom_event_message 内部完成事件门禁与审计落库。
delivered = 0
last_error = ""
for user in users:
if not user.wecom_userid:
continue
outcome = send_wecom_event_message(
event_type=WECOM_EVENT_TYPE, user=user, title=title, content=content,
jump_path="/workspace",
)
if outcome.get("ok"):
delivered += 1
else:
last_error = str(outcome.get("reason") or "send_failed")
if delivered:
return {"status": "success", "delivered": delivered}
return {
"status": "failed",
"error_code": "WECOM_SEND_FAILED",
"error_message": last_error or "no wecom-bound recipients",
}
- Step 4: 运行测试确认通过
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_wecom_sender.py -q
Expected: 4 passed。
- Step 5: Stage
git add backend/app/services/in_transit_transfer/wecom_sender.py backend/tests/services/in_transit_transfer/test_wecom_sender.py
Task 5: 09:00 handler 接线(sender + 通知标记)+ users 选项源
Files:
- Modify:
backend/app/services/schedule/in_transit_transfer_job.py(整文件替换为下方最终版) - Modify:
backend/app/services/schedule/job_options.py(注册users提供器) - Test:
backend/tests/services/in_transit_transfer/test_schedule_jobs.py(追加)
Interfaces:
-
Consumes: Task 2
_wanted_source_codes、Task 4WecomSummarySender。 -
Produces:
run_in_transit_transfer_schedule(task, run)最终行为——来源留空兜底;recipients 非空时构造 sender 并置run.response_summary_json["domain_notification_managed"]=True;空数据日输出 warningno executable items; execution and notification skipped;返回 7 元组。 -
Produces:
job_options.list_job_options("users") -> [{label, value, description}](active 用户,value=user.id)。 -
Step 1: 追加失败测试
向 backend/tests/services/in_transit_transfer/test_schedule_jobs.py 追加:
class _FakeSender:
"""记录实例化的发送器替身(断言 handler 接线,不发真实消息)。"""
instantiated = 0
def __init__(self):
type(self).instantiated += 1
def test_handler_wires_sender_and_domain_notification(monkeypatch):
"""配了通知人:构造 sender、置领域自管标记、recipients 透传。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
captured = {}
def _fake_auto_transfer(**kwargs):
captured.update(kwargs)
return job_mod.AutoTransferOutcome()
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
class _FakeSenderInner:
pass
monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner)
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True, "notify_user_ids": ["7"]})
run = ScheduleRun(run_no="RUNR-1", status="running")
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
assert captured["source_codes"] == ["CRANE_SGP"]
assert captured["recipients"] == ["7"]
assert isinstance(captured["sender"], _FakeSenderInner)
assert run.response_summary_json["domain_notification_managed"] is True
assert (total, success, failed, skipped) == (0, 0, 0, 0)
def test_handler_without_recipients_skips_domain_notification(monkeypatch):
"""未配通知人:sender=None、不置标记、落回框架通用通知(由框架按任务配置发送)。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
captured = {}
def _fake_auto_transfer(**kwargs):
captured.update(kwargs)
return job_mod.AutoTransferOutcome()
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-2", status="running")
job_mod.run_in_transit_transfer_schedule(task, run)
assert captured["sender"] is None
assert captured["recipients"] == []
assert not (run.response_summary_json or {}).get("domain_notification_managed")
文件头 import 区补 from types import SimpleNamespace 与 from app.services.schedule.in_transit_transfer_job import AutoTransferOutcome(若按上方代码从模块属性访问 job_mod.AutoTransferOutcome 则无需后者)。
- Step 2: 运行确认失败
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q
Expected: 新增两条 FAIL(当前 handler 无 sender 接线、_wanted_source_codes 已存在但 handler 未消费)。
- Step 3: 替换 handler 为最终版
将 backend/app/services/schedule/in_transit_transfer_job.py 整文件替换为:
"""自动调拨排程。
用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。
依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
不依赖其他排程成功;来源留空兜底为全部启用收料来源;配置了通知人时领域
自管通知(抑制通用排程完成卡片,避免同日双卡)。
"""
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 AutoTransferOutcome, run_auto_transfer
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
from app.services.in_transit_transfer.wecom_sender import WecomSummarySender
from app.services.schedule.job_registry import ScheduleExecuteResult
def _task_params(task: ScheduleTask) -> dict[str, Any]:
"""读取排程结构化参数(job_params 非字典时回落空对象)。"""
return task.job_params if isinstance(task.job_params, dict) else {}
def _wanted_source_codes(task: ScheduleTask) -> list[str]:
"""提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。
Args:
task: 排程任务(job_params.source_codes 可为列表/字符串/缺省)。
Returns:
去空白后的来源编码列表;留空时为 list_receipt_capable_source_codes() 结果。
"""
params = _task_params(task)
values = params.get("source_codes") or []
if isinstance(values, str):
values = [values]
codes = [str(item).strip() for item in values if str(item).strip()]
if not codes:
codes = list_receipt_capable_source_codes()
return codes
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。
Args:
task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。
run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。
Returns:
ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。
"""
params = _task_params(task)
source_codes = _wanted_source_codes(task)
recover_history = bool(params.get("recover_history", True))
recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()]
# 领域自管通知(对齐立账凭证检核先例):配置了通知人才发领域汇总卡,
# 并抑制通用排程完成卡片;未配置时回落通用卡片(框架按任务通知配置发送)。
sender = None
if recipients:
sender = WecomSummarySender()
run.response_summary_json = {
**(run.response_summary_json or {}),
"domain_notification_managed": True,
}
deps = transfer_deps.get_transfer_dependencies()
outcome = run_auto_transfer(
business_date=str(business_date_now()),
deps=deps,
source_codes=source_codes,
recover_history=recover_history,
sender=sender,
recipients=recipients,
)
results: list[dict[str, Any]] = []
errors: list[str] = list(outcome.errors)
recovery = outcome.recovery
warnings: list[str] = [
f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}",
]
if outcome.run_no:
results.append({
"run_no": outcome.run_no,
"status": outcome.run_status,
"notification_status": outcome.notification_status,
})
elif not outcome.errors:
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
warnings.append("no executable items; execution and notification skipped")
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
return (
success + recovery.recovered_count,
success,
recovery.still_blocked_count,
0,
results,
warnings,
errors,
)
- Step 4: 注册
users选项源
backend/app/services/schedule/job_options.py 在 _shipping_receipt_sources_options 之后新增:
def _users_options() -> list[dict[str, Any]]:
"""启用中的用户列表(value=user.id),供排程通知人类参数选择。"""
from app.models import User
users = (
User.query.filter(User.status == "active")
.order_by(User.username.asc())
.all()
)
return [
{
"label": user.real_name or user.username,
"value": user.id,
"description": None if not user.wecom_userid else "wecom",
}
for user in users
]
并在 _OPTIONS_PROVIDERS 注册表中加一行:
"users": _users_options,
- Step 5: 运行测试确认通过
Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py tests/services/in_transit_transfer/test_auto_transfer.py tests/services/in_transit_transfer/test_wecom_sender.py -q
Expected: 全部 passed。
- Step 6: Stage
git add backend/app/services/schedule/in_transit_transfer_job.py backend/app/services/schedule/job_options.py backend/tests/services/in_transit_transfer/test_schedule_jobs.py
Task 6: i18n 四语言补键 + 前端 build
Files:
- Modify:
frontend/src/locales/zh-CN/admin.json、zh-TW/admin.json、en/admin.json、th/admin.json(各schedule.form区新增 4 键)
Interfaces:
-
Consumes:
job_registry.py中三个参数 label_key(admin.schedule.form.transferSourceCodes / transferRecoverHistory / transferNotifyUsers)与 file-asset-cleanup 的 label_key(admin.schedule.form.platformJobFileAssetCleanup)。 -
Produces: 四语言
DynamicTaskParamsForm渲染文案;zh-CN 值与注册表 label 兜底逐字一致(来源实例/历史可恢复异常复核/通知人)。 -
Step 1: zh-CN 插入
在 zh-CN/admin.json 中定位行 "platformJobFaqHotAggregate": "FAQ 热点聚合",(约 2366 行),在该行后插入:
"platformJobFileAssetCleanup": "临时文件资产清理",
"transferSourceCodes": "来源实例",
"transferRecoverHistory": "历史可恢复异常复核",
"transferNotifyUsers": "通知人",
- Step 2: zh-TW 插入
在 zh-TW/admin.json 中定位行 "platformJobFaqHotAggregate": "FAQ 熱點聚合",(约 2155 行),在该行后插入:
"platformJobFileAssetCleanup": "暫存檔案資產清理",
"transferSourceCodes": "來源實例",
"transferRecoverHistory": "歷史可復原異常複核",
"transferNotifyUsers": "通知人",
- Step 3: en 插入
在 en/admin.json 中定位行 "platformJobFaqHotAggregate": "FAQ hot aggregate",(约 2254 行),在该行后插入:
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
"transferSourceCodes": "Source instances",
"transferRecoverHistory": "Recover retryable history",
"transferNotifyUsers": "Notify users",
- Step 4: th 插入
在 th/admin.json 中定位行 "platformJobFaqHotAggregate": "FAQ hot aggregate",(约 2150 行;该文件平台任务文案沿用英文为既有惯例),在该行后插入:
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
"transferSourceCodes": "Source instances",
"transferRecoverHistory": "Recover retryable history",
"transferNotifyUsers": "Notify users",
- Step 5: JSON 合法性校验(四语言)
cd frontend/src/locales && python -c "
import json
for lang in ['zh-CN', 'zh-TW', 'en', 'th']:
data = json.load(open(f'{lang}/admin.json', encoding='utf-8'))
form = data['schedule']['form']
missing = [k for k in ['platformJobFileAssetCleanup', 'transferSourceCodes', 'transferRecoverHistory', 'transferNotifyUsers'] if k not in form]
assert not missing, (lang, missing)
print('all four locales OK')
"
Expected: all four locales OK。
- Step 6: 前端 build
cd frontend && npm run build
Expected: build 通过(绿色)。
- Step 7: Stage
git add frontend/src/locales/zh-CN/admin.json frontend/src/locales/zh-TW/admin.json frontend/src/locales/en/admin.json frontend/src/locales/th/admin.json
Task 7: 文档同步 + 记忆更新 + 全量回归
Files:
- Modify:
docs/features/in-transit-transfer/technical.md:15(排程行改写) - Modify:
docs/features/in-transit-transfer/minimum-implementation-spec.md:859、docs/features/in-transit-transfer/roadmap.md:385(表格行标注下线) - Modify:
docs/funclist.md:763(排程/恢复/异常/通知行改写) - Modify:
.engramory-memory/in-transit-transfer.md(下一步区追加 2026-09-28 条目)
Interfaces:
-
Consumes: Task 1-6 的最终事实(类型下线、内建就绪保障、通知接线、来源兜底口径)。
-
Step 1: technical.md 排程行改写
docs/features/in-transit-transfer/technical.md 第 15 行由:
- **排程**:`in-transit-receipt-file`(08:00)与 `in-transit-transfer`(09:00)platform job(`schedule/job_registry.py`)。
改为:
- **排程**:仅 `in-transit-transfer` 一个 platform job(`schedule/job_registry.py`);执行时间由排程配置决定。文件就绪保障为自动调拨内建行为(调拨前逐来源检查当日 ready 文件:就绪复用,缺失自动触发收料 RPA),独立的 `in-transit-receipt-file` 排程类型已于 2026-09-28 下线删除(不设兼容层,已建排程需删除重建)。通知:配置「通知人」后每非空 Run 发一条企微明细汇总卡(复用 `schedule_completed` 事件开关)并抑制框架通用排程卡(`domain_notification_managed`);来源留空=全部启用且已配置收料报表的来源。
- Step 2: spec/roadmap 两处表格行标注
docs/features/in-transit-transfer/minimum-implementation-spec.md:859 该行改为:
| ~~`backend/app/services/schedule/in_transit_receipt_file_job.py`~~ | 已下线(2026-09-28):文件就绪保障内建于在途自动调拨,独立排程类型删除 |
docs/features/in-transit-transfer/roadmap.md:385 该行改为:
| ~~计划新增~~ 已下线(2026-09-28) | `backend/app/services/schedule/in_transit_receipt_file_job.py` | 文件准备职责内建于在途自动调拨排程 |
- Step 3: funclist.md 行改写
docs/funclist.md 第 763 行改为:
| 排程/恢复/异常/通知 | 后端已实现 | 在途自动调拨 platform job(执行时间由排程配置决定;调拨前内建当日收料文件就绪保障:就绪复用、缺失自动触发收料 RPA;原独立「在途收料文件抓取」排程类型已下线);来源留空=全部启用收料来源;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) |
- Step 4: 记忆笔记更新
.engramory-memory/in-transit-transfer.md 的「下一步」区顶部追加一条(frontmatter updated 改为 2026-09-28):
- **2026-09-28 排程收口(本条随实施更新状态)**:①独立「在途收料文件抓取」排程类型删除(用户拍板:就绪复用/缺失触发 RPA 是自动调拨内建行为,不设兼容层);「货代收料 RPA」零改动。②09:00 排程接线:来源留空兜底=`receipt_trigger_service.list_receipt_capable_source_codes`(enabled+收料配置口径);空数据日 `executable_count==0` 干净跳过(修复原"天天报 item_ids is required");企微汇总 `WecomSummarySender`(逐收件人 textcard、复用 schedule_completed 事件开关、配通知人才发并置 domain_notification_managed 抑制通用卡);`job_options` 注册 `users` 选项源(原「通知人」下拉会报 Unknown options source)。③四语言补 `transferSourceCodes/transferRecoverHistory/transferNotifyUsers/platformJobFileAssetCleanup`。实施计划 `docs/superpowers/plans/2026-09-28-transfer-schedule-consolidation.md`。
- Step 5: 全量回归
cd backend && python -m pytest tests/services/in_transit_transfer tests/test_freight_receipt_rpa_schedule.py -q
Expected: 全部 passed(test_freight_receipt_rpa_schedule.py 未改动且必须保持绿——它锁定"货代收料 RPA 零改动")。
cd backend && grep -rn "in-transit-receipt-file" app/ tests/ ../docs/features/in-transit-transfer/ --include="*.py" --include="*.md" | grep -v "已下线\|下线删除\|~~"
Expected: 仅剩标注"已下线"的历史记录行。
- Step 6: Stage
git add docs/features/in-transit-transfer/technical.md docs/features/in-transit-transfer/minimum-implementation-spec.md docs/features/in-transit-transfer/roadmap.md docs/funclist.md .engramory-memory/in-transit-transfer.md
验收路径(实施完成后给用户的操作说明)
- 管理端 → 排程管理 → 新增排程:执行模式=平台内置任务,平台任务选「在途自动调拨」;来源实例留空(=全部启用收料来源)、按需勾选「历史可恢复异常复核」与「通知人」;Cron 按业务期望配置。
- 「立即执行」:空数据日应看到 warning
no executable items; execution and notification skipped且 run 不算失败;有可执行行时 results 出现run_no/status/notification_status。 - 配置了通知人且 Run 非空:企微收到「在途自动调拨 RUN-…」textcard(状态+票数/已匹配/待查/可执行/不符/未成熟);同日不出现框架通用排程卡。
- 平台任务下拉中不再出现「在途收料文件抓取」;若历史环境建过该类型排程任务,会执行报 Unknown platform job,需删除重建。