feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约
将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。 共享目录与 Worker 契约一次切换至 onhand/inbound/upload, 并补 outbound 骨架与 tt16 排程 job key 迁移。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
bf3154033b
commit
ffc0d4a430
147 files changed
+4221
-2678
No files matched your search
@@ -0,0 +1 @@
|
||||
"""inbound:入站 RPA。"""
|
||||
@@ -0,0 +1,275 @@
|
||||
"""
|
||||
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 /
|
||||
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)。
|
||||
逻辑: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 后立刻推桥」的调用顺序逐点一致。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingReceiptNotificationDelivery,
|
||||
ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
User,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir
|
||||
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:
|
||||
"""只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
|
||||
|
||||
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
|
||||
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...),
|
||||
Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史
|
||||
载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。
|
||||
"""
|
||||
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')
|
||||
root = Path(configured_root).resolve()
|
||||
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
|
||||
name = Path(str(file_path).replace('\\', '/')).name
|
||||
path = (root / name).resolve()
|
||||
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
|
||||
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')
|
||||
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')
|
||||
return path.read_bytes()
|
||||
|
||||
|
||||
def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerminalHook) -> 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=...)。
|
||||
业务约束:钩子内部异常只记日志,绝不回滚归档终态(契约由实现方保持)。
|
||||
"""
|
||||
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()
|
||||
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()
|
||||
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。
|
||||
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.finished_at = datetime.utcnow()
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_callback_received', 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': 'empty',
|
||||
'callback_id': unit.callback_id,
|
||||
'error_code': unit.error_code,
|
||||
'error_message': unit.error_message,
|
||||
},
|
||||
metadata={'callback_status': status, 'skip_reason': unit.error_code},
|
||||
)
|
||||
db.session.commit()
|
||||
on_terminal(
|
||||
unit, ok=False, error_code=unit.error_code or 'no_receipt_data',
|
||||
error_message=unit.error_message or 'no_receipt_data',
|
||||
)
|
||||
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',
|
||||
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},
|
||||
)
|
||||
db.session.commit()
|
||||
on_terminal(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
|
||||
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()
|
||||
if existing:
|
||||
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))
|
||||
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})
|
||||
db.session.commit()
|
||||
on_terminal(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
|
||||
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]]:
|
||||
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。
|
||||
|
||||
Args:
|
||||
task: 排程任务行(job_params.limit 提供单批上限,1..1000)。
|
||||
run: 排程执行记录(本函数不改写 run,仅按排程协议返回计数/明细/日志)。
|
||||
Returns:
|
||||
排程平台 Job 协议七元组(总查得数、成功、失败、跳过 0、明细、错误、step_logs)。
|
||||
"""
|
||||
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()
|
||||
success = failed = 0
|
||||
errors: list[str] = []
|
||||
for report_file in rows:
|
||||
try:
|
||||
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',
|
||||
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}],
|
||||
)
|
||||
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',
|
||||
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}],
|
||||
)
|
||||
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: ShippingReceiptReportFile) -> 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: 已归档收料文件主键(ShippingReceiptReportFile.id)。
|
||||
force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。
|
||||
Returns:
|
||||
dict: success_count / failed_count(file_not_found 时附 reason)。
|
||||
"""
|
||||
report_file = db.session.get(ShippingReceiptReportFile, 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()
|
||||
if delivery and delivery.status == 'success' and not force:
|
||||
success_count += 1
|
||||
continue
|
||||
if delivery is None:
|
||||
delivery = ShippingReceiptNotificationDelivery(
|
||||
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_shipping_audit_event(
|
||||
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_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_shipping_audit_event(
|
||||
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_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_shipping_audit_event(
|
||||
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_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}
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
services/freight_rpa/inbound/trigger_io.py
|
||||
|
||||
用途:inbound(入站,原收料)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON
|
||||
原子写入,以及 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 单元重试)、
|
||||
in_transit_transfer.inbound_trigger_service(调拨按需/批量触发)、
|
||||
freight_rpa.common.worker_heartbeat(inbound trigger 目录探测/就绪检查)、
|
||||
freight_rpa.inbound.report_archive(drop 目录定位与回调 SCHEMA 校验,Task 10 下沉)等调用,
|
||||
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
|
||||
(Worker 侧 Task 12 对表:freight_rpa.inbound.v1 / inbound_export_batch)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
|
||||
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
|
||||
# (旧 receipt 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
|
||||
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
|
||||
SCHEMA = "freight_rpa.inbound.v1"
|
||||
ACTION_INBOUND_EXPORT_BATCH = "inbound_export_batch"
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def inbound_trigger_dir() -> Path | None:
|
||||
"""RPA inbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR);
|
||||
绝不回落到 onhand trigger 目录。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR")
|
||||
|
||||
|
||||
def inbound_drop_dir() -> Path | None:
|
||||
"""RPA inbound 导出文件落盘目录(FREIGHT_RPA_SHARED_INBOUND_DROP_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INBOUND_DROP_DIR")
|
||||
|
||||
|
||||
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
|
||||
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
|
||||
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
try:
|
||||
with open(temp_path, 'w', encoding='utf-8') as handle:
|
||||
json.dump(body, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, path)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def write_inbound_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""
|
||||
写入 inbound 批量 trigger 文件 inbound_export_batch_{run_no}.json
|
||||
([PROMPT_UPDATE] 2026-10-16 批次 R:文件名前缀随 Worker 侧 Task 12 一起由
|
||||
receipt_export_batch_* 切换为 inbound_export_batch_*;Worker 轮询 <root>/*.json
|
||||
按内容消费,schema/action 取本文件常量新值)。
|
||||
|
||||
Args:
|
||||
run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。
|
||||
units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。
|
||||
payload: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。
|
||||
"""
|
||||
trigger_dir = inbound_trigger_dir()
|
||||
if not trigger_dir or not units:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'inbound'
|
||||
body = {
|
||||
'schema_version': SCHEMA, 'action': ACTION_INBOUND_EXPORT_BATCH,
|
||||
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
|
||||
**(payload or {}),
|
||||
}
|
||||
path = trigger_dir / f'inbound_export_batch_{safe_run_no}.json'
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
Reference in new issue
Block a user