Merge branch 'hugo-auto-transfer' into dev

# Conflicts:
#	backend/app/api/shipping_notice_tools.py
This commit is contained in:
hugo committed 2026-09-30 00:34:28 +08:00
commit 6cf71679b7
143 files changed
+10145 -2132

No files matched your search

@@ -1,4 +1,10 @@
"""独立收料 RPA 排程等待态收口辅助。"""
"""
backend/app/services/schedule/freight_receipt_rpa_finalize.py
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微。
依赖:ShippingReceiptRpaUnitRun、shipping_receipt_rpa_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom。
"""
from __future__ import annotations
@@ -46,8 +52,142 @@ def apply_deferred_receipt_schedule_run_state(
return run
def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict:
"""
收料单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。
核心逻辑:仅在 awaiting_receipt_rpa 时,按已终态单元聚合 success/empty/failed 写入
ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at,
终态仍由 finalize_receipt_schedule_run_if_complete 负责。
Args:
schedule_run_id: 排程执行记录主键。
Returns:
dict: updated=True/False 及当前计数;非等待态返回 reason。
"""
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_receipt_rpa'):
return {'updated': False, 'reason': 'not_awaiting_receipt_callback'}
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
success_count = sum(unit.status == 'success' for unit in units)
skipped_count = sum(unit.status == 'empty' for unit in units)
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
# [STEP] 与库存进度同口径:只抬升计数,防乱序回调把笔数打回去。
run.success_count = max(int(run.success_count or 0), success_count)
run.skipped_count = max(int(run.skipped_count or 0), skipped_count)
run.failed_count = max(int(run.failed_count or 0), failed_count)
if run.total_count is None or int(run.total_count or 0) < len(units):
run.total_count = len(units)
summary = dict(summary)
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'processing_count': sum(unit.status == 'processing' for unit in units),
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
db.session.commit()
return {
'updated': True,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
}
def report_receipt_batch_progress(payload: dict) -> dict:
"""
Worker 每完成一笔收料导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。
核心逻辑:校验 schema + schedule_run_id;仅 awaiting_receipt_rpa 时抬升
ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。
Args:
payload: Worker 上报的累计 success/skipped/failed 与 schedule_run_id。
Returns:
dict: updated / rejected 及当前计数。
"""
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
return {'updated': False, 'reason': 'callback_schema_invalid'}
try:
schedule_run_id = int(payload.get('schedule_run_id')) if payload.get('schedule_run_id') is not None else None
except (TypeError, ValueError):
schedule_run_id = None
if not schedule_run_id:
return {'updated': False, 'reason': 'schedule_run_id_required'}
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_receipt_rpa'):
return {'updated': False, 'reason': 'not_awaiting_receipt_callback'}
incoming = {
'success_count': max(0, int(payload.get('success_count') or 0)),
'skipped_count': max(0, int(payload.get('skipped_count') or 0)),
'failed_count': max(0, int(payload.get('failed_count') or 0)),
}
run.success_count = max(int(run.success_count or 0), incoming['success_count'])
run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count'])
run.failed_count = max(int(run.failed_count or 0), incoming['failed_count'])
summary = dict(summary)
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'batch_run_no': str(payload.get('batch_run_no') or payload.get('run_no') or ''),
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
db.session.commit()
return {
'updated': True,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
}
def mark_receipt_unit_processing(payload: dict) -> dict:
"""
Worker 开始导出某收料单元时标记 processing(对齐库存 claimed / rpa_exporting)。
核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。
"""
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
return {'updated': False, 'reason': 'callback_schema_invalid'}
callback_id = str(payload.get('callback_id') or '').strip()
if not callback_id:
return {'updated': False, 'reason': 'callback_id_required'}
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
return {'updated': False, 'reason': 'unit_not_found'}
if unit.status in {'success', 'empty', 'failed', 'cancelled'}:
return {'updated': False, 'reason': 'already_terminal', 'status': unit.status}
if unit.status == 'processing':
return {'updated': True, 'status': 'processing', 'idempotent': True}
unit.status = 'processing'
db.session.commit()
if unit.schedule_run_id:
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id}
def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
"""当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。"""
"""
当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。
核心逻辑:聚合单元计数 → 预生成原始收料 ZIP 写入 summary → 企微发 textcard+单 ZIP。
"""
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'finalized': False, 'reason': 'schedule_run_not_found'}
@@ -69,9 +209,35 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) if run.started_at else 0
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count}
# [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。
archive_summary = {
'raw_receipt_zip_available': False,
'raw_receipt_zip_path': None,
'raw_receipt_file_count': 0,
'raw_receipt_file_ids': [],
'raw_receipt_zip_size': 0,
}
try:
from app.services.schedule.shipping_receipt_rpa_archive import persist_receipt_rpa_raw_zip_archive
archive_summary = persist_receipt_rpa_raw_zip_archive(run)
except Exception as archive_exc:
current_app.logger.error(
'[schedule-run] receipt RPA zip archive failed for run %s: %s',
run.run_no, archive_exc,
)
run.response_summary_json = {
**summary,
'awaiting_receipt_rpa': False,
'success_count': success_count,
'empty_count': skipped_count,
'failed_count': failed_count,
**archive_summary,
}
db.session.commit()
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+全部收料文件。
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+收料 ZIP。
try:
task = run.task
if task is not None and task.notify_enabled:
@@ -1,4 +1,13 @@
"""独立收料 RPA 排程:冻结站点配置并按 DBS Warehouse 展开执行单元。"""
"""
backend/app/services/schedule/freight_receipt_rpa_job.py
用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。
依赖:receipt_rpa.write_receipt_export_batch_trigger、assert_receipt_rpa_worker_ready、
ShippingInventorySource / ShippingReceiptReportConfig / ShippingReceiptRpaUnitRun、
ScheduleTask/Run。
逻辑:job_registry 的 freight-receipt-rpa 调用本 handler;写 trigger 前 fail-fast;
口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。
"""
from __future__ import annotations
@@ -6,8 +15,13 @@ import uuid
from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values, write_receipt_export_batch_trigger
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
from app.services.shipping_notice.rpa_worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_receipt_rpa_worker_ready,
)
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
@@ -24,7 +38,7 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]:
def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]:
"""读取已启用且收料配置已启用的站点,不依赖库存报表路径或解析绑定。"""
"""读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
wanted = _wanted_source_codes(task)
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
@@ -32,20 +46,27 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource,
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str, Any]]:
"""浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
return [
dict(item) for item in (config.query_parameters_json or [])
if isinstance(item, dict)
]
def _build_unit(
source: ShippingInventorySource, config: ShippingReceiptReportConfig,
warehouse_id: str | None, schedule_run_id: int,
source: ShippingInventorySource, config: ShippingReceiptReportConfig, schedule_run_id: int,
) -> ShippingReceiptRpaUnitRun:
"""冻结可审计的收料执行单元;DBS 日期字段不进入查询快照。"""
"""冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
callback_id = f'receipt:{uuid.uuid4().hex}'
snapshot = {
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': receipt_unit_parameters(config),
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config),
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
}
return ShippingReceiptRpaUnitRun(
schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type, warehouse_id=warehouse_id, callback_id=callback_id,
connector_type=source.connector_type, warehouse_id=None, callback_id=callback_id,
status='awaiting_rpa', config_snapshot_json=snapshot,
)
@@ -78,15 +99,35 @@ def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]:
def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
units: list[ShippingReceiptRpaUnitRun] = []
for source, config in _eligible_sources(task):
# Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
for warehouse_id in warehouses:
units.append(_build_unit(source, config, str(warehouse_id) if warehouse_id else None, run.id))
"""
写独立收料 trigger;每个勾选站点对应一个执行单元(与库存 RPA 同口径)。
核心逻辑:写 trigger 前 assert_receipt_rpa_worker_ready;离线立即 failed,
不创建 unit、不进入 awaiting_receipt_rpa。
"""
units: list[ShippingReceiptRpaUnitRun] = [
_build_unit(source, config, run.id) for source, config in _eligible_sources(task)
]
if not units:
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
# [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。
try:
assert_receipt_rpa_worker_ready()
except ServiceUnavailableError as exc:
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
detail_message = str((exc.details or {}).get('detail_message') or message)
return len(units), 0, len(units), 0, [], [detail_message], [{
'step': 'freight_receipt_rpa',
'status': 'failed',
'detail': {
'message': message,
'detail_message': detail_message,
'error_code': exc.code,
'reasons': (exc.details or {}).get('reasons') or [],
},
}]
db.session.add_all(units)
db.session.flush()
try:
@@ -1,57 +0,0 @@
"""独立收料文件抓取排程(08:00)。
用途:为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。
依赖:schedule.job_registry 的 ScheduleExecuteResult、transfer deps、file_preparation。
逻辑:与 09:00 自动调拨解耦;自动调拨仍会调用统一文件准备服务,不假设本排程成功。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.file_preparation import ensure_receipt_file_ready
from app.services.schedule.job_registry import ScheduleExecuteResult
def _wanted_sources(task: ScheduleTask) -> list[str]:
"""提取结构化 source_codes;留空代表全部启用来源。"""
params = task.job_params if isinstance(task.job_params, dict) else {}
values = params.get("source_codes") or []
if isinstance(values, str):
values = [values]
return [str(item).strip() for item in values if str(item).strip()]
def run_in_transit_receipt_file_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""08:00 收料文件抓取;按来源实例独立执行。"""
deps = transfer_deps.get_transfer_dependencies()
sources = _wanted_sources(task) or []
business_date = str(business_date_now())
total = success = failed = empty = 0
results: list[dict[str, Any]] = []
warnings: list[str] = []
errors: list[str] = []
for source_code in sources:
total += 1
try:
prepared = ensure_receipt_file_ready(
source_code=source_code,
business_date=business_date,
repository=deps.file_repository,
rpa_trigger=deps.rpa_trigger,
)
results.append({"source_code": source_code, "stage": prepared.stage})
if prepared.stage == "file_ready":
success += 1
elif prepared.stage == "waiting_rpa_callback":
empty += 1
else:
failed += 1
errors.append(f"{source_code}: {prepared.error_code or 'file_prep_failed'}")
except Exception as exc: # noqa: BLE001 —— 来源隔离
failed += 1
errors.append(f"{source_code}: {exc}")
return (total, success, failed, empty, results, warnings, errors)
@@ -1,8 +1,12 @@
"""自动调拨排程(09:00)。
"""自动调拨排程。
用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。
依赖:auto_transfer、transfer deps、ScheduleExecuteResult。
逻辑:复用统一文件准备服务,不假设 08:00 排程成功;来源实例独立执行。
依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
不依赖其他排程成功;来源留空兜底为全部启用收料来源;有通知人时构造
sender,仅在有 run_no 或空数据日(无 errors)后置 domain_notification_managed
抑制框架卡;硬失败不置标记以便框架兜底。
"""
from __future__ import annotations
@@ -11,42 +15,90 @@ from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.auto_transfer import run_auto_transfer
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
from app.services.in_transit_transfer.wecom_sender import WecomSummarySender
from app.services.schedule.job_registry import ScheduleExecuteResult
def _task_params(task: ScheduleTask) -> dict[str, Any]:
"""读取排程结构化参数(job_params 非字典时回落空对象)。"""
return task.job_params if isinstance(task.job_params, dict) else {}
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""09:00 自动调拨:恢复 + 预检 + 执行 + 通知。"""
def _wanted_source_codes(task: ScheduleTask) -> list[str]:
"""提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。
Args:
task: 排程任务(job_params.source_codes 可为列表/字符串/缺省)。
Returns:
去空白后的来源编码列表;留空时为 list_receipt_capable_source_codes() 结果。
"""
params = _task_params(task)
source_codes = params.get("source_codes") or []
if isinstance(source_codes, str):
source_codes = [source_codes]
values = params.get("source_codes") or []
if isinstance(values, str):
values = [values]
codes = [str(item).strip() for item in values if str(item).strip()]
if not codes:
codes = list_receipt_capable_source_codes()
return codes
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。
核心逻辑:有通知人时构造 WecomSummarySender 传入 run_auto_transfer;
仅在返回后按结果决定是否置 domain_notification_managed——有 run_no
(成功/部分失败领域卡路径)或无 errors(空数据日 C5)时抑制框架卡;
硬失败(无 run_no 且有 errors)不置标记,允许框架完成卡兜底。
Args:
task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。
run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。
Returns:
ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。
"""
params = _task_params(task)
source_codes = _wanted_source_codes(task)
recover_history = bool(params.get("recover_history", True))
recipients = params.get("notify_user_ids") or []
recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()]
# 有通知人时构造 sender 传入领域层;是否抑制框架卡见下方按 outcome 判定。
sender = WecomSummarySender() if recipients else None
deps = transfer_deps.get_transfer_dependencies()
outcome = run_auto_transfer(
business_date=str(business_date_now()),
deps=deps,
source_codes=[str(item).strip() for item in source_codes],
source_codes=source_codes,
recover_history=recover_history,
sender=None, # 企微发送器在 deps/运维接线处注入(本期先记录阶段结果)
recipients=[str(item) for item in recipients],
sender=sender,
recipients=recipients,
)
# [STEP] 领域自管通知门禁:仅在领域卡已发出(有 run_no)或空数据日
# (无 errors,C5 静默)时置标记;硬失败让框架完成卡兜底。
if recipients and (outcome.run_no or not outcome.errors):
run.response_summary_json = {
**(run.response_summary_json or {}),
"domain_notification_managed": True,
}
results: list[dict[str, Any]] = []
errors: list[str] = list(outcome.errors)
recovery = outcome.recovery
warnings: list[str] = [
f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}",
]
if outcome.run_no:
results.append({
"run_no": outcome.run_no,
"status": outcome.run_status,
"notification_status": outcome.notification_status,
})
recovery = outcome.recovery
elif not outcome.errors:
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
warnings.append("no executable items; execution and notification skipped")
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
return (
success + recovery.recovered_count,
@@ -54,6 +106,6 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
recovery.still_blocked_count,
0,
results,
[f"recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}"],
warnings,
errors,
)
@@ -64,11 +64,31 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
} for source, _config in rows]
def _users_options() -> list[dict[str, Any]]:
"""启用中的用户列表(value=user.id),供排程通知人类参数选择。"""
from app.models import User
users = (
User.query.filter(User.status == "active")
.order_by(User.username.asc())
.all()
)
return [
{
"label": user.real_name or user.username,
"value": user.id,
"description": None if not user.wecom_userid else "wecom",
}
for user in users
]
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
"agent_apps": _agent_apps_options,
"shipping_inventory_sources": _shipping_inventory_sources_options,
"shipping_receipt_sources": _shipping_receipt_sources_options,
"users": _users_options,
}
+4 -25
View File
@@ -193,7 +193,6 @@ def _register_builtin_platform_jobs() -> None:
description="按预付款、出货款、验收款、质保款的三轮升级规则发送企业微信提醒。",
category="procurement",
))
from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule
from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule
register_platform_job(PlatformJobDefinition(
@@ -472,35 +471,15 @@ def _register_builtin_platform_jobs() -> None:
),
defaults=dict(DEFAULT_OA_SALES_RELEASE_JOB_PARAMS),
))
register_platform_job(PlatformJobDefinition(
key="in-transit-receipt-file",
label="在途收料文件抓取",
handler=run_in_transit_receipt_file_schedule,
description=(
"每日 08:00 为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。"
"09:00 自动调拨仍会调用统一文件准备服务,不假设本排程成功。"
),
category="platform",
params_schema=(
{
"key": "source_codes",
"type": "multi_select",
"label": "来源实例",
"label_key": "admin.schedule.form.transferSourceCodes",
"required": False,
"default": [],
"options_source": "shipping_inventory_sources",
},
),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key="in-transit-transfer",
label="在途自动调拨",
handler=run_in_transit_transfer_schedule,
description=(
"每日 09:00 自动处理新增可调拨项与历史可恢复异常;"
"每非空 Run 发送一条企微汇总通知;通知失败不改变 ERP 结果。"
"自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪"
"(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;"
"每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。"
"执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。"
),
category="platform",
params_schema=(
@@ -10,6 +10,7 @@ from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
@@ -85,6 +86,7 @@ def serialize_run(run: ScheduleRun) -> dict:
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
'inventory_raw_zip_available': inventory_raw_zip_available_from_summary(summary),
'receipt_raw_zip_available': receipt_raw_zip_available_from_summary(summary),
'kb_sync_status': run.kb_sync_status,
'kb_group_id': run.kb_group_id,
'kb_document_id': run.kb_document_id,
@@ -103,10 +103,11 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
"""
构造排程企微 textcard 跳转 query 参数。
核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 与 download 意图,
由前端在登录后自动触发一次下载,失败时保留手动下载入口。
核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1
与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。
"""
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
params: dict[str, Any] = {
@@ -116,6 +117,9 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
if inventory_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'inventory_raw_zip'
elif receipt_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'receipt_raw_zip'
return params
@@ -123,9 +127,9 @@ def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptRepor
"""
收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。
核心逻辑:库存与收料 RPA 共用同一企微通知出口(_notify_schedule_run_wecom),
本函数是收料侧的唯一分叉点——按 platform_api_path 识别收料排程,返回该 run
全部单元已归档且未被清理(archive_deleted_at 为空)的报表文件。
核心逻辑:按 platform_api_path 识别收料排程,返回该 run 全部单元已归档且
未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP,
本函数保留给管理员单文件重发等旁路读取。
"""
from app.models import ShippingReceiptRpaUnitRun
@@ -154,7 +158,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
组装排程完成企微 textcard 正文。
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
有原始库存归档时提示点击卡片进入 HXOPS 并在登录后自动下载(URL 仅放 jump_url,不写进正文)。
有原始库存/收料归档时提示包已随通知发送或可点击下载。
"""
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
skipped_count = int(run.skipped_count or 0)
@@ -168,12 +172,12 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
receipt_files = _receipt_report_files_for_run(run)
if receipt_files:
description += f'\n收料报表文件 {len(receipt_files)} 份:已随本通知发送'
if receipt_raw_zip_available_from_summary(summary):
description += '\n原始收料包:已随本通知发送;亦可点击本通知登录后下载'
return description
@@ -183,7 +187,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
则跳过以免与领域缺件/失败告警重复。
库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包;
收料附加该 run 全部单元的收料报表文件(见 _receipt_report_files_for_run)。
收料附加该 run 的原始收料 ZIP(不再逐文件推送)。
"""
from app.services.integrations.wecom.notify import (
upload_wecom_temp_media,
@@ -244,20 +248,20 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
run.run_no, exc,
)
receipt_media: list[tuple[str, str]] = []
for receipt_file in _receipt_report_files_for_run(run):
try:
from app.services.file_assets.storage import file_asset_storage
receipt_zip_media_id = None
receipt_zip_file_name = None
try:
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download
receipt_media_id = upload_wecom_temp_media(
file_asset_storage.get_bytes(receipt_file.storage_key), receipt_file.original_filename,
)
receipt_media.append((receipt_media_id, receipt_file.original_filename))
except Exception as exc:
current_app.logger.warning(
'[wecom-schedule] receipt file media upload failed for run %s file %s: %s',
run.run_no, receipt_file.id, exc,
)
receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run)
receipt_zip_media_id = upload_wecom_temp_media(
receipt_zip_path.read_bytes(), receipt_zip_file_name,
)
except Exception as exc:
current_app.logger.info(
'[wecom-schedule] raw receipt zip media skipped for run %s: %s',
run.run_no, exc,
)
textcard_ok_count = 0
errors = []
@@ -314,21 +318,23 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
except Exception as exc:
errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
for receipt_media_id, receipt_filename in receipt_media:
if receipt_zip_media_id:
try:
receipt_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_receipt_file', u,
title, f'[收料报表] {receipt_filename}', uuid.uuid4().hex,
receipt_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_receipt_raw_zip', u,
title, f'[原始收料包] {receipt_zip_file_name}', uuid.uuid4().hex,
)
receipt_data = send_wecom_file_message(u.wecom_userid, receipt_media_id)
if receipt_data.get('errcode') == 0:
receipt_audit.status = 'sent'
receipt_zip_data = send_wecom_file_message(u.wecom_userid, receipt_zip_media_id)
if receipt_zip_data.get('errcode') == 0:
receipt_zip_audit.status = 'sent'
else:
receipt_audit.error_code = str(receipt_data.get('errcode'))
receipt_audit.error_message = str(receipt_data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: receipt file errcode={receipt_data.get("errcode")}')
receipt_zip_audit.error_code = str(receipt_zip_data.get('errcode'))
receipt_zip_audit.error_message = str(receipt_zip_data.get('errmsg', 'unknown'))[:255]
errors.append(
f'{u.real_name or u.username}: receipt zip errcode={receipt_zip_data.get("errcode")}'
)
except Exception as exc:
errors.append(f'{u.real_name or u.username}: receipt file exception={exc}')
errors.append(f'{u.real_name or u.username}: receipt zip exception={exc}')
if textcard_ok_count > 0:
run.wecom_notified = True
@@ -0,0 +1,306 @@
"""
backend/app/services/schedule/shipping_receipt_rpa_archive.py
用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingReceiptReportFile / ShippingReceiptRpaUnitRun、
file_asset_storage、timezone_util、freight_receipt_rpa_finalize.is_freight_receipt_rpa_task。
逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`;
warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。
"""
from __future__ import annotations
import json
import re
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from flask import current_app
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.services.file_assets.storage import file_asset_storage
from app.services.schedule.freight_receipt_rpa_finalize import is_freight_receipt_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员'
_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
'raw_receipt_zip_available': False,
'raw_receipt_zip_path': None,
'raw_receipt_file_count': 0,
'raw_receipt_file_ids': [],
'raw_receipt_zip_size': 0,
}
def get_receipt_archive_dir() -> str:
"""
返回收料 RPA 原始 ZIP 归档根目录(自动创建)。
核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径,
避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。
"""
configured = ''
if current_app:
raw = current_app.config.get('FREIGHT_RPA_RECEIPT_ARCHIVE_DIR')
configured = str(raw).strip() if raw is not None else ''
if not configured:
from app.core.config.settings import Config
configured = str(Config.FREIGHT_RPA_RECEIPT_ARCHIVE_DIR or '').strip()
archive_dir = Path(configured)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
"""
推导企微/下载展示名中的当地时刻。
核心逻辑:与库存归档同构——started_at → created_at → finished_at →
解析 RUN{yyyyMMddHHmmss}* → utcnow;再转到任务 schedule_timezone。
"""
when_utc: datetime | None = None
for value in (run.started_at, run.created_at, run.finished_at):
if isinstance(value, datetime):
when_utc = value
break
if when_utc is None:
match = re.match(r'^RUN(\d{14})', str(run.run_no or '').strip())
if match:
try:
when_utc = datetime.strptime(match.group(1), '%Y%m%d%H%M%S')
except ValueError:
when_utc = None
if when_utc is None:
when_utc = datetime.now(timezone.utc).replace(tzinfo=None)
task = getattr(run, 'task', None)
tz_name = getattr(task, 'schedule_timezone', None) if task is not None else None
tz = resolve_schedule_tzinfo(tz_name)
if when_utc.tzinfo is None:
when_utc = when_utc.replace(tzinfo=timezone.utc)
return when_utc.astimezone(tz)
def receipt_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
收料 RPA 企微附件共用前缀:收料RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
Args:
run: 排程执行记录。
Returns:
不含角色后缀与扩展名的展示名前缀。
"""
when = _attachment_when_from_run(run)
return f"收料RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
def receipt_raw_zip_download_name(run: ScheduleRun) -> str:
"""
收料 ZIP 的企微/浏览器下载展示名。
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f'{receipt_rpa_attachment_stem(run)}-收料.zip'
def _receipt_raw_zip_archive_path(run_no: str) -> Path:
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
return Path(get_receipt_archive_dir()) / f'{run_no}.zip'
def _iter_packable_receipt_files(run: ScheduleRun):
"""
遍历该 run 下可打包的收料归档文件。
核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。
Yields:
ShippingReceiptReportFile: 可从 MinIO 读取的归档记录。
"""
if not is_freight_receipt_rpa_task(getattr(run, 'task', None)):
return
rows = (
ShippingReceiptReportFile.query.join(
ShippingReceiptRpaUnitRun,
ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id,
)
.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.id.asc())
.all()
)
for report_file in rows:
yield report_file
def receipt_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
"""
从 response_summary_json 读取原始收料 ZIP 是否可下载。
核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。
"""
if not isinstance(summary, dict):
return False
return bool(summary.get('raw_receipt_zip_available'))
def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
"""
finalize 阶段预生成原始收料 ZIP 归档并返回 summary 字段。
核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 <archive_dir>/<run_no>.zip
(含 manifest.json);无可用文件时返回 raw_receipt_zip_available=false。
Args:
run: 收料 RPA ScheduleRun。
Returns:
dict: raw_receipt_zip_available / path / file_count / file_ids / zip_size。
"""
packable_files = list(_iter_packable_receipt_files(run))
if not packable_files:
return dict(_EMPTY_ARCHIVE_SUMMARY)
archive_path = _receipt_raw_zip_archive_path(run.run_no)
files_manifest: list[dict[str, Any]] = []
with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
for zip_index, report_file in enumerate(packable_files, start=1):
unit = report_file.unit_run
source_code = str(getattr(unit, 'source_code', None) or '').strip()
warehouse_id = str(getattr(unit, 'warehouse_id', None) or '').strip()
original_name = str(report_file.original_filename or '').strip() or 'receipt.xlsx'
suffix = Path(original_name).suffix or '.xlsx'
entry_name = _build_zip_entry_name(
index=zip_index,
source_code=source_code,
warehouse_id=warehouse_id,
original_suffix=suffix,
)
# [STEP] 收料归档在 MinIO:读字节后 writestr,不依赖本地 storage_path。
data = file_asset_storage.get_bytes(report_file.storage_key)
archive.writestr(entry_name, data)
files_manifest.append({
'file_id': report_file.id,
'source_code': source_code,
'warehouse_id': warehouse_id,
'file_name': entry_name,
'original_file_name': original_name,
'sha256': report_file.sha256,
})
manifest = {
'run_no': run.run_no,
'total_count': int(run.total_count or 0),
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'files': files_manifest,
}
archive.writestr(
'manifest.json',
json.dumps(manifest, ensure_ascii=False, indent=2),
)
return {
'raw_receipt_zip_available': True,
'raw_receipt_zip_path': str(archive_path.resolve()),
'raw_receipt_file_count': len(files_manifest),
'raw_receipt_file_ids': [item['file_id'] for item in files_manifest],
'raw_receipt_zip_size': int(archive_path.stat().st_size),
}
def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != '.zip':
return False
if not resolved.is_file():
return False
archive_dir = Path(get_receipt_archive_dir()).resolve()
try:
resolved.relative_to(archive_dir)
except ValueError:
return False
return True
def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
"""
解析 run 已归档的原始收料 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_receipt_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
Raises:
NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not receipt_raw_zip_available_from_summary(summary):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path_raw = str(summary.get('raw_receipt_zip_path') or '').strip()
if not zip_path_raw:
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path = Path(zip_path_raw)
if not _is_allowed_receipt_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), receipt_raw_zip_download_name(run)
def _sanitize_zip_segment(value: str) -> str:
"""ZIP 内文件名片段安全化,避免路径穿越与非法字符。"""
cleaned = re.sub(r'[^\w\-.]+', '_', str(value or '').strip())
return cleaned or 'unknown'
def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str:
"""
包内短标签:优先 source_code;无则回退仓码;再否则 receipt。
warehouse_id / file_id 已写入 manifest.json;条目名不必再叠仓码。
"""
source = str(source_code or '').strip()
if source:
return source
warehouse = str(warehouse_id or '').strip()
if warehouse and warehouse.lower() not in {'unknown', 'na'}:
return warehouse
return 'receipt'
def _build_zip_entry_name(
*,
index: int,
source_code: str,
warehouse_id: str,
original_suffix: str,
) -> str:
"""
生成 ZIP 内单文件条目名(不含目录)。
核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。
"""
label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id))
suffix = original_suffix if original_suffix.startswith('.') else f'.{original_suffix}'
return f'{index:03d}_{label}{suffix}'