Files
syops/docs/superpowers/plans/2026-09-25-transfer-evidence-sync.md
T
hugo 5412ddc7a8 feat(in-transit-transfer): 收料成功同步调拨证据并落库调用日志留档
- 新增 evidence_sync:收料归档 success 终态桥接触发调拨证据同步,桥内异常只记日志不回滚归档终态
- 迁移 wd7e:integration_calls 新增 wire_json 线级事实留档与 business_ref 业务锚点列,完成调用日志闭环
- receipt_report_storage 在 success 分支挂接同步桥,收料链路正确性不受桥内异常影响
- 同步 demand/funclist/technical 跨域文档与证据同步实施计划
- test(sso):旧 Redis 协议下线断言由 tickets 改用 orders 端点措辞
2026-09-27 18:17:06 +08:00

1357 lines
70 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.
# 在途调拨证据同步与匹配瘦身 实施计划
> **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:** 把「点匹配才解析文件」重构为「文件落地即解析写入待办(主)+ 动作时 sha 比对兜底(备)」,匹配退化为只查 ERP 库存+比对;同时修重查圈行口径 bug、退役 10 分钟 TTL(改为 worker 写前库存复查)、出清文件消失行。
**Architecture:** 三层各挂精确判据——证据轴(收料文件)由 `evidence_sync` 在文件落地时同步(收料回调桥模式挂接,try/except 仅日志+自行 commit),匹配/重查动作前置 sha 校验兜底;账面轴(ERP 库存)由匹配查询 + worker 写前复查覆盖;消失行统一 `blocked_file_removed` 出清到待处理池。13 状态冻结契约不动:待查行 = `status='matching'` + `result_code='pending_stock_check'`。
**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic(后端);Vue 3 + vue-i18n 四语言(前端);pytest / vitest。
**Spec:** 本计划实现 2026-09-25 会话定稿设计(主备双层:落地解析为主、动作对齐兜底;RPA 模块独立化缓办另立项)。设计要点将随 Task 14 固化到 `docs/features/in-transit-transfer/technical.md`。前置已完成(不在本计划内):库存查询契约 v2(`warehouse_code`/`stock_quantity`/`stock_unit` 必填,代码+绑定/接口配置已同窗切换);单位只取 ERP `stock_unit`(img09)。
## Global Constraints
- 13 个业务状态冻结(`status.py` 提示词契约):**禁止新增状态值**;待查行用 `status='matching'`(已在 CheckConstraint `ck_transfer_invoice_items_status` 白名单)+ 新 result_code `pending_stock_check`。
- 终态行(success/duplicate_success/manually_closed/cancelled/executing/result_unknown)**绝不复活**:任何同步/匹配路径不得改写。
- 本计划仅一处 DDL:`transfer_invoice_items.matching_id` 放开非空(落地同步行尚无匹配归属);其余零迁移。
- 执行安全底线不变:门禁③文件版本对账保留 fail-closed;`result_unknown`/续跑(final_only=True)路径**不做**写前库存复查(票可能已建成,D7② 只触发末步)。
- 收料回调桥:try/except 包裹、失败仅 `logger.warning`、桥内自行 commit——收料归档主链路零依赖零风险。
- i18n:新增/修改文案必须 zh-CN / zh-TW / en / th 四语言同步,禁止硬编码中文。
- **禁止 `git commit` 步骤**(仓库规则:仅用户明确批准后统一提交);每个任务以 `git add` 暂存收尾。
- 注释三层规范(AGENTS.md §5):新文件模块 docstring(用途/依赖/逻辑)、每个核心函数含 Args/Returns docstring、关键决策用行内注释说明「为什么」。
- 测试断言注释:关键 assert 带 `[断言意图]` 说明(docs/test_plan_matrix.md §1)。
- ⚠️ `matching_service.py` 正被并行会话同时改动:**每个任务开工前先 `git status` + 重读目标文件**,以工作区现状为准。
- 后端测试命令:`cd backend && ./.venv/Scripts/python.exe -m pytest <path> -q`;前端:`cd frontend && npx vitest run <path>`;收口 `npm run build`。
## File Structure
| 文件 | 动作 | 职责 |
| --- | --- | --- |
| `backend/app/services/in_transit_transfer/evidence_sync.py` | 新增 | 证据同步唯一实现:`sync_source_rows`(解析→三分类写入)、`align_scope_rows`(sha 比对兜底入口) |
| `backend/app/services/in_transit_transfer/matching_service.py` | 重构 | `run_matching` 瘦身为「兜底对齐→圈行→成熟过滤→路由分组查库存→行落位」;`create_matching` 删解析/upsert/消失标记段;counts 口径扩展 |
| `backend/app/services/in_transit_transfer/retry_service.py` | 修改 | `requery_items` 圈行改 scope;`requery_*` 前置兜底对齐;`retry_item` 拒绝 file_removed 行 |
| `backend/app/services/in_transit_transfer/execution_service.py` | 修改 | 删 TTL 门禁(`_gated_items`② 与 `_recheck_gates` TTL 段);`_execute_document` 增写前库存复查(仅全量重跑路径) |
| `backend/app/services/in_transit_transfer/contracts.py` | 修改 | `MatchingCountsDTO` + `pending_stock_check_count`/`invalid_count` |
| `backend/app/services/in_transit_transfer/serializers.py` | 修改 | `serialize_summary` 透传新计数 |
| `backend/app/services/shipping_notice/receipt_report_storage.py` | 修改 | 新增 `_sync_transfer_evidence` 桥(成功回调后触发证据同步) |
| `backend/migrations/versions/tt1a2b3c4d5e6f_transfer_item_matching_id_nullable.py` | 新增 | matching_id 放开非空(唯一 DDL) |
| `backend/app/models/in_transit_transfer.py` | 修改 | `matching_id` 类型注解 `Optional[int]` |
| `backend/tests/services/in_transit_transfer/test_evidence_sync.py` | 新增 | 同步三分类/幂等跳过/终态保护/零 ERP 断言 |
| `backend/tests/services/in_transit_transfer/`(既有匹配测试群) | 迁移 | 夹具从「给文件→匹配」迁到「sync 预置行→匹配查库存」 |
| `frontend/src/features/chat/types/transfer.types.ts` | 修改 | counts 类型 +2 字段 |
| `frontend/src/features/chat/components/messages/TransferMatchCard.vue` | 修改 | 待查/已失效计数格、待查徽标、fileChanged 文案语义 |
| `frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue` | 修改 | file_removed 行隐藏「重查」 |
| `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` | 修改 | transfer 段 +3 key、改 1 key |
| `docs/features/in-transit-transfer/technical.md`、`docs/funclist.md` | 修改 | 管道重写文档化 + RPA 模块独立化建议条目 |
---
### Task 1: 重查圈行口径修复(止血,独立可交付)
**Files:**
- Modify: `backend/app/services/in_transit_transfer/retry_service.py`(`requery_items`,约 224-270 行区域)
- Test: `backend/tests/services/in_transit_transfer/test_requery_scope.py`(新增)
**Interfaces:**
- Consumes: `matching_service.scope_item_query(matching)`(已有,按 scope_json 圈行的 BaseQuery);`matching_service.RESULT_FILE_REMOVED`(常量 `"blocked_file_removed"`)。
- Produces: `requery_items(matching_no=..., deps=..., invoice_nos=...)` 行为变更——命中范围从 matching_id 归属改为 scope 谓词(后续任务依赖此语义,不再改)。
- [x] **Step 1: 写失败测试**
新建 `backend/tests/services/in_transit_transfer/test_requery_scope.py`:
```python
"""重查圈行口径回归:视图(scope 圈行)能看到的行,重查必须够得着。
用途:锁死 2026-09-24 上午「点重查毫无反应」缺陷——requery_items 曾按
matching_id 圈行,而行归属解耦后行停在首次创建的匹配上(不迁移),
今天匹配卡(新 matching)重查恒命中 0 行。
依赖:app fixture、repo_fakes.make_transfer_deps、models。
逻辑:造两份同 scope 匹配;行归属旧匹配;经新匹配号重查必须命中该行;
file_removed 行即使可恢复状态也不可重查。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
from app.services.in_transit_transfer.retry_service import requery_items
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
pytestmark = [pytest.mark.usefixtures("app")]
def _seed(scope_sources, business_date, matching_no):
run = TransferRun(run_no=f"RUN-{matching_no}", trigger_type="manual",
business_date=business_date, status="matching",
source_codes_json=scope_sources, counts_json={}, transfer_type="in_transit_to_hub")
db.session.add(run)
db.session.flush()
matching = TransferMatching(
matching_no=matching_no, run_id=run.id, business_date=business_date,
status="success",
scope_json={"source_codes": scope_sources, "receipt_date_from": None,
"receipt_date_to": None, "transfer_type": "in_transit_to_hub"},
file_snapshot_json={}, mapping_version="v0", strategy_version="v0",
counts_json={}, estimated_transfer_quantity="0",
estimated_external_write_count=0, matching_hash="sha256:x",
expires_at=datetime.utcnow(),
)
db.session.add(matching)
db.session.flush()
return run, matching
def _seed_row(matching, invoice_no):
row = TransferInvoiceItem(
matching_id=matching.id, source_code="CRANE", invoice_no=invoice_no,
material_no="MAT-1", material_name="n", specification="",
receipt_date="2026-09-20", status="blocked_recoverable",
result_code="blocked_quantity_mismatch", result_message="strict quantity mismatch",
from_warehouse="HTP-D43", to_warehouse="HTP-D49", receipt_quantity="36",
external_quantity="30", lot_no=invoice_no, receipt_warehouse_code="W1",
unit="PCS", raw_lines_json=[],
)
db.session.add(row)
db.session.flush()
return row
def test_requery_hits_row_created_under_other_matching(app):
# [断言意图] 行归属匹配 A,经匹配 B(同 scope)发起重查必须命中——scope 口径。
_, matching_a = _seed(["CRANE"], "2026-09-24", "MTG-A")
row = _seed_row(matching_a, "HOX-1")
_, matching_b = _seed(["CRANE"], "2026-09-24", "MTG-B")
deps, _, _ = make_transfer_deps(None)
outcome = requery_items(matching_no=matching_b.matching_no, deps=deps,
invoice_nos=["HOX-1"], actor_id="1")
assert outcome["total"] == 1 # [断言意图] scope 圈行命中旧匹配的行
assert outcome["results"][0]["ok"] is True
assert outcome["results"][0]["item_id"] == row.id
def test_requery_skips_file_removed_rows(app):
# [断言意图] file_removed 行不允许重查翻回可执行(消失证据不可恢复)。
_, matching_a = _seed(["CRANE"], "2026-09-24", "MTG-C")
removed = _seed_row(matching_a, "HOX-RM")
removed.result_code = "blocked_file_removed"
removed.result_message = "receipt row removed from latest file"
db.session.flush()
deps, _, _ = make_transfer_deps(None)
outcome = requery_items(matching_no=matching_a.matching_no, deps=deps,
invoice_nos=["HOX-RM"], actor_id="1")
assert outcome["total"] == 0 # [断言意图] 失效行被圈行排除
```
- [x] **Step 2: 运行确认失败**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_requery_scope.py -q`
Expected: 两个用例 FAIL(现状 matching_id 过滤命中 0 行 / file_removed 行被重查)。
- [x] **Step 3: 最小实现**
`retry_service.py` 顶部 import 区补:
```python
from sqlalchemy import or_
from app.services.in_transit_transfer.matching_service import (
RESULT_FILE_REMOVED,
TransferDeps,
scope_item_query,
)
```
`requery_items` 内替换圈行查询(原 `TransferInvoiceItem.query.filter(TransferInvoiceItem.matching_id == matching.id, ...)` 三行):
```python
# [口径统一] 圈行必须与匹配卡视图同谓词(scope:来源+日期区间+类型前缀)——
# 行归属解耦后 matching_id 停留在首次创建值,按它圈行会漏掉全部存量行。
# file_removed 行排除:消失证据不可重查恢复(唯一出口=人工关闭/出清)。
query = (
scope_item_query(matching)
.filter(
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
or_(
TransferInvoiceItem.result_code.is_(None),
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED,
),
)
)
```
- [x] **Step 4: 运行确认通过**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_requery_scope.py tests/services/in_transit_transfer/test_batch_actions.py -q`
Expected: 全部 PASS。
- [x] **Step 5: 暂存**
```bash
git add backend/app/services/in_transit_transfer/retry_service.py backend/tests/services/in_transit_transfer/test_requery_scope.py
```
---
### Task 2: evidence_sync 证据同步模块 + matching_id 放开非空
**Files:**
- Create: `backend/app/services/in_transit_transfer/evidence_sync.py`
- Modify: `backend/app/models/in_transit_transfer.py`(`matching_id` 注解,约 241 行)
- Create: `backend/migrations/versions/tt1a2b3c4d5e6f_transfer_item_matching_id_nullable.py`
- Test: `backend/tests/services/in_transit_transfer/test_evidence_sync.py`(新增)
**Interfaces:**
- Consumes: `deps.file_repository.latest_ready_file(source_code=, business_date=) -> ReadyReceiptFile|None`(`ReadyReceiptFile.checksum`=sha256、`.rows`、`.file_version`);`parse_movement_rows(source_code=, rows=)`;`aggregate_invoices(rows, file_version=)`;`filter_invoices_for_type(invoices, transfer_type)`;`deps.route_resolver.resolve(source_code=, invoice_no=, warehouse_code=) -> RouteMapping`;`matching_service._item_evaluated_sha(item)`。
- Produces(后续任务依赖,签名冻结):
- `SYNC_RESULT_PENDING = "pending_stock_check"`
- `sync_source_rows(*, source_code: str, deps: TransferDeps, business_date: str, now: datetime) -> SyncOutcome | None`(无可用文件返回 None;**不 commit,只 flush**,提交归调用方)
- `align_scope_rows(*, source_codes: list[str], deps: TransferDeps, business_date: str, now: datetime) -> dict[str, SyncOutcome | None]`(None=已对齐或无文件,无需解析)
- `SyncOutcome(source_code, file_sha256, inserted, refreshed, reset_pending, removed)`(全 int 除前两项)
- [x] **Step 1: 放开 matching_id 非空(模型 + 迁移)**
`app/models/in_transit_transfer.py` 约 241 行:
```python
# 行归属解耦后 matching_id 仅留痕(首次创建值);落地证据同步行尚无匹配归属
# (2026-09-25),放开非空。uq_transfer_invoice_items_matching_grain 含本列,
# NULL 行不受该唯一约束保护——同步的幂等去重由 evidence_sync 应用层按
# (source, invoice, material, receipt_date) 四元组负责(见 evidence_sync)。
matching_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=True, index=True)
```
新建迁移 `backend/migrations/versions/tt1a2b3c4d5e6f_transfer_item_matching_id_nullable.py`(down_revision 用 `flask db heads` 实测值,当前应为 `tt0d1e2f3a4b`):
```python
"""transfer_invoice_items.matching_id 放开非空
Revision ID: tt1a2b3c4d5e6f
Revises: tt0d1e2f3a4b
Create Date: 2026-09-25
用途:落地证据同步行(evidence_sync)尚无匹配归属,matching_id 允许 NULL。
注意:downgrade 要求表中不存在 matching_id IS NULL 的行(先清同步行再降级)。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt1a2b3c4d5e6f'
down_revision = 'tt0d1e2f3a4b'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.alter_column('matching_id', existing_type=sa.Integer(), nullable=True)
def downgrade():
with op.batch_alter_table('transfer_invoice_items') as batch_op:
batch_op.alter_column('matching_id', existing_type=sa.Integer(), nullable=False)
```
Run: `cd backend && ./.venv/Scripts/python.exe -m flask db upgrade`
Expected: 迁移应用成功,`flask db heads` 单 head `tt1a2b3c4d5e6f`。
- [x] **Step 2: 写失败测试**
新建 `backend/tests/services/in_transit_transfer/test_evidence_sync.py`:
```python
"""证据同步三分类写入回归。
用途:锁死 evidence_sync 的核心语义——新行插入(待查态)、既有行按文件刷新、
值变重置库存侧、消失行失效、终态行绝不触碰、全程零 ERP 调用。
依赖:repo_fakes(Fake 文件仓库注入文件行)、app fixture。
逻辑:通过 Fake repository 的 latest_ready_file 提供文件;直接断言行级状态。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer.evidence_sync import (
SYNC_RESULT_PENDING,
sync_source_rows,
)
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
pytestmark = [pytest.mark.usefixtures("app")]
NOW = datetime(2026, 9, 25, 10, 0, 0)
def _pending_count(source_code="CRANE"):
return TransferInvoiceItem.query.filter_by(
source_code=source_code, result_code=SYNC_RESULT_PENDING).count()
def test_sync_inserts_pending_rows_without_erp(app, dbs_ready_file):
# [断言意图] 首次同步:文件行全部落库为待查态;ERP 能力零调用。
deps, _, erp = make_transfer_deps(dbs_ready_file)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert outcome is not None and outcome.inserted > 0 # [断言意图] 有新行
assert outcome.removed == 0
assert _pending_count("DBS-AWSBI") == outcome.inserted
row = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").first()
assert row.status == "matching" # [断言意图] 13 状态内的待查表达
assert row.result_code == SYNC_RESULT_PENDING
assert row.matching_id is None # [断言意图] 落地行尚无匹配归属
assert erp.query_calls == getattr(erp, "query_calls", 0) # [断言意图] 零 ERP 调用
def test_sync_is_idempotent_when_sha_unchanged(app, dbs_ready_file):
# [断言意图] 同文件重复同步:整行跳过,不续新鲜度、不产生新行。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
before = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all()
stamps = [r.updated_at for r in before]
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
after = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all()
assert [r.id for r in after] == [r.id for r in before]
assert [r.updated_at for r in after] == stamps # [断言意图] sha 一致零写入
def test_sync_marks_vanished_rows_and_never_touches_terminal(app, dbs_ready_file):
# [断言意图] 新版文件里消失的行 → blocked_file_removed;终态行保持既定事实。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
doomed = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").first()
doomed.status = "ready_to_execute" # 模拟上一版可执行
db.session.flush()
terminal = TransferInvoiceItem(
matching_id=None, source_code="DBS-AWSBI", invoice_no="HOX-TERMINAL",
material_no="MAT-X", material_name="n", specification="", receipt_date="2026-09-19",
status="success", result_code=None, from_warehouse="W", to_warehouse="H",
receipt_quantity="1", lot_no="L", receipt_warehouse_code="W1", unit="PCS",
raw_lines_json=[], updated_at=NOW,
)
db.session.add(terminal)
db.session.flush()
deps2, repo2, _ = make_transfer_deps(dbs_ready_file)
# 换一版不含任何行的文件:直接改 Fake 仓库返回(executor 按 repo_fakes 实际
# 结构注入空 rows 的 ReadyReceiptFile,checksum 用不同 sha)。
repo2.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="sha256:EMPTY"[:64])
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps2,
business_date="2026-08-06", now=NOW)
db.session.refresh(doomed)
assert doomed.status == "blocked_recoverable" # [断言意图] 消失行失效
assert doomed.result_code == "blocked_file_removed"
db.session.refresh(terminal)
assert terminal.status == "success" # [断言意图] 终态行不复活
```
注意:`repo2.set_next_file` / `erp.query_calls` 若与 `repo_fakes`/`fakes.py` 现有接口不符,**以扩展 fake 为准**(在 `repo_fakes` 的 Fake 仓库上加 `set_next_file(source_code, rows, checksum)` 覆盖下一次 `latest_ready_file` 返回;在 FakeErp 上加 `query_calls` 计数器),不改动产品代码迁就测试。
- [x] **Step 3: 运行确认失败**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_evidence_sync.py -q`
Expected: FAIL(`evidence_sync` 模块不存在)。
- [x] **Step 4: 实现 evidence_sync.py**
新建 `backend/app/services/in_transit_transfer/evidence_sync.py`:
```python
"""services/in_transit_transfer/evidence_sync.py
用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写,
主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。
依赖:file_parser / invoice_aggregator / transfer_type / source_file_status /
matching_service(_item_evaluated_sha 复用)/ models / audit。
逻辑:一次解析三分类写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
整行跳过(幂等,不续新鲜度);sha 变了业务值没变 → 只换版本戳;业务值变了
→ 刷新值并重置回待查(旧库存是对旧数量查的,作废);文件里消失 →
blocked_file_removed(出清,见 scope 视图与待处理池)。全程零外部调用
(不查 ERP、不触发 RPA);终态行绝不触碰;不 commit 只 flush(提交归调用方:
落地桥自行 commit,匹配/重查随主事务)。13 状态冻结契约内表达待查态:
status='matching' + result_code='pending_stock_check'。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
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.audit import build_transfer_audit_event
from app.services.in_transit_transfer.file_parser import parse_movement_rows
from app.services.in_transit_transfer.invoice_aggregator import aggregate_invoices
from app.services.in_transit_transfer.matching_service import (
RESULT_FILE_REMOVED,
RouteNotResolvedError,
_item_evaluated_sha,
)
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
from app.services.in_transit_transfer.transfer_type import (
TransferType,
filter_invoices_for_type,
)
SYNC_RESULT_PENDING = "pending_stock_check"
# 终态集合与 matching_service 原地刷新口径一致:同步永不触碰既定事实。
_TERMINAL_ITEM_STATUSES = frozenset({
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
status_machine.TransferStatus.CANCELLED.value,
status_machine.TransferStatus.EXECUTING.value,
status_machine.TransferStatus.RESULT_UNKNOWN.value,
})
@dataclass(frozen=True)
class SyncOutcome:
"""一次来源同步的结果计数(审计与兜底日志的数据源)。"""
source_code: str
file_sha256: str
inserted: int = 0 # 文件有、本地无 → 插入待查行
refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留
reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废)
removed: int = 0 # 文件里消失 → blocked_file_removed
skipped: int = 0 # sha 未变的幂等跳过
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
"""解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。
Args:
source_code: 来源实例编码。
deps: TransferDeps(只用 file_repository 与 route_resolver)。
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。
Returns:
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None。
"""
ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date)
if ready is None:
return None
parsed = parse_movement_rows(source_code=source_code, rows=ready.rows)
invoices = filter_invoices_for_type(
aggregate_invoices(parsed, file_version=ready.file_version),
TransferType.IN_TRANSIT_TO_HUB,
)
existing = TransferInvoiceItem.query.filter(
TransferInvoiceItem.source_code == source_code,
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
).all()
by_key = {(r.source_code, r.invoice_no, r.material_no, r.receipt_date): r for r in existing}
outcome = SyncOutcome(source_code=source_code, file_sha256=ready.checksum or "")
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "removed": 0, "skipped": 0}
incoming_keys: set[tuple] = set()
for invoice in invoices:
receipt_date_iso = invoice.receipt_date.isoformat()
key = (source_code, invoice.invoice_no, invoice.material_no, receipt_date_iso)
incoming_keys.add(key)
row = by_key.get(key)
evidence_changed = row is None or (
str(row.receipt_quantity) != str(invoice.receipt_quantity)
or (row.lot_no or "") != (invoice.lot_no or "")
or (row.receipt_warehouse_code or "") != (invoice.warehouse_code or "")
)
if row is not None and not evidence_changed and _item_evaluated_sha(row) == ready.checksum:
counters["skipped"] += 1 # [幂等] 同文件重复落地:零写入
continue
if row is None:
from_wh, to_wh = _resolve_route_best_effort(deps, source_code, invoice)
db.session.add(TransferInvoiceItem(
matching_id=None, # 落地行尚无匹配归属(列已放开非空)
source_code=source_code,
invoice_no=invoice.invoice_no,
material_no=invoice.material_no,
material_name=invoice.material_name,
specification=invoice.specification,
receipt_date=receipt_date_iso,
status=status_machine.TransferStatus.MATCHING.value,
result_code=SYNC_RESULT_PENDING,
result_message=None,
from_warehouse=from_wh,
to_warehouse=to_wh,
receipt_quantity=str(invoice.receipt_quantity),
external_quantity=None,
lot_no=invoice.lot_no or "",
receipt_warehouse_code=invoice.warehouse_code or "",
unit="", # 单位只取 ERP stock_unit,匹配查询时落列
raw_lines_json=[
{"sheet": line.sheet, "row_no": line.row_no,
"file_version": line.file_version, "file_sha256": ready.checksum}
for line in invoice.raw_lines
],
updated_at=now,
))
counters["inserted"] += 1
continue
# [版本戳] 行随最新文件版本刷新(消失标记行同样换戳,保证对齐入口收敛)。
row.raw_lines_json = [
{"sheet": line.sheet, "row_no": line.row_no,
"file_version": line.file_version, "file_sha256": ready.checksum}
for line in invoice.raw_lines
]
if evidence_changed:
row.receipt_quantity = str(invoice.receipt_quantity)
row.lot_no = invoice.lot_no or ""
row.receipt_warehouse_code = invoice.warehouse_code or ""
row.material_name = invoice.material_name
row.specification = invoice.specification
if row.status not in (status_machine.TransferStatus.MATCHING.value,):
row.status = status_machine.TransferStatus.MATCHING.value
row.result_code = SYNC_RESULT_PENDING
row.result_message = None
row.external_quantity = None # 旧库存对旧数量,作废待重查
counters["reset_pending"] += 1
else:
counters["refreshed"] += 1
row.updated_at = now
for key, row in by_key.items():
if key in incoming_keys:
continue
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
row.result_code = RESULT_FILE_REMOVED
row.result_message = "receipt row removed from latest file"
row.updated_at = now
counters["removed"] += 1
db.session.flush()
outcome = SyncOutcome(source_code=source_code, file_sha256=outcome.file_sha256, **counters)
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_EVIDENCE_SYNCED",
aggregate_type="transfer_source",
aggregate_id=source_code,
actor_type="system",
result="success",
after={
"file_sha256": outcome.file_sha256,
"inserted": outcome.inserted, "refreshed": outcome.refreshed,
"reset_pending": outcome.reset_pending, "removed": outcome.removed,
"skipped": outcome.skipped,
},
))
return outcome
def align_scope_rows(*, source_codes: list[str], deps, business_date: str, now: datetime) -> dict:
"""兜底对齐入口:行版本戳 ≠ 最新文件 sha 的来源才重新解析(一致直通零开销)。
【AI 触发时机】:匹配(run_matching STEP 0)与重查(requery_* STEP 0)调用;
落地同步(主链路)失败的静默兜底——稳态下 sha 一致,本函数零解析直通。
Returns:
{source_code: SyncOutcome|None};None=已对齐或无可用文件(未解析)。
"""
outcomes: dict = {}
for code in source_codes:
latest = resolve_source_file_status(source_code=code) or {}
latest_sha = latest.get("file_sha256")
if not latest_sha:
outcomes[code] = None
continue
rows = TransferInvoiceItem.query.filter(
TransferInvoiceItem.source_code == code,
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
).all()
row_shas = {_item_evaluated_sha(r) for r in rows}
if row_shas == {latest_sha}:
outcomes[code] = None # 已对齐:直通
continue
outcomes[code] = sync_source_rows(source_code=code, deps=deps,
business_date=business_date, now=now)
return outcomes
def _resolve_route_best_effort(deps, source_code: str, invoice) -> tuple[str, str]:
"""同步期预解析路由落列(纯配置查表);解析失败留空不阻断(匹配时再解析)。"""
try:
route = deps.route_resolver.resolve(
source_code=source_code, invoice_no=invoice.invoice_no,
warehouse_code=invoice.warehouse_code or "",
)
return route.from_warehouse, route.to_warehouse
except RouteNotResolvedError:
return "", ""
```
- [x] **Step 5: 运行确认通过 + 全量回归**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_evidence_sync.py -q`
Expected: PASS。
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer -q`
Expected: 既有套件不受影响(本任务只增不改),PASS。
- [x] **Step 6: 暂存**
```bash
git add backend/app/services/in_transit_transfer/evidence_sync.py backend/app/models/in_transit_transfer.py backend/migrations/versions/tt1a2b3c4d5e6f_transfer_item_matching_id_nullable.py backend/tests/services/in_transit_transfer/test_evidence_sync.py backend/tests/services/in_transit_transfer/repo_fakes.py
```
---
### Task 3: 收料回调落地桥(主链路挂接)
**Files:**
- Modify: `backend/app/services/shipping_notice/receipt_report_storage.py`(`_advance_transfer_source_job` 旁新增桥函数;在 success 终态调用点追加触发)
- Test: `backend/tests/services/in_transit_transfer/test_evidence_sync.py`(追加桥行为用例)
**Interfaces:**
- Consumes: Task 2 `sync_source_rows`。
- Produces: 收料回调 success 终态 → 调拨证据同步被触发(失败仅日志不影响归档)。
- [x] **Step 1: 写失败测试(桥的隔离语义)**
在 `test_evidence_sync.py` 追加:
```python
def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog):
# [断言意图] 同步崩溃只记日志:异常绝不向收料回调链路传播。
from app.services.in_transit_transfer import evidence_sync
def _boom(**kwargs):
raise RuntimeError("sync crashed")
monkeypatch.setattr(evidence_sync, "sync_source_rows", _boom)
import logging
with caplog.at_level(logging.WARNING):
result = evidence_sync.sync_and_commit_for_callback(
source_code="CRANE", business_date="2026-09-25", now=NOW)
assert result is False # [断言意图] 失败被吞、返回 False
assert any("TRANSFER_EVIDENCE_SYNC" in r.message for r in caplog.records)
def test_receipt_bridge_commits_on_success(app, dbs_ready_file, monkeypatch):
# [断言意图] 成功路径自行 commit(B3 教训:不依赖调用方提交时机)。
from app.services.in_transit_transfer import evidence_sync
deps, _, _ = make_transfer_deps(dbs_ready_file)
monkeypatch.setattr(
"app.services.in_transit_transfer.deps.get_transfer_dependencies", lambda: deps)
ok = evidence_sync.sync_and_commit_for_callback(
source_code="DBS-AWSBI", business_date="2026-08-06", now=NOW)
assert ok is True
assert _pending_count("DBS-AWSBI") > 0 # [断言意图] 已持久化(含 commit)
def test_receipt_bridge_skips_when_no_file(app):
# [断言意图] 来源无可用文件:静默返回 True(无事发生,非错误)。
from app.services.in_transit_transfer import evidence_sync
assert evidence_sync.sync_and_commit_for_callback(
source_code="NO-SUCH", business_date="2026-09-25", now=NOW) is True
```
- [x] **Step 2: 运行确认失败**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_evidence_sync.py -q`
Expected: 3 个新用例 FAIL(`sync_and_commit_for_callback` 不存在)。
- [x] **Step 3: 实现**
`evidence_sync.py` 追加:
```python
def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: datetime) -> bool:
"""收料回调桥专用入口:同步 + 自行 commit + 异常全吞(仅 warning 日志)。
【AI 触发时机】:收料 RPA 回调 success 终态落文件后由
shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路
的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。
Returns:
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志)。
"""
from flask import current_app
try:
outcome = sync_source_rows(source_code=source_code, deps=_default_deps(),
business_date=business_date, now=now)
db.session.commit()
if outcome is not None:
current_app.logger.info(
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s removed=%s skipped=%s",
source_code, outcome.inserted, outcome.refreshed,
outcome.reset_pending, outcome.removed, outcome.skipped)
return True
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring)
current_app.logger.warning(
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
db.session.rollback()
return False
def _default_deps():
from app.services.in_transit_transfer.deps import get_transfer_dependencies
return get_transfer_dependencies()
```
`receipt_report_storage.py`:找到 `_advance_transfer_source_job(unit, ok=True, file_no=..., file_sha256=...)` 的 **success 调用点**(`ingest_receipt_callback` 内 success 终态分支),紧随其后追加:
```python
# [调拨证据同步·主链路] 文件落地即解析写待办;桥模式失败仅日志(见
# in_transit_transfer/evidence_sync.sync_and_commit_for_callback)。
if ok and file_no:
try:
from datetime import datetime as _dt
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
sync_and_commit_for_callback(
source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(),
)
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
```
(executor 按该文件实际 success 分支的变量名对齐 `file_no/file_sha256` 与 `current_app` 导入方式;失败/empty 分支**不**触发同步。)
- [x] **Step 4: 运行确认通过**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_evidence_sync.py tests/services/shipping_notice -q`
Expected: 全部 PASS(shipping 既有套件不受影响)。
- [x] **Step 5: 暂存**
```bash
git add backend/app/services/in_transit_transfer/evidence_sync.py backend/app/services/shipping_notice/receipt_report_storage.py backend/tests/services/in_transit_transfer/test_evidence_sync.py
```
---
### Task 4: run_matching 瘦身重建 + create_matching 清理 + counts 扩展 + 存量测试迁移
> 本任务是最大改造块:匹配从「解析文件→行落库」变为「兜底对齐→按 DB 行查库存落位」。任务结束标准 = 匹配相关全量测试重新全绿。
**Files:**
- Modify: `backend/app/services/in_transit_transfer/matching_service.py`(`run_matching` 重写、`create_matching` 删段、`_matching_rows` 新增、counts 计算、`restore_matching`/`_item_dto` 适配)
- Modify: `backend/app/services/in_transit_transfer/contracts.py`(`MatchingCountsDTO` +2 字段)
- Modify: `backend/app/services/in_transit_transfer/serializers.py`(`serialize_summary` 透传)
- Modify: 既有匹配测试(迁移清单见 Step 5)
**Interfaces:**
- Consumes: Task 2 `align_scope_rows` / `SYNC_RESULT_PENDING`;契约 v2 `StockTarget(material_no, warehouse_code, lot_no)` / `stock.lookup_row(...)`;`route_resolver.resolve`。
- Produces:
- `run_matching(*, source_codes, business_date, deps, active_source_job_key=None, receipt_date_from=None, receipt_date_to=None, transfer_type=None) -> MatchingRunResult`(签名不变)
- `MatchingCountsDTO` 新字段:`pending_stock_check_count: int = 0`、`invalid_count: int = 0`
- `serialize_summary` counts 含新字段(前端 Task 9 消费)
- [x] **Step 1: counts DTO 与序列化扩展**
`contracts.py` `MatchingCountsDTO`(约 66 行)加两字段:
```python
pending_stock_check_count: int = 0 # 文件已落地、尚未查 ERP 库存的待查行
invalid_count: int = 0 # blocked_file_removed(已出清,不进默认视图)
```
`serializers.serialize_summary` counts 字典补两键透传(键名与字段同名)。
- [x] **Step 2: 重写 run_matching(对齐 STEP 0 + 圈行管道)**
`matching_service.py`:`run_matching` 主体替换为(保留函数签名与 `MatchingRunResult` 契约;`_matching_invoices` 删除,新增 `_matching_rows`):
```python
def run_matching(*, source_codes, business_date, deps, active_source_job_key=None,
receipt_date_from=None, receipt_date_to=None, transfer_type=None) -> MatchingRunResult:
"""执行一次匹配(对齐→圈行→查库存→落位;文件解析已上移 evidence_sync)。
【语义变更 2026-09-25】本函数不再解析收料文件:行由文件落地同步(主)或
STEP 0 兜底对齐(备)写入;本函数只做「成熟过滤 → 路由分组批量查库存 →
数量比对落位」。来源无可用文件时保留既有 UX:触发 RPA 抓取并标 file 阶段。
"""
# ...(前段校验:source_codes 非空 / 类型合法 / 日期范围卡控,原样保留)...
now = datetime.utcnow()
# [STEP 0] 证据兜底对齐:sha 不一致的来源先重解析(落地同步失败的静默兜底)。
align_scope_rows(source_codes=list(source_codes), deps=deps,
business_date=business_date, now=now)
sources, file_snapshot = [], {}
for source_code in source_codes:
file_status = resolve_source_file_status(source_code=source_code) or {}
if not file_status.get("file_sha256"):
prepared = ensure_receipt_file_ready( # 缺文件触发 RPA(既有 UX 保留)
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,
)
sources.append(SourceProgressDTO(source_code=source_code, stage=prepared.stage,
error_code=prepared.error_code,
error_message=prepared.error_message))
continue
file_snapshot[source_code] = {
"file_no": file_status.get("file_no"),
"file_version": f"sha256:{file_status.get('file_sha256')}"[:64],
"checksum": file_status.get("file_sha256"),
}
sources.append(SourceProgressDTO(
source_code=source_code, stage="file_ready",
file_no=file_status.get("file_no"),
file_version=f"sha256:{file_status.get('file_sha256')}"[:64],
checksum=file_status.get("file_sha256"),
))
items, pending_stock_check_count = _matching_rows(
source_codes=list(source_codes), business_date=business_date, deps=deps,
receipt_date_from=receipt_date_from, receipt_date_to=receipt_date_to,
file_snapshot=file_snapshot, now=now,
)
# counts/estimated/snapshot/hash/sources 组装(结构不变,counts 加新桶)
```
`_matching_rows`(新函数,替代 `_matching_invoices`):
```python
def _matching_rows(*, source_codes, business_date, deps,
receipt_date_from, receipt_date_to, file_snapshot, now) -> list:
"""对 scope 内全部非终态非失效行执行「成熟过滤→路由分组批量查库存→落位」。
行更新只写库存侧字段(status/result_code/result_message/external_quantity/
from_warehouse/to_warehouse/unit/updated_at);raw_lines 版本戳归
evidence_sync 所有,匹配不碰。
Returns:
(items DTO 列表, pending_count)——pending_count=落位前的待查行数(counts 桶)。
"""
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.source_code.in_(source_codes),
TransferInvoiceItem.status.not_in(_SYNC_TERMINAL_STATUSES),
or_(TransferInvoiceItem.result_code.is_(None),
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED), # 失效行不参与
)
if receipt_date_from:
query = query.filter(TransferInvoiceItem.receipt_date >= str(receipt_date_from))
if receipt_date_to:
query = query.filter(TransferInvoiceItem.receipt_date <= str(receipt_date_to))
scope_rows_all = query.order_by(TransferInvoiceItem.receipt_date.asc(), TransferInvoiceItem.id.asc()).all()
eligible_to = eligible_receipt_date_to(business_date)
pending_count = 0
matured: list[tuple[TransferInvoiceItem, RouteMapping]] = []
output: list = []
for row in scope_rows_all:
# [口径] 待查行计数先于落位统计(落位会改写 result_code)。
if row.status == MATCHING and row.result_code == SYNC_RESULT_PENDING:
pending_count += 1
maturity = maturity_status(row.receipt_date, business_date)
if maturity == MATURITY_NOT_MATURED:
row.status = status_machine.TransferStatus.NOT_MATURED.value
row.result_code = "not_matured"
row.updated_at = now
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, int(deps.strategy.confirm_ttl_seconds)))
continue
if maturity == MATURITY_FUTURE:
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
row.result_code = "blocked_future_date"
row.result_message = "future receipt date"
row.updated_at = now
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, int(deps.strategy.confirm_ttl_seconds)))
continue
# [路由重解析] 配置可能已变:以本次解析值为准(执行期写前复查兜底漂移)。
route = deps.route_resolver.resolve(
source_code=row.source_code, invoice_no=row.invoice_no,
warehouse_code=row.receipt_warehouse_code or "",
)
row.from_warehouse, row.to_warehouse = route.from_warehouse, route.to_warehouse
matured.append((row, route))
groups: dict[str, list[tuple[TransferInvoiceItem, RouteMapping]]] = {}
for row, route in matured:
groups.setdefault(route.external_org, []).append((row, route))
for external_org, entries in groups.items():
targets = [StockTarget(material_no=r.material_no, warehouse_code=r.from_warehouse,
lot_no=r.lot_no or "") for r, _ in entries]
try:
stock = deps.capabilities.query_stock(
operation_id=f"op-{uuid.uuid4().hex[:12]}", external_org=external_org, targets=targets)
except ExternalQueryTimeoutError:
for r, _route in entries:
r.status = BLOCKED; r.result_code = "external_query_timeout"
r.result_message = "external query timeout"; r.updated_at = now
output.append(_item_dto(r, file_snapshot.get(r.source_code) or {}, now, int(deps.strategy.confirm_ttl_seconds)))
continue
except Exception as exc: # noqa: BLE001 —— 组级降级(绑定缺失/连接失败),不炸整来源
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
for r, _route in entries:
r.status = BLOCKED; r.result_code = RESULT_EXTERNAL_QUERY_FAILED
r.result_message = f"external query failed: {detail}"; r.updated_at = now
output.append(_item_dto(r, file_snapshot.get(r.source_code) or {}, now, int(deps.strategy.confirm_ttl_seconds)))
continue
for r, route in entries:
stock_row = stock.lookup_row(material_no=r.material_no,
warehouse_code=route.from_warehouse, lot_no=r.lot_no or "")
if stock_row is None:
r.status = BLOCKED; r.result_code = RESULT_INVENTORY_NOT_FOUND
r.result_message = "external inventory not found"
r.external_quantity = "0"; r.unit = ""
else:
stock_unit = (stock_row.stock_unit or "").strip()
if not stock_unit: # ERP 契约恒非空;出现即 ERP 数据异常,行级阻断
r.status = BLOCKED; r.result_code = RESULT_MISSING_UNIT
r.result_message = "external inventory unit is missing"
r.external_quantity = str(stock_row.quantity); r.unit = ""
else:
match = classify_quantity_match(Decimal(r.receipt_quantity), stock_row.quantity)
r.external_quantity = str(stock_row.quantity); r.unit = stock_unit
r.status = (READY if match == RESULT_EXECUTABLE else BLOCKED)
r.result_code = None if match == RESULT_EXECUTABLE else match
r.result_message = "" if match == RESULT_EXECUTABLE else "strict quantity mismatch"
r.updated_at = now
output.append(_item_dto(r, file_snapshot.get(r.source_code) or {}, now, int(deps.strategy.confirm_ttl_seconds)))
return output, pending_count
```
(executor 落码时把 `BLOCKED/READY` 换成 `status_machine.TransferStatus.*.value` 全名;`_org_of` 不要实现——按注释用 (row, route) 二元组分组的正确写法;常量 `RESULT_MISSING_UNIT` 沿用模块既有定义;`_SYNC_TERMINAL_STATUSES` 即 evidence_sync 的终态集合,从 evidence_sync import 或本模块已有 `_terminal_item_statuses` 复用。)
- [x] **Step 3: create_matching 清理**
`create_matching`:删除「文件准备→解析→聚合→过滤」段(run_matching 已不解析);删除 upsert-by-quad 段与「消失行标记」段(归属 evidence_sync);保留 TransferRun/SourceJob/TransferMatching 落库与 hash 留痕——其中 items 快照改为从 `_matching_rows` 处理后的行投影组装(形状保持既有键:source_code/invoice_no/from_warehouse/to_warehouse/receipt_quantity/external_quantity/result,Hash 形状变化安全:hash 已是纯留痕不拦执行)。`ensure_receipt_file_ready` 的调用只保留在 run_matching 缺文件分支(见 Step 2)。
- [x] **Step 4: counts 口径更新**
`run_matching` 尾部 counts 计算(`pending_stock_check_count` 直接消费 `_matching_rows` 返回值;`invalid_count` 用同口径的排除前计数——实现建议:在 `_matching_rows` 内对 scope 全量行先数 `result_code == RESULT_FILE_REMOVED` 的行数并一并返回,或在此处按同 filter 补一条 count 查询):
```python
invalid_count = TransferInvoiceItem.query.filter(
TransferInvoiceItem.source_code.in_(source_codes),
TransferInvoiceItem.result_code == RESULT_FILE_REMOVED,
*([] if not (receipt_date_from or receipt_date_to) else [
*( [TransferInvoiceItem.receipt_date >= str(receipt_date_from)] if receipt_date_from else [] ),
*( [TransferInvoiceItem.receipt_date <= str(receipt_date_to)] if receipt_date_to else [] ),
]),
).count()
counts = MatchingCountsDTO(
file_invoice_count=..., not_matured_count=..., matched_count=...,
executable_count=..., blocked_count=...,
pending_stock_check_count=pending_stock_check_count,
invalid_count=invalid_count,
)
```
`restore_matching` 的 counts 同口径(它已按 scope 圈行,内存补两个桶:pending=status matching 且 result_code=pending_stock_check;invalid=result_code=blocked_file_removed;file_removed 行继续从 items 输出中排除)。
- [x] **Step 5: 存量测试迁移(使匹配全量重新全绿)**
新增测试助手(放 `tests/services/in_transit_transfer/repo_fakes.py` 或 conftest):
```python
def seed_rows_from_file(source_code, deps, business_date, now=None):
"""把测试文件夹具落成待办行(迁移期桥接:旧「给文件→匹配」夹具的等价物)。"""
from app.services.in_transit_transfer.evidence_sync import sync_source_rows
return sync_source_rows(source_code=source_code, deps=deps,
business_date=business_date, now=now or datetime.utcnow())
```
逐文件迁移(顺序执行,每文件迁完跑该文件确认绿):
1. `tests/services/in_transit_transfer/test_matching_service.py` —— 「dbs_ready_file + run_matching」用例:`run_matching` 前插 `seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")`;断言不变(行字段语义一致)。
2. `tests/services/in_transit_transfer/test_query_inventory_gateway.py` —— 同上加 seed;`test_not_matured_not_queried` 夹具同日收料行改由 seed 后构造(receipt_date=业务日当天)。
3. `tests/services/in_transit_transfer/test_execute_items.py`、`test_orchestrator.py`、`test_backlog_service.py`、`test_matching_inplace.py`、`test_batch_actions.py`、`tests/api/test_in_transit_transfer_api.py`、`tests/jobs/test_in_transit_transfer_jobs.py`、`tests/performance/test_in_transit_transfer.py` —— 同模式:凡「文件夹具直接进 run_matching/create_matching」的用例,前进 seed;`create_matching` 用例断言计数键补默认 0(新字段有默认值,通常无需改)。
4. `tests/services/in_transit_transfer/test_matching_inplace.py` —— 原地刷新语义用例改走 evidence_sync(sync 两次、第二次换文件内容验证 reset_pending),原「匹配原地刷新」断言意图保留在对 sync 的断言上。
- [x] **Step 6: 全量回归**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer tests/services/integration_connector tests/api/test_in_transit_transfer_api.py tests/jobs/test_in_transit_transfer_jobs.py -q`
Expected: 全部 PASS。
- [x] **Step 7: 暂存**
```bash
git add backend/app/services/in_transit_transfer/matching_service.py backend/app/services/in_transit_transfer/contracts.py backend/app/services/in_transit_transfer/serializers.py backend/tests/services/in_transit_transfer/
```
---
### Task 5: 重查前置兜底对齐
**Files:**
- Modify: `backend/app/services/in_transit_transfer/retry_service.py`(`requery_items` / `requery_items_by_ids` 开头)
- Test: `backend/tests/services/in_transit_transfer/test_requery_scope.py`(追加)
**Interfaces:**
- Consumes: Task 2 `align_scope_rows`。
- Produces: 重查/恢复处理动作前置对齐语义(待处理异常后门封死)。
- [x] **Step 1: 写失败测试**
`test_requery_scope.py` 追加:
```python
def test_requery_aligns_stale_source_first(app, dbs_ready_file, monkeypatch):
# [断言意图] 行 sha 落后于最新文件时,重查第一步先对齐(兜底语义)。
called = {}
from app.services.in_transit_transfer import evidence_sync
def _fake_align(**kwargs):
called["sources"] = kwargs.get("source_codes")
return {code: None for code in kwargs.get("source_codes") or []}
monkeypatch.setattr(evidence_sync, "align_scope_rows", _fake_align)
monkeypatch.setattr(
"app.services.in_transit_transfer.retry_service.align_scope_rows", _fake_align)
_, matching = _seed(["CRANE"], "2026-09-25", "MTG-D")
deps, _, _ = make_transfer_deps(None)
requery_items(matching_no=matching.matching_no, deps=deps, invoice_nos=None, actor_id="1")
assert called.get("sources") == ["CRANE"] # [断言意图] 兜底对齐被前置调用
```
- [x] **Step 2: 运行确认失败**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_requery_scope.py::test_requery_aligns_stale_source_first -q`
Expected: FAIL(重查未调用对齐)。
- [x] **Step 3: 实现**
`retry_service.py`:`requery_items` 与 `requery_items_by_ids` 函数体开头追加(import `align_scope_rows` 置顶):
```python
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
align_scope_rows(source_codes=sorted({code for code in _affected_sources(...)}),
deps=deps, business_date=str(business_date_now()), now=datetime.utcnow())
```
实现说明:`requery_items` 受影响来源 = matching.scope_json 的 source_codes;`requery_items_by_ids` 受影响来源 = 按 item_ids 查回行的 `source_code` 去重(先查行再对齐再重查)。
- [x] **Step 4: 运行确认通过 + 暂存**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_requery_scope.py tests/services/in_transit_transfer/test_batch_actions.py -q`
Expected: PASS。
```bash
git add backend/app/services/in_transit_transfer/retry_service.py backend/tests/services/in_transit_transfer/test_requery_scope.py
```
---
### Task 6: TTL 退役(执行门禁降为展示提示)
**Files:**
- Modify: `backend/app/services/in_transit_transfer/execution_service.py`(`_gated_items` 门禁② 约 154-166 行;`_recheck_gates` TTL 段 约 508-513 行)
- Modify: `backend/app/services/in_transit_transfer/strategy.py`(`confirm_ttl_seconds` docstring 语义)
- Test: `backend/tests/services/in_transit_transfer/`(删除/改写 stale 拒绝用例)
**Interfaces:**
- Consumes: 无。
- Produces: `TRANSFER.ITEMS_STALE` 错误码退役;`_gated_items` 只剩「存在且可执行 + 文件版本对账」两道门禁。
- [x] **Step 1: 定位并删除 stale 拒绝用例**
Run: `cd backend && grep -rn "ITEMS_STALE\|items_stale\|stale" tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py --include="*.py" -l`
对每个命中文件:删除「构造超 TTL 行 → 断言 400 ITEMS_STALE」类用例;`_recheck_gates` 的 stale 分支用例改写为「文件对账仍拦截」(保留 file_changed 语义)。
- [x] **Step 2: 删除门禁②与 worker TTL 复核**
`_gated_items` 删除 `[门禁②]` 段(154-166 行)与 docstring 中②的描述(①③重编号为①②);`_recheck_gates` 删除 `ttl_seconds/now/for item ... items_stale` 段(508-513 行),docstring 同步(「新鲜度 + 文件 Hash」→「文件 Hash」)。
`strategy.py` `confirm_ttl_seconds` 字段注释改为:
```python
# 纯展示阈值:行 stale 徽标(「库存数据已过期,请重查」提示)的判定窗口;
# 不再作为执行门禁(2026-09-25 退役)——防错由文件版本对账 + worker 写前
# 库存复查承担(见 execution_service)。
```
- [x] **Step 3: 全量回归 + 暂存**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py -q`
Expected: PASS。
```bash
git add backend/app/services/in_transit_transfer/execution_service.py backend/app/services/in_transit_transfer/strategy.py backend/tests/services/in_transit_transfer/
```
---
### Task 7: worker 写前库存复查(仅全量重跑路径)
**Files:**
- Modify: `backend/app/services/in_transit_transfer/execution_service.py`(`_execute_document` 约 552 行起;新增 `_recheck_stock_for_document`)
- Test: `backend/tests/services/in_transit_transfer/test_execute_items.py`(或新建 `test_write_recheck.py`)
**Interfaces:**
- Consumes: 契约 v2 `deps.capabilities.query_stock` / `stock.lookup_row`;`quantity.classify_quantity_match`。
- Produces: `_recheck_stock_for_document(items, *, deps, request_id) -> list[TransferInvoiceItem]`(返回可继续建单的行;漂移/查无行已原位刷新为最新事实并置 blocked)。
- [x] **Step 1: 写失败测试**
```python
def test_write_recheck_blocks_drifted_rows_before_erp_write(app, dbs_ready_file, monkeypatch):
# [断言意图] 提交后库存被移走:worker 复查发现漂移 → 行阻断带最新数量、票失败、不写 ERP。
# 编排:seed 行 + 匹配(库存 1200)→ 篡改 FakeErp 库存为 5 → execute run。
...
def test_write_recheck_passes_when_stock_unchanged(app, dbs_ready_file):
# [断言意图] 库存未变:复查直通,照常建单成功(不增加额外阻断)。
...
```
(executor 按 `test_execute_items.py` 既有编排补全代码:复用其 `_INVOICE_TUPLES`/seed/matching/execute 既有路径,中途改 `erp.seed_stock(...)` 制造漂移;断言 `doc.status=="business_failed"`、行 `result_code=="blocked_quantity_mismatch"` 且 `external_quantity=="5"`、FakeErp 无 create 调用。)
- [x] **Step 2: 运行确认失败**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_write_recheck.py -q`
Expected: 漂移用例 FAIL(现状照常写 ERP 成功)。
- [x] **Step 3: 实现**
`execution_service.py` 新增:
```python
def _recheck_stock_for_document(items, *, deps, request_id):
"""写前库存复查(仅全量重跑路径):按组织批量重查一次,漂移/查无行原位
刷新为最新事实并移出本票(fail-closed 不写 ERP)。
result_unknown/executing 续跑(final_only=True)不复查——票可能已建成,
D7② 只触发末步,任何阻断都可能制造假失败。
"""
grouped: dict[str, list[tuple]] = {}
for item in items:
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "")
grouped.setdefault(route.external_org, []).append((item, route))
kept: list = []
for external_org, entries in grouped.items():
targets = [StockTarget(material_no=i.material_no, warehouse_code=r.from_warehouse,
lot_no=i.lot_no or "") for i, r in entries]
try:
stock = deps.capabilities.query_stock(
operation_id=f"op-{uuid.uuid4().hex[:12]}", external_org=external_org, targets=targets)
except Exception: # noqa: BLE001 —— 复查自身失败不额外造失败:交给写路径既有语义
kept.extend(i for i, _ in entries)
continue
for item, route in entries:
row = stock.lookup_row(material_no=item.material_no,
warehouse_code=route.from_warehouse, lot_no=item.lot_no or "")
if row is None:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found"
item.result_message = "external inventory not found (write recheck)"
item.external_quantity = "0"
continue
if classify_quantity_match(Decimal(item.receipt_quantity), row.quantity) != RESULT_EXECUTABLE:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_quantity_mismatch"
item.result_message = "strict quantity mismatch (write recheck)"
item.external_quantity = str(row.quantity)
continue
item.external_quantity = str(row.quantity) # 刷新为最新账面
kept.append(item)
return kept
```
`_execute_document` 接线:把 STEP 2 的 `final_only` 判定**上移到 STEP 1 之后**(纯读 doc.status,不改状态),STEP 1 路由漂移过滤之后追加:
```python
if not final_only:
active = _recheck_stock_for_document(active, deps=deps, request_id=request_id)
db.session.flush()
if not active:
doc.status = "business_failed"
doc.error_code = "stock_drifted"
doc.error_message = "all ticket rows drifted from current stock (write recheck)"
db.session.flush()
return
```
顶部补 `StockTarget` / `classify_quantity_match` / `Decimal` / `uuid` import(按文件既有 import 风格)。
- [x] **Step 4: 运行确认通过 + 全量回归 + 暂存**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer tests/jobs/test_in_transit_transfer_jobs.py -q`
Expected: PASS。
```bash
git add backend/app/services/in_transit_transfer/execution_service.py backend/tests/services/in_transit_transfer/
```
---
### Task 8: 失效行拒绝重查(单行路径兜底)
**Files:**
- Modify: `backend/app/services/in_transit_transfer/retry_service.py`(`retry_item` 状态校验后)
- Test: `backend/tests/services/in_transit_transfer/test_requery_scope.py`(追加)
- [x] **Step 1: 写失败测试**
```python
def test_retry_item_rejects_file_removed_row(app):
# [断言意图] batch-requery 按直取 id 的路径同样拦不住消失行 → 单行入口必须拒绝。
from app.core.errors import ValidationError
from app.services.in_transit_transfer.retry_service import retry_item
_, matching = _seed(["CRANE"], "2026-09-25", "MTG-E")
row = _seed_row(matching, "HOX-RM2")
row.result_code = "blocked_file_removed"
db.session.flush()
deps, _, _ = make_transfer_deps(None)
with pytest.raises(ValidationError) as exc:
retry_item(item_id=row.id, deps=deps, kind="external_recheck")
assert exc.value.code == "TRANSFER.RETRY_NOT_ALLOWED" # [断言意图] 消失行不可重查
```
- [x] **Step 2: 运行确认失败 → Step 3: 实现**
`retry_item` 在 `if item.status not in _RETRYABLE_STATUSES:` 校验后追加:
```python
if item.result_code == "blocked_file_removed":
raise ValidationError("removed rows cannot be requeried; close or wait for re-sync",
code="TRANSFER.RETRY_NOT_ALLOWED")
```
- [x] **Step 4: 运行确认通过 + 暂存**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_requery_scope.py -q`
```bash
git add backend/app/services/in_transit_transfer/retry_service.py backend/tests/services/in_transit_transfer/test_requery_scope.py
```
---
### Task 9: 前端卡片 + 类型 + 四语言
**Files:**
- Modify: `frontend/src/features/chat/types/transfer.types.ts`(`TransferMatchingCounts`)
- Modify: `frontend/src/features/chat/components/messages/TransferMatchCard.vue`
- Modify: `frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue`
- Modify: `frontend/src/locales/zh-CN/chat.json`、`zh-TW/chat.json`、`en/chat.json`、`th/chat.json`
- Test: `frontend/src/features/chat/components/messages/transferCards.spec.ts`
**Interfaces:**
- Consumes: 后端 counts 新字段 `pending_stock_check_count` / `invalid_count`;行 `result='pending_stock_check'`。
- Produces: 展示层四语言契约键:`chat.transfer.resultPendingStockCheck`、`chat.transfer.invalidRowCount`;`chat.transfer.fileChangedRow` 文案变更。
- [x] **Step 1: types 扩展**
`transfer.types.ts` `TransferMatchingCounts` 增:
```ts
/** 文件已落地、尚未查 ERP 库存的待查行数 */
pending_stock_check_count?: number;
/** 文件消失已出清的失效行数(不进默认视图) */
invalid_count?: number;
```
- [x] **Step 2: TransferMatchCard**
计数卡(`transfer-match-counts` grid)在「预计 ERP 单据」后追加两格:
```html
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-secondary">{{ summary.counts.pending_stock_check_count ?? 0 }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.pendingStockCheckCount') }}</div>
</div>
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-muted">{{ summary.counts.invalid_count ?? 0 }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.invalidRowCount') }}</div>
</div>
```
(`grid-cols-2 sm:grid-cols-5` → `sm:grid-cols-7`。)
`resultLabel` map 加 `'pending_stock_check': 'chat.transfer.resultPendingStockCheck'`;徽标 class 给 pending 加 amber 分支(与 not_matured 同色系)。
- [x] **Step 3: TransferBacklogSummaryCard**
行操作按钮:`v-if="item.result_code === 'blocked_file_removed'"` 时隐藏「重查」、仅留「标记无需继续处理」(按该组件现有按钮结构改条件渲染)。
- [x] **Step 4: i18n 四语言**
`locales/zh-CN/chat.json` transfer 段:
```json
"resultPendingStockCheck": "待查库存",
"pendingStockCheckCount": "待查库存",
"invalidRowCount": "已失效 {count} 行",
"fileChangedRow": "文件已更新,将自动对齐",
```
`zh-TW`:`待查庫存` / `待查庫存` / `已失效 {count} 行` / `檔案已更新,將自動對齊`;`en`:`Pending stock check` / `Pending stock check` / `{count} invalid rows` / `File updated; data will realign`;`th`:`รอตรวจสอบสต๊อก` / `รอตรวจสอบสต๊อก` / `{count} แถวหมดอายุ` / `ไฟล์อัปเดตแล้ว ข้อมูลจะจัดตำแหน่งใหม่อัตโนมัติ`。同时**删除** `toastExecuteStale`(四语言)并全库 grep 确认无引用残留。
- [x] **Step 5: vitest 契约测试**
`transferCards.spec.ts`:counts 新字段渲染断言 + pending 徽标文案断言(按该 spec 既有挂载/断言模式补两个用例)。
Run: `cd frontend && npx vitest run src/features/chat/components/messages/transferCards.spec.ts`
Expected: PASS。
Run: `cd frontend && npm run build`
Expected: build 通过。
- [x] **Step 6: 暂存**
```bash
git add frontend/src/features/chat frontend/src/locales
```
---
### Task 10: 文档固化 + 全量回归收口
**Files:**
- Modify: `docs/features/in-transit-transfer/technical.md`(新增管道章节)
- Modify: `docs/funclist.md`(行为描述核对)
- Modify: `docs/superpowers/plans/`(本文件勾选收尾)
- [x] **Step 1: technical.md 新章节「三层管道与门禁(2026-09-25 定稿)」**
内容要点(写入 §6.2 之后):
1. **证据轴**:文件落地(收料回调桥 `_sync_transfer_evidence`)→ `evidence_sync.sync_source_rows` 三分类写入(新行=待查 `matching`+`pending_stock_check`;刷新;消失=`blocked_file_removed` 出清)。匹配/重查动作前置 `align_scope_rows` 兜底(sha 一致直通)。桥模式:try/except 仅日志 + 自行 commit,收料主链路零依赖。
2. **账面轴**:匹配=按组织批量查库存+数量比对;worker 写前库存复查(仅全量重跑;final_only 不复查);「库存数据已过期」为纯展示提示(`confirm_ttl_seconds` 仅作提示阈值)。
3. **门禁终态**:执行=存在可执行 + 文件版本对账(fail-closed)+ worker 写前复查;`TRANSFER.ITEMS_STALE` 退役。
4. 待查行契约:`status='matching'` + `result_code='pending_stock_check'`(13 状态冻结内);`matching_id` 放开非空(迁移 `tt1a2b3c4d5e6f`),同步行应用层四元组幂等。
5. RPA 回调模块独立化建议(缓办另立项)。
- [x] **Step 2: funclist 核对**(调拨条目行为描述与三层管道一致;无新功能项则仅校对措辞)。
- [x] **Step 3: 全量回归**
```bash
cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer tests/services/integration_connector tests/api/test_in_transit_transfer_api.py tests/jobs/test_in_transit_transfer_jobs.py -q
cd frontend && npx vitest run src/features/chat && npm run build
```
Expected: 全绿。冒烟清单(手动):匹配→清单出现待查/可执行;RPA 重试落地后行自动刷新;勾选可执行生成调拨单成功;库存漂移时执行票 business_failed 且行带最新数量。
- [x] **Step 4: 暂存**
```bash
git add docs/features/in-transit-transfer/technical.md docs/funclist.md docs/superpowers/plans/2026-09-25-transfer-evidence-sync.md
```
---
## 任务依赖与顺序
Task 1(独立)→ Task 2 → Task 3 → Task 4 → Task 5 → Task 6 → Task 7 → Task 8 → Task 9 → Task 10。Task 1 可与 Task 2 并行;Task 9 依赖 Task 4 的 counts 字段;Task 10 收尾。