Files
hugo 0cf3c24119 refactor(in-transit-transfer): 行归属解耦、按行执行三层门禁并重构术语为匹配
- 行不迁移:匹配记录降级为评估留痕(scope/counts/hash 留痕不拦执行),
  匹配/重查原地刷新行并续行级新鲜度(updated_at)
- 执行改按行:POST /items/execute 三层门禁(行级新鲜度 TTL/文件版本对账/写前复查),
  Run 留痕不绑匹配记录;消失行 blocked_file_removed fail-closed 入异常池
- 恢复处理收敛为行级重查(batch-resume 删除);待处理池补齐匹配窗口字段,
  排序改业务稳定键(收料日期→Invoice→created_at,操作不再引起跳位)
- 首页待办看板四队列:可调拨明细/待恢复异常/已人工关闭/结果未知;「最近预检」移除;
  收料日期默认 T-1 并加输入期限制;「重新查询 ERP」更名「重查」
- 术语重构 precheck→match:表 transfer_matchings、列 matching_id/matching_no/matching_hash、
  API /matchings、单号前缀 MTG、状态值 prechecking→matching(迁移 rn1a2b3c4d5e6,模块未上线无兼容层)
- 修复 integration_connector mapping 扇出嵌套丢行缺陷;对账结论:0 vs 30/40/36
  系收料仓库映射曾指向错误账套 TGHX(已改 TGHX1),探针留档 backend/tmp
- 测试:后端 in_transit_transfer+api+connector 393 passed;前端 chat 713 passed;build ✓
2026-09-24 00:24:03 +08:00

183 lines
6.1 KiB
Python
Raw Permalink 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.
"""在途调拨审计服务。
用途:构建只追加审计事件(TransferAuditEvent),对快照脱敏并计算
before/after Hash 与事件 Hash,保证 Phase 4 Hash 校验可复算。
依赖:app.models.TransferAuditEvent、标准库 hashlib/json。
逻辑:所有快照先 sanitize(剔除密码/Token/密钥),再参与 Hash;
event_hash 由事件自身稳定字段复算,不依赖对象内部状态。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Mapping
import hashlib
import json
from app.models import TransferAuditEvent
# 敏感字段片段:命中即从审计快照中剔除(Secret 永不进入审计/Hash/日志)。
AUDIT_FORBIDDEN_KEY_FRAGMENTS = (
"password", "secret", "token", "ciphertext", "credential",
"api_key", "apikey", "webhook", "authorization", "auth",
)
def is_forbidden_audit_key(key: str) -> bool:
"""判断键名是否命中敏感片段(大小写不敏感)。"""
lowered = str(key or "").lower()
return any(fragment in lowered for fragment in AUDIT_FORBIDDEN_KEY_FRAGMENTS)
def sanitize_snapshot(value: Any) -> Any:
"""递归剔除敏感键,返回可安全持久化的快照副本。
Args:
value: 原始快照(dict/list/标量)。
Returns:
脱敏后的副本。
"""
if isinstance(value, dict):
return {
str(key): sanitize_snapshot(item)
for key, item in value.items()
if not is_forbidden_audit_key(str(key))
}
if isinstance(value, (list, tuple)):
return [sanitize_snapshot(item) for item in value]
return value
def canonical_hash(value: Any) -> str:
"""对脱敏快照计算 SHA-256(键排序 + 紧凑 JSON)。
Args:
value: 任意 JSON 可序列化值。
Returns:
64 位十六进制 Hash。
"""
payload = json.dumps(
sanitize_snapshot(value),
ensure_ascii=True, sort_keys=True, separators=(",", ":"), default=str,
)
return hashlib.sha256(payload.encode("ascii")).hexdigest()
def snapshot_diff(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, Any]:
"""计算前后快照顶层差异。
Args:
before: 变更前快照。
after: 变更后快照。
Returns:
{"added": {...}, "removed": {...}, "changed": {key: (before, after)}}。
"""
before_keys = set(before)
after_keys = set(after)
return {
"added": {key: after[key] for key in sorted(after_keys - before_keys)},
"removed": {key: before[key] for key in sorted(before_keys - after_keys)},
"changed": {
key: (before[key], after[key])
for key in sorted(before_keys & after_keys)
if before[key] != after[key]
},
}
def _event_hash_inputs(event: TransferAuditEvent) -> dict[str, Any]:
"""事件 Hash 的稳定输入字段(含 created_at,保证复算一致)。"""
created = event.created_at or datetime.utcnow()
return {
"event_type": event.event_type,
"aggregate_type": event.aggregate_type,
"aggregate_id": event.aggregate_id,
"run_no": event.run_no,
"matching_no": event.matching_no,
"invoice_no": event.invoice_no,
"item_id": event.item_id,
"attempt_no": event.attempt_no,
"actor_type": event.actor_type,
"actor_id": event.actor_id,
"actor_role": event.actor_role,
"actor_display": event.actor_display,
"request_id": event.request_id,
"operation_id": event.operation_id,
"source": event.source,
"result": event.result,
"error_code": event.error_code,
"before_hash": event.before_hash,
"after_hash": event.after_hash,
"created_at": created.isoformat(),
}
def compute_event_hash(event: TransferAuditEvent) -> str:
"""由存储字段复算事件 Hash(Hash 校验作业的复算口径)。"""
return canonical_hash(_event_hash_inputs(event))
def build_transfer_audit_event(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
run_no: str | None = None,
matching_no: str | None = None,
invoice_no: str | None = None,
item_id: str | None = None,
attempt_no: str | None = None,
actor_type: str = "system",
actor_id: str | None = None,
actor_role: str | None = None,
actor_display: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
before: Any = None,
after: Any = None,
) -> TransferAuditEvent:
"""构造一条已计算 Hash 的审计事件(未落库,由调用方提交)。
Args:
event_type / aggregate_type / aggregate_id: 事件类型与聚合对象。
run_no / matching_no / invoice_no / item_id / attempt_no: 业务关联。
actor_*: 操作者(user/worker/schedule/admin/rpa)。
request_id / operation_id: 关联上下文。
before / after: 前后快照(自动脱敏并计算 Hash)。
Returns:
TransferAuditEvent 实例(before_hash/after_hash/event_hash 已填)。
"""
before_sanitized = sanitize_snapshot(before if before is not None else {})
after_sanitized = sanitize_snapshot(after if after is not None else {})
created_at = datetime.utcnow()
event = TransferAuditEvent(
event_type=event_type,
aggregate_type=aggregate_type,
aggregate_id=aggregate_id,
run_no=run_no,
matching_no=matching_no,
invoice_no=invoice_no,
item_id=item_id,
attempt_no=attempt_no,
actor_type=actor_type,
actor_id=actor_id,
actor_role=actor_role,
actor_display=actor_display,
request_id=request_id,
operation_id=operation_id,
source=source,
result=result,
error_code=error_code,
before_json=before_sanitized,
after_json=after_sanitized,
before_hash=canonical_hash(before_sanitized),
after_hash=canonical_hash(after_sanitized),
created_at=created_at,
)
event.event_hash = compute_event_hash(event)
return event