Files
hugo abf3d48927 feat(in-transit-transfer): 自动调拨联动收料就绪并分层来源错误
- 调度整合:退役 in_transit_receipt_file_job,收料归档收敛 shipping_receipt_rpa_archive,排程注册表统一
- 自动调拨 Job:调拨前确保各来源当日收料文件就绪(缺失自动触发收料 RPA),严格等量匹配后生成 ERP 调拨单
- worker 手动唤醒:排程工作台支持手动唤醒与 runs 透视,heartbeat 协议同步
- 收料缺失幸存 T2:parse_failed 状态落库(迁移 q4c5)
- 来源错误分层与 stale 时钟换源:改挂 inventory_checked_at 库存查得时刻,展示阈值与执行门禁解耦(迁移 t5a6)
- 新增 wecom_sender 企微通知:每非空 Run 汇总一条,通知失败不影响 ERP 结果
- 同步排程工作台/调拨卡片前端、chat/admin 文案四语言、RPA 脚本与测试全家
2026-09-30 00:20:06 +08:00

272 lines
12 KiB
Python

"""
backend/app/api/schedule/runs.py
用途:排程运行触发与运行记录查询 API。
依赖:schedule.blueprint、services/schedule/query_service、queue_service。
逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。
"""
from __future__ import annotations
from datetime import datetime
from io import BytesIO
import uuid
from flask import jsonify, request, send_file
from app import db
from app.api.schedule.blueprint import schedule_admin_bp
from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.errors import ConflictError, NotFoundError
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.services.schedule.query_service import get_run, list_runs, serialize_run
from app.services.schedule.queue_service import enqueue_manual_schedule_run
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
@require_admin
def run_schedule(task_id: int):
"""
手动触发排程并立即返回 queued 运行记录。
核心逻辑:queue_service 同事务创建 ScheduleRun + Job;独立 worker 后台执行。
"""
task = db.session.get(ScheduleTask, task_id)
if not task:
raise NotFoundError('Not found')
user = get_current_user()
run, _job_id, created = enqueue_manual_schedule_run(
task.id,
triggered_by_user_id=getattr(user, 'id', None),
)
if not created:
raise ConflictError('该排程正在等待或执行中,请等待完成后再试', details={'run_id': run.id})
fresh = db.session.get(ScheduleRun, run.id)
return jsonify(serialize_run(fresh))
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
@require_admin
def get_schedule_runs(task_id: int):
"""按任务 ID 分页/过滤返回运行记录。"""
status = str(request.args.get('status') or '').strip() or None
limit = int(request.args.get('limit') or 100)
started_after = None
started_before = None
sa = request.args.get('started_after')
sb = request.args.get('started_before')
if sa:
try:
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
except (ValueError, TypeError):
pass
if sb:
try:
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
except (ValueError, TypeError):
pass
return jsonify(
list_runs(
task_id=task_id,
status=status,
started_after=started_after,
started_before=started_before,
limit=limit,
)
)
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
@require_admin
def get_schedule_run(run_id: int):
"""返回单条运行记录详情。"""
run = get_run(run_id)
if not run:
raise NotFoundError('Not found')
return jsonify(serialize_run(run))
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
@require_admin
def get_schedule_run_excel(run_id: int):
"""下载运行结果 Excel 附件。"""
run = get_run(run_id)
if not run:
raise NotFoundError('Not found')
if not run.excel_file_data:
raise NotFoundError('Excel not found')
buf = BytesIO(run.excel_file_data)
return send_file(
buf,
as_attachment=True,
download_name=run.excel_file_name or 'result.xlsx',
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/inventory-raw-zip', methods=['GET'])
@require_admin
def get_schedule_run_inventory_raw_zip(run_id: int):
"""下载库存 RPA 排程 run 的原始库存 Excel 打包(ZIP + manifest)。"""
run = get_run(run_id)
if not run:
raise NotFoundError('Not found')
zip_path, file_name = resolve_inventory_raw_zip_download(run)
return send_file(
zip_path,
as_attachment=True,
download_name=file_name,
mimetype='application/zip',
)
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/receipt-raw-zip', methods=['GET'])
@require_admin
def get_schedule_run_receipt_raw_zip(run_id: int):
"""
下载收料 RPA 排程 run 的原始收料 Excel 打包(ZIP + manifest)。
核心逻辑:对齐 inventory-raw-zip;展示名为 收料RPA-{日期}-{时刻}-收料.zip。
"""
run = get_run(run_id)
if not run:
raise NotFoundError('Not found')
zip_path, file_name = resolve_receipt_raw_zip_download(run)
return send_file(
zip_path,
as_attachment=True,
download_name=file_name,
mimetype='application/zip',
)
@schedule_admin_bp.route('/receipt-report-files/<int:file_id>/resend', methods=['POST'])
@require_admin
def resend_receipt_report_file(file_id: int):
"""管理员重发已归档的收料文件;禁止借重发重新触发 RPA 导出。"""
report_file = db.session.get(ShippingReceiptReportFile, file_id)
if report_file is None or report_file.archive_deleted_at is not None:
raise NotFoundError('Receipt report file not found')
user = get_current_user()
outcome = deliver_receipt_file(report_file.id, force=True)
append_shipping_audit_event(
event_type='shipping_receipt_report_notification_resent', aggregate_type='shipping_receipt_file',
aggregate_id=str(report_file.id), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), unit_id=report_file.unit_run_id, result='success',
after={'status': 'resent', 'owner_user_id': getattr(user, 'id', None)},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'success_count': int(outcome.get('success_count', 0)), 'failed_count': int(outcome.get('failed_count', 0))},
)
db.session.commit()
return jsonify({'success': True, 'data': outcome})
@schedule_admin_bp.route('/receipt-rpa-units', methods=['GET'])
@require_admin
def list_receipt_rpa_units():
"""管理员查看收料单元运行事实,供失败单元填写原因后人工重试。"""
status = str(request.args.get('status') or '').strip().lower()
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
from app.core.errors import ValidationError
raise ValidationError('status is invalid')
try:
limit = max(1, min(int(request.args.get('limit') or 100), 200))
except (TypeError, ValueError):
from app.core.errors import ValidationError
raise ValidationError('limit is invalid')
query = ShippingReceiptRpaUnitRun.query.order_by(
ShippingReceiptRpaUnitRun.created_at.desc(), ShippingReceiptRpaUnitRun.id.desc(),
)
if status:
query = query.filter(ShippingReceiptRpaUnitRun.status == status)
units = query.limit(limit).all()
user = get_current_user()
append_shipping_audit_event(
event_type='shipping_receipt_rpa_units_listed', aggregate_type='shipping_receipt_unit_collection',
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), result='success',
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
metadata={'surface': 'workspace_receipt_report_files'},
)
db.session.commit()
return jsonify({'success': True, 'data': {'items': [{
'id': unit.id,
'source_code': unit.source_code,
'warehouse_id': unit.warehouse_id,
'status': unit.status,
'error_code': unit.error_code,
'error_message': unit.error_message,
'retry_of_id': unit.retry_of_id,
'schedule_run_id': unit.schedule_run_id,
'created_at': unit.created_at.isoformat() if unit.created_at else None,
'finished_at': unit.finished_at.isoformat() if unit.finished_at else None,
} for unit in units]}})
@schedule_admin_bp.route('/receipt-rpa-units/<int:unit_id>/retry', methods=['POST'])
@require_admin
def retry_receipt_rpa_unit(unit_id: int):
"""管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。"""
failed = db.session.get(ShippingReceiptRpaUnitRun, unit_id)
if failed is None:
raise NotFoundError('Receipt RPA unit not found')
if failed.status not in {'failed', 'cancelled'}:
raise ConflictError('Only failed receipt RPA units can be retried')
data = request.get_json(silent=True) or {}
reason = str(data.get('reason') or '').strip()
if not reason:
from app.core.errors import ValidationError
raise ValidationError('reason is required', code='SHIPPING.RECEIPT_RETRY_REASON_REQUIRED')
user = get_current_user()
retry = ShippingReceiptRpaUnitRun(
schedule_run_id=failed.schedule_run_id, inventory_source_id=failed.inventory_source_id,
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
warehouse_id=failed.warehouse_id, callback_id=f'receipt:{uuid.uuid4().hex}', status='awaiting_rpa',
config_snapshot_json=dict(failed.config_snapshot_json or {}),
)
db.session.add(retry)
db.session.flush()
source = retry.inventory_source
profile = source.rpa_profile if source is not None else None
if source is None or profile is None or not profile.enabled:
db.session.rollback()
raise ConflictError('Receipt RPA profile is unavailable')
snapshot = dict(retry.config_snapshot_json or {})
trigger_unit = {
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
'connector_type': retry.connector_type, 'warehouse_id': retry.warehouse_id,
'rpa_profile_id': profile.id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'credential_envelope': {'username_ciphertext': profile.username_ciphertext, 'password_ciphertext': profile.password_ciphertext},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(snapshot.get('query_parameters_json') or []), 'config_snapshot': snapshot,
}
retry.trigger_snapshot_json = trigger_unit
run = retry.schedule_run
trigger_path = write_receipt_export_batch_trigger(
f'{run.run_no}-retry-{retry.id}', [trigger_unit],
{'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': 'shipping_receipt_rpa.v1', 'retry_of_unit_id': failed.id},
)
if not trigger_path:
db.session.rollback()
raise ConflictError('Receipt RPA trigger directory is unavailable')
run.status = 'running'
run.finished_at = None
summary = dict(run.response_summary_json or {})
summary['awaiting_receipt_rpa'] = True
run.response_summary_json = summary
append_shipping_audit_event(
event_type='shipping_receipt_rpa_unit_retried', aggregate_type='shipping_receipt_unit',
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
before={'status': failed.status, 'error_code': failed.error_code},
after={'status': retry.status, 'source_run_no': retry.callback_id, 'owner_user_id': getattr(user, 'id', None)},
metadata={'retry_of_id': failed.id},
)
db.session.commit()
return jsonify({'success': True, 'data': {'unit_id': retry.id, 'retry_of_id': failed.id, 'callback_id': retry.callback_id, 'trigger_path': trigger_path}})