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>
This commit is contained in:
hugoandCursor committed 2026-10-19 10:46:06 +08:00
1 parent ffc0d4a430
commit 39fe3c05f2
453 files changed
+17945 -8646

No files matched your search

@@ -1,9 +1,14 @@
"""
services/freight_rpa/common/callback_sinks.py
用途:RPA 回调业务 sink 注册表——freight_rpa 侧的回调分发缝。
用途:RPA 回调「进度类」sink 注册表——freight_rpa 侧的回调分发缝(批次 B Task 6 起
与文件事实分发分工:文件/报表就绪类回调走 freight_rpa.reports.dispatch.
dispatch_report_fact——归档入口先 db.session.commit() 再投递 ReportFact,
kind 未注册同样 404 FREIGHT_RPA.SINK_NOT_REGISTERED;进度类 kind
(inbound-unit-progress / inbound-batch-progress / onhand-batch-claimed 等)
仍走本模块的 register_sink / dispatch_sink,不改 envelope)。
依赖:app.core.errors.AppError。
逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,onhand 等待拆端点按 kind 分发到
逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,进度类端点按 kind 分发到
组合根(create_app / api 层)注册的业务处理器;未注册的 kind 显式 404,
绝不静默吞回调。Task 9/10 落地 workflow_protocol / report_archive 时由
组合根调用 register_sink 注入真实业务持久化处理器。
@@ -0,0 +1,384 @@
"""freight_rpa/common/report_audit.py
用途:货代 RPA 域(inbound 回调归档、保留期清理、通知投递)写入
ShippingAuditEvent 统一审计账本的唯一入口(批次 B Task 6)。
依赖:app.models.ShippingAuditEvent(允许 import 模型)、app.core.errors.
ValidationError、SQLAlchemy 会话(app.db)。
逻辑:替代此前对 app.services.shipping_notice.audit_service 的依赖——freight_rpa
包禁止 import app.services.shipping_notice.*(import 边界由 tests/services/
freight_rpa/test_import_boundary.py 的空白名单锁定),故本模块以与
append_shipping_audit_event 相同的关键字面直接写同一个 ShippingAuditEvent
模型,事件名(shipping_inbound_rpa_callback_received /
shipping_inbound_report_archived 等)与聚合键保持不变,避免审计查询断档。
与 audit_service 的有意差异(均为本域受控场景):
(1)before/after 快照不做白名单投影——本域快照键均为受控诊断键
(status/error_code/sha256/file_size 等),原样入 snapshot 列;
(2)不做 XFA 加密完整快照(本域无敏感完整载荷);
(3)保留期恒为 None(货代统一审计账本永久保留);
(4)event_hash 以本地稳定哈希对核心字段集合计算,previous_event_hash
取同聚合最新一条已 flush 事件的 event_hash(链结构与 audit_service 同构)。
本模块不提交事务,由调用方与业务写入同一事务提交;写入失败时业务不得 commit。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ShippingAuditEvent
# 与 audit_service 同源的 actor/result 白名单(模型 CHECK 约束同集)。
_ALLOWED_ACTOR_TYPES = frozenset({'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'})
_ALLOWED_RESULTS = frozenset({'success', 'failure', 'rejected', 'ignored'})
# 审计元数据/快照禁止键本地冻结子集(凭据 / 正文 / URL 类;自
# shipping_notice.progress_audit_contract.AUDIT_FORBIDDEN_KEYS 裁剪,仅供本域防呆)。
_FORBIDDEN_AUDIT_KEYS = frozenset({
'api_key',
'api_base_url',
'authorization',
'body',
'content',
'document_text',
'email_body',
'minio',
'object_key',
'object_url',
'password',
'prompt',
'provider_config',
'quote',
'raw_content',
'raw_output',
'secret',
'token',
'url',
'user_agent',
})
def _is_forbidden_audit_key(key: str) -> bool:
"""键名大小写不敏感命中本地禁止键集合(与 audit_service 判定同构)。"""
return str(key or '').strip().lower() in _FORBIDDEN_AUDIT_KEYS
def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]:
"""
递归收集命中敏感黑名单的键路径(dict/list 均遍历,嵌套路径稳定拼接)。
Returns:
命中键路径列表(调用方排序后入 ValidationError.details)。
"""
found: list[str] = []
if isinstance(payload, dict):
for key, child in payload.items():
key_text = str(key)
child_path = f'{path}.{key_text}' if path else key_text
if _is_forbidden_audit_key(key_text):
found.append(child_path)
found.extend(_collect_forbidden_keys(child, path=child_path))
elif isinstance(payload, list):
for index, child in enumerate(payload):
found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]'))
return found
def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
"""验证元数据仅含脱敏诊断事实,阻断凭据、正文与 URL 进入审计账本。"""
safe = dict(metadata or {})
forbidden = _collect_forbidden_keys(safe)
if forbidden:
raise ValidationError(
'RPA report audit metadata contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return safe
def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None:
"""校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。"""
if refs is None:
return None
if not isinstance(refs, list):
raise ValidationError(
f'RPA report audit {field_name} must be a list',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
)
forbidden = _collect_forbidden_keys(refs)
if forbidden:
raise ValidationError(
f'RPA report audit {field_name} contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return refs
def _stable_hash(value: Any) -> str:
"""对受控状态对象生成 SHA-256(排序键 + 紧凑分隔符,与 audit_service 同构)。"""
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
def _snapshot_diff(before: Any, after: Any) -> dict[str, Any] | None:
"""
计算前后快照顶层差异(changed/added/removed 三段;无变化返回 None)。
核心逻辑:值均为受控诊断键原样比较(本域快照不做白名单投影,见模块 docstring)。
"""
left = before if isinstance(before, dict) else {}
right = after if isinstance(after, dict) else {}
changed: dict[str, Any] = {}
added: dict[str, Any] = {}
removed: dict[str, Any] = {}
for key in sorted(set(left) | set(right)):
if key in left and key in right:
if left[key] != right[key]:
changed[key] = {'from': left[key], 'to': right[key]}
elif key in right:
added[key] = right[key]
else:
removed[key] = left[key]
if not changed and not added and not removed:
return None
return {'changed': changed, 'added': added, 'removed': removed}
def _resolve_previous_event_hash(*, aggregate_type: str, aggregate_id: str) -> str | None:
"""
读取同聚合最新一条事件的 event_hash 作为哈希链前驱。
核心逻辑:按 id 倒序取一条;缺失或旧数据无 hash 时返回 None(链从本条起锚)。
调用方须先 flush 保证同事务先前事件可查(与 audit_service 顺序一致)。
"""
previous = (
ShippingAuditEvent.query
.filter_by(aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128])
.order_by(ShippingAuditEvent.id.desc())
.first()
)
if previous is None:
return None
return str(previous.event_hash) if previous.event_hash else None
def _event_hash_payload(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
action: str | None,
result: str | None,
reason_code: str | None,
run_no: str | None,
task_no: str | None,
operation_id: str | None,
request_id: str | None,
actor_type: str,
actor_id: str | None,
before_snapshot: dict[str, Any] | None,
after_snapshot: dict[str, Any] | None,
diff_json: dict[str, Any] | None,
previous_event_hash: str | None,
sensitivity_level: str | None,
) -> dict[str, Any]:
"""组装参与 event_hash 计算的稳定字段集合(字段集与 audit_snapshot_service 同构)。"""
return {
'event_type': event_type,
'aggregate_type': aggregate_type,
'aggregate_id': aggregate_id,
'action': action,
'result': result,
'reason_code': reason_code,
'workflow_id': None,
'workflow_item_id': None,
'workflow_item_version_id': None,
'version_no': None,
'run_no': run_no,
'document_id': None,
'review_case_no': None,
'task_no': task_no,
'operation_id': operation_id,
'request_id': request_id,
'actor_type': actor_type,
'actor_id': actor_id,
'before_snapshot': before_snapshot,
'after_snapshot': after_snapshot,
'diff': diff_json,
'previous_event_hash': previous_event_hash,
'sensitivity_level': sensitivity_level,
}
def append_rpa_report_event(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
run_no: str | None = None,
task_no: str | None = None,
intake_no: str | None = None,
actor_type: str = 'system',
actor_id: str | int | None = None,
actor_role: str | None = None,
actor_display: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
correlation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
conversation_id: str | None = None,
unit_id: str | int | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
owner_user_id: str | int | None = None,
attempt_no: int | None = None,
action: str | None = None,
reason_code: str | None = None,
reason: str | None = None,
before: Any = None,
after: Any = None,
evidence_refs: list[dict[str, Any]] | None = None,
artifact_refs: list[dict[str, Any]] | None = None,
context_refs: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
sensitivity_level: str | None = None,
) -> ShippingAuditEvent:
"""
追加一条货代 RPA 审计事实(freight_rpa 域唯一审计写入口)。
用途:与 shipping_notice.audit_service.append_shipping_audit_event 关键字兼容的
RPA 域替代品——调用方(report_archive 等)自 audit_service 迁移时仅改函数名,
事件名与聚合键原样保持,避免审计查询断档(见模块 docstring 的四处有意差异)。
核心逻辑:[STEP 1] 校验 actor_type/result 白名单 + 元数据/引用脱敏;
[STEP 2] 计算 before/after 稳定哈希与顶层 diff;
[STEP 3] flush 后取同聚合前驱 event_hash,对核心字段集合计算 event_hash;
[STEP 4] 写入 ShippingAuditEvent(保留期恒 None=永久)并 flush,不 commit。
Args:
event_type: 稳定业务事件名(如 shipping_inbound_rpa_callback_received);
禁止传入用户自由文本。
aggregate_type/aggregate_id: 业务聚合类型与稳定编号(软引用,不使用外键)。
run_no/task_no: 排程 run / task 软引用(截断 64)。
actor_type/actor_id/actor_role/actor_display: 操作主体四元组
(actor_type 必须在 user/system/rpa/chatflow/admin/worker 内)。
result: success / failure / rejected / ignored(白名单外抛 ValidationError)。
before/after: 受控状态快照(本域不做白名单投影,键须为诊断类,禁敏感键)。
evidence_refs/artifact_refs: FileAsset ID、SHA-256 等标识引用;禁止 URL/正文。
metadata: 仅允许原因码、计数等脱敏诊断事实(禁止键见 _FORBIDDEN_AUDIT_KEYS)。
unit_id/document_id/review_case_no/owner_user_id/attempt_no: 业务关联软引用。
action/reason_code/reason/error_code/conversation_id/correlation_id/source/
request_id/operation_id/intake_no/sensitivity_level: 追溯与分级补充字段。
Returns:
尚未提交的 ShippingAuditEvent,由调用方与业务写入在同一事务提交。
Raises:
ValidationError: actor/result 非法,或元数据/快照引用包含正文、凭据等敏感键。
"""
# [STEP 1] 校验与脱敏(错误码与 audit_service 共用,避免同义分裂)。
if actor_type not in _ALLOWED_ACTOR_TYPES:
raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID')
if result is not None and result not in _ALLOWED_RESULTS:
raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID')
safe_metadata = _sanitize_metadata(metadata)
if before is not None and _collect_forbidden_keys(before):
raise ValidationError(
'RPA report audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(before)))},
)
if after is not None and _collect_forbidden_keys(after):
raise ValidationError(
'RPA report audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(after)))},
)
# [STEP 2] 快照哈希与顶层差异。
before_snapshot = before if isinstance(before, dict) else None
after_snapshot = after if isinstance(after, dict) else None
diff_json = _snapshot_diff(before, after)
# [STEP 3] 哈希链:flush 保证同事务先前事件可查,再取前驱并计算本条 event_hash。
db.session.flush()
previous_event_hash = _resolve_previous_event_hash(
aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128],
)
resolved_run_no = str(run_no)[:64] if run_no else None
resolved_task_no = str(task_no)[:64] if task_no else None
resolved_actor_id = str(actor_id)[:128] if actor_id is not None else None
resolved_operation_id = str(operation_id)[:64] if operation_id else None
resolved_request_id = str(request_id)[:64] if request_id else None
resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None
event_hash = _stable_hash(_event_hash_payload(
event_type=str(event_type)[:64],
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
action=str(action)[:64] if action else None,
result=result,
reason_code=str(reason_code)[:128] if reason_code else None,
run_no=resolved_run_no,
task_no=resolved_task_no,
operation_id=resolved_operation_id,
request_id=resolved_request_id,
actor_type=actor_type,
actor_id=resolved_actor_id,
before_snapshot=before_snapshot,
after_snapshot=after_snapshot,
diff_json=diff_json,
previous_event_hash=previous_event_hash,
sensitivity_level=resolved_sensitivity,
))
# [STEP 4] 写入事件(保留期恒 None=永久保留;不 commit,由调用方保证原子性)。
event = ShippingAuditEvent(
event_type=str(event_type)[:64],
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
run_no=resolved_run_no,
task_no=resolved_task_no,
intake_no=str(intake_no)[:64] if intake_no else None,
actor_type=actor_type,
actor_id=resolved_actor_id,
actor_role=str(actor_role)[:64] if actor_role else None,
actor_display=str(actor_display)[:128] if actor_display else None,
request_id=resolved_request_id,
operation_id=resolved_operation_id,
correlation_id=str(correlation_id)[:64] if correlation_id else None,
source=str(source)[:32] if source else None,
result=result,
error_code=str(error_code)[:64] if error_code else None,
conversation_id=str(conversation_id)[:100] if conversation_id else None,
unit_id=str(unit_id)[:64] if unit_id is not None else None,
document_id=str(document_id)[:64] if document_id is not None else None,
review_case_no=str(review_case_no)[:64] if review_case_no else None,
owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None,
attempt_no=int(attempt_no) if attempt_no is not None else None,
action=str(action)[:64] if action else None,
reason_code=str(reason_code)[:128] if reason_code else None,
reason=str(reason)[:2000] if reason else None,
before_hash=_stable_hash(before_snapshot) if before_snapshot is not None else None,
after_hash=_stable_hash(after_snapshot) if after_snapshot is not None else None,
before_snapshot_json=before_snapshot,
after_snapshot_json=after_snapshot,
diff_json=diff_json,
previous_event_hash=previous_event_hash,
event_hash=event_hash,
sensitivity_level=resolved_sensitivity,
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
context_refs_json=dict(context_refs or {}) if context_refs else None,
metadata_json=safe_metadata,
retention_expires_at=None,
)
db.session.add(event)
db.session.flush()
return event
# 供测试与契约引用的冻结黑名单导出(与 audit_service.FORBIDDEN_AUDIT_METADATA_KEYS 对应的本地子集)。
RPA_FORBIDDEN_AUDIT_KEYS = _FORBIDDEN_AUDIT_KEYS
@@ -35,10 +35,10 @@ RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换——
# inventory_export→onhand_export、receipt_export→inbound_export(freight_upload 不变);
# inventory_export→onhand_export、receipt_export→inbound_export;上传能力为 freight_rpa_upload;
# worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。
ONHAND_EXPORT_CAPABILITY = "onhand_export"
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload"
INBOUND_EXPORT_CAPABILITY = "inbound_export"
# inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。
INBOUND_WORKER_ID_SUFFIX = "-inbound"
@@ -59,7 +59,7 @@ _REASON_USER_HINTS: dict[str, str] = {
"environment_mismatch": "Worker 环境与后端环境不一致",
"missing_onhand_export_capability": "Worker 未声明 onhand_export 能力",
"missing_inbound_export_capability": "Worker 未声明 inbound_export 能力",
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力",
"missing_freight_rpa_upload_capability": "Worker 未声明 freight_rpa_upload 能力",
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
@@ -454,7 +454,7 @@ def _worker_is_eligible(
backend_env: 后端归一环境(dev/test/prod)。
ttl_seconds: 心跳 TTL。
now: 当前 epoch 秒。
required_capability: 必选能力(onhand_export / inbound_export / freight_upload)。
required_capability: 必选能力(onhand_export / inbound_export / freight_rpa_upload)。
Returns:
(是否合格, 不合格原因列表)。
@@ -482,7 +482,7 @@ def _worker_is_eligible(
def _missing_capability_reason(required_capability: str) -> str:
"""按必选能力生成缺失原因码(onhand_export / inbound_export / freight_upload)。"""
"""按必选能力生成缺失原因码(onhand_export / inbound_export / freight_rpa_upload)。"""
return f"missing_{required_capability}_capability"
@@ -610,7 +610,7 @@ def _check_rpa_worker_ready_for_capability(
message, detail_message = "ready", "ready"
else:
failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
if required_capability == FREIGHT_RPA_UPLOAD_CAPABILITY:
detail = _summarize_reasons(failure.reasons)
message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
detail_message = f"{message}({detail})" if detail else message
@@ -731,7 +731,7 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
检查货代上传 RPA 是否可安全自动触发。
核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与
freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
freight_rpa_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
Returns:
RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。
@@ -740,7 +740,7 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
return _check_rpa_worker_ready_for_capability(
trigger_dir=upload_trigger_dir(),
required_capability=FREIGHT_UPLOAD_CAPABILITY,
required_capability=FREIGHT_RPA_UPLOAD_CAPABILITY,
extra_reasons=_freight_upload_config_reasons(),
)
@@ -777,7 +777,7 @@ def assert_freight_upload_rpa_ready() -> None:
"checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(),
"trigger_dir": str(upload_trigger_dir() or ""),
"capability": FREIGHT_UPLOAD_CAPABILITY,
"capability": FREIGHT_RPA_UPLOAD_CAPABILITY,
},
)
@@ -906,7 +906,7 @@ def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]:
"upload_trigger_dir": str(upload_trigger_dir() or ""),
"reasons": readiness.reasons,
"workers": workers,
"freight_upload": {
"freight_rpa_upload": {
"ready": freight_readiness.ready,
"message": freight_readiness.message,
"detail_message": freight_readiness.detail_message,
@@ -4,19 +4,24 @@ services/freight_rpa/inbound/report_archive.py
用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
三年保留期、不写库存快照表)、到期对象清理(retention)、单文件企微投递与管理员
强制重发(resend)。批次 R Task 10 自 shipping_notice.receipt_report_storage /
schedule.freight_inbound_rpa_retention / shipping_notice.receipt_report_notification
平移而来(函数名 receipt 词根→inbound;模型 ShippingReceiptReport* 引用不变——批次 S 才改表)。
依赖:models(ShippingReceiptReportFile / ShippingReceiptRpaUnitRun / ShippingReceiptNotificationDelivery /
schedule.freight_rpa_inbound_retention / shipping_notice.receipt_report_notification
平移而来(函数名 receipt 词根→inbound;模型 ShippingInboundReport* 引用不变——批次 S 才改表)。
依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun / FreightRpaInboundNotificationDelivery /
User / ScheduleRun 相关模型经行对象访问)、file_assets.storage、integrations.wecom.notify、
freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
shipping_notice.audit_service(适应度测试白名单内,本模块唯一 shipping_notice 业务依赖,
见 tests/services/freight_rpa/test_import_boundary.py)。
freight_rpa.common.report_audit(本域唯一审计写入口,批次 B Task 6 起替代
shipping_notice.audit_service——freight_rpa 禁止 import shipping_notice 业务模块,
边界由 tests/services/freight_rpa/test_import_boundary.py 空白名单锁定)、
freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递,Task 6)。
逻辑:Worker 回调进入 /api/freight-rpa/inbound-batch-ready 后由组合根注册的业务 sink
(shipping_notice.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
empty/success/failed 三个终态分支各自 commit;终态落库后的业务桥(推进在途调拨来源任务、
调拨证据同步)与排程终态归集(finalize)经 on_terminal 钩子回调 shipping_notice 侧实现,
本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa,
与拆分前「归档 commit 后立刻推桥」的调用顺序逐点一致。
empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」——
commit 后构造 ReportFact(report_kind='inbound', ...) 调 dispatch_report_fact;
处理函数异常原样外抛(不吞、不回滚已提交终态),kind 未注册时 404
FREIGHT_RPA.SINK_NOT_REGISTERED;同一 unit_run_id + sha256 已有文件时不插第二行、
仍投递 ok=True 的事实供处理函数重试。业务收尾(推进在途调拨来源任务、调拨证据
同步、排程终态归集)改由 Task 7 的处理函数(handle_inbound_report 等)承担,
本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa。
"""
from __future__ import annotations
@@ -24,26 +29,24 @@ from __future__ import annotations
import hashlib
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Callable
from typing import Any
from flask import current_app
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
ShippingReceiptNotificationDelivery,
ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
FreightRpaInboundNotificationDelivery,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
User,
)
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media
from app.services.shipping_notice.audit_service import append_shipping_audit_event
# 终态落库后的业务收尾钩子:由 shipping_notice 域注入(推进在途调拨来源任务 + 调拨证据同步
# + 排程终态归集),契约 = 原 storage.ingest_receipt_callback 中「commit 之后的桥/finalize 尾巴」。
InboundTerminalHook = Callable[..., None]
def _read_inbound_callback_file(file_path: str) -> bytes:
@@ -73,21 +76,29 @@ def _read_inbound_callback_file(file_path: str) -> bytes:
return path.read_bytes()
def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerminalHook) -> dict[str, Any]:
def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
"""幂等接收单个 inbound 单元回调,原样归档三年且不写库存快照表。
Args:
payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。
on_terminal: 必填业务收尾钩子(shipping_notice 域注入,见模块 docstring);在每个终态
分支 commit 之后、以与拆分前完全一致的实参被调用——
empty/failed: on_terminal(unit, ok=False, error_code=..., error_message=...);
success: on_terminal(unit, ok=True, file_no=..., file_sha256=...)。
业务约束:钩子内部异常只记日志,绝不回滚归档终态(契约由实现方保持)。
Returns:
dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。
Raises:
ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。
NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。
AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。
业务顺序(Task 6 契约):每个终态分支先 db.session.commit() 再构造
ReportFact(report_kind='inbound', source_code=unit.source_code, ...) 调
dispatch_report_fact;事实恒带 unit_run_id=unit.id(Task 7 修复轮 2——
含 failure/empty 与幂等重放,处理函数据此精确定位本单元的排程 run);
处理函数异常原样外抛(不吞、不回滚已提交终态);
同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实
(供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。
"""
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID')
callback_id = str(payload.get('callback_id') or '').strip()
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
raise NotFoundError('Receipt RPA unit not found', code='SHIPPING.RECEIPT_UNIT_NOT_FOUND')
status = str(payload.get('status') or '').strip().lower()
@@ -98,8 +109,8 @@ def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerm
unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64]
unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000]
unit.finished_at = datetime.utcnow()
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
append_rpa_report_event(
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success',
before=before,
@@ -111,46 +122,67 @@ def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerm
},
metadata={'callback_status': status, 'skip_reason': unit.error_code},
)
# [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
db.session.commit()
on_terminal(
unit, ok=False, error_code=unit.error_code or 'no_receipt_data',
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False,
error_code=unit.error_code or 'no_receipt_data',
error_message=unit.error_message or 'no_receipt_data',
)
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': 'empty'}
if status != 'success':
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow()
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
append_rpa_report_event(
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='failure',
before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'callback_status': status},
)
# [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
db.session.commit()
on_terminal(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False,
error_code=unit.error_code, error_message=unit.error_message,
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': 'failed'}
data = _read_inbound_callback_file(str(payload.get('file_path') or ''))
sha256 = hashlib.sha256(data).hexdigest()
claimed = str(payload.get('sha256') or '').lower()
if claimed and claimed != sha256:
raise ValidationError('receipt callback sha256 mismatch', code='SHIPPING.RECEIPT_CALLBACK_SHA_MISMATCH')
existing = ShippingReceiptReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
existing = FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
if existing:
# [STEP] 幂等重放:不插第二行,仍投递 ok=True 事实(同一 file_id),供处理函数重试;
# unit_run_id 自单元行回填(Task 7 修复轮 2)。
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=existing.id, sha256=sha256, ok=True,
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': unit.status, 'file_id': existing.id, 'idempotent': True}
filename = Path(str(payload.get('original_filename') or payload.get('file_path') or 'receipt.xlsx')).name
storage_key = f'shipping/receipt-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx'
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
record = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3))
record = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3))
db.session.add(record)
unit.status = 'success'; unit.finished_at = datetime.utcnow()
db.session.flush()
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
append_rpa_report_event(event_type='shipping_inbound_report_archived', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
# [STEP] 先 commit 归档,再投递 ok=True 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
db.session.commit()
on_terminal(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=record.id, sha256=sha256, ok=True,
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。
Args:
@@ -161,11 +193,11 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
"""
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
now = datetime.utcnow()
rows = ShippingReceiptReportFile.query.filter(
ShippingReceiptReportFile.archive_expires_at.is_not(None),
ShippingReceiptReportFile.archive_expires_at <= now,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
rows = FreightRpaInboundReportFile.query.filter(
FreightRpaInboundReportFile.archive_expires_at.is_not(None),
FreightRpaInboundReportFile.archive_expires_at <= now,
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
).order_by(FreightRpaInboundReportFile.id).limit(limit).all()
success = failed = 0
errors: list[str] = []
for report_file in rows:
@@ -173,8 +205,8 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
file_asset_storage.delete_object(report_file.storage_key)
report_file.archive_deleted_at = now
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
append_rpa_report_event(
event_type='shipping_inbound_report_archive_deleted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='success',
before={'status': 'archived'}, after={'status': 'archive_deleted'},
@@ -183,8 +215,8 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
success += 1
except Exception as exc:
errors.append(f'{report_file.id}: {exc}')
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
append_rpa_report_event(
event_type='shipping_inbound_report_archive_delete_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='failure',
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
@@ -195,7 +227,7 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]:
def _recipient_ids(report_file: FreightRpaInboundReportFile) -> list[int]:
"""从所属排程冻结的接收人列表取目标用户;停用通知时返回空。"""
run = report_file.unit_run.schedule_run
task = run.task if run else None
@@ -208,23 +240,23 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
"""向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。
Args:
file_id: 已归档收料文件主键(ShippingReceiptReportFile.id)。
file_id: 已归档收料文件主键(FreightRpaInboundReportFile.id)。
force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。
Returns:
dict: success_count / failed_count(file_not_found 时附 reason)。
"""
report_file = db.session.get(ShippingReceiptReportFile, file_id)
report_file = db.session.get(FreightRpaInboundReportFile, file_id)
if report_file is None:
return {'success_count': 0, 'failed_count': 0, 'reason': 'file_not_found'}
success_count = failed_count = 0
for user_id in _recipient_ids(report_file):
key = f'receipt:file:{report_file.id}:user:{user_id}'
delivery = ShippingReceiptNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
delivery = FreightRpaInboundNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
if delivery and delivery.status == 'success' and not force:
success_count += 1
continue
if delivery is None:
delivery = ShippingReceiptNotificationDelivery(
delivery = FreightRpaInboundNotificationDelivery(
unit_run_id=report_file.unit_run_id, report_file_id=report_file.id, recipient_user_id=user_id,
message_type='file', idempotency_key=key, status='pending',
)
@@ -234,8 +266,8 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
if user is None or not user.wecom_userid:
delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding'
failed_count += 1
append_shipping_audit_event(
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
@@ -252,8 +284,8 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.error_code = None; delivery.error_message = None
delivery.response_summary_json = {'media_uploaded': True, 'errcode': 0}
success_count += 1
append_shipping_audit_event(
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', aggregate_id=str(report_file.id),
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id),
actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='success',
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
@@ -262,8 +294,8 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
except Exception as exc:
delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]
failed_count += 1
append_shipping_audit_event(
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
@@ -5,7 +5,7 @@ services/freight_rpa/inbound/trigger_io.py
原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 schedule.freight_inbound_rpa_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
逻辑:由 schedule.freight_rpa_inbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
in_transit_transfer.inbound_trigger_service(调拨按需/批量触发)、
freight_rpa.common.worker_heartbeat(inbound trigger 目录探测/就绪检查)、
freight_rpa.inbound.report_archive(drop 目录定位与回调 SCHEMA 校验,Task 10 下沉)等调用,
@@ -3,8 +3,8 @@ services/freight_rpa/onhand/attempts.py
用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。
逻辑:由 shipping_notice 的 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,
决定是否还能继续触发 RPA 重试;事件类型字符串(inventory_rpa_* 等)是落库数据值,
逻辑:由 shipping_notice 的 onhand_rpa_workflow、fulfillment_workflow 等模块调用本文件,
决定是否还能继续触发 RPA 重试;事件类型字符串(onhand_rpa_* 等)是落库数据值,
随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。
"""
@@ -20,8 +20,8 @@ DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
_ONHAND_SUCCESS_EVENTS = {
"inventory_uploaded",
"inventory_parsed",
"inventory_rpa_drop_ingested",
"inventory_rpa_ready",
"onhand_rpa_drop_ingested",
"onhand_rpa_ready",
"inventory_template_mapping_used",
}
@@ -49,10 +49,10 @@ def onhand_rpa_attempts(task: ShippingNotice | None) -> int:
since: datetime | None = last_reset.created_at if last_reset else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
ShippingTaskEvent.event_type == "onhand_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_failed"
ShippingTaskEvent.event_type == "onhand_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
@@ -2,7 +2,7 @@
services/freight_rpa/onhand/callback_cleanup.py
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记
(Task 9 自 shipping_notice.inventory_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
(Task 9 自 shipping_notice.onhand_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
依赖:freight_rpa.onhand.trigger_io(onhand_drop_dir / onhand_processed_dir)、json、uuid、Flask current_app。
逻辑:commit 后由 shipping_notice 业务 sink 调用尝试归档;失败则移入 .hxops_quarantine 并入队;
scheduler/worker 启动时定期消费队列。
@@ -0,0 +1,84 @@
"""freight_rpa/onhand/report_store.py
用途:freight_rpa_onhand_report_files 的写入唯一入口(阶段 B Task 5)——发货域
(shipping_notice)与调度等其他消费方不得自行构造 FreightRpaOnhandReportFile 行,
插入/按主键更新统一经本模块收敛,保证报表事实写入只发生在货代 RPA 域。
依赖:app.db、app.models.FreightRpaOnhandReportFile、app.core.errors.NotFoundError。
逻辑:insert_onhand_report 接收与 FreightRpaOnhandReportFile 列同名的关键字参数
(storage_path、file_sha256、onhand_lines_json、field_mapping_json、
snapshot_status、warehouse_id、source_code、rpa_run_no 等),flush 后
返回 file_id;update_onhand_report 按主键更新给定列。两者都【只 flush 不
commit】——事务提交时机归属调用方;两者都【不创建任务关联】——
shipping_task_onhand_links 等 link 表归发货域,由调用方自行维护。
【禁止】import app.services.shipping_notice / in_transit_transfer(import
方向只能反过来,边界由 tests/services/shipping_notice/
test_report_model_boundary.py 锁定)。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import NotFoundError
from app.models import FreightRpaOnhandReportFile
def insert_onhand_report(**columns: Any) -> int:
"""插入 freight_rpa_onhand_report_files 一行并 flush。返回 file_id。不创建任务关联,不 commit。
【AI 触发时机】:任何需要新增在手/库存快照文件记录的场景
(RPA 回调入快照、人工上传保存、空快照记录)须调用本函数,禁止在
shipping_notice 域内直接构造 FreightRpaOnhandReportFile 行。
核心逻辑:[STEP 1] 以与模型列同名的关键字参数构造行;
[STEP 2] db.session.add + flush(拿到自增主键且同事务内可见);
[STEP 3] 返回 int 主键,供调用方按需经 db.session.get 取回 ORM 对象。
Args:
**columns: FreightRpaOnhandReportFile 的任意合法列关键字(禁止传入不存在的
列名,非法列名会在构造时抛 TypeError)。无默认值语义变化——
列默认值仍由模型定义(default=)承担。
Returns:
新插入行的 file_id(int)。
Raises:
TypeError: 传入了模型不存在的列关键字。
sqlalchemy.exc.IntegrityError: 唯一约束(如 onhand_file_no / RPA 幂等索引)
冲突,由调用方决定 savepoint 回滚或复用既有行。
"""
row = FreightRpaOnhandReportFile(**columns)
db.session.add(row)
db.session.flush()
return int(row.id)
def update_onhand_report(file_id: int, **columns: Any) -> None:
"""按 file_id 更新该行的给定列并 flush。不 commit。
【AI 触发时机】:快照过期(snapshot_status→expired)、批次同身份改写
share_mode、identity_status 回填等针对既有在手报表行的列更新场景。
核心逻辑:[STEP 1] 按主键取行(命中身份缓存即为同一 ORM 对象,调用方
持有的引用会同步可见更新),缺失抛 NotFoundError(fail-closed,禁止静默
吞掉错配);[STEP 2] 逐列 setattr;[STEP 3] flush。【不 commit】——
事务归属调用方;【不动任务关联】——link 表更新归发货域。
Args:
file_id: freight_rpa_onhand_report_files 主键(int;禁止传入非整数 ID)。
**columns: 要更新的列名与取值(禁止传入模型不存在的列名)。
Raises:
NotFoundError: file_id 对应的行不存在。
TypeError: 传入了模型不存在的列关键字。
"""
row = db.session.get(FreightRpaOnhandReportFile, file_id)
if row is None:
raise NotFoundError(
f"Onhand report file not found: {file_id}",
details={'file_id': file_id},
)
for key, value in columns.items():
setattr(row, key, value)
db.session.flush()
@@ -5,7 +5,7 @@ services/freight_rpa/onhand/trigger_io.py
单任务导出 trigger 写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、inventory_rpa_workflow(回调 schema 校验)、
逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、onhand_rpa_workflow(回调 schema 校验)、
per_source_rpa_service(回调 schema 校验)、freight_rpa.common.worker_heartbeat(目录探测)等调用,
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
(Worker 侧 Task 12 对表:freight_rpa.onhand.v1 / onhand_export / onhand_export_batch)。
@@ -3,11 +3,11 @@ services/freight_rpa/onhand/workflow_protocol.py
用途:onhand(在手库存)RPA 回调协议态——attempt 行记账、run_no 幂等键、轮次校验、
排程进度记账与超时窗口判定的纯协议层。
依赖:app.models(ShippingTaskEvent / ShippingTaskInventoryRpaAttempt / ScheduleRun)、
依赖:app.models(ShippingTaskEvent / FreightRpaOnhandTaskAttempt / ScheduleRun)、
app.extensions.db、freight_rpa.onhand 包内模块;**禁止 import 任何
shipping_notice 业务模块**(import 边界由 tests/services/freight_rpa/test_import_boundary.py
AST 全包扫描锁死,含函数内延迟 import)。
逻辑:Task 9 拆分自 shipping_notice.inventory_rpa_workflow——回调进入
逻辑:Task 9 拆分自 shipping_notice.onhand_rpa_workflow——回调进入
/api/freight-rpa/* 蓝图后,业务 sink(shipping_notice.rpa_sinks 注册)在原事务内
调用本模块完成协议记账(不改变 commit 时机),再由域内业务函数做快照落盘/
门禁推进/审计投影;快照、Gate、状态机等业务终态一律留在 shipping_notice。
@@ -21,7 +21,7 @@ from pathlib import Path
from typing import Any
from app.extensions import db
from app.models import ScheduleRun, ShippingTaskEvent, ShippingTaskInventoryRpaAttempt
from app.models import ScheduleRun, ShippingTaskEvent, FreightRpaOnhandTaskAttempt
def latest_task_event(task: Any, event_type: str) -> ShippingTaskEvent | None:
@@ -61,7 +61,7 @@ def is_legacy_trigger_run_no(run_no: str) -> bool:
def expected_rpa_callback_run_no(task: Any) -> str:
"""读取任务最近一次 RPA 触发记录的 run_no(事件 detail 优先,缺失回退 trigger 文件)。"""
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
last_trigger = latest_task_event(task, "onhand_rpa_triggered")
if not last_trigger:
return ""
detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {}
@@ -101,9 +101,9 @@ def resolve_effective_callback_run_no(task: Any, payload: dict[str, Any]) -> str
def get_consumed_inventory_rpa_run_no(task: Any) -> str:
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
attempt = (
ShippingTaskInventoryRpaAttempt.query
FreightRpaOnhandTaskAttempt.query
.filter_by(task_no=str(task.task_no or ''), status='consumed')
.order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
.order_by(FreightRpaOnhandTaskAttempt.consumed_at.desc(), FreightRpaOnhandTaskAttempt.id.desc())
.first()
)
return str(getattr(attempt, 'source_run_no', '') or '').strip()
@@ -119,7 +119,7 @@ def mark_inventory_rpa_run_no_consumed(task: Any, run_no: str) -> None:
if not effective:
return
attempt = (
ShippingTaskInventoryRpaAttempt.query
FreightRpaOnhandTaskAttempt.query
.filter_by(task_no=str(task.task_no or ''), source_run_no=effective)
.one_or_none()
)
@@ -199,7 +199,7 @@ def record_onhand_batch_progress(
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
# commit 时机与拆分前 inventory_rpa_workflow.report_inventory_batch_progress 完全一致:
# commit 时机与拆分前 onhand_rpa_workflow.report_inventory_batch_progress 完全一致:
# 校验通过、计数写完后立即提交,再由业务层构造响应。
db.session.commit()
return {
@@ -221,7 +221,7 @@ def compute_rpa_wait_window(
【AI 触发时机】:业务层已确认任务处于 RPA 等待态、需要判断是否超时或调度复查时调用。
Args:
triggered_at: 最近一次 inventory_rpa_triggered 事件的 created_at。
triggered_at: 最近一次 onhand_rpa_triggered 事件的 created_at。
timeout_seconds: 超时阈值秒数(由业务层 tool_common 读取配置)。
now: 可注入当前时间(测试用);缺省 utcnow。
@@ -0,0 +1,45 @@
"""freight_rpa/reports/__init__.py
用途:报表读域(阶段 B Task 3)——发货(shipping_notice 域)与在途调拨
(in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包。
依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。
逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice)
一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。
本包不得 import app.services.shipping_notice 或 app.services.in_transit_transfer
(import 边界由 tests/services/freight_rpa/test_report_queries.py 与
test_import_boundary.py 锁定)。
"""
from app.services.freight_rpa.reports.facts import REPORT_KINDS, ReportFact, require_report_kind
from app.services.freight_rpa.reports.queries import (
InboundConfigView,
InboundFileView,
OnhandConfigView,
SiteView,
clear_inbound_parse_failure,
get_inbound_config,
get_onhand_config,
get_site,
latest_usable_inbound_file,
mark_inbound_parse_failure,
read_inbound_file_bytes,
usable_inbound_file_condition,
)
__all__ = [
'REPORT_KINDS',
'InboundConfigView',
'InboundFileView',
'OnhandConfigView',
'ReportFact',
'SiteView',
'clear_inbound_parse_failure',
'get_inbound_config',
'get_onhand_config',
'get_site',
'latest_usable_inbound_file',
'mark_inbound_parse_failure',
'read_inbound_file_bytes',
'require_report_kind',
'usable_inbound_file_condition',
]
@@ -0,0 +1,78 @@
"""freight_rpa/reports/dispatch.py
用途:报表事实(ReportFact)处理函数注册表与分发缝——RPA 回调「先 commit
终态、再投递事实」的第二段分发(批次 B Task 6)。
依赖:app.core.errors.AppError、freight_rpa.reports.facts(ReportFact、
require_report_kind)。
逻辑:组合根(Task 7 的 shipping_notice.rpa_sinks.register_inbound_sinks /
register_onhand_sinks 等)在应用启动时调用 register_report_handler 注入各
kind 的业务处理函数;归档入口(如 freight_rpa.inbound.report_archive.
ingest_inbound_callback)在每个终态 db.session.commit() 之后调用
dispatch_report_fact。kind 未注册时显式 404(FREIGHT_RPA.
SINK_NOT_REGISTERED,与 common.callback_sinks.dispatch_sink 同码),
绝不静默吞事实;处理函数异常原样向外抛(供 Worker/上层重试整笔回调)。
本模块不 commit、不 rollback。
"""
from __future__ import annotations
from typing import Callable
from app.core.errors import AppError
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
# 报表事实处理函数契约:接收单个 ReportFact,返回 None;
# 异常由调用方外抛重试,处理函数内部禁止自行吞异常。
Handler = Callable[[ReportFact], None]
# kind → 处理函数注册表(模块级单例;同 kind 重复注册为覆盖)。
_REPORT_HANDLERS: dict[str, Handler] = {}
def register_report_handler(report_kind: str, handler: Handler) -> None:
"""
注册一个报表事实处理函数(由组合根在应用启动时调用)。
【AI 触发时机】:组合根装配(Task 7 的 register_inbound_sinks /
register_onhand_sinks)时调用;测试直接调用注入临时处理函数。
核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound /
outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。
Args:
report_kind: 报表种类字符串(必须在 REPORT_KINDS 白名单内)。
handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用,
不校验其内部行为。
Raises:
ValidationError: report_kind 不在白名单(code=SHIPPING.RECEIPT_CALLBACK_INVALID)。
"""
kind = require_report_kind(report_kind)
_REPORT_HANDLERS[kind] = handler
def dispatch_report_fact(fact: ReportFact) -> None:
"""
把已随终态 commit 的报表事实投递给对应 kind 的处理函数。
【AI 触发时机】:归档入口(如 ingest_inbound_callback)在每个终态
db.session.commit() 之后调用;禁止用于 commit 之前的路径(非法载荷 /
单元不存在 / 落库失败均不得投递)。
核心逻辑:kind 经 require_report_kind 校验后查注册表;命中即调用处理函数,
其异常原样向外抛(不包日志、不吞);未注册抛
AppError(code='FREIGHT_RPA.SINK_NOT_REGISTERED', http_status=404)。
本函数不 commit、不 rollback。
Args:
fact: 终态已落库后构造好的报表事实(report_kind/source_code/file_id/
sha256/ok/error_code/error_message)。
Raises:
ValidationError: fact.report_kind 不在白名单。
AppError: kind 未注册处理函数(404;归档终态已提交不回滚,
Worker 重试整笔回调即可补投递)。
"""
kind = require_report_kind(fact.report_kind)
handler = _REPORT_HANDLERS.get(kind)
if handler is None:
raise AppError(
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
message=f'No report handler registered for kind: {kind}',
http_status=404,
)
handler(fact)
@@ -0,0 +1,71 @@
"""freight_rpa/reports/facts.py
用途:定义跨域报表「事实」的传输契约——report kind 白名单与 ReportFact。
依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。
逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作;
report kind 只认 onhand / inbound / outbound,非法值抛
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),
与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。
本模块不 import shipping_notice / in_transit_transfer。
【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递
必从单元行回填,供消费方处理函数精确定位本次回调收尾的执行单元。
"""
from __future__ import annotations
from dataclasses import dataclass
from app.core.errors import ValidationError
# 【AI 触发时机】AI 或调用方在构造 ReportFact / 分发报表回调前必须先用
# require_report_kind 归一化校验 kind;白名单之外的取值一律拒绝。
REPORT_KINDS = ('onhand', 'inbound', 'outbound')
# 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码,
# 避免为同一类入参错误分裂出多个近义 code。
_INVALID_KIND_ERROR_CODE = 'SHIPPING.RECEIPT_CALLBACK_INVALID'
@dataclass(frozen=True)
class ReportFact:
"""一份回报表的事实行(跨域只读传输对象)。
用途:RPA 回调归档后,由 freight_rpa 域产生、发货/调拨域消费的最小事实快照;
ok=False 时 error_code/error_message 描述失败原因。
约束:frozen 不可变;file_id/sha256 允许 None(抓取失败时无产物可指);
unit_run_id 为归档入口回填的执行单元主键(Task 7 修复轮 2 起每次投递
必带——处理函数据此精确定位「本次回调收尾的单元」,禁止按来源猜最新),
允许 None 仅为兼容手工构造事实的旧调用方,dispatch 产线恒非空。
"""
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
unit_run_id: int | None = None
def require_report_kind(value: str) -> str:
"""校验并原样返回合法的 report kind。
用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。
核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),fail-closed。
Args:
value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。
Returns:
原样返回通过校验的 value(不含默认值/归一化,调用方以返回值为准)。
Raises:
ValidationError: value 不在白名单内(HTTP 400,不可重试)。
"""
if value not in REPORT_KINDS:
raise ValidationError(
f"Unsupported report kind: {value!r}",
code=_INVALID_KIND_ERROR_CODE,
details={'report_kind': value, 'allowed': list(REPORT_KINDS)},
)
return value
@@ -0,0 +1,599 @@
"""freight_rpa/reports/queries.py
用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+
解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露
freight_rpa 报表事实(站点、登录连接、在手/入站报表配置、入站解析方案、
入站归档文件),使消费方不再直接 import freight_rpa 模型表。
依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig /
FreightRpaInboundReportConfig / FreightRpaInboundReportFile;登录连接
(RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、
app.core.errors(NotFoundError)、
file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。
逻辑:【禁止】import app.services.shipping_notice 或 app.services.in_transit_transfer
——方向只能反过来(门禁模块阶段 B Task 4 起引用本模块的过滤表达式)。
usable / expired_inbound_file_condition 是入站归档文件「可用/失效」过滤
表达式的唯一权威(自 in_transit_transfer/inbound_file_gate.py 迁移,
两条件同核 _fresh_and_retention_valid 推导,规则文本只此一份):可用 =
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 +
未过期(archive_expires_at 为空视为长期有效或晚于当前时刻);失效 =
未删除 且 核心不成立。业务日窗口换算(date_policy.business_date_utc_window
的数学)以私有 helper 内联在本文件,就是为了不 import in_transit_transfer
(import 禁令)而保持口径逐位一致。
【阶段 B Task 4】站点视图补主键/连接绑定/仓库识别方式与入站配置视图补
config_id/config_version;新增登录连接(get_rpa_login_profile)、入站解析
方案(get_inbound_parsing_profile)、失效文件存在性(has_expired_inbound_
file)、重建通道归档清单(list_reparseable_inbound_files)、入站可用站点
编码清单(list_inbound_configured_source_codes)——供 in_transit_transfer
收敛为「只按 source_code / file_id 读取」的只读函数消费面。
mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from sqlalchemy import ColumnElement, and_, not_, or_
from app import db
from app.core.errors import NotFoundError
from app.models import (
FreightRpaInboundReportConfig,
FreightRpaInboundReportFile,
FreightRpaOnhandReportConfig,
FreightRpaSource,
)
from app.services.file_assets.storage import file_asset_storage
# 解析失败分层三列的截断上限,对齐列宽(String(64) / Text≈2000),
# 防止上游超长错误信息把写入顶爆。
_PARSE_ERROR_CODE_MAX = 64
_PARSE_ERROR_MESSAGE_MAX = 2000
# 业务时区固定 Asia/Shanghai(与 in_transit_transfer.date_policy 同值;本包内
# 复制而非 import,见文件头 import 禁令)。
_SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
_UTC_TZ = ZoneInfo("UTC")
def _business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
自 in_transit_transfer/date_policy.business_date_utc_window 逐位内联(阶段 B
Task 3 修复轮 1):数据库统一存 naive UTC,直接取 .date() 与业务日比较会
漂移 8 小时,必须先换算窗口再比较;不能 import date_policy,故复制其数学
并保持口径一致(此处内联即唯一权威,门禁模块后续引用本包)。
Args:
now: 可选时刻;naive 按 UTC 兼容处理(与 date_policy 口径一致),
缺省取当前 Asia/Shanghai 时刻。
Returns:
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
"""
if now is None:
now = datetime.now(_SHANGHAI_TZ)
if now.tzinfo is None:
now = now.replace(tzinfo=_UTC_TZ)
sh_now = now.astimezone(_SHANGHAI_TZ)
start_utc = (
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=_SHANGHAI_TZ)
.astimezone(_UTC_TZ)
.replace(tzinfo=None)
)
return start_utc, start_utc + timedelta(hours=24)
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
"""新鲜度 + 保留期核心条件(不含删除态;可用/失效两条件同核推导,规则文本只此一份)。"""
window_start, window_end = _business_date_utc_window(now)
return and_(
FreightRpaInboundReportFile.created_at >= window_start,
FreightRpaInboundReportFile.created_at < window_end,
or_(
FreightRpaInboundReportFile.archive_expires_at.is_(None),
FreightRpaInboundReportFile.archive_expires_at > now,
),
)
def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「当前可用的入站归档文件」SQL 条件(唯一权威,供门禁模块引用)。
判定(与 in_transit_transfer/inbound_file_gate 现行口径逐位一致):
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
(created_at ∈ 业务日 UTC [窗口起, 窗口止) 窗口,naive UTC 存储)+
未过期(archive_expires_at 为空视为长期有效,否则须晚于判定时刻)。
本表达式全量自 inbound_file_gate.py 复制(阶段 B Task 3),此后以此为单一
事实来源,门禁模块改为引用本函数(禁止反向 import 出现环)。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
_fresh_and_retention_valid(now),
)
def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
判定:未删除(archive_deleted_at 为空)且 新鲜度+保留期核心不成立
(保留期已到 或 非当天业务日抓取)——与可用条件同核(_fresh_and_retention_valid)
推导,口径只存在一处。阶段 B Task 4 自 in_transit_transfer/inbound_file_gate
迁移至此(语义逐位一致),此后以本文件为唯一权威;命中即提示重试重抓,
不报 ready,也不等待保留期清理任务落位。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
not_(_fresh_and_retention_valid(now)),
)
@dataclass(frozen=True)
class SiteView:
"""库存站点的只读视图:连接与模板绑定、启停状态(不含报表定义,s18 起)。
阶段 B Task 4 增补三字段(调拨域路由/触发按 source_code 读站点主键与识别
方式时不再引用站点模型):source_id(站点主键,供映射查询等 FK 路径)、
rpa_profile_id(登录连接绑定)、warehouse_resolution_mode(仓库识别方式)。
"""
source_code: str
display_name: str
connector_type: str
excel_template_id: int | None
enabled: bool
source_id: int = 0
rpa_profile_id: int = 0
warehouse_resolution_mode: str = ""
@dataclass(frozen=True)
class RpaLoginProfileView:
"""RPA 登录连接只读视图(freight_rpa_profiles 行)。
凭据密文原样透传(username/password_ciphertext)——仅限投递 RPA Worker
trigger,禁止出现在任何日志/接口响应中。
"""
profile_id: int
profile_code: str
login_url: str
login_config: dict
username_ciphertext: str | None
password_ciphertext: str | None
enabled: bool
@dataclass(frozen=True)
class OnhandConfigView:
"""在手报表配置只读视图(freight_rpa_onhand_report_configs 行)。"""
report_path_json: dict
query_parameters_json: list
parsing_profile_id: int | None
@dataclass(frozen=True)
class InboundConfigView:
"""入站报表配置只读视图(freight_rpa_inbound_report_configs 行),与在手同构。
阶段 B Task 4 增补 config_id / config_version(调拨入站触发落可审计单元行
快照需要配置行主键与版本,不再引用配置模型)。
"""
report_path_json: dict
query_parameters_json: list
parsing_profile_id: int | None
config_id: int = 0
config_version: int = 1
@dataclass(frozen=True)
class InboundProfileView:
"""入站解析方案只读视图(freight_rpa_parsing_profiles 行)。
定义(definition_json:field_mapping / sheet_name / header_row_index 等)
原样透出;status/purpose 的 published-inbound 门禁决策归调用方按场景
自行 fail-closed(运行期取数、重建、触发守卫口径一致,见各自消费方)。
"""
profile_id: int
profile_code: str
version: int
status: str
purpose: str
definition_json: dict
@dataclass(frozen=True)
class InboundFileView:
"""入站归档文件的只读视图;source_code 取自其所属执行单元行。
parse_failed_at 为解析失败分层的事实列(None=未失败/已清除)——阶段 B
Task 4 增补,供来源状态投影与证据同步判断 parse_failed,免除调用方二次查询。
"""
file_id: int
source_code: str
sha256: str
storage_key: str
original_filename: str
created_at: datetime
parse_failed_at: datetime | None = None
def get_site(source_code: str) -> SiteView | None:
"""按 source_code 返回库存站点只读视图。
用途:调拨/发货域读取站点连接、模板绑定与启停(例如入站触发预检)时调用,
替代直接查询 FreightRpaSource。
核心逻辑:按 source_code 精确查第一条;命中即映射为 SiteView(frozen),否则 None。
Args:
source_code: 站点实例编码(大小写敏感,禁止传入模糊值)。
Returns:
SiteView;站点不存在返回 None(调用方自行 fail-closed)。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
if site is None:
return None
return SiteView(
source_code=site.source_code,
display_name=site.display_name,
connector_type=site.connector_type,
excel_template_id=site.excel_template_id,
enabled=bool(site.enabled),
# [阶段 B Task 4] 调拨域(路由解析/入站触发)所需站点主键与识别方式。
source_id=site.id,
rpa_profile_id=site.rpa_profile_id,
warehouse_resolution_mode=str(site.warehouse_resolution_mode or ""),
)
def get_onhand_config(source_code: str) -> OnhandConfigView | None:
"""按 source_code 返回在手报表配置只读视图。
用途:RPA 触发读路径取报表路径、查询条件与解析方案绑定(s18 起配置挂在
freight_rpa_onhand_report_configs,站点行不再承载这三列)。
核心逻辑:join 站点表按 source_code 查配置行,命中即映射视图;站点或配置行
缺失一律返回 None(fail-closed,调用方判 None 后阻断触发)。
Args:
source_code: 站点实例编码。
Returns:
OnhandConfigView;站点无配置返回 None。
"""
config = (
FreightRpaOnhandReportConfig.query
.join(FreightRpaSource, FreightRpaOnhandReportConfig.source_id == FreightRpaSource.id)
.filter(FreightRpaSource.source_code == source_code)
.first()
)
if config is None:
return None
return OnhandConfigView(
report_path_json=dict(config.report_path_json or {}),
query_parameters_json=list(config.query_parameters_json or []),
parsing_profile_id=config.parsing_profile_id,
)
def get_inbound_config(source_code: str) -> InboundConfigView | None:
"""按 source_code 返回入站报表配置只读视图(与在手配置同构)。
用途:调拨入站触发读路径取收料报表定义;收料不设独立启停,是否运行由站点
enabled 与本配置行是否存在决定。
核心逻辑:join 站点表按 source_code 查 freight_rpa_inbound_report_configs 行,
命中即映射视图;缺失返回 None。
Args:
source_code: 站点实例编码。
Returns:
InboundConfigView;站点或配置不存在返回 None。
"""
config = (
FreightRpaInboundReportConfig.query
.join(FreightRpaSource, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id)
.filter(FreightRpaSource.source_code == source_code)
.first()
)
if config is None:
return None
return InboundConfigView(
report_path_json=dict(config.report_path_json or {}),
query_parameters_json=list(config.query_parameters_json or []),
parsing_profile_id=config.parsing_profile_id,
# [阶段 B Task 4] 触发快照(config_snapshot)所需的配置行主键与版本。
config_id=config.id,
config_version=int(config.config_version or 1),
)
def get_rpa_login_profile(source_code: str) -> RpaLoginProfileView | None:
"""按 source_code 返回站点绑定的 RPA 登录连接只读视图。
用途:调拨入站 RPA 触发装配 trigger unit(登录页、凭据密文信封、连接编码)
时调用,替代直接查询站点与其登录连接模型。
核心逻辑:按 source_code 取站点行再走 rpa_profile 关系;站点或连接缺失一律
返回 None(fail-closed,调用方判 None 后阻断触发)。凭据密文
原样透出(仅限投递 Worker trigger,调用方禁止落日志/响应)。
Args:
source_code: 站点实例编码(大小写敏感)。
Returns:
RpaLoginProfileView;站点或连接不存在返回 None。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
profile = site.rpa_profile if site is not None else None
if profile is None:
return None
return RpaLoginProfileView(
profile_id=profile.id,
profile_code=profile.profile_code,
login_url=profile.login_url,
login_config=dict(profile.login_config_json or {}),
username_ciphertext=profile.username_ciphertext,
password_ciphertext=profile.password_ciphertext,
enabled=bool(profile.enabled),
)
def get_inbound_parsing_profile(source_code: str) -> InboundProfileView | None:
"""按 source_code 返回入站配置绑定的解析方案只读视图。
用途:调拨运行期取数(movement_file_repository)、清空重建
(backlog_reparse_service)与 RPA 触发守卫(deps)读取入站文件解析
规则定义时调用,替代直接持有配置模型关系。
核心逻辑:站点 → 入站配置 → 配置绑定的解析方案,任一环节缺失返回 None;
不校验 status/purpose(调用方按场景自行 fail-closed,见
InboundProfileView docstring)。
Args:
source_code: 站点实例编码。
Returns:
InboundProfileView;无配置、未绑定或方案行缺失返回 None。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
config = site.inbound_report_config if site is not None else None
profile = config.parsing_profile if config is not None else None
if profile is None:
return None
return InboundProfileView(
profile_id=profile.id,
profile_code=profile.profile_code,
version=int(profile.version or 1),
status=profile.status,
purpose=profile.purpose,
definition_json=dict(profile.definition_json or {}),
)
def _inbound_file_view(report: FreightRpaInboundReportFile) -> InboundFileView:
"""把归档文件 ORM 行映射为冻结只读视图(本模块内唯一映射点,字段增补只改此处)。"""
return InboundFileView(
file_id=report.id,
source_code=report.unit_run.source_code,
sha256=report.sha256,
storage_key=report.storage_key,
original_filename=report.original_filename,
created_at=report.created_at,
parse_failed_at=report.parse_failed_at,
)
def has_expired_inbound_file(source_code: str, *, now: datetime | None = None) -> bool:
"""返回某来源是否存在「未删除但已失效」的入站归档文件(expired 投影依据)。
用途:调拨来源状态投影(source_file_status.resolve_source_file_status)判断
该来源是否需要因文件失效(隔日旧文件 / 保留期已到但清理未落位)提示
重抓时调用;只读不写,判定与 usable/expired 条件同核不漂移。
核心逻辑:经执行单元行的 source_code 过滤 + expired_inbound_file_condition,
存在任一命中即 True(纯存在性判断,不取列数据不排序)。
Args:
source_code: 来源实例编码(写在执行单元行上)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
bool:存在失效但未清理的归档文件 → True;否则 False。
"""
expired = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
expired_inbound_file_condition(now=now),
)
.first()
)
return expired is not None
def list_reparseable_inbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]:
"""维护通道:列出某来源全部可重建入站归档(未删除 + 未过保留期),不设当日门禁。
用途:调拨待匹配桶「清空并重新解析」(movement_file_repository →
backlog_reparse_service,spec §6)按来源取重建清单时调用。
运行期取数(latest_usable_inbound_file)的当日 fail-closed 门禁是
运行期语义;本方法是显式的历史重建通道(spec §6),两者不得混用。
核心逻辑:join 路径与 latest_usable_inbound_file 同款(经执行单元行
source_code 过滤),但【刻意无当日门禁】——重建对象正是历史
归档;保留期口径一致(archive_expires_at 为空视为长期有效)、
未删除(archive_deleted_at 为空)。按 created_at/id 升序返回
(重建必须按归档时间序重落,保证幂等重放顺序确定)。只读查询,
不触碰对象存储字节(字节由调用方按需经 read_inbound_file_bytes 取)。
Args:
source_code: 来源实例编码(经执行单元行 source_code 关联)。
now: 保留期判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
InboundFileView 列表(created_at 升序;无可重建归档为空表)。
"""
now = now or datetime.utcnow()
reports = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
or_(
FreightRpaInboundReportFile.archive_expires_at.is_(None),
FreightRpaInboundReportFile.archive_expires_at > now,
),
)
.order_by(FreightRpaInboundReportFile.created_at.asc(), FreightRpaInboundReportFile.id.asc())
.all()
)
return [_inbound_file_view(report) for report in reports]
def list_inbound_configured_source_codes() -> list[str]:
"""列出已配置入站报表的启用站点编码(调拨排程缺省执行范围)。
用途:在途自动调拨排程 source_codes 留空时的缺省范围
(inbound_trigger_service.list_inbound_capable_source_codes 委托本函数)
——入站文件只能来自已配置入站报表的启用站点。
核心逻辑:站点 join 入站配置行、仅启用站点、按 source_code 排序;只读查询。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
rows = db.session.query(FreightRpaSource.source_code).join(
FreightRpaInboundReportConfig,
FreightRpaInboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all()
return [str(code) for (code,) in rows]
def latest_usable_inbound_file(
source_code: str,
*,
now: datetime | None = None,
) -> InboundFileView | None:
"""返回某来源当前「可用」的入站归档文件只读视图,最新优先。
用途:调拨匹配取文件、证据下载等读路径调用;口径与匹配链路原有
_latest_usable_report_file 相同——经执行单元行的 source_code 过滤,
可用门禁(未删除 + 当天业务日抓取 + 未过期,见
usable_inbound_file_condition),按 created_at/id 倒序取第一条。
只读不写、不 flush 不 commit。
Args:
source_code: 来源实例编码(写在 FreightRpaInboundUnitRun.source_code 上)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
仅供测试冻结窗口或调用方显式指定业务时刻,生产调用缺省即可。
Returns:
InboundFileView;来源无可用文件(未抓取/已失效/已清理)返回 None。
"""
report = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
usable_inbound_file_condition(now=now),
)
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
.first()
)
if report is None:
return None
return _inbound_file_view(report)
def read_inbound_file_bytes(file_id: int) -> bytes:
"""按 file_id 读取入站归档文件的对象字节。
用途:调拨/发货域需要文件原文(匹配重解析、证据下载)时调用,替代各自
持有模型 + file_asset_storage 的双跳查询。
核心逻辑:[STEP 1] 按主键取 FreightRpaInboundReportFile,缺失抛 NotFoundError
(fail-closed);[STEP 2] 以文件的 storage_key 调
file_asset_storage.get_bytes 读取并返回字节(不含元数据)。
Args:
file_id: 归档文件主键(int;禁止传入非整数 ID)。
Returns:
文件完整字节内容。
Raises:
NotFoundError: file_id 对应的归档文件不存在(HTTP 404)。
"""
report = db.session.get(FreightRpaInboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Inbound report file not found: {file_id}",
details={'file_id': file_id},
)
return file_asset_storage.get_bytes(report.storage_key)
def mark_inbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None:
"""标记一份入站归档文件解析失败(写入解析失败三分层列)。
用途:入站归档文件解析(schema/字段校验)失败时把失败事实落到文件上,
使来源状态投影为 parse_failed、阻止下游当作 ready 使用。
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError;[STEP 2] 只更新
parse_failed_at(当前 UTC)/ parse_error_code(截断 64)/
parse_error_message(截断 2000)三列;[STEP 3] db.session.flush()
使同事务内投影立即可见。【不 commit】——调用方处于自己的事务,
提交/回滚归属调用方,service 层禁止越权提交。
Args:
file_id: 归档文件主键(须已入库)。
error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
Returns:
None。失败标记随调用方事务落库。
Raises:
NotFoundError: file_id 对应的归档文件不存在。
"""
report = db.session.get(FreightRpaInboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Inbound report file not found: {file_id}",
details={'file_id': file_id},
)
report.parse_failed_at = datetime.utcnow()
report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX]
report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX]
db.session.flush()
def clear_inbound_parse_failure(file_id: int) -> None:
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
用途:同一文件重新解析成功、或确认可恢复后调用;不要在文件已被
清理/过期后调用(无业务意义)。
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError(与其他按 id 操作
同口径,避免静默吞掉错配);[STEP 2] 将 parse_failed_at /
parse_error_code / parse_error_message 置 None(三者全空即未失败的
约定态);[STEP 3] flush。【不 commit】——事务归属调用方。
Args:
file_id: 归档文件主键(须已入库)。
Returns:
None。清除随调用方事务落库。
Raises:
NotFoundError: file_id 对应的归档文件不存在。
"""
report = db.session.get(FreightRpaInboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Inbound report file not found: {file_id}",
details={'file_id': file_id},
)
report.parse_failed_at = None
report.parse_error_code = None
report.parse_error_message = None
db.session.flush()
@@ -7,10 +7,10 @@ services/freight_rpa/upload/trigger_io.py
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 shipping_notice.fulfillment_workflow(upload_to_freight 触发上传)、
freight_rpa.common.worker_heartbeat(上传目录就绪探测)调用,
与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相
([PROMPT_UPDATE] 2026-10-16 批次 R 新裁定:upload 契约随发布窗口一次切换——
action 由 shipment_upload 改为 outbound_upload、schema 由 shipping_notice_upload_rpa.v1
改为 freight_rpa.upload.v1,Worker 侧 Task 12 同窗口对齐,旧串全仓清零)。
与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相。
upload 是与 onhand/inbound/outbound 同级的独立域;action 对齐心跳能力
freight_rpa_upload(FREIGHT_RPA_UPLOAD_CAPABILITY),禁止 outbound_* / shipment_* 作为 upload action;
schema 为 freight_rpa.upload.v1(批次 R 曾误用 outbound 词根,已纠回 freight_rpa_upload)。
"""
from __future__ import annotations
@@ -28,7 +28,7 @@ from flask import current_app
# Worker 触发契约常量:后端写入侧单一真相,禁止再写字面量(Worker 侧常量见
# scripts/freight_rpa/common/rpa_callbacks.py 邻域的 inbound/onhand 对齐方式)。
SCHEMA = "freight_rpa.upload.v1"
ACTION_OUTBOUND_UPLOAD = "outbound_upload"
ACTION_FREIGHT_RPA_UPLOAD = "freight_rpa_upload"
def _path(key: str) -> Path | None:
@@ -124,7 +124,7 @@ def write_upload_trigger(
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
body = {
"action": ACTION_OUTBOUND_UPLOAD,
"action": ACTION_FREIGHT_RPA_UPLOAD,
"schema_version": SCHEMA,
"task_no": task_no,
"attempt_id": attempt_id,