Files
syops/docs/superpowers/plans/2026-10-18-freight-rpa-phase-b.md
T
hugoandCursor 39fe3c05f2 feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 10:46:06 +08:00

717 lines
40 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Freight RPA 阶段 B 实施计划(报表归属与回调事实)
> **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:** 在当前 Flask 进程内,让 `freight_rpa` 拥有登录连接、库存站点、在手/入站报表配置和两类报表文件;发货通知与在途调拨只按 `source_code` 读取,并只更新自己的任务。
**Architecture:** 批次 S 的未执行迁移已经把解析方案表落到 `freight_rpa_parsing_profiles`,本计划不再写第二条改名。新迁移 `s18` 挂在 `s17c` 之后:新建 `freight_rpa_onhand_report_configs` 并搬走站点上的三列,再把 `shipping_onhand_files` 改名为 `freight_rpa_onhand_report_files`(列不动)。回调在 RPA 事务提交文件之后,用 `ReportFact` 调用已注册处理函数;处理函数失败不回滚文件。不引入队列,不拆第二个服务。
**Tech Stack:** Flask、SQLAlchemy 2.0、Alembic、Vue 3 + TypeScript、pytest。Python 用 `backend/.venv/Scripts/python.exe`,命令在 `backend/` 下执行。
**Spec:** `docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md`
## Global Constraints
- 不把 `freight_rpa` 拆成第二个可部署服务,不引入消息队列。
- 不新做出站抓取。出站配置和出站文件表等出站立项再加,命名与在手、入站相同。
- 不把履约出货改名为 outbound,不改 `freight_upload`。
- 不改合同付款的 `shipment`(发货款),不改 `movement`,不改历史 MinIO 对象键(含 `shipping/receipt-reports/`)。
- 不改写已有的阶段 A 计划与 spec。
- 不改这些仍只服务在手的表:`freight_rpa_onhand_fields`、外部仓库映射、发货路由规则、配置测试。不改它们的表名和归属。
- 不把在手文件表里的解析行、字段映射、快照状态拆到另一张表。入站文件表只存原文件,两张表的列保持不同。
- `report_kind` 取值 `onhand`、`inbound`、`outbound`,与解析方案 `purpose` 相同。本阶段实际送达的是 `onhand` 和 `inbound`。
- 批次 S、D 已在工作区且未提交。本计划的代码继续改在这份工作区上。禁止 `git add -A`。禁止 `git commit`(提交须用户显式批准)。每任务只 `git add` 该任务列出的路径。
- 解析方案最终表名已经写在未执行的 `s17b` 里。禁止再添加 `freight_rpa_onhand_parsing_profiles` 这个名字。
- 站点启用规则:已有在手报表配置且其中 `parsing_profile_id` 非空,并且站点 `excel_template_id` 非空。PostgreSQL 的 CHECK 不能跨表,所以模板仍留在站点行的 CHECK 上,解析方案改由保存站点的服务拒绝。
- 注释:改签名或协作关系时同步文件头和函数 docstring(AGENTS.md §5)。
- 新增 `error.code` 时补齐 `locales/*/errors.json` 四语言。本计划复用已有码,不新造码,除非某步写明。
## 文件地图
| 路径 | 职责 |
| --- | --- |
| `backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py` | 新建在手配置表、搬三列、改在手文件表名、downgrade |
| `backend/app/models/shipping_onhand_config.py` | 站点去掉三列;新增 `ShippingOnhandReportConfig` |
| `backend/app/models/shipping.py` | `ShippingOnhandFile.__tablename__` 改为 `freight_rpa_onhand_report_files` |
| `backend/app/services/freight_rpa/reports/facts.py` | `ReportFact` 与取值校验 |
| `backend/app/services/freight_rpa/reports/queries.py` | 按 `source_code` / `file_id` 的只读查询,以及入站解析结果标记 |
| `backend/app/services/freight_rpa/reports/dispatch.py` | 提交后调用处理函数;未注册则 `FREIGHT_RPA.SINK_NOT_REGISTERED` |
| `backend/app/services/freight_rpa/common/report_audit.py` | 写既有 `ShippingAuditEvent`,替代对 `shipping_notice.audit_service` 的 import |
| `backend/app/services/freight_rpa/onhand/report_store.py` | 在手报表行的插入与更新(含解析列) |
| `backend/app/services/in_transit_transfer/inbound_report_handler.py` | inbound 事实只推进 `TransferSourceJob` |
| `backend/app/services/shipping_notice/onhand_report_handler.py` | onhand 事实只更新发货门禁、候选和任务关联 |
| `docs/adr/0004-freight-rpa-report-ownership.md` | 阶段 B 归属决策 |
| `docs/features/freight-rpa/GLOSSARY.md` | 站点归属改为 RPA |
---
### Task 1: 迁移在手配置表与在手文件表名
**Files:**
- Create: `backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py`
- Modify: `backend/app/models/shipping_onhand_config.py`
- Modify: `backend/app/models/shipping.py`(`ShippingOnhandFile.__tablename__` 与指向 `shipping_onhand_files` 的 `ForeignKey`)
- Modify: `backend/app/models/__init__.py`(导出 `ShippingOnhandReportConfig`)
- Modify: 下列文件里的 `ForeignKey('shipping_onhand_files.id')` 改为 `ForeignKey('freight_rpa_onhand_report_files.id')`:`shipping_onhand_mapping.py`、`shipping_excel_template.py`、`shipping_onhand_preparation.py`、`shipping_notice_line_onhand_match.py`
- Test: `backend/tests/test_migration_s18_phase_b_report_ownership.py`
**Interfaces:**
- Consumes: 批次 S 之后库上已有 `freight_rpa_sources.report_path_json`、`query_parameters_json`、`parsing_profile_id`,以及表 `shipping_onhand_files`。`s17b` 的解析方案目标名已是 `freight_rpa_parsing_profiles`。
- Produces: 表 `freight_rpa_onhand_report_configs`(列:`id`、`source_id` 唯一、`parsing_profile_id` 可空、`report_path_json` JSON 非空、`query_parameters_json` JSON 非空、`config_version` int 默认 1、`created_by`、`updated_by`、`created_at`、`updated_at`)。站点行不再有那三列。`ck_freight_rpa_sources_enabled_bindings` 换成 `ck_freight_rpa_sources_enabled_template`,表达式 `enabled = false OR excel_template_id IS NOT NULL`。模型类 `ShippingOnhandReportConfig`,关系 `ShippingOnhandSource.onhand_report_config`(`uselist=False`)。`ShippingOnhandFile.__tablename__ == 'freight_rpa_onhand_report_files'`,列与改名前相同。
- [ ] **Step 1: 写失败测试**
`backend/tests/test_migration_s18_phase_b_report_ownership.py` 沿用 `tests/test_migration_s17_batch_s_rename.py` 的 `_load` + SQLite `Operations` 手法。测试不从迁移模块读取期望表名。
```python
def test_s18_revision_follows_s17c():
migration = _load("s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py")
assert migration.revision == "s18d1e2f3a4b5"
assert migration.down_revision == "s17c2d3e4f5a6"
def test_s17b_parsing_profile_target_is_final_name():
s17b = _load("s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py")
assert ("shipping_inventory_parsing_profiles", "freight_rpa_parsing_profiles") in s17b._TABLE_RENAMES
assert "freight_rpa_onhand_parsing_profiles" not in str(s17b._TABLE_RENAMES)
def test_s18_upgrade_moves_onhand_config_and_renames_files_then_downgrade_restores(op):
# op fixture:内存 SQLite,先跑 s17b.upgrade 再跑 s17c.upgrade(或桩出 s17c 之后的两张表)。
# 桩站点一行:source_code='DSV',report_path_json={'menu':'onhand'},
# query_parameters_json=[{'name':'wh'}],parsing_profile_id=1,excel_template_id=9。
# 桩 shipping_onhand_files 一行:id=7,onhand_lines_json=[{'sku':'A'}],snapshot_status='ready'。
migration = _load("s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py")
migration.upgrade()
config_cols = _column_names(op, "freight_rpa_onhand_report_configs")
assert {"source_id", "report_path_json", "query_parameters_json", "parsing_profile_id"} <= set(config_cols)
source_cols = _column_names(op, "freight_rpa_sources")
assert "report_path_json" not in source_cols
assert "parsing_profile_id" not in source_cols
assert "source_code" in source_cols
file_cols = _column_names(op, "freight_rpa_onhand_report_files")
assert "onhand_lines_json" in file_cols
assert "snapshot_status" in file_cols
row = op.get_bind().exec_driver_sql(
"SELECT report_path_json, parsing_profile_id FROM freight_rpa_onhand_report_configs"
).one()
assert row.parsing_profile_id == 1
migration.downgrade()
assert "report_path_json" in _column_names(op, "freight_rpa_sources")
assert "onhand_lines_json" in _column_names(op, "shipping_onhand_files")
assert "freight_rpa_onhand_parsing_profiles" not in _table_names(op)
```
- [ ] **Step 2: 跑测试确认失败**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/test_migration_s18_phase_b_report_ownership.py -q`
Expected: FAIL,迁移文件不存在。
- [ ] **Step 3: 写迁移与模型**
`revision = "s18d1e2f3a4b5"`,`down_revision = "s17c2d3e4f5a6"`。
upgrade 顺序:
1. `op.create_table('freight_rpa_onhand_report_configs', ...)`,`UniqueConstraint('source_id', name='uq_freight_rpa_onhand_report_configs_source')`,`source_id` 外键 `freight_rpa_sources.id` `ondelete='CASCADE'`,`parsing_profile_id` 外键 `freight_rpa_parsing_profiles.id`。
2. `INSERT INTO freight_rpa_onhand_report_configs (source_id, report_path_json, query_parameters_json, parsing_profile_id, config_version, created_at, updated_at) SELECT id, report_path_json, query_parameters_json, parsing_profile_id, config_version, created_at, updated_at FROM freight_rpa_sources`。
3. `op.drop_constraint('ck_freight_rpa_sources_enabled_bindings', 'freight_rpa_sources', type_='check')`。若库上的历史约束名仍是改名前的名字,用反射按「定义里同时含 `parsing_profile_id` 与 `excel_template_id`」找到那一条再删。
4. 删掉站点上的 `report_path_json`、`query_parameters_json`、`parsing_profile_id`。
5. `op.create_check_constraint('ck_freight_rpa_sources_enabled_template', 'freight_rpa_sources', 'enabled = false OR excel_template_id IS NOT NULL')`。
6. `op.rename_table('shipping_onhand_files', 'freight_rpa_onhand_report_files')`。然后复用 `s17b` 里「对象名包含旧表名则替换」的扫描,旧串 `shipping_onhand_files`,新串 `freight_rpa_onhand_report_files`。新名超过 63 字符时沿用 `s17b` 的截断函数。列名不改。
downgrade 相反:文件表改回 `shipping_onhand_files`,把三列加回 `freight_rpa_sources`,从配置表 `UPDATE` 回去,丢掉配置表,恢复 `ck_freight_rpa_sources_enabled_bindings` 原文 `enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)`。
模型:`ShippingOnhandSource` 删除三列与 `parsing_profile` 关系;启用 CHECK 改为模板那条。新增 `ShippingOnhandReportConfig`,字段与上表一致,`inventory_source` 关系命名与入站配置的 `ShippingInboundReportConfig` 相同风格。`ShippingParsingProfile.sources` 改为指向配置行。`ShippingOnhandFile.__tablename__ = 'freight_rpa_onhand_report_files'`。文件头写明:在手文件表归 RPA,列仍含解析行与快照状态。
- [ ] **Step 4: 跑测试确认通过**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/test_migration_s18_phase_b_report_ownership.py tests/test_migration_s17_batch_s_rename.py -q`
Expected: PASS。
- [ ] **Step 5: 只暂存本任务路径**
```powershell
git add backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py backend/tests/test_migration_s18_phase_b_report_ownership.py backend/app/models/shipping_onhand_config.py backend/app/models/shipping.py backend/app/models/__init__.py backend/app/models/shipping_onhand_mapping.py backend/app/models/shipping_excel_template.py backend/app/models/shipping_onhand_preparation.py backend/app/models/shipping_notice_line_onhand_match.py
```
---
### Task 2: 站点启用与管理端改读写在手配置
**Files:**
- Modify: `backend/app/services/admin/shipping_onhand_admin_service.py`
- Modify: `frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue`(库存报表配置卡片的绑定字段)
- Test: `backend/tests/test_admin_freight_rpa_onhand_config.py`
**Interfaces:**
- Consumes: `ShippingOnhandReportConfig`,站点行上的 `excel_template_id`、`enabled`。
- Produces: `assert_onhand_source_can_enable(source: ShippingOnhandSource) -> None`。`enabled` 为真且缺少配置、或配置的 `parsing_profile_id` 为空、或 `excel_template_id` 为空时抛 `ValidationError(code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')`。站点 DTO 不再带 `report_path_json` / `query_parameters_json` / `parsing_profile_id`;改为 `onhand_report_config: { id, report_path_json, query_parameters_json, parsing_profile_id } | null`。保存在手配置的函数 `save_onhand_report_config(source_id: int, data: dict, actor_id: int | None) -> dict`,没有配置行时插入,有则更新,并递增该行的 `config_version`。
- [ ] **Step 1: 写失败测试**
```python
def test_enabled_source_requires_onhand_profile_and_template(app, db_session):
source = _source(enabled=True, excel_template_id=None)
db_session.add(source)
db_session.commit()
with pytest.raises(ValidationError) as exc:
assert_onhand_source_can_enable(source)
assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED"
def test_save_onhand_report_config_does_not_write_source_columns(app, db_session):
source = _source(enabled=False, excel_template_id=9)
db_session.add(source)
db_session.commit()
save_onhand_report_config(source.id, {
"report_path_json": {"menu": "stock"},
"query_parameters_json": [],
"parsing_profile_id": _published_onhand_profile_id(),
}, actor_id=1)
db_session.refresh(source)
assert not hasattr(source, "report_path_json")
config = ShippingOnhandReportConfig.query.filter_by(source_id=source.id).one()
assert config.report_path_json == {"menu": "stock"}
assert config.parsing_profile.purpose == "onhand"
```
`parsing_profile.purpose` 不是 `onhand` 时,`save_onhand_report_config` 抛 `ValidationError(code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')`。入站配置的保存函数保持只接受 `purpose='inbound'`。
- [ ] **Step 2: 跑测试确认失败**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/test_admin_freight_rpa_onhand_config.py -q`
Expected: FAIL,`assert_onhand_source_can_enable` 未定义。
- [ ] **Step 3: 改服务与页面**
`shipping_onhand_admin_service.py` 里现在写 `source.report_path_json`、`source.query_parameters_json`、`source.parsing_profile_id` 的分支改写配置行。解析方案绑定审计仍写 `freight_rpa_onhand_source_parsing_binding_audits`,`parsing_profile_id` 取自配置行。`FreightRpaPage.vue` 的库存报表配置卡片改绑 `onhand_report_config` 的三个字段;收料卡片继续绑入站配置。站点头部仍编辑 `source_code`、`display_name`、`connector_type`、`rpa_profile_id`、`excel_template_id`、仓库模式。不新增文案。
触发抓取读路径的同一任务内改完,否则管理端能存、排程仍读已删除的列:
- `backend/app/services/shipping_notice/onhand_trigger_batch.py`:`report_path_json` / `query_parameters_json` / `parsing_profile_id` 从 `source.onhand_report_config` 取。配置缺失则沿用现有「站点未就绪」错误,不新造码。
- `backend/app/services/freight_rpa/onhand/trigger_io.py` 若直接读这三列,同样改读配置。
- [ ] **Step 4: 跑测试确认通过**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/test_admin_freight_rpa_onhand_config.py tests/test_admin_freight_rpa_routes.py -q`
Expected: PASS。
- [ ] **Step 5: 只暂存本任务路径**
```powershell
git add backend/app/services/admin/shipping_onhand_admin_service.py backend/app/services/shipping_notice/onhand_trigger_batch.py backend/app/services/freight_rpa/onhand/trigger_io.py frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue backend/tests/test_admin_freight_rpa_onhand_config.py
```
---
### Task 3: 报表只读查询
**Files:**
- Create: `backend/app/services/freight_rpa/reports/__init__.py`
- Create: `backend/app/services/freight_rpa/reports/facts.py`
- Create: `backend/app/services/freight_rpa/reports/queries.py`
- Test: `backend/tests/services/freight_rpa/test_report_queries.py`
**Interfaces:**
- Consumes: `ShippingOnhandSource`、`ShippingOnhandReportConfig`、`ShippingInboundReportConfig`、`ShippingInboundReportFile`、`ShippingOnhandFile`、`usable_inbound_file_condition()`(现位于 `in_transit_transfer/inbound_file_gate.py`,本任务把可用条件的过滤表达式复制进 `queries.py`,门禁模块下一步改为调用这里,避免 `freight_rpa` import `in_transit_transfer`)。
- Produces:
```python
@dataclass(frozen=True)
class ReportFact:
report_kind: str
source_code: str
file_id: int | None
sha256: str | None
ok: bool
error_code: str | None = None
error_message: str | None = None
def require_report_kind(value: str) -> str:
"""只接受 onhand、inbound、outbound。其他值抛 ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID')。"""
@dataclass(frozen=True)
class SiteView:
source_code: str
display_name: str
connector_type: str
excel_template_id: int | None
enabled: bool
@dataclass(frozen=True)
class OnhandConfigView:
report_path_json: dict
query_parameters_json: list
parsing_profile_id: int | None
@dataclass(frozen=True)
class InboundConfigView:
report_path_json: dict
query_parameters_json: list
parsing_profile_id: int | None
@dataclass(frozen=True)
class InboundFileView:
file_id: int
source_code: str
sha256: str
storage_key: str
original_filename: str
created_at: datetime
def get_site(source_code: str) -> SiteView | None: ...
def get_onhand_config(source_code: str) -> OnhandConfigView | None: ...
def get_inbound_config(source_code: str) -> InboundConfigView | None: ...
def latest_usable_inbound_file(source_code: str) -> InboundFileView | None: ...
def read_inbound_file_bytes(file_id: int) -> bytes: ...
def mark_inbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None: ...
def clear_inbound_parse_failure(file_id: int) -> None: ...
```
`latest_usable_inbound_file` 的过滤与今天 `matching_service._latest_usable_report_file` 相同:经 unit run 的 `source_code`,未删除、未过期、按 `created_at`/`id` 倒序第一条。`read_inbound_file_bytes` 用现有 `file_asset_storage` 按 `storage_key` 读取。找不到文件抛 `NotFoundError`。
- [ ] **Step 1: 写失败测试**
```python
def test_latest_usable_inbound_file_returns_newest(app, db_session):
older = _inbound_file(source_code="DSV", sha256="a" * 64, created_at=datetime(2026, 10, 1))
newer = _inbound_file(source_code="DSV", sha256="b" * 64, created_at=datetime(2026, 10, 2))
db_session.add_all([older, newer])
db_session.commit()
view = latest_usable_inbound_file("DSV")
assert view is not None
assert view.file_id == newer.id
assert view.sha256 == "b" * 64
def test_report_kind_rejects_shipment():
with pytest.raises(ValidationError):
require_report_kind("shipment")
assert require_report_kind("outbound") == "outbound"
```
- [ ] **Step 2: 跑测试确认失败**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_report_queries.py -q`
Expected: FAIL,模块不存在。
- [ ] **Step 3: 实现查询模块**
文件头写明:本模块是发货与调拨读报表的唯一入口;不 import `shipping_notice` 或 `in_transit_transfer`。`mark_inbound_parse_failure` 只更新 `parse_failed_at`、`parse_error_code`、`parse_error_message` 后 `flush`,不 `commit`(调用方处于自己的事务)。
- [ ] **Step 4: 跑测试确认通过**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_report_queries.py -q`
Expected: PASS。
- [ ] **Step 5: 只暂存本任务路径**
```powershell
git add backend/app/services/freight_rpa/reports backend/tests/services/freight_rpa/test_report_queries.py
```
---
### Task 4: 在途调拨改为只读函数
**Files:**
- Modify: `backend/app/services/in_transit_transfer/matching_service.py`
- Modify: `backend/app/services/in_transit_transfer/movement_file_repository.py`
- Modify: `backend/app/services/in_transit_transfer/source_file_status.py`
- Modify: `backend/app/services/in_transit_transfer/inbound_file_gate.py`
- Modify: `backend/app/services/in_transit_transfer/inbound_trigger_service.py`
- Modify: `backend/app/services/in_transit_transfer/backlog_reparse_service.py`
- Modify: `backend/app/services/in_transit_transfer/deps.py`
- Modify: `backend/app/services/in_transit_transfer/evidence_sync.py`(它经 `_latest_usable_report_file` 取文件)
- Test: `backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py`
**Interfaces:**
- Consumes: Task 3 的 `latest_usable_inbound_file`、`read_inbound_file_bytes`、`get_inbound_config`、`get_site`、`mark_inbound_parse_failure`、`clear_inbound_parse_failure`。
- Produces: 上述文件不再出现 `from app.models import ShippingInboundReportFile` 或 `ShippingInboundReportConfig` 或 `ShippingOnhandSource`。`matching_service._latest_usable_report_file` 删除,调用处改为 `latest_usable_inbound_file`。解析失败标记改为 `mark_inbound_parse_failure(file_id=...)`。
- [ ] **Step 1: 写失败测试**
```python
def test_in_transit_does_not_import_rpa_report_models():
root = Path(__file__).resolve().parents[3] / "app" / "services" / "in_transit_transfer"
banned = ("ShippingInboundReportFile", "ShippingInboundReportConfig", "ShippingOnhandSource", "ShippingOnhandReportConfig")
hits = []
for path in root.rglob("*.py"):
text = path.read_text(encoding="utf-8")
for name in banned:
if name in text:
hits.append(f"{path.name}: {name}")
assert hits == []
```
- [ ] **Step 2: 跑测试确认失败**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_inbound_report_read_boundary.py -q`
Expected: FAIL,列出 `matching_service.py` 等文件。
- [ ] **Step 3: 替换查询**
`matching_service` 里原 `_latest_usable_report_file` 的调用改为:
```python
from app.services.freight_rpa.reports.queries import latest_usable_inbound_file, read_inbound_file_bytes
view = latest_usable_inbound_file(source_code)
if view is None:
return None
payload = read_inbound_file_bytes(view.file_id)
```
后续只用 `view.file_id`、`view.sha256`、`view.created_at`。`source_file_status.py` 的写标记改为 `mark_inbound_parse_failure` / `clear_inbound_parse_failure`。`inbound_trigger_service.py` 读站点与入站配置改为 `get_site` / `get_inbound_config`。`inbound_file_gate.py` 若只剩过滤表达式,改为从 `queries.py` 引用,自身不再 import 模型。
- [ ] **Step 4: 跑测试确认通过**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_inbound_report_read_boundary.py tests/services/in_transit_transfer -q`
Expected: PASS。既有匹配测试仍绿。
- [ ] **Step 5: 只暂存本任务路径**
```powershell
git add backend/app/services/in_transit_transfer backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py
```
---
### Task 5: 发货通知改为只读函数,在手文件写入收进 RPA
**Files:**
- Create: `backend/app/services/freight_rpa/onhand/report_store.py`
- Modify: `backend/app/services/shipping_notice/onhand_snapshot_store.py`(`create_inventory_snapshot_from_rpa`、`create_empty_rpa_inventory_snapshot`、`get_or_create_rpa_inventory_snapshot` 改为调用 report_store,不再自己 `ShippingOnhandFile(...)`)
- Modify: `backend/app/services/shipping_notice/onhand_file_store.py`(`save_task_inventory_upload` 的插入改为调用 report_store)
- Modify: 仍直接构造或查询 `ShippingOnhandFile` / `ShippingInboundReportConfig` 的发货模块:`onhand_rpa_workflow.py`、`onhand_source_repository.py`、`inbound_report_access.py`、`query_service.py`
- Test: `backend/tests/services/shipping_notice/test_report_model_boundary.py`
**Interfaces:**
- Consumes: Task 3 的查询函数。`ShippingOnhandFile` 列集合不变。
- Produces:
```python
def insert_onhand_report(**columns: Any) -> int:
"""插入 freight_rpa_onhand_report_files 一行并 flush。返回 file_id。不创建任务关联,不 commit。"""
def update_onhand_report(file_id: int, **columns: Any) -> None:
"""按 file_id 更新该行的给定列并 flush。不 commit。"""
```
发货侧可以继续更新 `shipping_task_onhand_links`、候选集、行匹配、核验。禁止再 `db.session.add(ShippingOnhandFile(...))`。
- [ ] **Step 1: 写失败测试**
```python
def test_shipping_notice_does_not_construct_rpa_report_rows():
root = Path(__file__).resolve().parents[3] / "app" / "services" / "shipping_notice"
banned_snippets = ("ShippingOnhandFile(", "ShippingInboundReportFile(", "ShippingInboundReportConfig(")
hits = []
for path in root.rglob("*.py"):
text = path.read_text(encoding="utf-8")
for snippet in banned_snippets:
if snippet in text:
hits.append(f"{path.name}: {snippet}")
assert hits == []
```
- [ ] **Step 2: 跑测试确认失败**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/shipping_notice/test_report_model_boundary.py -q`
Expected: FAIL,命中 `onhand_file_store.py` 与 `onhand_snapshot_store.py`。
- [ ] **Step 3: 挪走插入**
`report_store.insert_onhand_report` 接收今天 `ShippingOnhandFile(...)` 已有的列关键字(`storage_path`、`file_sha256`、`onhand_lines_json`、`field_mapping_json`、`snapshot_status`、`warehouse_id`、`source_code`、`rpa_run_no` 等),不增列。`onhand_snapshot_store.create_inventory_snapshot_from_rpa` 在得到 `file_id` 之后仍调用现有的 `link_snapshot_to_task`,关联表留在发货域。查询改用 `get_onhand_config` / `get_site`。`inbound_report_access.py` 的下载改 `read_inbound_file_bytes`。
- [ ] **Step 4: 跑测试确认通过**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/shipping_notice/test_report_model_boundary.py tests/test_freight_rpa_batch_s_grep_gate.py -q`
Expected: PASS。
- [ ] **Step 5: 只暂存本任务路径**
```powershell
git add backend/app/services/freight_rpa/onhand/report_store.py backend/app/services/shipping_notice/onhand_snapshot_store.py backend/app/services/shipping_notice/onhand_file_store.py backend/app/services/shipping_notice/onhand_rpa_workflow.py backend/app/services/shipping_notice/onhand_source_repository.py backend/app/services/shipping_notice/inbound_report_access.py backend/app/services/shipping_notice/query_service.py backend/tests/services/shipping_notice/test_report_model_boundary.py
```
---
### Task 6: 回调先提交文件,再投递事实
**Files:**
- Create: `backend/app/services/freight_rpa/reports/dispatch.py`
- Create: `backend/app/services/freight_rpa/common/report_audit.py`
- Modify: `backend/app/services/freight_rpa/inbound/report_archive.py`
- Modify: `backend/app/services/freight_rpa/common/callback_sinks.py`(文件头说明文件就绪走 `dispatch_report_fact`,进度类 kind 仍走 `dispatch_sink`)
- Modify: `backend/tests/services/freight_rpa/test_import_boundary.py`
- Test: `backend/tests/services/freight_rpa/test_report_fact_dispatch.py`
**Interfaces:**
- Consumes: `ReportFact`、`register_sink` 的未注册错误码 `FREIGHT_RPA.SINK_NOT_REGISTERED`(http 404)。
- Produces:
```python
Handler = Callable[[ReportFact], None]
def register_report_handler(report_kind: str, handler: Handler) -> None: ...
def dispatch_report_fact(fact: ReportFact) -> None:
"""kind 无处理函数时抛 AppError(code='FREIGHT_RPA.SINK_NOT_REGISTERED', http_status=404)。
本函数不 commit、不 rollback。"""
```
`ingest_inbound_callback` 去掉 `on_terminal` 参数。每个终态分支在 `db.session.commit()` 之后构造 `ReportFact(report_kind='inbound', source_code=unit.source_code, file_id=..., sha256=..., ok=..., error_code=..., error_message=...)` 并调用 `dispatch_report_fact`。同一 `unit_run_id + sha256` 已有文件时不插入第二行,仍投递 `ok=True` 的事实(供处理函数重试)。处理函数抛出的异常原样向外抛,不包一层日志后吞掉。
`append_shipping_audit_event(...)` 的调用改为 `report_audit.append_rpa_report_event(...)`,关键字与现函数相同,内部写入同一个 `ShippingAuditEvent` 模型(允许 import 模型,禁止 import `app.services.shipping_notice.audit_service`)。事件名字符串保持 `shipping_inbound_rpa_callback_received` 与 `shipping_inbound_report_archived`,避免审计查询断档。
`test_import_boundary.py` 的 `ALLOWED_SHIPPING_NOTICE` 改为空集。`file_assets` 那条白名单一并删除(包内已经不引用它)。
- [ ] **Step 1: 写失败测试**
```python
def test_handler_failure_keeps_committed_file(app, db_session, monkeypatch):
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
def boom(fact: ReportFact) -> None:
raise RuntimeError("handler down")
register_report_handler("inbound", boom)
with pytest.raises(RuntimeError, match="handler down"):
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
assert ShippingInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
def test_second_delivery_does_not_insert_another_file(app, db_session):
seen: list[ReportFact] = []
register_report_handler("inbound", seen.append)
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
payload = _success_payload(unit, sha256_file=b"abc")
ingest_inbound_callback(payload)
ingest_inbound_callback(payload)
assert ShippingInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
assert [fact.file_id for fact in seen] == [seen[0].file_id, seen[0].file_id]
def test_missing_handler_raises_sink_not_registered(app, db_session):
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
with pytest.raises(AppError) as exc:
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
assert ShippingInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
```
- [ ] **Step 2: 跑测试确认失败**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_report_fact_dispatch.py -q`
Expected: FAIL,`ingest_inbound_callback` 仍要求 `on_terminal`。
- [ ] **Step 3: 改归档与审计**
非法载荷、单元不存在、配置缺失维持现有 4xx(`SHIPPING.RECEIPT_CALLBACK_INVALID`、`SHIPPING.RECEIPT_UNIT_NOT_FOUND`),在 `commit` 之前抛出,不调用 `dispatch_report_fact`。落 MinIO 或插行失败时事务回滚,同样不投递。`freight_upload` 的 trigger 与回调文件不改。
- [ ] **Step 4: 跑测试确认通过**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_report_fact_dispatch.py tests/services/freight_rpa/test_import_boundary.py tests/test_freight_receipt_rpa_callback.py -q`
Expected: PASS。旧回调测试里若仍向 `ingest_inbound_callback` 传 `on_terminal=`,改成注册 `register_report_handler`。
- [ ] **Step 5: 只暂存本任务路径**
```powershell
git add backend/app/services/freight_rpa/reports/dispatch.py backend/app/services/freight_rpa/common/report_audit.py backend/app/services/freight_rpa/inbound/report_archive.py backend/app/services/freight_rpa/common/callback_sinks.py backend/tests/services/freight_rpa/test_report_fact_dispatch.py backend/tests/services/freight_rpa/test_import_boundary.py backend/tests/test_freight_receipt_rpa_callback.py
```
---
### Task 7: 业务处理函数只改自己的任务
**Files:**
- Create: `backend/app/services/in_transit_transfer/inbound_report_handler.py`
- Create: `backend/app/services/shipping_notice/onhand_report_handler.py`
- Modify: `backend/app/services/shipping_notice/rpa_sinks.py`
- Modify: `backend/app/services/shipping_notice/inbound_report_storage.py`(去掉吞掉异常的 `_advance_transfer_source_job`;终态推进改由调拨处理函数承担)
- Modify: `backend/app/__init__.py`(`register_onhand_sinks` / `register_inbound_sinks` 里增加 `register_report_handler`)
- Modify: `backend/app/services/in_transit_transfer/inbound_callback_bridge.py`(`advance_source_job_from_inbound_callback` 保持只更新 `status='waiting_rpa_callback'` 的行)
- Test: `backend/tests/services/in_transit_transfer/test_inbound_report_handler.py`
**Interfaces:**
- Consumes: `ReportFact`、`advance_source_job_from_inbound_callback`、`register_report_handler`。
- Produces:
```python
def handle_inbound_report(fact: ReportFact) -> None:
"""report_kind 必须是 inbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready;
ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。"""
def handle_onhand_report(fact: ReportFact) -> None:
"""report_kind 必须是 onhand。用 fact.file_id 更新发货门禁与候选。不写 TransferSourceJob。
不插入 freight_rpa_onhand_report_files。"""
```
`register_inbound_sinks` 调用 `register_report_handler('inbound', handle_inbound_report)`。`register_onhand_sinks` 调用 `register_report_handler('onhand', handle_onhand_report)`。进度类 sink(`inbound-unit-progress`、`onhand-batch-claimed` 等)仍走 `register_sink`,不改 envelope。
在手回调 `rpa_report_inventory` / `rpa_report_inventory_batch`:先 `insert_onhand_report` 或 `update_onhand_report`,`db.session.commit()`,再 `dispatch_report_fact(ReportFact(report_kind='onhand', ...))`。处理函数抛错时文件行还在。
证据同步 `sync_and_commit_for_callback` 改由 `handle_inbound_report` 在推进 `file_ready` 之后调用。它抛错时文件已提交,异常继续向外抛,供 Worker 重试。排程终态 `finalize_receipt_schedule_run_if_complete` 仍由该处理函数在调拨推进之后调用;函数本身在 `schedule` 包,`freight_rpa` 不 import 它。
- [ ] **Step 1: 写失败测试**
```python
def test_unregistered_transfer_handler_leaves_job_waiting(app, db_session):
job = _waiting_job(source_code="DSV")
db_session.add(job)
db_session.commit()
# 不注册 handle_inbound_report
with pytest.raises(AppError) as exc:
ingest_inbound_callback(_success_payload_for("DSV"))
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
db_session.refresh(job)
assert job.status == "waiting_rpa_callback"
def test_handler_fail_then_success_advances_once(app, db_session, monkeypatch):
job = _waiting_job(source_code="DSV")
db_session.add(job)
db_session.commit()
calls = {"n": 0}
def flaky(fact: ReportFact) -> None:
calls["n"] += 1
if calls["n"] == 1:
raise RuntimeError("once")
handle_inbound_report(fact)
register_report_handler("inbound", flaky)
payload = _success_payload_for("DSV")
with pytest.raises(RuntimeError):
ingest_inbound_callback(payload)
ingest_inbound_callback(payload)
db_session.refresh(job)
assert job.status == "file_ready"
assert ShippingInboundReportFile.query.count() == 1
def test_no_waiting_job_is_success(app, db_session):
register_report_handler("inbound", handle_inbound_report)
ingest_inbound_callback(_success_payload_for("DSV"))
assert TransferSourceJob.query.filter_by(source_code="DSV").count() == 0
```
- [ ] **Step 2: 跑测试确认失败**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_inbound_report_handler.py -q`
Expected: FAIL,`handle_inbound_report` 未定义。
- [ ] **Step 3: 接上两个处理函数**
`handle_inbound_report` 在 `fact.ok and fact.file_id` 时调用:
```python
advance_source_job_from_inbound_callback(
source_code=fact.source_code,
file_no=str(fact.file_id),
file_sha256=fact.sha256,
callback_ok=True,
)
```
否则 `callback_ok=False`,带上 `fact.error_code` 与 `fact.error_message`。返回 `None` 时直接结束。不要在这里捕获异常。`inbound_report_storage._advance_transfer_source_job` 的 `except Exception: logger.warning` 删除,避免再次把失败吞掉。
- [ ] **Step 4: 跑测试确认通过**
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_inbound_report_handler.py tests/test_freight_receipt_rpa_callback.py tests/services/freight_rpa/test_import_boundary.py -q`
Expected: PASS。
- [ ] **Step 5: 只暂存本任务路径**
```powershell
git add backend/app/services/in_transit_transfer/inbound_report_handler.py backend/app/services/shipping_notice/onhand_report_handler.py backend/app/services/shipping_notice/rpa_sinks.py backend/app/services/shipping_notice/inbound_report_storage.py backend/app/__init__.py backend/app/services/in_transit_transfer/inbound_callback_bridge.py backend/tests/services/in_transit_transfer/test_inbound_report_handler.py
```
---
### Task 8: ADR、术语与切换说明
**Files:**
- Create: `docs/adr/0004-freight-rpa-report-ownership.md`
- Modify: `docs/features/freight-rpa/GLOSSARY.md`(站点一条)
- Modify: `docs/features/freight-rpa/cutover-runbook.md` 第 5 节的升级目标 revision
- Modify: `docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md` 状态行改为「已有实施计划」,并加上本计划路径。不改其他段落。
**Interfaces:**
- Consumes: 本计划 Task 1–7 的表名与 `ReportFact` 字段。
- Produces: ADR 记录「同一进程、提交后调用处理函数、无队列」。GLOSSARY 站点句改为归属 `freight_rpa`。Runbook 的 `flask db current` 目标改为 `s18d1e2f3a4b5`,并写明它包含 `s17b`、`s17c`。
- [ ] **Step 1: 写 ADR**
标题:Freight RPA 报表归 RPA,业务方只消费报表事实。
正文按 `docs/adr/0002-transfer-type-configuration.md` 的篇幅,写清三句:
1. 登录连接、站点、在手配置、入站配置、解析方案、在手文件、入站文件由 `freight_rpa` 写入。
2. 文件在 RPA 事务提交之后,同一次 HTTP 请求调用 `handle_onhand_report` / `handle_inbound_report`。失败返回 5xx,文件保留,Worker 重试。
3. 不另建服务、不引入消息队列。出站抓取不在本决策内;`report_kind=outbound` 只占位。
- [ ] **Step 2: 改 GLOSSARY 与 runbook**
`GLOSSARY.md` 第 51–52 行改为:
```markdown
**站点(Source)**:
一个货代抓取目标(如 DSV AWS、Crane NA),持有登录连接与报表配置。表 `freight_rpa_sources` 归属 freight_rpa。发货通知与在途调拨只保存 source_code。
```
`cutover-runbook.md` 第 5 节把 `flask db current` 的期望从 `tt16c7d8e9f0a1b2` 改为 `s18d1e2f3a4b5`。同节加一句:该 revision 依次包含批次 R 的任务键、批次 S 的表改名与枚举、阶段 B 的在手配置表和在手文件表名。冒烟三条链路的文字不改:在手导出、入站导出、履约上传。
- [ ] **Step 3: 核对用词**
在 `docs/adr/0004-freight-rpa-report-ownership.md` 与 `docs/features/freight-rpa/GLOSSARY.md` 中搜索 `归属 shipping_notice`,结果应为空。搜索 `freight_upload`,runbook 的履约上传冒烟仍在。
- [ ] **Step 4: 只暂存本任务路径**
```powershell
git add docs/adr/0004-freight-rpa-report-ownership.md docs/features/freight-rpa/GLOSSARY.md docs/features/freight-rpa/cutover-runbook.md docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md
```
---
## 自检
| 设计条款 | 任务 |
| --- | --- |
| 在手配置表,三列搬离站点 | Task 1、Task 2 |
| 解析方案表名在 s17b,库上不出现 `freight_rpa_onhand_parsing_profiles` | Task 1 测试 |
| 在手文件只改表名 | Task 1 |
| 启用规则换检查位置 | Task 2 |
| 只读函数:站点、配置、最新入站文件、按 file_id 读内容 | Task 3、Task 4、Task 5 |
| 调拨与发货不再为查询 import 报表模型 | Task 4、Task 5 的门禁测试 |
| 回调事实含 outbound 取值;本阶段投递 onhand 与 inbound | Task 3、Task 6、Task 7 |
| 未注册处理函数、重复回调、失败后再成功 | Task 6、Task 7 |
| 文件提交不依赖处理函数 | Task 6 |
| `freight_rpa` 不 import 发货工作流与 `audit_service` | Task 6 边界测试 |
| 不改 `freight_upload`、不做出站抓取、不拆服务 | Global Constraints;Task 6 写明不改 upload 文件 |
| ADR 0004 与 GLOSSARY | Task 8 |
不在本计划里的项:排程函数名 `run_freight_receipt_rpa_*`、表名 `freight_rpa_inbound_rpa_unit_runs` 与 `freight_rpa_onhand_task_rpa_attempts` 的中间 `rpa`、Worker 日志行 `[freight_inbound_rpa_worker]`。设计文档没有要求改它们。