""" backend/app/api/schedule/runs.py 用途:排程运行触发与运行记录查询 API。 依赖:schedule.blueprint、services/schedule/query_service、queue_service、 freight_rpa inbound/outbound archive 与 trigger_io。 逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。 入站/出站 raw-zip 下载与失败单元 list/retry 对照同构。 """ 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, FreightRpaInboundUnitRun, FreightRpaOutboundUnitRun 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.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download from app.services.schedule.freight_rpa_inbound_archive import resolve_inbound_raw_zip_download from app.services.schedule.freight_rpa_outbound_archive import resolve_outbound_raw_zip_download from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_SCHEMA, write_outbound_export_batch_trigger @schedule_admin_bp.route('/schedules//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( '该排程正在等待或执行中,请等待完成后再试', code='SCHEDULE.RUN_ALREADY_ACTIVE', details={'run_id': run.id}, ) fresh = db.session.get(ScheduleRun, run.id) return jsonify(serialize_run(fresh)) @schedule_admin_bp.route('/schedules//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/', 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//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//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//inbound-raw-zip', methods=['GET']) @require_admin def get_schedule_run_inbound_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_inbound_raw_zip_download(run) return send_file( zip_path, as_attachment=True, download_name=file_name, mimetype='application/zip', ) @schedule_admin_bp.route('/inbound-rpa-units', methods=['GET']) @require_admin def list_inbound_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 = FreightRpaInboundUnitRun.query.order_by( FreightRpaInboundUnitRun.created_at.desc(), FreightRpaInboundUnitRun.id.desc(), ) if status: query = query.filter(FreightRpaInboundUnitRun.status == status) units = query.limit(limit).all() user = get_current_user() append_shipping_audit_event( event_type='shipping_inbound_rpa_units_listed', aggregate_type='shipping_inbound_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': 'admin_inbound_rpa_units'}, ) 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('/inbound-rpa-units//retry', methods=['POST']) @require_admin def retry_inbound_rpa_unit(unit_id: int): """管理员为失败入站单元创建独立重试事实;旧单元永不覆盖。""" failed = db.session.get(FreightRpaInboundUnitRun, unit_id) if failed is None: raise NotFoundError('Inbound RPA unit not found') if failed.status not in {'failed', 'cancelled'}: raise ConflictError('Only failed inbound 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.INBOUND_RETRY_REASON_REQUIRED') user = get_current_user() retry = FreightRpaInboundUnitRun( schedule_run_id=failed.schedule_run_id, source_id=failed.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'inbound:{uuid.uuid4().hex}', status='awaiting_rpa', config_snapshot_json=dict(failed.config_snapshot_json or {}), ) db.session.add(retry) db.session.flush() source = retry.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('Inbound 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_inbound_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': SCHEMA, 'retry_of_unit_id': failed.id}, ) if not trigger_path: db.session.rollback() raise ConflictError('Inbound RPA trigger directory is unavailable') run.status = 'running' run.finished_at = None summary = dict(run.response_summary_json or {}) summary['awaiting_inbound_rpa'] = True run.response_summary_json = summary append_shipping_audit_event( event_type='shipping_inbound_rpa_unit_retried', aggregate_type='shipping_inbound_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}}) @schedule_admin_bp.route('/schedule-runs//outbound-raw-zip', methods=['GET']) @require_admin def get_schedule_run_outbound_raw_zip(run_id: int): """ 下载出站 RPA 排程 run 的原始出站 Excel 打包(ZIP + manifest)。 核心逻辑:对齐 inbound-raw-zip;展示名为 出站RPA-{日期}-{时刻}-出站.zip。 """ run = get_run(run_id) if not run: raise NotFoundError('Not found') zip_path, file_name = resolve_outbound_raw_zip_download(run) return send_file( zip_path, as_attachment=True, download_name=file_name, mimetype='application/zip', ) @schedule_admin_bp.route('/outbound-rpa-units', methods=['GET']) @require_admin def list_outbound_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 = FreightRpaOutboundUnitRun.query.order_by( FreightRpaOutboundUnitRun.created_at.desc(), FreightRpaOutboundUnitRun.id.desc(), ) if status: query = query.filter(FreightRpaOutboundUnitRun.status == status) units = query.limit(limit).all() user = get_current_user() append_shipping_audit_event( event_type='shipping_outbound_rpa_units_listed', aggregate_type='shipping_outbound_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': 'admin_outbound_rpa_units'}, ) 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('/outbound-rpa-units//retry', methods=['POST']) @require_admin def retry_outbound_rpa_unit(unit_id: int): """管理员为失败出站单元创建独立重试事实;旧单元永不覆盖。调拨按需单元无排程 run 时仍可重试。""" failed = db.session.get(FreightRpaOutboundUnitRun, unit_id) if failed is None: raise NotFoundError('Outbound RPA unit not found') if failed.status not in {'failed', 'cancelled'}: raise ConflictError('Only failed outbound 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.OUTBOUND_RETRY_REASON_REQUIRED') user = get_current_user() retry = FreightRpaOutboundUnitRun( schedule_run_id=failed.schedule_run_id, source_id=failed.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'outbound:{uuid.uuid4().hex}', status='awaiting_rpa', config_snapshot_json=dict(failed.config_snapshot_json or {}), ) db.session.add(retry) db.session.flush() source = retry.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('Outbound 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 run_no = run.run_no if run is not None else f'outbound-retry-{retry.id}' trigger_meta = { 'schema_version': OUTBOUND_SCHEMA, 'retry_of_unit_id': failed.id, } if run is not None: trigger_meta['schedule_run_id'] = run.id trigger_meta['schedule_task_id'] = run.schedule_task_id trigger_path = write_outbound_export_batch_trigger( f'{run_no}-retry-{retry.id}', [trigger_unit], trigger_meta, ) if not trigger_path: db.session.rollback() raise ConflictError('Outbound RPA trigger directory is unavailable') if run is not None: run.status = 'running' run.finished_at = None summary = dict(run.response_summary_json or {}) summary['awaiting_outbound_rpa'] = True run.response_summary_json = summary append_shipping_audit_event( event_type='shipping_outbound_rpa_unit_retried', aggregate_type='shipping_outbound_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}})