feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。 - 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。 - 更新 ORM 模型,增加出站报表相关的持久化模型。 - 统一命名规范,确保在手、入站与出站的概念一致性。
This commit is contained in:
1 parent
39fe3c05f2
commit
911afa0f73
152 files changed
+9861
-2984
No files matched your search
@@ -2,19 +2,16 @@
|
||||
services/freight_rpa/inbound/report_archive.py
|
||||
|
||||
用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
|
||||
三年保留期、不写库存快照表)、到期对象清理(retention)、单文件企微投递与管理员
|
||||
强制重发(resend)。批次 R Task 10 自 shipping_notice.receipt_report_storage /
|
||||
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 根)、
|
||||
三年保留期、不写库存快照表)与到期对象清理(retention)。per-file 企微投递与 resend
|
||||
已拆除(Task 2);排程终态通知仍走 freight_rpa_inbound_finalize 统一出口。
|
||||
依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun、ScheduleRun 经行对象访问)、
|
||||
file_assets.storage、freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
|
||||
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 完成原样归档,
|
||||
(in_transit_transfer.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
|
||||
empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」——
|
||||
commit 后构造 ReportFact(report_kind='inbound', ...) 调 dispatch_report_fact;
|
||||
处理函数异常原样外抛(不吞、不回滚已提交终态),kind 未注册时 404
|
||||
@@ -36,19 +33,14 @@ from flask import current_app
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
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
|
||||
|
||||
|
||||
def _read_inbound_callback_file(file_path: str) -> bytes:
|
||||
"""只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
|
||||
|
||||
@@ -59,7 +51,7 @@ def _read_inbound_callback_file(file_path: str) -> bytes:
|
||||
"""
|
||||
configured_root = str(inbound_drop_dir() or '').strip()
|
||||
if not configured_root:
|
||||
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||
raise ValidationError('inbound callback file root is unavailable', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
|
||||
root = Path(configured_root).resolve()
|
||||
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
|
||||
name = Path(str(file_path).replace('\\', '/')).name
|
||||
@@ -67,12 +59,12 @@ def _read_inbound_callback_file(file_path: str) -> bytes:
|
||||
try:
|
||||
path.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise ValidationError('receipt callback file is outside receipt drop root', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') from exc
|
||||
raise ValidationError('inbound callback file is outside inbound drop root', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') from exc
|
||||
if path.suffix.lower() != '.xlsx' or not path.is_file():
|
||||
raise ValidationError('receipt callback file must be an existing xlsx', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||
raise ValidationError('inbound callback file must be an existing xlsx', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
|
||||
max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024
|
||||
if path.stat().st_size > max_size:
|
||||
raise ValidationError('receipt callback file exceeds configured size limit', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||
raise ValidationError('inbound callback file exceeds configured size limit', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
|
||||
return path.read_bytes()
|
||||
|
||||
|
||||
@@ -96,23 +88,23 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
(供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。
|
||||
"""
|
||||
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
|
||||
raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID')
|
||||
raise ValidationError('inbound callback schema_version is invalid', code='SHIPPING.INBOUND_CALLBACK_INVALID')
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
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')
|
||||
raise NotFoundError('Inbound RPA unit not found', code='SHIPPING.INBOUND_UNIT_NOT_FOUND')
|
||||
status = str(payload.get('status') or '').strip().lower()
|
||||
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
|
||||
if status in {'empty', 'no_data'}:
|
||||
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。
|
||||
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_inbound_data。
|
||||
unit.status = 'empty'
|
||||
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.error_code = str(payload.get('error_code') or 'no_inbound_data')[:64]
|
||||
unit.error_message = str(payload.get('error_message') or 'no_inbound_data')[:2000]
|
||||
unit.finished_at = datetime.utcnow()
|
||||
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',
|
||||
actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success',
|
||||
before=before,
|
||||
after={
|
||||
'status': 'empty',
|
||||
@@ -127,17 +119,17 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
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',
|
||||
error_code=unit.error_code or 'no_inbound_data',
|
||||
error_message=unit.error_message or 'no_inbound_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()
|
||||
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.INBOUND_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'inbound export failed')[:2000]; unit.finished_at = datetime.utcnow()
|
||||
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',
|
||||
actor_type='rpa', actor_id='inbound-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},
|
||||
)
|
||||
@@ -154,7 +146,7 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
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')
|
||||
raise ValidationError('inbound callback sha256 mismatch', code='SHIPPING.INBOUND_CALLBACK_SHA_MISMATCH')
|
||||
existing = FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
|
||||
if existing:
|
||||
# [STEP] 幂等重放:不插第二行,仍投递 ok=True 事实(同一 file_id),供处理函数重试;
|
||||
@@ -171,7 +163,7 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.add(record)
|
||||
unit.status = 'success'; unit.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
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})
|
||||
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='inbound-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': 'inbound_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()
|
||||
@@ -210,7 +202,7 @@ def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int
|
||||
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'},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
success += 1
|
||||
except Exception as exc:
|
||||
@@ -220,88 +212,8 @@ def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int
|
||||
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]},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
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: FreightRpaInboundReportFile) -> list[int]:
|
||||
"""从所属排程冻结的接收人列表取目标用户;停用通知时返回空。"""
|
||||
run = report_file.unit_run.schedule_run
|
||||
task = run.task if run else None
|
||||
if task is None or not task.notify_enabled:
|
||||
return []
|
||||
return sorted({int(user_id) for user_id in (task.notify_user_ids_json or []) if str(user_id).isdigit()})
|
||||
|
||||
|
||||
def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
|
||||
"""向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。
|
||||
|
||||
Args:
|
||||
file_id: 已归档收料文件主键(FreightRpaInboundReportFile.id)。
|
||||
force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。
|
||||
Returns:
|
||||
dict: success_count / failed_count(file_not_found 时附 reason)。
|
||||
"""
|
||||
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 = 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 = 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',
|
||||
)
|
||||
db.session.add(delivery)
|
||||
db.session.flush()
|
||||
user = db.session.get(User, user_id)
|
||||
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_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'},
|
||||
after={'delivery_status': delivery.status, 'error_code': delivery.error_code},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
|
||||
)
|
||||
continue
|
||||
try:
|
||||
media_id = upload_wecom_temp_media(file_asset_storage.get_bytes(report_file.storage_key), report_file.original_filename)
|
||||
result = send_wecom_file_message(user.wecom_userid, media_id)
|
||||
if int(result.get('errcode', -1)) != 0:
|
||||
raise RuntimeError(str(result.get('errmsg') or result.get('errcode')))
|
||||
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_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}],
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
|
||||
)
|
||||
except Exception as exc:
|
||||
delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]
|
||||
failed_count += 1
|
||||
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'},
|
||||
after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
|
||||
)
|
||||
db.session.commit()
|
||||
return {'success_count': success_count, 'failed_count': failed_count}
|
||||
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'inbound_retention', 'status': 'completed'}]
|
||||
Reference in new issue
Block a user