""" 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.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//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//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('/receipt-report-files//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//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}})