外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。 Co-authored-by: Cursor <cursoragent@cursor.com>
572 lines
31 KiB
Markdown
572 lines
31 KiB
Markdown
# 当前归档重新解析 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:** 来源卡展开的当前证据文件可以本地重新解析并幂等落档,不触发 RPA。
|
||
|
||
**Architecture:** 新服务 `reparse_current_file` 自己找出站或入站的最新可用归档,然后调用已经存在的 `sync_outbound_source_rows` / `sync_source_rows`(它们只 flush)。结构错误沿用现有 `mark_*_parse_failure`。HTTP 层只做鉴权、参数和 envelope。前端按钮只画在清单第一行,请求体不带 `file_id`。
|
||
|
||
**Tech Stack:** Flask、SQLAlchemy 2.0、Vue 3、Vitest、pytest。后端测试在 `backend/`,Python 用 `backend/.venv/Scripts/python.exe`。前端测试在 `frontend/`,用 `npx vitest run`。
|
||
|
||
**Spec:** `docs/superpowers/specs/2026-10-21-transfer-current-file-reparse-design.md`
|
||
|
||
## Global Constraints
|
||
|
||
- 入站和出站各自有「重新解析」。当天该流已有可用归档时可以点,状态是就绪或解析失败都可以。
|
||
- 只解析该流当前最新一份可用归档(`created_at`、`id` 倒序第一条,与 `latest_usable_*_file` 相同),并幂等写入异动档。不写 RPA trigger。
|
||
- 请求不接受 `file_id`。服务端自己取最新一份,避免清单过期时重放历史文件。
|
||
- 同一份文件再解析一次:摘要未变则跳过已有档行,不另插一行。
|
||
- 没有可用归档:422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。
|
||
- 有归档但没有已发布的对应 purpose 规则:422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`。不把文件标成解析失败。规则缺失不是文件错误。
|
||
- 结构校验失败(`MovementFileSchemaError`):回滚档行,把 `parse_failed` 写到当前文件,HTTP 200,`ok: false`,`file_status: parse_failed`,带 `error_message`。
|
||
- 其他异常(数据库截断、连接失败):回滚,不标解析失败,HTTP 200,`ok: false`,`error_message` 为异常文本。文件状态保持原投影。
|
||
- 成功:HTTP 200,`ok: true`,返回 `inserted` / `updated` / `skipped` / `sealed_skipped` 和解析后的 `file_status`。审计沿用落档函数已有的 `TRANSFER_EVIDENCE_SYNCED`,不另造事件。
|
||
- `file_version` 只经 `movement_file_version`。本入口不自己拼版本戳。
|
||
- 展开清单后只有第一行显示「重新解析」。↻ 与 `POST /sources/{source_code}/retry-rpa` 不变。
|
||
- 不调用 `POST /backlog/pending-match/reparse`,不删除已有档行。
|
||
- 新增用户可见文案同时写入 `zh-CN` / `zh-TW` / `en` / `th`。新增 `error.code` 同步写入四份 `locales/*/errors.json`。
|
||
- 每个任务结束于 `git add`。不要在计划步骤里 `git commit`。
|
||
|
||
## File Structure
|
||
|
||
- `backend/app/services/in_transit_transfer/current_file_reparse.py`:取当前归档、调用既有落档函数、提交或回滚、返回计数。不触发 RPA,不拼 `file_version`。
|
||
- `backend/app/api/in_transit_transfer/__init__.py`:新增 `POST /sources/<source_code>/reparse`。不改 `retry-rpa`。
|
||
- `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`:服务行为。
|
||
- `backend/tests/api/test_in_transit_transfer_api.py`:无文件 422、无权限 403。
|
||
- `frontend/src/features/chat/api/transfer.api.ts` 与 `types/transfer.types.ts`:请求与响应类型。
|
||
- `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue`:第一行按钮。
|
||
- `frontend/src/features/chat/components/messages/TransferMessageView.vue`:成功后 `loadSources`。
|
||
- `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` 与 `errors.json`:按钮文案和两个错误码。
|
||
- `docs/features/in-transit-transfer/technical.md`、`docs/funclist.md`:登记入口。
|
||
|
||
---
|
||
|
||
### Task 1: 当前文件重解析服务
|
||
|
||
**Files:**
|
||
- Create: `backend/app/services/in_transit_transfer/current_file_reparse.py`
|
||
- Create: `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`
|
||
- Test: `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `sync_outbound_source_rows(*, source_code: str, now: datetime) -> SyncOutcome | None`;`sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None`;`latest_usable_outbound_file` / `latest_usable_inbound_file`;`mark_outbound_parse_failure` / `mark_inbound_parse_failure`;`resolve_source_file_status(*, source_code: str, record_kind: str) -> dict`;`MovementFileSchemaError`。
|
||
- Produces: `reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult`。`CurrentReparseResult` 字段:`source_code: str`、`record_kind: str`、`ok: bool`、`file_status: str`、`file_id: int | None`、`inserted: int`、`updated: int`、`skipped: int`、`sealed_skipped: int`、`error_code: str | None`、`error_message: str | None`。
|
||
|
||
- [ ] **Step 1: Write the failing test**
|
||
|
||
新建 `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`。文件头写明用途是锁定「当前归档重解析、不触发 RPA」。导入 `pytest`、`datetime`、`AppError`、`TransferAuditEvent`、`TransferMovementLedger`、`FreightRpaOutboundReportFile`、`FreightRpaOutboundUnitRun`、`reparse_current_file`、`movement_file_version`、`factories`。把 `test_outbound_evidence_sync.py` 里的 `outbound_storage` fixture 和 `_seed_outbound_world` 抄进来,来源仍用全局种子 `DSV360_AWSDU`,`created_at` 用 `datetime.utcnow()`,否则当天可用门禁会把文件看成过期。`pytestmark = [pytest.mark.usefixtures("app")]`。
|
||
|
||
```python
|
||
def test_reparse_outbound_inserts_ledger_without_new_rpa_run(outbound_storage):
|
||
# [断言意图] 已落地出站文件重解析后出现 outbound 档行,且不新增出站执行单元。
|
||
report = _seed_outbound_world()
|
||
runs_before = FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count()
|
||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||
])
|
||
|
||
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||
|
||
assert result.ok is True
|
||
assert result.file_id == report.id
|
||
assert result.inserted == 1
|
||
assert result.file_status == "ready"
|
||
assert TransferMovementLedger.query.filter_by(
|
||
source_code=SOURCE, record_kind="outbound", doc_no="ASN-O1").count() == 1
|
||
assert FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count() == runs_before
|
||
assert TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").count() == 1
|
||
|
||
|
||
def test_reparse_same_outbound_file_skips_existing_row(outbound_storage):
|
||
# [断言意图] 同一份摘要再解析一次不插入第二行。
|
||
_seed_outbound_world()
|
||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||
])
|
||
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||
|
||
again = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||
|
||
assert again.ok is True
|
||
assert again.inserted == 0
|
||
assert again.skipped == 1
|
||
assert TransferMovementLedger.query.filter_by(
|
||
source_code=SOURCE, record_kind="outbound").count() == 1
|
||
|
||
|
||
def test_reparse_schema_failure_marks_file_and_lands_nothing(outbound_storage):
|
||
# [断言意图] 单号缺失是结构失败:零档行,文件变为 parse_failed,响应带原因。
|
||
report = _seed_outbound_world()
|
||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx(
|
||
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
|
||
|
||
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||
|
||
assert result.ok is False
|
||
assert result.file_status == "parse_failed"
|
||
assert result.inserted == 0
|
||
assert "missing_invoice_no" in (result.error_message or "")
|
||
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
|
||
assert marked.parse_failed_at is not None
|
||
assert TransferMovementLedger.query.filter_by(
|
||
source_code=SOURCE, record_kind="outbound").count() == 0
|
||
|
||
|
||
def test_reparse_without_published_profile_does_not_mark_parse_failed(outbound_storage):
|
||
# [断言意图] 规则未发布不是文件错误,不写 parse_failed。
|
||
report = _seed_outbound_world(profile_status="draft")
|
||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||
])
|
||
|
||
with pytest.raises(AppError) as exc_info:
|
||
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||
|
||
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE"
|
||
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
|
||
assert marked.parse_failed_at is None
|
||
|
||
|
||
def test_reparse_without_file_raises():
|
||
# [断言意图] 没有可用归档时拒绝,而不是去触发 RPA。
|
||
with pytest.raises(AppError) as exc_info:
|
||
reparse_current_file(
|
||
source_code="DSV360_AWSDU", record_kind="outbound", now=datetime.utcnow())
|
||
|
||
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_FILE"
|
||
assert exc_info.value.http_status == 422
|
||
|
||
|
||
def test_reparse_non_schema_error_does_not_mark_parse_failed(outbound_storage, monkeypatch):
|
||
# [断言意图] 数据库一类异常回滚后不把文件标成解析失败,并把异常文本带回。
|
||
report = _seed_outbound_world()
|
||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||
])
|
||
|
||
def _boom(**_kwargs):
|
||
raise RuntimeError("value too long for varchar(64)")
|
||
|
||
monkeypatch.setattr(
|
||
"app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows",
|
||
_boom,
|
||
)
|
||
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||
|
||
assert result.ok is False
|
||
assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED"
|
||
assert "varchar(64)" in (result.error_message or "")
|
||
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
|
||
assert marked.parse_failed_at is None
|
||
assert TransferMovementLedger.query.filter_by(
|
||
source_code=SOURCE, record_kind="outbound").count() == 0
|
||
```
|
||
|
||
`_seed_outbound_world` 增加可选参数 `profile_status: str = "published"`,传给 `FreightRpaParsingProfile.status`。入站成功路径用下面这个测试,归档时间同样取 `datetime.utcnow()`:
|
||
|
||
```python
|
||
def test_reparse_inbound_inserts_ledger(archive_storage):
|
||
# [断言意图] 入站当前文件走 sync_source_rows,record_kind 为 inbound。
|
||
source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_NOW")
|
||
storage_key = "archive/CRANE_REPARSE_NOW/current.xlsx"
|
||
report = factories.seed_reparse_archive_file(
|
||
source, sha="c" * 64, storage_key=storage_key, created_at=datetime.utcnow())
|
||
archive_storage.objects[storage_key] = factories.build_movement_xlsx([
|
||
["ASN-I1", "1", "I", "MAT-I1", "连接器", "LOT-I1", 10, "2026-08-05"],
|
||
])
|
||
|
||
result = reparse_current_file(
|
||
source_code="CRANE_REPARSE_NOW", record_kind="inbound", now=datetime.utcnow())
|
||
|
||
assert result.ok is True
|
||
assert result.file_id == report.id
|
||
assert result.inserted == 1
|
||
row = TransferMovementLedger.query.filter_by(
|
||
source_code="CRANE_REPARSE_NOW", record_kind="inbound").one()
|
||
assert row.doc_no == "ASN-I1"
|
||
assert row.file_version == movement_file_version("c" * 64)
|
||
```
|
||
|
||
`archive_storage` fixture 与 `test_backlog_reparse_service.py` 相同:替换 `file_asset_storage.get_bytes`。
|
||
|
||
- [ ] **Step 2: Run test to verify it fails**
|
||
|
||
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_current_file_reparse.py -q`
|
||
|
||
Expected: FAIL,`reparse_current_file` 无法导入。
|
||
|
||
- [ ] **Step 3: Write minimal implementation**
|
||
|
||
新建 `backend/app/services/in_transit_transfer/current_file_reparse.py`。文件头写明:用途是对当前可用归档做一次本地重解析;依赖 `evidence_sync.sync_source_rows`、`outbound_evidence_sync.sync_outbound_source_rows`、`source_file_status`、`freight_rpa.reports.queries` 的 mark/latest 函数;逻辑是先确认文件和已发布规则,再落档并提交,失败按规格回滚。
|
||
|
||
```python
|
||
@dataclass(frozen=True)
|
||
class CurrentReparseResult:
|
||
"""一次当前归档重解析的返回。"""
|
||
|
||
source_code: str
|
||
record_kind: str
|
||
ok: bool
|
||
file_status: str
|
||
file_id: int | None
|
||
inserted: int = 0
|
||
updated: int = 0
|
||
skipped: int = 0
|
||
sealed_skipped: int = 0
|
||
error_code: str | None = None
|
||
error_message: str | None = None
|
||
|
||
|
||
def reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult:
|
||
"""重解析该来源当前最新可用归档并提交。
|
||
|
||
核心逻辑:先取 latest usable 文件。没有文件抛 CURRENT_REPARSE_NO_FILE。
|
||
有文件则调用既有 sync_*_source_rows。返回 None 表示没有已发布规则,抛
|
||
CURRENT_REPARSE_NO_PROFILE,不写 parse_failed。结构错误回滚后 mark_*_parse_failure
|
||
并单独提交。其他异常只回滚,不标解析失败。成功路径由 sync 函数里的
|
||
movement_file_version 写版本戳,本函数不拼 sha256: 前缀。
|
||
|
||
Args:
|
||
source_code: 来源实例编码。
|
||
record_kind: inbound 或 outbound。
|
||
now: 落档与新鲜度判定时刻。
|
||
Returns:
|
||
CurrentReparseResult。结构错误和其他落档异常时 ok 为 False。
|
||
Raises:
|
||
ValidationError: record_kind 不是 inbound 或 outbound。
|
||
AppError: TRANSFER.CURRENT_REPARSE_NO_FILE 或 TRANSFER.CURRENT_REPARSE_NO_PROFILE,HTTP 422。
|
||
"""
|
||
```
|
||
|
||
函数体按这个顺序写:
|
||
|
||
1. `kind = record_kind.strip()`。不在 `{"inbound", "outbound"}` 时 `raise ValidationError("record_kind must be inbound or outbound")`。
|
||
2. 出站用 `latest_usable_outbound_file(source_code, now=now)`,入站用 `latest_usable_inbound_file(source_code, now=now)`。结果是 `None` 时抛 `AppError(code="TRANSFER.CURRENT_REPARSE_NO_FILE", message="no usable archive file", http_status=422, details={"source_code": source_code, "record_kind": kind})`。
|
||
3. `try` 里调用落档。出站:`sync_outbound_source_rows(source_code=source_code, now=now)`。入站:`sync_source_rows(source_code=source_code, deps=get_transfer_dependencies(), business_date=business_date_now(), now=now)`。
|
||
4. 返回值是 `None`:抛 `AppError(code="TRANSFER.CURRENT_REPARSE_NO_PROFILE", message="no published parsing profile", http_status=422, details={"source_code": source_code, "record_kind": kind})`。此时还没有 commit。
|
||
5. `db.session.commit()`。再用 `resolve_source_file_status(source_code=source_code, record_kind=kind)` 填 `file_status`。返回 `ok=True` 和 outcome 的四个计数、`file_id=file_view.file_id`。
|
||
6. `except MovementFileSchemaError as exc`:`db.session.rollback()`,然后 `mark_outbound_parse_failure` 或 `mark_inbound_parse_failure`。`error_message` 取 `getattr(exc, "message", "") or str(exc)` 后截到 2000 字符(`AppError` 的 `str()` 可能是空串,行级原因在 `message` 里,例如 `missing_invoice_no`)。`error_code=exc.code`。`db.session.commit()` 只提交失败标记。再投影状态,返回 `ok=False`、同样的 `error_code` / `error_message`、计数全 0。
|
||
7. `except AppError`:原样抛出(第 4 步的无规则错误不能被下面的通用分支吃掉)。
|
||
8. `except Exception as exc`:`db.session.rollback()`,不调用 mark。投影状态后返回 `ok=False`、`error_code="TRANSFER.CURRENT_REPARSE_FAILED"`、`error_message=str(exc)[:500]`、计数全 0。
|
||
|
||
`sync_outbound_source_rows` 和 `sync_source_rows` 必须是本模块的顶层 import。非结构异常测试打桩的是 `app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows`。不要 import `trigger_inbound_rpa` 或 `trigger_outbound_rpa`。
|
||
|
||
- [ ] **Step 4: Run test to verify it passes**
|
||
|
||
Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_current_file_reparse.py -q`
|
||
|
||
Expected: PASS。
|
||
|
||
- [ ] **Step 5: Stage changes**
|
||
|
||
```bash
|
||
git add backend/app/services/in_transit_transfer/current_file_reparse.py backend/tests/services/in_transit_transfer/test_current_file_reparse.py
|
||
```
|
||
|
||
---
|
||
|
||
### Task 2: HTTP 入口
|
||
|
||
**Files:**
|
||
- Modify: `backend/app/api/in_transit_transfer/__init__.py`(放在 `retry_source_rpa_api` 前面)
|
||
- Modify: `backend/tests/api/test_in_transit_transfer_api.py`
|
||
- Test: `backend/tests/api/test_in_transit_transfer_api.py`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult`
|
||
- Produces: `POST /api/in-transit-transfer/sources/<source_code>/reparse`。body `{"record_kind": "inbound"|"outbound"}`,缺省 `inbound`。成功 envelope 的 `data` 是 `CurrentReparseResult` 的字段。无文件、无规则由服务抛出的 `AppError` 变成 422。
|
||
|
||
- [ ] **Step 1: Write the failing test**
|
||
|
||
在 `test_in_transit_transfer_api.py` 增加:
|
||
|
||
```python
|
||
def test_reparse_current_without_file_returns_422(client, admin_headers):
|
||
# [断言意图] 没有出站归档时重解析是 422,不是 202 抓取中。
|
||
response = client.post(
|
||
f"{API_PREFIX}/sources/DSV360_AWSDU/reparse",
|
||
headers=admin_headers,
|
||
json={"record_kind": "outbound"},
|
||
)
|
||
assert response.status_code == 422
|
||
assert response.get_json()["error"]["code"] == "TRANSFER.CURRENT_REPARSE_NO_FILE"
|
||
|
||
|
||
def test_reparse_current_forbidden(client, unauthorized_headers):
|
||
# [断言意图] 无调拨权限不能重解析。
|
||
response = client.post(
|
||
f"{API_PREFIX}/sources/DSV360_AWSDU/reparse",
|
||
headers=unauthorized_headers,
|
||
json={"record_kind": "inbound"},
|
||
)
|
||
assert response.status_code == 403
|
||
```
|
||
|
||
使用该文件已有的 `admin_headers` 和 `unauthorized_headers`。
|
||
|
||
- [ ] **Step 2: Run test to verify it fails**
|
||
|
||
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py::test_reparse_current_without_file_returns_422 tests/api/test_in_transit_transfer_api.py::test_reparse_current_forbidden -q`
|
||
|
||
Expected: FAIL,路由 404。
|
||
|
||
- [ ] **Step 3: Write minimal implementation**
|
||
|
||
在 `retry_source_rpa_api` 之前增加路由。不要修改 `retry_source_rpa_api` 的函数体。
|
||
|
||
```python
|
||
@in_transit_transfer_bp.route("/sources/<source_code>/reparse", methods=["POST"])
|
||
@require_transfer_permission
|
||
def reparse_current_file_api(source_code: str):
|
||
"""重解析该来源当前最新可用归档,不触发 RPA。
|
||
|
||
body 只读 record_kind,缺省 inbound。不接受 file_id。
|
||
"""
|
||
from app.services.in_transit_transfer.current_file_reparse import reparse_current_file
|
||
|
||
payload = request.get_json(silent=True) or {}
|
||
if not isinstance(payload, dict):
|
||
raise ValidationError("request body must be a JSON object")
|
||
record_kind = str(payload.get("record_kind") or "inbound").strip() or "inbound"
|
||
result = reparse_current_file(
|
||
source_code=str(source_code).strip(),
|
||
record_kind=record_kind,
|
||
now=datetime.utcnow(),
|
||
)
|
||
return _ok({
|
||
"source_code": result.source_code,
|
||
"record_kind": result.record_kind,
|
||
"ok": result.ok,
|
||
"file_status": result.file_status,
|
||
"file_id": result.file_id,
|
||
"inserted": result.inserted,
|
||
"updated": result.updated,
|
||
"skipped": result.skipped,
|
||
"sealed_skipped": result.sealed_skipped,
|
||
"error_code": result.error_code,
|
||
"error_message": result.error_message,
|
||
})
|
||
```
|
||
|
||
更新该 API 模块文件头的路由说明,加上这条 POST。`datetime` 若文件顶部未导入,沿用文件里已有的导入方式(`retry_source_rpa_api` 已使用 `datetime.utcnow()`,不要重复导入)。
|
||
|
||
- [ ] **Step 4: Run test to verify it passes**
|
||
|
||
Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py::test_reparse_current_without_file_returns_422 tests/api/test_in_transit_transfer_api.py::test_reparse_current_forbidden tests/services/in_transit_transfer/test_current_file_reparse.py -q`
|
||
|
||
Expected: PASS。
|
||
|
||
- [ ] **Step 5: Stage changes**
|
||
|
||
```bash
|
||
git add backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_in_transit_transfer_api.py
|
||
```
|
||
|
||
---
|
||
|
||
### Task 3: 来源卡按钮与四语文案
|
||
|
||
**Files:**
|
||
- Modify: `frontend/src/features/chat/types/transfer.types.ts`
|
||
- Modify: `frontend/src/features/chat/api/transfer.api.ts`
|
||
- Modify: `frontend/src/features/chat/api/transfer.api.spec.ts`
|
||
- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue`
|
||
- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`
|
||
- Modify: `frontend/src/features/chat/components/messages/TransferMessageView.vue`
|
||
- Modify: `frontend/src/locales/zh-CN/chat.json`
|
||
- Modify: `frontend/src/locales/zh-TW/chat.json`
|
||
- Modify: `frontend/src/locales/en/chat.json`
|
||
- Modify: `frontend/src/locales/th/chat.json`
|
||
- Modify: `frontend/src/locales/zh-CN/errors.json`
|
||
- Modify: `frontend/src/locales/zh-TW/errors.json`
|
||
- Modify: `frontend/src/locales/en/errors.json`
|
||
- Modify: `frontend/src/locales/th/errors.json`
|
||
- Test: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`、`frontend/src/features/chat/api/transfer.api.spec.ts`
|
||
|
||
**Interfaces:**
|
||
- Consumes: `POST /api/in-transit-transfer/sources/{sourceCode}/reparse`
|
||
- Produces: `reparseCurrentFile(sourceCode: string, recordKind: TransferRecordKind): Promise<TransferCurrentReparseResult>`。`TransferCurrentReparseResult` 字段与 Task 2 的 `data` 相同。
|
||
|
||
- [ ] **Step 1: Write the failing test**
|
||
|
||
在 `transfer.api.spec.ts` 旁路现有 `retryTransferSourceRpa` 用例增加:
|
||
|
||
```typescript
|
||
it('当前文件重解析 POST reparse,body 只有 record_kind', () => {
|
||
reparseCurrentFile('DSV360_AWSDU', 'outbound');
|
||
const calls = vi.mocked(requestJson).mock.calls;
|
||
expect(calls[0][0]).toBe('/api/in-transit-transfer/sources/DSV360_AWSDU/reparse');
|
||
expect(JSON.parse(String((calls[0][1] as RequestInit).body))).toEqual({ record_kind: 'outbound' });
|
||
});
|
||
```
|
||
|
||
按该文件已有的 `requestJson` mock 写法调整 `calls` 的取法。断言 body 里没有 `file_id`。
|
||
|
||
在 `TransferSourceSelectCard.spec.ts` 顶部、组件 import 之前增加 mock:
|
||
|
||
```typescript
|
||
const transferApiMocks = vi.hoisted(() => ({
|
||
listEvidenceFiles: vi.fn(),
|
||
reparseCurrentFile: vi.fn(),
|
||
}));
|
||
vi.mock('../../api/transfer.api', () => transferApiMocks);
|
||
```
|
||
|
||
新增用例:
|
||
|
||
```typescript
|
||
it('只在清单第一行显示重新解析,点击不发出 retry', async () => {
|
||
transferApiMocks.listEvidenceFiles.mockResolvedValue([
|
||
{ file_id: 25, original_filename: 'current.xlsx', created_at: '2026-10-21T10:00:00', sha256: 'abc', file_size: 10, presigned_url: 'https://files.example/current' },
|
||
{ file_id: 9, original_filename: 'older.xlsx', created_at: '2026-10-20T10:00:00', sha256: 'def', file_size: 10, presigned_url: 'https://files.example/older' },
|
||
]);
|
||
transferApiMocks.reparseCurrentFile.mockResolvedValue({
|
||
source_code: 'DBS-AWSBI', record_kind: 'inbound', ok: true, file_status: 'ready',
|
||
file_id: 25, inserted: 2, updated: 0, skipped: 0, sealed_skipped: 0,
|
||
error_code: null, error_message: null,
|
||
});
|
||
const wrapper = mount(TransferSourceSelectCard, {
|
||
props: { sources: readySources, transferTypes: defaultTransferTypes },
|
||
global: { plugins: [i18n] },
|
||
});
|
||
await wrapper.find('[data-testid="transfer-source-status-DBS-AWSBI"]').trigger('click');
|
||
await flushPromises();
|
||
const buttons = wrapper.findAll('[data-testid="transfer-evidence-reparse-DBS-AWSBI-inbound"]');
|
||
expect(buttons).toHaveLength(1);
|
||
await buttons[0].trigger('click');
|
||
expect(transferApiMocks.reparseCurrentFile).toHaveBeenCalledWith('DBS-AWSBI', 'inbound');
|
||
expect(wrapper.emitted('retry')).toBeUndefined();
|
||
expect(wrapper.emitted('reparsed')).toBeTruthy();
|
||
});
|
||
```
|
||
|
||
`flushPromises` 用 `import { flushPromises } from '@vue/test-utils'`。若现有 mount 助手已经包了 props,沿用那个助手,不要另写一套来源数据。
|
||
|
||
- [ ] **Step 2: Run test to verify it fails**
|
||
|
||
Run: `npx vitest run src/features/chat/api/transfer.api.spec.ts src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`
|
||
|
||
工作目录:`frontend/`。
|
||
|
||
Expected: FAIL,`reparseCurrentFile` 不存在,按钮找不到。
|
||
|
||
- [ ] **Step 3: Write minimal implementation**
|
||
|
||
`transfer.types.ts` 在 `TransferEvidenceFile` 后增加:
|
||
|
||
```typescript
|
||
export interface TransferCurrentReparseResult {
|
||
source_code: string;
|
||
record_kind: TransferRecordKind;
|
||
ok: boolean;
|
||
file_status: TransferSourceFileStatus['file_status'];
|
||
file_id: number | null;
|
||
inserted: number;
|
||
updated: number;
|
||
skipped: number;
|
||
sealed_skipped: number;
|
||
error_code: string | null;
|
||
error_message: string | null;
|
||
}
|
||
```
|
||
|
||
`transfer.api.ts` 在 `listEvidenceFiles` 后增加 `reparseCurrentFile`。JSDoc 写明:只重放当前最新归档;body 只有 `record_kind`;不触发 RPA。
|
||
|
||
```typescript
|
||
export const reparseCurrentFile = (
|
||
sourceCode: string,
|
||
recordKind: TransferRecordKind,
|
||
) =>
|
||
requestJson<TransferCurrentReparseResult>(
|
||
`${BASE}/sources/${encodeURIComponent(sourceCode)}/reparse`,
|
||
{
|
||
method: 'POST',
|
||
headers: jsonHeaders(),
|
||
body: JSON.stringify({ record_kind: recordKind }),
|
||
},
|
||
);
|
||
```
|
||
|
||
`TransferSourceSelectCard.vue`:
|
||
|
||
- import 改为 `listEvidenceFiles, reparseCurrentFile`。
|
||
- `defineEmits` 增加 `reparsed: []`。
|
||
- 增加 `reparsingKey = ref<string | null>(null)`。
|
||
- 清单 `v-for` 改成 `(file, index) in evidenceFilesOf(...)`。
|
||
- 仅当 `index === 0` 时,在预览链接前放按钮:
|
||
|
||
```vue
|
||
<button
|
||
v-if="index === 0"
|
||
type="button"
|
||
class="font-bold text-brand-700 disabled:opacity-50"
|
||
:disabled="reparsingKey === evidenceKey(source.source_code, stream.record_kind)"
|
||
:data-testid="`transfer-evidence-reparse-${source.source_code}-${stream.record_kind}`"
|
||
@click="reparseEvidence(source.source_code, stream.record_kind)"
|
||
>{{ t('chat.transfer.reparseCurrentFile') }}</button>
|
||
```
|
||
|
||
`reparseEvidence` 的 JSDoc 写明:调用 `reparseCurrentFile`,不 emit `retry`。成功且 `ok` 时 `success` 提示新增/更新数,并重新 `listEvidenceFiles` 写回 `evidenceByKey`,然后 `emit('reparsed')`。`ok === false` 时 `notifyError` 显示 `error_message`,同样刷新清单和 `emit('reparsed')`,让解析失败状态回到芯片上。抛错时只 `notifyError`。
|
||
|
||
`TransferMessageView.vue` 的来源卡增加 `@reparsed="transfer.loadSources()"`。不要改 `onSourceRetry`。
|
||
|
||
四份 `chat.json` 的 `chat.transfer` 里,紧挨 `previewEvidence` 增加:
|
||
|
||
| key | zh-CN | zh-TW | en | th |
|
||
| --- | --- | --- | --- | --- |
|
||
| `reparseCurrentFile` | 重新解析 | 重新解析 | Reparse | แยกวิเคราะห์ซ้ำ |
|
||
| `reparseCurrentFileDone` | 已重新解析:新增 {inserted},更新 {updated} | 已重新解析:新增 {inserted},更新 {updated} | Reparsed: {inserted} inserted, {updated} updated | แยกวิเคราะห์ซ้ำแล้ว: เพิ่ม {inserted} อัปเดต {updated} |
|
||
|
||
四份 `errors.json` 的 `TRANSFER.*` 段增加:
|
||
|
||
| key | zh-CN | zh-TW | en | th |
|
||
| --- | --- | --- | --- | --- |
|
||
| `TRANSFER.CURRENT_REPARSE_NO_FILE` | 当前没有可重新解析的归档文件。 | 目前沒有可重新解析的歸檔檔案。 | No archived file is available to reparse. | ไม่มีไฟล์ที่เก็บถาวรให้แยกวิเคราะห์ซ้ำ |
|
||
| `TRANSFER.CURRENT_REPARSE_NO_PROFILE` | 当前证据流没有已发布的解析规则。 | 目前證據流沒有已發布的解析規則。 | This evidence stream has no published parsing profile. | สตรีมหลักฐานนี้ไม่มีโปรไฟล์การแยกวิเคราะห์ที่เผยแพร่แล้ว |
|
||
|
||
更新 `TransferSourceSelectCard.vue` 文件头依赖,写上 `reparseCurrentFile`。函数 `reparseEvidence` 上方按项目 JSDoc 写用途、参数、返回值。
|
||
|
||
- [ ] **Step 4: Run test to verify it passes**
|
||
|
||
Run: `npx vitest run src/features/chat/api/transfer.api.spec.ts src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`
|
||
|
||
工作目录:`frontend/`。
|
||
|
||
Expected: PASS。既有来源卡用例仍然通过。若 mock 替换了整个 `transfer.api` 导致其他用例缺导出,只补那些用例实际会调用的导出,不要改断言去迁就 mock。
|
||
|
||
- [ ] **Step 5: Stage changes**
|
||
|
||
```bash
|
||
git add frontend/src/features/chat/types/transfer.types.ts frontend/src/features/chat/api/transfer.api.ts frontend/src/features/chat/api/transfer.api.spec.ts frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts frontend/src/features/chat/components/messages/TransferMessageView.vue frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json frontend/src/locales/zh-CN/errors.json frontend/src/locales/zh-TW/errors.json frontend/src/locales/en/errors.json frontend/src/locales/th/errors.json
|
||
```
|
||
|
||
---
|
||
|
||
### Task 4: 文档
|
||
|
||
**Files:**
|
||
- Modify: `docs/features/in-transit-transfer/technical.md`(来源 API 表,约第 70 行 `retry-rpa` 那一行之后)
|
||
- Modify: `docs/funclist.md`(「来源重试合并触发与知情范围确认」那一行之后)
|
||
|
||
**Interfaces:**
|
||
- Consumes: Task 2 的路由和两个错误码。
|
||
- Produces: 文档与代码一致。无新代码。
|
||
|
||
- [ ] **Step 1: Update the API table**
|
||
|
||
在 `technical.md` 的来源路由表,`POST /sources/{source_code}/retry-rpa` 下一行增加:
|
||
|
||
`POST /sources/{source_code}/reparse`:重解析当前最新可用归档(body `record_kind`,缺省 inbound;不接受 file_id;不触发 RPA)。成功 200,`ok/file_status/file_id/inserted/updated/skipped/sealed_skipped`。无文件 422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。无已发布规则 422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`,不标 parse_failed。结构失败 200 `ok: false` 且文件为 `parse_failed`。其他异常 200 `ok: false`,不标 parse_failed。与待匹配 `POST /backlog/pending-match/reparse` 不是同一条链路。
|
||
|
||
- [ ] **Step 2: Update the feature list**
|
||
|
||
在 `funclist.md` 来源重试行后增加一行:
|
||
|
||
「当前归档重新解析(2026-10-21)」已实现。来源卡证据清单第一行「重新解析」调用 `POST /sources/{source_code}/reparse`,只重放该流入站或出站的最新可用归档并幂等落档,不触发 RPA,不删除档行。↻ 仍是重新抓取。待匹配「清空并重新解析」仍是整桶重建。
|
||
|
||
- [ ] **Step 3: Stage changes**
|
||
|
||
```bash
|
||
git add docs/features/in-transit-transfer/technical.md docs/funclist.md docs/superpowers/specs/2026-10-21-transfer-current-file-reparse-design.md docs/superpowers/plans/2026-10-21-transfer-current-file-reparse.md
|
||
```
|