diff --git a/backend/.env b/backend/.env new file mode 100644 index 00000000..a8c7b996 --- /dev/null +++ b/backend/.env @@ -0,0 +1,58 @@ +INTEGRATION_API_BASE=http://192.168.100.230:8891 +INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh + + +# 是否启用 JWT 认证 +AUTH_JWT_REQUIRED=true + +# AUTH_LOGIN_MODE=casdoor +# 如果需要用户密码登录,修改该值为password +AUTH_LOGIN_MODE=password + +# Casdoor JWT 验签三件套 +AUTH_JWT_ISSUER=http://ai.well-trust.com:8870 +AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 +AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks + +# Casdoor OAuth +CASDOOR_BASE_URL=http://192.168.100.230:8870 +CASDOOR_CLIENT_ID=758be5fcba2df784fdb4 +CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab +# CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback +CASDOOR_REDIRECT_URI=http://192.168.100.230:8881/casdoor-callback +CASDOOR_SCOPE=openid profile email + +# 是否保留本地密码登录/本地JWT兼容(按你当前需求建议保留) +AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true +AUTH_ALLOW_LOCAL_JWT=true +AUTH_LOCAL_JWT_ISSUER=hxops-backend +AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend +AUTH_LOCAL_JWT_EXPIRES_HOURS=12 + +GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu +GJL_API_BASE=https://api.siliconflow.cn/v1 +GJL_MODEL=deepseek-ai/DeepSeek-V3 + +# HR SQL Server Configuration +HR_SQLSERVER_HOST=192.168.100.191 +HR_SQLSERVER_PORT=1433 +HR_SQLSERVER_DATABASE=NH_N8_HEXIN +HR_SQLSERVER_USERNAME=AI_Knowledge_Base_Hr +HR_SQLSERVER_PASSWORD=hoo-thai@123_AI_HR +HR_SQLSERVER_DRIVER=SQL Server +HR_SQLSERVER_ENCRYPT=no +HR_SQLSERVER_TRUST_CERT=yes +HR_SQLSERVER_TIMEOUT=10 + +DATABASE_URL=postgresql://postgres:postgres@localhost:5432/hxops_db + +# SRM SQL Server Configuration +SRM_SQLSERVER_HOST=192.168.55.106 +SRM_SQLSERVER_PORT=1433 +SRM_SQLSERVER_DATABASE=HX-SRM +SRM_SQLSERVER_USERNAME=sa +SRM_SQLSERVER_PASSWORD=sa@moreyou456 +SRM_SQLSERVER_DRIVER=SQL Server +SRM_SQLSERVER_ENCRYPT=no +SRM_SQLSERVER_TRUST_CERT=yes +SRM_SQLSERVER_TIMEOUT=10 \ No newline at end of file diff --git a/backend/app/__init__.py b/backend/app/__init__.py index d7563b37..72e91ed8 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -51,6 +51,8 @@ def create_app(config_name='default'): from app.api.user import user_bp from app.api.knowledge_base import knowledge_base_bp from app.api.integration import integration_bp + from app.api.schedule_admin import schedule_admin_bp + from app.api.workspace_schedule import workspace_schedule_bp # 聊天相关接口 app.register_blueprint(chat_bp, url_prefix='/api/chat') @@ -64,6 +66,8 @@ def create_app(config_name='default'): app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb') # 知识库外部集成接口(供聊天/外部系统按 Dify 映射反查源文件) app.register_blueprint(integration_bp, url_prefix='/api/integration') + app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin') + app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace') # Eagerly load persisted runtime settings so the very first request after # a worker boot already sees the admin-saved configuration (otherwise the @@ -71,6 +75,8 @@ def create_app(config_name='default'): # serve the defaults baked into config.py / the image). with app.app_context(): _apply_persisted_settings(app) + from app.services.schedule.scheduler_service import start_scheduler + start_scheduler(app) @app.before_request def _sync_persisted_settings(): diff --git a/backend/app/api/schedule_admin.py b/backend/app/api/schedule_admin.py new file mode 100644 index 00000000..739aa658 --- /dev/null +++ b/backend/app/api/schedule_admin.py @@ -0,0 +1,205 @@ +from __future__ import annotations + +import threading +from datetime import datetime + +from flask import Blueprint, current_app, jsonify, request, send_file + +from app.decorators import require_admin +from app import db +from app.models import ScheduleRun, ScheduleTask +from app.auth_jwt import get_current_user +from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task +from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no + +schedule_admin_bp = Blueprint('schedule_admin', __name__) + + +@schedule_admin_bp.route('/schedules', methods=['GET']) +@require_admin +def get_schedules(): + return jsonify(list_tasks()) + + +@schedule_admin_bp.route('/schedules', methods=['POST']) +@require_admin +def post_schedule(): + data = request.get_json(silent=True) or {} + user = get_current_user() + task = create_task( + name=str(data.get('name') or '').strip(), + schedule_type='platform_app', + owner_user_id=int(data.get('owner_user_id')), + cron_expr=str(data.get('cron_expr') or '').strip(), + wait_seconds=int(data.get('wait_seconds') or 0), + dify_agent_id=(int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None), + platform_api_path=str(data.get('platform_api_path') or '').strip() or None, + notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], + notify_enabled=bool(data.get('notify_enabled', True)), + enabled=bool(data.get('enabled', True)), + actor_id=getattr(user, 'id', None), + ) + return jsonify(serialize_task(task)), 201 + + +@schedule_admin_bp.route('/schedules/', methods=['GET']) +@require_admin +def get_schedule(task_id: int): + task = db.session.get(ScheduleTask, task_id) + if not task: + return jsonify({'error': 'Not found'}), 404 + return jsonify(serialize_task(task)) + + +@schedule_admin_bp.route('/schedules/', methods=['PATCH']) +@require_admin +def patch_schedule(task_id: int): + task = db.session.get(ScheduleTask, task_id) + if not task: + return jsonify({'error': 'Not found'}), 404 + data = request.get_json(silent=True) or {} + user = get_current_user() + task = update_task(task, payload=data, actor_id=getattr(user, 'id', None)) + return jsonify(serialize_task(task)) + + +@schedule_admin_bp.route('/schedules/', methods=['DELETE']) +@require_admin +def delete_schedule(task_id: int): + task = db.session.get(ScheduleTask, task_id) + if not task: + return jsonify({'error': 'Not found'}), 404 + runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).all() + for r in runs: + if r.excel_file_path: + try: + from pathlib import Path + p = Path(r.excel_file_path) + if p.exists(): + p.unlink() + except Exception: + pass + db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False) + db.session.delete(task) + db.session.commit() + return jsonify({'ok': True}) + + +@schedule_admin_bp.route('/schedules//enable', methods=['POST']) +@require_admin +def enable_schedule(task_id: int): + task = db.session.get(ScheduleTask, task_id) + if not task: + return jsonify({'error': 'Not found'}), 404 + task.enabled = True + if task.cron_expr: + try: + from croniter import croniter + iter = croniter(task.cron_expr, datetime.utcnow()) + task.next_run_at = iter.get_next(datetime) + except Exception: + task.next_run_at = None + db.session.commit() + return jsonify({'ok': True}) + + +@schedule_admin_bp.route('/schedules//disable', methods=['POST']) +@require_admin +def disable_schedule(task_id: int): + task = db.session.get(ScheduleTask, task_id) + if not task: + return jsonify({'error': 'Not found'}), 404 + task.enabled = False + db.session.commit() + return jsonify({'ok': True}) + + +@schedule_admin_bp.route('/schedules//run', methods=['POST']) +@require_admin +def run_schedule(task_id: int): + task = db.session.get(ScheduleTask, task_id) + if not task: + return jsonify({'error': 'Not found'}), 404 + user = get_current_user() + + run = ScheduleRun( + run_no=_generate_run_no(), + schedule_task_id=task.id, + trigger_type='manual', + triggered_by_user_id=getattr(user, 'id', None), + started_at=datetime.utcnow(), + status='running', + ) + db.session.add(run) + db.session.commit() + + app = current_app._get_current_object() + run_id = run.id + + def _background(): + with app.app_context(): + t = db.session.get(ScheduleTask, task_id) + r = db.session.get(ScheduleRun, run_id) + if not t or not r: + return + try: + run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r) + except Exception as exc: + try: + r = db.session.get(ScheduleRun, run_id) + if r and r.status == 'running': + r.status = 'failed' + r.error_message = str(exc) + r.finished_at = datetime.utcnow() + db.session.commit() + except Exception: + db.session.rollback() + current_app.logger.error("[schedule-run] run_id=%s failed: %s", run_id, exc, exc_info=True) + + t = threading.Thread(target=_background, daemon=True, name=f"schedule-run-{run_id}") + t.start() + + 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): + 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) + except (ValueError, TypeError): + pass + if sb: + try: + started_before = datetime.fromisoformat(sb) + 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: + return jsonify({'error': 'Not found'}), 404 + return jsonify(serialize_run(run)) + + +@schedule_admin_bp.route('/schedule-runs//excel', methods=['GET']) +@require_admin +def get_schedule_run_excel(run_id: int): + run = get_run(run_id) + if not run: + return jsonify({'error': 'Not found'}), 404 + if not run.excel_file_path: + return jsonify({'error': 'Excel not found'}), 404 + return send_file(run.excel_file_path, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx') diff --git a/backend/app/api/workspace_schedule.py b/backend/app/api/workspace_schedule.py new file mode 100644 index 00000000..0bbd65fb --- /dev/null +++ b/backend/app/api/workspace_schedule.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from datetime import datetime + +from flask import Blueprint, jsonify, request, send_file + +from app.auth_jwt import get_current_user +from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run + +workspace_schedule_bp = Blueprint('workspace_schedule', __name__) + + +def _require_user(): + user = get_current_user() + if not user: + return None, (jsonify({'error': 'Unauthorized'}), 401) + return user, None + + +@workspace_schedule_bp.route('/schedule-runs', methods=['GET']) +def workspace_schedule_runs(): + user, err = _require_user() + if err: + return err + status = str(request.args.get('status') or '').strip() or None + schedule_name = str(request.args.get('schedule_name') or '').strip() or None + started_after_str = request.args.get('started_after') + started_before_str = request.args.get('started_before') + started_after = datetime.fromisoformat(started_after_str) if started_after_str else None + started_before = datetime.fromisoformat(started_before_str) if started_before_str else None + limit = int(request.args.get('limit') or 100) + return jsonify(list_runs( + notify_user_id=user.id, + schedule_name=schedule_name, + status=status, + started_after=started_after, + started_before=started_before, + limit=limit, + )) + + +@workspace_schedule_bp.route('/schedule-runs/', methods=['GET']) +def workspace_schedule_run_detail(run_id: int): + user, err = _require_user() + if err: + return err + run = get_run(run_id) + if not run: + return jsonify({'error': 'Not found'}), 404 + if not can_view_run(run, user.id): + return jsonify({'error': 'Forbidden'}), 403 + return jsonify(serialize_run(run)) + + +@workspace_schedule_bp.route('/schedule-runs//excel', methods=['GET']) +def workspace_schedule_run_excel(run_id: int): + user, err = _require_user() + if err: + return err + run = get_run(run_id) + if not run: + return jsonify({'error': 'Not found'}), 404 + if not can_view_run(run, user.id): + return jsonify({'error': 'Forbidden'}), 403 + if not run.excel_file_path: + return jsonify({'error': 'Excel not found'}), 404 + return send_file(run.excel_file_path, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx') diff --git a/backend/app/config.py b/backend/app/config.py index b99be645..de35ce13 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -30,7 +30,7 @@ def _load_environment_files() -> str: 1. .env.shared 2. .env. 3. .env.local (only for dev) - 4. system environment variables (always highest because override=False) + 4. system environment variables (always highest, never overridden) """ env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV')) shared_file = _ROOT_DIR / '.env.shared' @@ -44,7 +44,7 @@ def _load_environment_files() -> str: if env_name == 'dev': local_file = _ROOT_DIR / '.env.local' if local_file.exists(): - load_dotenv(local_file, override=False) + load_dotenv(local_file, override=True) return env_name @@ -136,6 +136,27 @@ class Config: AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER') AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE') AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12')) + SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true' + SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '') + SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433') + SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '') + SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '') + SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '') + SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server') + SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no') + SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes') + SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15')) + SMTP_HOST = os.getenv('SMTP_HOST', '') + SMTP_PORT = int(os.getenv('SMTP_PORT', '25')) + SMTP_USER = os.getenv('SMTP_USER', '') + SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '') + SMTP_FROM = os.getenv('SMTP_FROM', '') + SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true' + SCHEDULE_EXCEL_STORAGE_ROOT = os.getenv( + 'SCHEDULE_EXCEL_STORAGE_ROOT', + str(_BACKEND_DIR / 'data' / 'schedules'), + ) + INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:8880') class DevelopmentConfig(Config): @@ -153,6 +174,7 @@ class TestingConfig(Config): SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' WTF_CSRF_ENABLED = False SQLALCHEMY_ENGINE_OPTIONS = {} + SCHEDULE_WORKER_ENABLED = False config = { diff --git a/backend/app/models.py b/backend/app/models.py index 3309162b..1a937fd1 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -546,3 +546,67 @@ class WecomCallbackAudit(Base): error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + +class ScheduleTask(Base): + __tablename__ = 'schedule_tasks' + __table_args__ = ( + Index('ix_schedule_tasks_enabled_next_run', 'enabled', 'next_run_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + schedule_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) + name: Mapped[str] = mapped_column(String(128), index=True) + schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app') + owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True) + cron_expr: Mapped[str] = mapped_column(String(64)) + wait_seconds: Mapped[int] = mapped_column(Integer, default=0) + dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True) + platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[]) + notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True) + enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True) + next_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True) + last_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id]) + dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id]) + + +class ScheduleRun(Base): + __tablename__ = 'schedule_runs' + __table_args__ = ( + Index('ix_schedule_runs_task_created', 'schedule_task_id', 'created_at'), + Index('ix_schedule_runs_status_created', 'status', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + run_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) + schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True) + trigger_type: Mapped[str] = mapped_column(String(16), default='cron') + triggered_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True) + duration_ms: Mapped[int] = mapped_column(Integer, default=0) + status: Mapped[str] = mapped_column(String(32), default='queued', index=True) + total_count: Mapped[int] = mapped_column(Integer, default=0) + success_count: Mapped[int] = mapped_column(Integer, default=0) + failed_count: Mapped[int] = mapped_column(Integer, default=0) + skipped_count: Mapped[int] = mapped_column(Integer, default=0) + api_request_json: Mapped[Optional[dict]] = mapped_column(JSON) + api_response_json: Mapped[Optional[dict]] = mapped_column(JSON) + response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON) + error_message: Mapped[Optional[str]] = mapped_column(Text) + excel_file_path: Mapped[Optional[str]] = mapped_column(Text) + excel_file_name: Mapped[Optional[str]] = mapped_column(String(255)) + excel_file_size: Mapped[Optional[int]] = mapped_column(Integer) + mail_sent: Mapped[bool] = mapped_column(Boolean, default=False) + mail_sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + mail_error: Mapped[Optional[str]] = mapped_column(Text) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + + task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id]) + diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index ac4fa4d4..d86000e1 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -87,6 +87,207 @@ class DifyService: return f"{base}/chat-messages" return f"{base}/v1/chat-messages" + @staticmethod + def _stringify_inputs(inputs: dict[str, Any] | None) -> dict[str, Any]: + def _convert(v): + if v is None: + return "" + if isinstance(v, dict): + return {kk: _convert(vv) for kk, vv in v.items()} + if isinstance(v, list): + return [_convert(i) for i in v] + return str(v) + return {k: _convert(v) for k, v in (inputs or {}).items()} + + @staticmethod + def _build_workflow_url(base_url: str) -> str: + base = str(base_url or "").strip().rstrip("/") + if not base: + return "/v1/workflows/run" + if base.endswith("/v1/workflows/run"): + base = base[: -len("/v1/workflows/run")].rstrip("/") + elif base.endswith("/workflows/run"): + base = base[: -len("/workflows/run")].rstrip("/") + if base.endswith("/v1"): + return f"{base}/workflows/run" + return f"{base}/v1/workflows/run" + + @staticmethod + def run_workflow_streaming( + *, + agent, + inputs: dict[str, Any] | None = None, + user: str = "system", + timeout: tuple[int, int] = (5, 300), + ) -> dict[str, Any]: + base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE + url = DifyService._build_workflow_url(base_url) + + headers = { + "Authorization": f"Bearer {agent.dify_api_key}", + "Content-Type": "application/json", + } + payload = { + "inputs": DifyService._stringify_inputs(inputs), + "response_mode": "streaming", + "user": str(user or "system"), + } + + if current_app: + current_app.logger.info( + "[workflow-streaming] start user=%s agent_id=%s url=%s", + user, + getattr(agent, "id", None), + url, + ) + + result: dict[str, Any] = {} + workflow_run_id: str | None = None + + try: + with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp: + if not resp.ok: + body = resp.text[:2000] + if current_app: + current_app.logger.error( + "[workflow-streaming] dify error status=%s url=%s body=%s", + resp.status_code, url, body, + ) + resp.raise_for_status() + + for line in resp.iter_lines(decode_unicode=True): + if not line: + continue + if not line.startswith("data:"): + continue + raw = line[len("data:"):].strip() + if not raw: + continue + try: + evt = json.loads(raw) + except json.JSONDecodeError: + continue + + event_type = evt.get("event", "") + + if event_type == "workflow_started": + workflow_run_id = (evt.get("data") or {}).get("workflow_run_id") + if current_app: + current_app.logger.info( + "[workflow-streaming] started run_id=%s", + workflow_run_id, + ) + + elif event_type == "workflow_finished": + result = evt.get("data") or {} + if current_app: + current_app.logger.info( + "[workflow-streaming] finished status=%s", + result.get("status"), + ) + + elif event_type == "error": + err_msg = evt.get("message") or str(evt) + if current_app: + current_app.logger.error( + "[workflow-streaming] dify stream error: %s", + err_msg, + ) + raise RuntimeError(f"Dify workflow error: {err_msg}") + + except requests.exceptions.RequestException as exc: + if result: + if current_app: + current_app.logger.info( + "[workflow-streaming] connection dropped but result already captured", + ) + elif workflow_run_id: + if current_app: + current_app.logger.warning( + "[workflow-streaming] connection dropped, polling result for run_id=%s", + workflow_run_id, + ) + result = DifyService._poll_workflow_result( + agent=agent, + workflow_run_id=workflow_run_id, + max_wait=timeout[1] if isinstance(timeout, tuple) else 300, + ) + else: + if current_app: + current_app.logger.error( + "[workflow-streaming] request error (no run_id): %s", + exc, + ) + raise + + return result if isinstance(result, dict) else {} + + @staticmethod + def _poll_workflow_result( + *, + agent, + workflow_run_id: str, + max_wait: int = 300, + interval: int = 10, + ) -> dict[str, Any]: + base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE + base = str(base_url).strip().rstrip("/") + if base.endswith("/v1/workflows/run"): + base = base[: -len("/v1/workflows/run")].rstrip("/") + elif base.endswith("/workflows/run"): + base = base[: -len("/workflows/run")].rstrip("/") + if base.endswith("/v1"): + poll_url = f"{base}/workflows/run/{workflow_run_id}" + else: + poll_url = f"{base}/v1/workflows/run/{workflow_run_id}" + + headers = { + "Authorization": f"Bearer {agent.dify_api_key}", + "Content-Type": "application/json", + } + + elapsed = 0 + while elapsed < max_wait: + time.sleep(interval) + elapsed += interval + + try: + resp = requests.get(poll_url, headers=headers, timeout=(5, 30)) + if not resp.ok: + if current_app: + current_app.logger.warning( + "[workflow-poll] status=%s url=%s", + resp.status_code, poll_url, + ) + continue + + data = resp.json() if resp.content else {} + status = data.get("status", "") + + if current_app: + current_app.logger.info( + "[workflow-poll] run_id=%s status=%s elapsed=%ds", + workflow_run_id, status, elapsed, + ) + + if status in ("succeeded", "failed", "stopped"): + return data + + except requests.exceptions.RequestException as exc: + if current_app: + current_app.logger.warning( + "[workflow-poll] request error: %s", + exc, + ) + continue + + if current_app: + current_app.logger.error( + "[workflow-poll] timed out after %ds run_id=%s", + max_wait, workflow_run_id, + ) + return {} + @staticmethod def stream_chat(query: str, user_id: int, agent, conversation_id: str = None): """ diff --git a/backend/app/services/schedule/__init__.py b/backend/app/services/schedule/__init__.py new file mode 100644 index 00000000..1547cf97 --- /dev/null +++ b/backend/app/services/schedule/__init__.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import requests +from typing import Any, Callable +from urllib.parse import urlparse + +from flask import current_app + +from app import db +from app.models import Agent, ScheduleRun, ScheduleTask +from app.services.schedule.srm_service import run_rohs_doc_check_dify_job + +ScheduleExecuteResult = tuple[int, int, int, list[dict[str, Any]], list[str]] +ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult] + + +def normalize_platform_api_path(path: str | None) -> str: + value = str(path or "").strip() + if not value: + return "" + parsed = urlparse(value) + if parsed.scheme in {"http", "https"}: + return value + if not value.startswith("/"): + value = "/" + value + return value + + +def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + endpoint = normalize_platform_api_path(task.platform_api_path) + if not endpoint: + raise RuntimeError("platform_api_path is missing") + + base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/") + url = endpoint if endpoint.startswith("http://") or endpoint.startswith("https://") else (f"{base}{endpoint}" if base else endpoint) + + payload = { + "run_no": run.run_no, + "schedule_task_id": task.id, + "schedule_name": task.name, + "dify_agent_id": task.dify_agent_id, + } + + run.api_request_json = payload + db.session.commit() + + try: + resp = requests.post(url, json=payload, timeout=(5, 60)) + resp.raise_for_status() + data = resp.json() if resp.content else {} + except requests.RequestException as e: + data = {} + if e.response is not None: + try: + data = e.response.json() + except Exception: + data = {"error_text": e.response.text} + else: + data = {"error": str(e)} + run.api_response_json = data + db.session.commit() + raise e + + run.api_response_json = data + db.session.commit() + + summary = data.get("summary") if isinstance(data, dict) and isinstance(data.get("summary"), dict) else {} + details = data.get("details") if isinstance(data, dict) and isinstance(data.get("details"), list) else [] + errors = data.get("errors") if isinstance(data, dict) and isinstance(data.get("errors"), list) else [] + + total = int(summary.get("total_count") if summary.get("total_count") is not None else (len(details) or 1)) + success = int(summary.get("success_count") if summary.get("success_count") is not None else total) + failed = int(summary.get("failed_count") if summary.get("failed_count") is not None else max(0, total - success)) + return total, success, failed, details, [str(e) for e in errors if str(e).strip()] + + +def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + agent = db.session.get(Agent, task.dify_agent_id) if task.dify_agent_id else None + if task.dify_agent_id and (not agent or not agent.dify_api_key): + raise RuntimeError("dify_agent_id is invalid or key is missing") + + host = str(current_app.config.get("SRM_SQLSERVER_HOST") or "").strip() + if not host: + raise RuntimeError("SRM_SQLSERVER_HOST is not configured") + + port = str(current_app.config.get("SRM_SQLSERVER_PORT") or "1433").strip() + database = str(current_app.config.get("SRM_SQLSERVER_DATABASE") or "").strip() + username = str(current_app.config.get("SRM_SQLSERVER_USERNAME") or "").strip() + password = str(current_app.config.get("SRM_SQLSERVER_PASSWORD") or "").strip() + driver = str(current_app.config.get("SRM_SQLSERVER_DRIVER") or "SQL Server").strip() + encrypt = str(current_app.config.get("SRM_SQLSERVER_ENCRYPT") or "no").strip().lower() + trust_cert = str(current_app.config.get("SRM_SQLSERVER_TRUST_CERT") or "yes").strip().lower() + + conn_str = ( + f"DRIVER={{{driver}}};" + f"SERVER={host},{port};" + f"DATABASE={database};" + f"UID={username};" + f"PWD={password};" + f"Encrypt={encrypt};" + f"TrustServerCertificate={trust_cert};" + ) + + return run_rohs_doc_check_dify_job( + conn_str=conn_str, + run_no=run.run_no, + agent=agent, + user=str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system"), + wait_seconds=task.wait_seconds or 120, + ) + + +_SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = { + "default": _run_common_executor, + "srm_rohs_doc_check": _run_srm_rohs_doc_check_executor, +} + + +def register_schedule_executor(name: str, executor: ScheduleExecutor) -> None: + key = str(name or "").strip().lower() + if not key: + raise ValueError("executor name is required") + _SCHEDULE_EXECUTOR_REGISTRY[key] = executor + + +def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor: + path = normalize_platform_api_path(task.platform_api_path) + if path: + lookup_key = path.lstrip("/").lower() + if lookup_key in _SCHEDULE_EXECUTOR_REGISTRY: + return _SCHEDULE_EXECUTOR_REGISTRY[lookup_key] + return _SCHEDULE_EXECUTOR_REGISTRY["default"] diff --git a/backend/app/services/schedule/excel_service.py b/backend/app/services/schedule/excel_service.py new file mode 100644 index 00000000..e07bb780 --- /dev/null +++ b/backend/app/services/schedule/excel_service.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from openpyxl import Workbook + + +def export_schedule_result_excel(*, run_no: str, summary: dict, details: list[dict], root_dir: str) -> tuple[str | None, str | None, int]: + if not details: + return None, None, 0 + + out_root = Path(root_dir) + out_root.mkdir(parents=True, exist_ok=True) + + rows: list[dict[str, Any]] = [] + for row in details: + output = row.get('dify_output') + if not isinstance(output, dict): + output = {} + entry = dict(output) + for k in ('writeback_ok', 'error'): + if k in row: + entry[k] = row[k] + rows.append(entry) + + headers: list[str] = [] + for row in rows: + for k in row: + if k not in headers: + headers.append(k) + + wb = Workbook() + ws = wb.active + ws.title = 'result' + ws.append(headers) + + for row in rows: + ws.append([row.get(k, '') for k in headers]) + + file_name = f'schedule_{run_no}.xlsx' + file_path = out_root / file_name + wb.save(file_path) + size = file_path.stat().st_size + return str(file_path), file_name, int(size) diff --git a/backend/app/services/schedule/mail_service.py b/backend/app/services/schedule/mail_service.py new file mode 100644 index 00000000..9b00a92f --- /dev/null +++ b/backend/app/services/schedule/mail_service.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import smtplib +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText + + +def send_schedule_mail(*, smtp_host: str, smtp_port: int, smtp_user: str, smtp_password: str, use_tls: bool, from_addr: str, to_addrs: list[str], subject: str, html_body: str) -> None: + if not to_addrs: + return + msg = MIMEMultipart('alternative') + msg['Subject'] = subject + msg['From'] = from_addr + msg['To'] = ', '.join(to_addrs) + msg.attach(MIMEText(html_body, 'html', 'utf-8')) + + with smtplib.SMTP(smtp_host, smtp_port, timeout=20) as server: + if use_tls: + server.starttls() + if smtp_user: + server.login(smtp_user, smtp_password) + server.sendmail(from_addr, to_addrs, msg.as_string()) + + +def build_schedule_mail_html(*, schedule_name: str, run_no: str, status: str, total: int, success: int, failed: int) -> str: + return ( + "" + "

排程执行结果

" + "" + f"" + f"" + f"" + f"" + f"" + f"" + "
排程{schedule_name}
执行单号{run_no}
状态{status}
总数{total}
成功{success}
失败{failed}
" + ) diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py new file mode 100644 index 00000000..1bec1258 --- /dev/null +++ b/backend/app/services/schedule/query_service.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +from datetime import datetime +from typing import Optional + +from sqlalchemy import func +from sqlalchemy.orm import joinedload + +from app import db +from app.models import ScheduleRun, ScheduleTask + + +def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dict: + return { + 'id': task.id, + 'schedule_no': task.schedule_no, + 'name': task.name, + 'schedule_type': task.schedule_type, + 'owner_user_id': task.owner_user_id, + 'owner_username': task.owner.username if task.owner else None, + 'cron_expr': task.cron_expr, + 'wait_seconds': task.wait_seconds, + 'dify_agent_id': task.dify_agent_id, + 'platform_api_path': task.platform_api_path, + 'notify_user_ids_json': task.notify_user_ids_json or [], + 'notify_enabled': bool(task.notify_enabled), + 'enabled': bool(task.enabled), + 'next_run_at': task.next_run_at.isoformat() if task.next_run_at else None, + 'last_run_at': task.last_run_at.isoformat() if task.last_run_at else None, + 'last_status': last_status, + 'created_at': task.created_at.isoformat() if task.created_at else None, + 'updated_at': task.updated_at.isoformat() if task.updated_at else None, + } + + +def serialize_run(run: ScheduleRun) -> dict: + return { + 'id': run.id, + 'run_no': run.run_no, + 'schedule_task_id': run.schedule_task_id, + 'schedule_name': run.task.name if run.task else None, + 'trigger_type': run.trigger_type, + 'triggered_by_user_id': run.triggered_by_user_id, + 'started_at': run.started_at.isoformat() if run.started_at else None, + 'finished_at': run.finished_at.isoformat() if run.finished_at else None, + 'duration_ms': run.duration_ms, + 'status': run.status, + 'total_count': run.total_count, + 'success_count': run.success_count, + 'failed_count': run.failed_count, + 'skipped_count': run.skipped_count, + 'api_request_json': run.api_request_json, + 'api_response_json': run.api_response_json, + 'response_summary_json': run.response_summary_json, + 'error_message': run.error_message, + 'excel_file_name': run.excel_file_name, + 'excel_file_size': run.excel_file_size, + 'mail_sent': bool(run.mail_sent), + 'mail_sent_at': run.mail_sent_at.isoformat() if run.mail_sent_at else None, + 'mail_error': run.mail_error, + 'created_at': run.created_at.isoformat() if run.created_at else None, + } + + +def list_tasks() -> list[dict]: + latest_run_subquery = ( + db.session.query( + ScheduleRun.schedule_task_id.label('task_id'), + func.max(ScheduleRun.id).label('last_run_id'), + ) + .group_by(ScheduleRun.schedule_task_id) + .subquery() + ) + rows = ( + db.session.query(ScheduleTask, ScheduleRun.status.label('last_status')) + .options(joinedload(ScheduleTask.owner)) + .outerjoin(latest_run_subquery, latest_run_subquery.c.task_id == ScheduleTask.id) + .outerjoin(ScheduleRun, ScheduleRun.id == latest_run_subquery.c.last_run_id) + .order_by(ScheduleTask.created_at.desc()) + .all() + ) + return [serialize_task(task, last_status=last_status) for task, last_status in rows] + + +def list_runs( + *, + task_id: Optional[int] = None, + owner_user_id: Optional[int] = None, + notify_user_id: Optional[int] = None, + schedule_name: Optional[str] = None, + status: Optional[str] = None, + started_after: Optional[datetime] = None, + started_before: Optional[datetime] = None, + limit: int = 100, +) -> list[dict]: + query = db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id) + if task_id is not None: + query = query.filter(ScheduleRun.schedule_task_id == task_id) + if schedule_name: + query = query.filter(ScheduleTask.name.ilike(f'%{schedule_name}%')) + if status: + query = query.filter(ScheduleRun.status == status) + if started_after is not None: + query = query.filter(ScheduleRun.started_at >= started_after) + if started_before is not None: + query = query.filter(ScheduleRun.started_at < started_before) + if owner_user_id is not None: + query = query.filter(ScheduleTask.owner_user_id == owner_user_id) + if notify_user_id is not None: + query = query.filter( + (ScheduleTask.owner_user_id == notify_user_id) + | ScheduleTask.notify_user_ids_json.cast(db.String).ilike(f'%{notify_user_id}%') + ) + runs = query.order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 500))).all() + return [serialize_run(r) for r in runs] + + +def get_run(run_id: int) -> ScheduleRun | None: + return db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).filter(ScheduleRun.id == run_id).first() + + +def can_view_run(run: ScheduleRun, user_id: int) -> bool: + task = run.task + if not task: + return False + if task.owner_user_id == user_id: + return True + notify = task.notify_user_ids_json or [] + return int(user_id) in {int(x) for x in notify if str(x).isdigit()} diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py new file mode 100644 index 00000000..1a24f751 --- /dev/null +++ b/backend/app/services/schedule/scheduler_service.py @@ -0,0 +1,252 @@ +from __future__ import annotations + +import threading +import time +import uuid +from datetime import datetime +from typing import Any + +from croniter import croniter +from flask import current_app + +from app import db +from app.models import ScheduleRun, ScheduleTask, User +from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor +from app.services.schedule.excel_service import export_schedule_result_excel +from app.services.schedule.mail_service import build_schedule_mail_html, send_schedule_mail + +_worker_started = False +_worker_lock = threading.Lock() + + +def _generate_schedule_no() -> str: + return f"SCH{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}" + + +def _generate_run_no() -> str: + return f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}" + + +def create_task( + *, + name: str, + schedule_type: str, + owner_user_id: int, + cron_expr: str, + wait_seconds: int, + dify_agent_id: int | None, + platform_api_path: str | None, + notify_user_ids_json: list[int] | None, + notify_enabled: bool, + enabled: bool, + actor_id: int | None, +) -> ScheduleTask: + if not normalize_platform_api_path(platform_api_path): + raise ValueError("platform_api_path is required for platform_app") + + task = ScheduleTask( + schedule_no=_generate_schedule_no(), + name=name, + schedule_type="platform_app", + owner_user_id=owner_user_id, + cron_expr=cron_expr, + wait_seconds=max(0, int(wait_seconds or 0)), + dify_agent_id=dify_agent_id, + platform_api_path=normalize_platform_api_path(platform_api_path) or None, + notify_user_ids_json=notify_user_ids_json or [], + notify_enabled=bool(notify_enabled), + enabled=bool(enabled), + created_by=actor_id, + updated_by=actor_id, + ) + if task.enabled and task.cron_expr: + try: + iter = croniter(task.cron_expr, datetime.utcnow()) + task.next_run_at = iter.get_next(datetime) + except Exception: + task.next_run_at = None + task.enabled = False + db.session.add(task) + db.session.commit() + return task + + +def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int | None) -> ScheduleTask: + for key in [ + "name", + "owner_user_id", + "cron_expr", + "wait_seconds", + "dify_agent_id", + "notify_enabled", + "enabled", + ]: + if key in payload: + setattr(task, key, payload[key]) + if "platform_api_path" in payload: + task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None + if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list): + task.notify_user_ids_json = payload.get("notify_user_ids_json") + + if not normalize_platform_api_path(task.platform_api_path): + raise ValueError("platform_api_path is required for platform_app") + task.schedule_type = "platform_app" + + if task.enabled and task.cron_expr: + try: + iter = croniter(task.cron_expr, datetime.utcnow()) + task.next_run_at = iter.get_next(datetime) + except Exception: + task.next_run_at = None + else: + task.next_run_at = None + + task.updated_by = actor_id + db.session.commit() + return task + + +def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun: + if run is None: + run = ScheduleRun( + run_no=_generate_run_no(), + schedule_task_id=task.id, + trigger_type=trigger_type, + triggered_by_user_id=triggered_by_user_id, + started_at=datetime.utcnow(), + status="running", + ) + db.session.add(run) + db.session.commit() + + start_ts = time.time() + try: + executor = resolve_schedule_executor(task) + total_count, success_count, failed_count, details, errors = executor(task, run) + + duration_ms = int((time.time() - start_ts) * 1000) + if total_count == 0 and not errors: + status = "success" + run.error_message = "无待处理数据" + elif failed_count == 0: + status = "success" + elif success_count == 0: + status = "failed" + else: + status = "partial_failed" + + file_path, file_name, file_size = export_schedule_result_excel( + run_no=run.run_no, + summary={ + "status": status, + "total_count": total_count, + "success_count": success_count, + "failed_count": failed_count, + "duration_ms": duration_ms, + }, + details=details, + root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(), + ) + + run.finished_at = datetime.utcnow() + run.duration_ms = duration_ms + run.status = status + run.total_count = total_count + run.success_count = success_count + run.failed_count = failed_count + run.skipped_count = 0 + run.response_summary_json = { + "errors": errors[:20], + "schedule_type": task.schedule_type, + "platform_api_path": task.platform_api_path, + } + run.error_message = "; ".join(errors[:3]) if errors else None + run.excel_file_path = file_path + run.excel_file_name = file_name + run.excel_file_size = file_size or 0 + + if task.notify_enabled: + users = db.session.query(User).filter(User.id.in_(task.notify_user_ids_json or [])).all() + to_addrs = [u.email for u in users if u.email] + if to_addrs: + try: + send_schedule_mail( + smtp_host=str(current_app.config.get("SMTP_HOST") or ""), + smtp_port=int(current_app.config.get("SMTP_PORT") or 25), + smtp_user=str(current_app.config.get("SMTP_USER") or ""), + smtp_password=str(current_app.config.get("SMTP_PASSWORD") or ""), + use_tls=bool(current_app.config.get("SMTP_USE_TLS", True)), + from_addr=str(current_app.config.get("SMTP_FROM") or current_app.config.get("SMTP_USER") or "noreply@example.com"), + to_addrs=to_addrs, + subject=f"排程执行结果 {task.name} {run.run_no}", + html_body=build_schedule_mail_html( + schedule_name=task.name, + run_no=run.run_no, + status=status, + total=total_count, + success=success_count, + failed=failed_count, + ), + ) + run.mail_sent = True + run.mail_sent_at = datetime.utcnow() + except Exception as mail_exc: + run.mail_sent = False + run.mail_error = str(mail_exc) + + task.last_run_at = datetime.utcnow() + db.session.commit() + return run + except Exception as exc: + run.finished_at = datetime.utcnow() + run.duration_ms = int((time.time() - start_ts) * 1000) + run.status = "failed" + run.error_message = str(exc) + db.session.commit() + return run + + +def start_scheduler(app): + global _worker_started + with _worker_lock: + if _worker_started: + return + _worker_started = True + + if not bool(app.config.get("SCHEDULE_WORKER_ENABLED", True)): + return + + def _loop(): + with app.app_context(): + while True: + try: + now = datetime.utcnow() + due_tasks = db.session.query(ScheduleTask).filter( + ScheduleTask.enabled.is_(True), + ScheduleTask.next_run_at.isnot(None), + ScheduleTask.next_run_at <= now, + ).limit(5).all() + for task in due_tasks: + try: + run_task_now(task, trigger_type="cron", triggered_by_user_id=None) + except Exception as e: + current_app.logger.error("[schedule-worker] task_id=%s run failed: %s", task.id, e, exc_info=True) + db.session.rollback() + + if task.cron_expr: + try: + iter = croniter(task.cron_expr, datetime.utcnow()) + task.next_run_at = iter.get_next(datetime) + except Exception: + task.next_run_at = None + task.enabled = False + else: + task.next_run_at = None + + db.session.commit() + except Exception: + db.session.rollback() + time.sleep(30) + + t = threading.Thread(target=_loop, daemon=True, name="schedule-worker") + t.start() diff --git a/backend/app/services/schedule/srm_service.py b/backend/app/services/schedule/srm_service.py new file mode 100644 index 00000000..5c0db6ef --- /dev/null +++ b/backend/app/services/schedule/srm_service.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +from typing import Any + +from flask import current_app +from app.services.dify import DifyService + +try: + import pyodbc # type: ignore +except Exception: # pragma: no cover + pyodbc = None + + +FIXED_ROHS_SQL = """ +select + TOP(100) + t2.supplier_code as supplier_code, + t2.supplier_name as supplier_name, + t2.material_code as item_code, + t2.material_name as item_name, + t1.id as id, + t1.material as material, + t1.material_name as material_name, + t1.third_code as third_code, + t1.test_item as test_item, + t1.pb as pb, + t1.cd as cd, + t1.hg as hg, + t1.cr6 as cr6, + t1.pbbs as pbbs, + t1.pbdes as pbdes, + t1.dbp as dbp, + t1.bbp as bbp, + t1.dehp as dehp, + t1.dibp as dibp, + t1.cl as cl, + t1.br as br, + COALESCE(CONVERT(VARCHAR(19), t1.test_date, 120), '1970-01-01 00:00:00') as test_date, + 'http://srm.well-trust.com:8090/hexin-boot/sys/common/static/' + COALESCE(t1.attachment, '') as attachment +from + control_harmful_substances t1, + control_harmful t2 +where + 1 = 1 + and t1.control_harmful_id = t2.id + and t1.def11 is null + and t2.def1 = '7' +""" + + +def _connect(conn_str: str): + if pyodbc is None: + raise RuntimeError('pyodbc is not installed') + return pyodbc.connect(conn_str, timeout=15) + + +def fetch_rohs_records(conn_str: str) -> list[dict[str, Any]]: + conn = _connect(conn_str) + try: + cur = conn.cursor() + cur.execute(FIXED_ROHS_SQL) + cols = [c[0] for c in cur.description] + rows = cur.fetchall() + return [{cols[i]: row[i] for i in range(len(cols))} for row in rows] + finally: + conn.close() + + +def writeback_rohs(conn_str: str, *, row_id: str, run_no: str, judgement: str, reason: str) -> None: + conn = _connect(conn_str) + try: + cur = conn.cursor() + cur.execute( + "UPDATE control_harmful_substances SET def11=?, def12=?, def13=? WHERE id=?", + (run_no, judgement, reason, str(row_id)), + ) + conn.commit() + finally: + conn.close() + + +def _derive_judgement_and_reason(data: dict[str, Any]) -> tuple[str, str]: + judgement = str(data.get("judgement") or data.get("result") or "人工判定").strip() + reason = str(data.get("reason") or "").strip() + if judgement not in {"合格", "不合格", "人工判定"}: + reason = (reason + " | 返回值异常:" + judgement).strip(" |") + judgement = "人工判定" + return judgement, reason + + +def run_rohs_doc_check_dify_job(*, conn_str: str, run_no: str, agent=None, user: str = "schedule_system", wait_seconds: int = 120) -> tuple[int, int, int, list[dict[str, Any]], list[str]]: + use_dify = agent is not None + if use_dify and not getattr(agent, "dify_api_key", None): + raise RuntimeError("dify_agent_id is set, but Dify api key is missing") + + rows = fetch_rohs_records(conn_str) + total_count = len(rows) + details: list[dict[str, Any]] = [] + success_count = 0 + failed_count = 0 + errors: list[str] = [] + + for row in rows: + item = dict(row) + try: + if use_dify: + dify_res = DifyService.run_workflow_streaming( + agent=agent, + inputs={"inputs": {"run_no": run_no, "records": item}}, + user=user, + timeout=(5, max(300, int(wait_seconds))), + ) + outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res + if current_app: + current_app.logger.info( + "[srm-dify] judgement=%s reason=%s", + outputs.get("judgement") if isinstance(outputs, dict) else None, + outputs.get("reason") if isinstance(outputs, dict) else None, + ) + judgement, reason = _derive_judgement_and_reason(outputs if isinstance(outputs, dict) else {}) + item["dify_output"] = outputs if isinstance(outputs, dict) else {} + else: + judgement = "人工判定" + reason = "未配置 Agent ID,跳过 Dify" + + try: + writeback_rohs( + conn_str, + row_id=str(row.get("id")), + run_no=run_no, + judgement=judgement, + reason=reason, + ) + item.update({"judgement": judgement, "reason": reason, "writeback_ok": True, "error": None}) + success_count += 1 + except Exception as wb_exc: + if current_app: + current_app.logger.error("[srm-dify] writeback failed row_id=%s error=%s", row.get("id"), wb_exc) + item.update({"judgement": judgement, "reason": reason, "writeback_ok": False, "error": str(wb_exc)}) + failed_count += 1 + errors.append(f"writeback row_id={row.get('id')}: {wb_exc}") + except Exception as exc: + item.update({"judgement": "人工判定", "reason": f"执行异常:{exc}", "writeback_ok": False, "error": str(exc)}) + failed_count += 1 + errors.append(str(exc)) + details.append(item) + + return total_count, success_count, failed_count, details, errors diff --git a/backend/data/schedules/schedule_RUN202605180636031839.xlsx b/backend/data/schedules/schedule_RUN202605180636031839.xlsx new file mode 100644 index 00000000..7b8577e8 Binary files /dev/null and b/backend/data/schedules/schedule_RUN202605180636031839.xlsx differ diff --git a/backend/data/schedules/schedule_RUN20260518064805B22C.xlsx b/backend/data/schedules/schedule_RUN20260518064805B22C.xlsx new file mode 100644 index 00000000..55c6370c Binary files /dev/null and b/backend/data/schedules/schedule_RUN20260518064805B22C.xlsx differ diff --git a/backend/migrations/versions/dc9a4a2683df_merge_heads.py b/backend/migrations/versions/dc9a4a2683df_merge_heads.py new file mode 100644 index 00000000..ce4f9576 --- /dev/null +++ b/backend/migrations/versions/dc9a4a2683df_merge_heads.py @@ -0,0 +1,24 @@ +"""merge heads + +Revision ID: dc9a4a2683df +Revises: 2a4b6c8d0e1f, f5c3d4e5a6b7 +Create Date: 2026-05-16 15:11:20.476298 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'dc9a4a2683df' +down_revision = ('2a4b6c8d0e1f', 'f5c3d4e5a6b7') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/backend/migrations/versions/f3a1b2c3d4e5_add_schedule_tables.py b/backend/migrations/versions/f3a1b2c3d4e5_add_schedule_tables.py new file mode 100644 index 00000000..2d0205e3 --- /dev/null +++ b/backend/migrations/versions/f3a1b2c3d4e5_add_schedule_tables.py @@ -0,0 +1,111 @@ +"""add schedule tables + +Revision ID: f3a1b2c3d4e5 +Revises: f2b3c4d5e6f7 +Create Date: 2026-05-15 20:30:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f3a1b2c3d4e5' +down_revision = 'f2b3c4d5e6f7' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'schedule_tasks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('schedule_no', sa.String(length=64), nullable=False), + sa.Column('name', sa.String(length=128), nullable=False), + sa.Column('schedule_type', sa.String(length=32), nullable=False), + sa.Column('owner_user_id', sa.Integer(), nullable=False), + sa.Column('cron_expr', sa.String(length=64), nullable=False), + sa.Column('wait_seconds', sa.Integer(), nullable=False), + sa.Column('dify_agent_id', sa.Integer(), nullable=True), + sa.Column('notify_user_ids_json', sa.JSON(), nullable=True), + sa.Column('notify_enabled', sa.Boolean(), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False), + sa.Column('next_run_at', sa.DateTime(), nullable=True), + sa.Column('last_run_at', sa.DateTime(), nullable=True), + sa.Column('created_by', sa.Integer(), nullable=True), + sa.Column('updated_by', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['dify_agent_id'], ['agents.id'], ), + sa.ForeignKeyConstraint(['owner_user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['updated_by'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_schedule_tasks_enabled'), 'schedule_tasks', ['enabled'], unique=False) + op.create_index(op.f('ix_schedule_tasks_enabled_next_run'), 'schedule_tasks', ['enabled', 'next_run_at'], unique=False) + op.create_index(op.f('ix_schedule_tasks_id'), 'schedule_tasks', ['id'], unique=False) + op.create_index(op.f('ix_schedule_tasks_name'), 'schedule_tasks', ['name'], unique=False) + op.create_index(op.f('ix_schedule_tasks_next_run_at'), 'schedule_tasks', ['next_run_at'], unique=False) + op.create_index(op.f('ix_schedule_tasks_owner_user_id'), 'schedule_tasks', ['owner_user_id'], unique=False) + op.create_index(op.f('ix_schedule_tasks_schedule_no'), 'schedule_tasks', ['schedule_no'], unique=True) + + op.create_table( + 'schedule_runs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('run_no', sa.String(length=64), nullable=False), + sa.Column('schedule_task_id', sa.Integer(), nullable=False), + sa.Column('trigger_type', sa.String(length=16), nullable=False), + sa.Column('triggered_by_user_id', sa.Integer(), nullable=True), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('duration_ms', sa.Integer(), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False), + sa.Column('total_count', sa.Integer(), nullable=False), + sa.Column('success_count', sa.Integer(), nullable=False), + sa.Column('failed_count', sa.Integer(), nullable=False), + sa.Column('skipped_count', sa.Integer(), nullable=False), + sa.Column('response_summary_json', sa.JSON(), nullable=True), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('excel_file_path', sa.Text(), nullable=True), + sa.Column('excel_file_name', sa.String(length=255), nullable=True), + sa.Column('excel_file_size', sa.Integer(), nullable=True), + sa.Column('mail_sent', sa.Boolean(), nullable=False), + sa.Column('mail_sent_at', sa.DateTime(), nullable=True), + sa.Column('mail_error', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['schedule_task_id'], ['schedule_tasks.id'], ), + sa.ForeignKeyConstraint(['triggered_by_user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_schedule_runs_created_at'), 'schedule_runs', ['created_at'], unique=False) + op.create_index(op.f('ix_schedule_runs_finished_at'), 'schedule_runs', ['finished_at'], unique=False) + op.create_index(op.f('ix_schedule_runs_id'), 'schedule_runs', ['id'], unique=False) + op.create_index(op.f('ix_schedule_runs_run_no'), 'schedule_runs', ['run_no'], unique=True) + op.create_index(op.f('ix_schedule_runs_schedule_task_id'), 'schedule_runs', ['schedule_task_id'], unique=False) + op.create_index(op.f('ix_schedule_runs_started_at'), 'schedule_runs', ['started_at'], unique=False) + op.create_index(op.f('ix_schedule_runs_status'), 'schedule_runs', ['status'], unique=False) + op.create_index(op.f('ix_schedule_runs_status_created'), 'schedule_runs', ['status', 'created_at'], unique=False) + op.create_index(op.f('ix_schedule_runs_task_created'), 'schedule_runs', ['schedule_task_id', 'created_at'], unique=False) + + +def downgrade(): + op.drop_index(op.f('ix_schedule_runs_task_created'), table_name='schedule_runs') + op.drop_index(op.f('ix_schedule_runs_status_created'), table_name='schedule_runs') + op.drop_index(op.f('ix_schedule_runs_status'), table_name='schedule_runs') + op.drop_index(op.f('ix_schedule_runs_started_at'), table_name='schedule_runs') + op.drop_index(op.f('ix_schedule_runs_schedule_task_id'), table_name='schedule_runs') + op.drop_index(op.f('ix_schedule_runs_run_no'), table_name='schedule_runs') + op.drop_index(op.f('ix_schedule_runs_id'), table_name='schedule_runs') + op.drop_index(op.f('ix_schedule_runs_finished_at'), table_name='schedule_runs') + op.drop_index(op.f('ix_schedule_runs_created_at'), table_name='schedule_runs') + op.drop_table('schedule_runs') + + op.drop_index(op.f('ix_schedule_tasks_schedule_no'), table_name='schedule_tasks') + op.drop_index(op.f('ix_schedule_tasks_owner_user_id'), table_name='schedule_tasks') + op.drop_index(op.f('ix_schedule_tasks_next_run_at'), table_name='schedule_tasks') + op.drop_index(op.f('ix_schedule_tasks_name'), table_name='schedule_tasks') + op.drop_index(op.f('ix_schedule_tasks_id'), table_name='schedule_tasks') + op.drop_index(op.f('ix_schedule_tasks_enabled_next_run'), table_name='schedule_tasks') + op.drop_index(op.f('ix_schedule_tasks_enabled'), table_name='schedule_tasks') + op.drop_table('schedule_tasks') diff --git a/backend/migrations/versions/f4b2c3d4e5f6_add_platform_api_path_to_schedule_tasks.py b/backend/migrations/versions/f4b2c3d4e5f6_add_platform_api_path_to_schedule_tasks.py new file mode 100644 index 00000000..439ca2d7 --- /dev/null +++ b/backend/migrations/versions/f4b2c3d4e5f6_add_platform_api_path_to_schedule_tasks.py @@ -0,0 +1,25 @@ +"""add platform_api_path to schedule_tasks + +Revision ID: f4b2c3d4e5f6 +Revises: f3a1b2c3d4e5 +Create Date: 2026-05-16 17:20:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f4b2c3d4e5f6' +down_revision = 'f3a1b2c3d4e5' +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column('schedule_tasks', sa.Column('platform_api_path', sa.String(length=500), nullable=True)) + + +def downgrade(): + op.drop_column('schedule_tasks', 'platform_api_path') + diff --git a/backend/migrations/versions/f5c3d4e5a6b7_fix_schedule_tasks_indexes_and_defaults.py b/backend/migrations/versions/f5c3d4e5a6b7_fix_schedule_tasks_indexes_and_defaults.py new file mode 100644 index 00000000..a16c4cb9 --- /dev/null +++ b/backend/migrations/versions/f5c3d4e5a6b7_fix_schedule_tasks_indexes_and_defaults.py @@ -0,0 +1,26 @@ +"""fix schedule_tasks indexes and defaults + +Revision ID: f5c3d4e5a6b7 +Revises: f4b2c3d4e5f6 +Create Date: 2026-06-15 10:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +revision = 'f5c3d4e5a6b7' +down_revision = 'f4b2c3d4e5f6' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_index(op.f('ix_schedule_tasks_dify_agent_id'), 'schedule_tasks', ['dify_agent_id'], unique=False) + + op.execute("UPDATE schedule_tasks SET schedule_type = 'platform_app' WHERE schedule_type = 'dify_app'") + op.execute("UPDATE schedule_tasks SET notify_user_ids_json = '[]'::jsonb WHERE notify_user_ids_json IS NULL") + + +def downgrade(): + op.drop_index(op.f('ix_schedule_tasks_dify_agent_id'), table_name='schedule_tasks') diff --git a/backend/migrations/versions/f6d4e5f6a7b8_add_api_request_and_response_to_schedule_runs.py b/backend/migrations/versions/f6d4e5f6a7b8_add_api_request_and_response_to_schedule_runs.py new file mode 100644 index 00000000..788412e4 --- /dev/null +++ b/backend/migrations/versions/f6d4e5f6a7b8_add_api_request_and_response_to_schedule_runs.py @@ -0,0 +1,25 @@ +"""add api request and response to schedule_runs + +Revision ID: f6d4e5f6a7b8 +Revises: dc9a4a2683df +Create Date: 2026-06-16 10:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +revision = 'f6d4e5f6a7b8' +down_revision = 'dc9a4a2683df' +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column('schedule_runs', sa.Column('api_request_json', sa.JSON(), nullable=True)) + op.add_column('schedule_runs', sa.Column('api_response_json', sa.JSON(), nullable=True)) + + +def downgrade(): + op.drop_column('schedule_runs', 'api_response_json') + op.drop_column('schedule_runs', 'api_request_json') diff --git a/backend/requirements.txt b/backend/requirements.txt index 081a5eb6..992d5bcd 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -34,3 +34,4 @@ python-pptx==1.0.2 beautifulsoup4==4.14.2 lxml==6.0.2 typer==0.17.4 +croniter diff --git a/backend/tests/test_schedule_api.py b/backend/tests/test_schedule_api.py new file mode 100644 index 00000000..18dcb061 --- /dev/null +++ b/backend/tests/test_schedule_api.py @@ -0,0 +1,87 @@ +from app import db +from app.models import Agent, ScheduleRun, ScheduleTask, User + + +def _mk_admin(): + admin = User(username='admin', email='admin@example.com', role='admin', status='active') + admin.set_password('x') + db.session.add(admin) + return admin + + +def _mk_user(name: str, email: str): + user = User(username=name, email=email, role='user', status='active') + user.set_password('x') + db.session.add(user) + return user + + +def test_schedule_crud_and_workspace_visibility(app, client, admin_headers): + with app.app_context(): + _mk_admin() + owner = _mk_user('owner_u', 'owner@example.com') + notify = _mk_user('notify_u', 'notify@example.com') + other = _mk_user('other_u', 'other@example.com') + agent = Agent(name='dify-agent', dify_api_key='k', api_base_url='http://localhost:5001/v1', type='api') + db.session.add(agent) + db.session.commit() + + owner_id = owner.id + notify_id = notify.id + other_id = other.id + agent_id = agent.id + + create_res = client.post('/api/admin/schedules', headers=admin_headers, json={ + 'name': 'rohs-schedule', + 'schedule_type': 'dify_app', + 'owner_user_id': owner_id, + 'cron_expr': '0 */30 * * *', + 'wait_seconds': 5, + 'dify_agent_id': agent_id, + 'notify_user_ids_json': [notify_id], + 'notify_enabled': True, + 'enabled': True, + }) + assert create_res.status_code == 201 + task = create_res.get_json() + task_id = task['id'] + + list_res = client.get('/api/admin/schedules', headers=admin_headers) + assert list_res.status_code == 200 + assert any(x['id'] == task_id for x in list_res.get_json()) + + with app.app_context(): + run = ScheduleRun( + run_no='RUNTEST001', + schedule_task_id=task_id, + trigger_type='manual', + status='success', + total_count=1, + success_count=1, + failed_count=0, + skipped_count=0, + duration_ms=100, + mail_sent=False, + ) + db.session.add(run) + db.session.commit() + run_id = run.id + + owner_headers = {'X-Username': 'owner_u', 'Content-Type': 'application/json'} + notify_headers = {'X-Username': 'notify_u', 'Content-Type': 'application/json'} + other_headers = {'X-Username': 'other_u', 'Content-Type': 'application/json'} + + owner_runs = client.get('/api/workspace/schedule-runs', headers=owner_headers) + assert owner_runs.status_code == 200 + assert any(r['id'] == run_id for r in owner_runs.get_json()) + + notify_runs = client.get('/api/workspace/schedule-runs', headers=notify_headers) + assert notify_runs.status_code == 200 + assert any(r['id'] == run_id for r in notify_runs.get_json()) + + other_runs = client.get('/api/workspace/schedule-runs', headers=other_headers) + assert other_runs.status_code == 200 + assert all(r['id'] != run_id for r in other_runs.get_json()) + + denied = client.get(f'/api/workspace/schedule-runs/{run_id}', headers=other_headers) + assert denied.status_code == 403 diff --git a/frontend/dist/index.html b/frontend/dist/index.html index 04126117..5efd4cf6 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -10,8 +10,13 @@ AI工作台 +<<<<<<< Updated upstream +======= + + +>>>>>>> Stashed changes
diff --git a/frontend/src/api/schedule.ts b/frontend/src/api/schedule.ts new file mode 100644 index 00000000..be0121c2 --- /dev/null +++ b/frontend/src/api/schedule.ts @@ -0,0 +1,97 @@ +import { getAuthHeaders } from '../utils/auth'; + +export interface ScheduleTask { + id: number; + schedule_no: string; + name: string; + schedule_type: string; + owner_user_id: number; + owner_username?: string | null; + cron_expr: string; + wait_seconds: number; + dify_agent_id?: number | null; + platform_api_path?: string | null; + notify_user_ids_json: number[]; + notify_enabled: boolean; + enabled: boolean; + next_run_at?: string | null; + last_run_at?: string | null; + last_status?: string | null; + created_at?: string | null; + updated_at?: string | null; +} + +export interface ScheduleRun { + id: number; + run_no: string; + schedule_task_id: number; + schedule_name?: string | null; + trigger_type: string; + started_at?: string | null; + finished_at?: string | null; + duration_ms: number; + status: string; + total_count: number; + success_count: number; + failed_count: number; + skipped_count: number; + api_request_json?: Record | null; + api_response_json?: Record | null; + response_summary_json?: Record | null; + error_message?: string | null; + excel_file_name?: string | null; + excel_file_size?: number | null; + mail_sent: boolean; + mail_sent_at?: string | null; + mail_error?: string | null; + created_at?: string | null; +} + +async function getJson(url: string): Promise { + const res = await fetch(url, { headers: getAuthHeaders() }); + if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error || 'Request failed'); + return (await res.json()) as T; +} + +export const listAdminSchedules = () => getJson('/api/admin/schedules'); +export const createAdminSchedule = (payload: Partial) => + fetch('/api/admin/schedules', { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, + body: JSON.stringify(payload), + }); +export const updateAdminSchedule = (id: number, payload: Partial) => + fetch(`/api/admin/schedules/${id}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, + body: JSON.stringify(payload), + }); +export const deleteAdminSchedule = (id: number) => + fetch(`/api/admin/schedules/${id}`, { + method: 'DELETE', + headers: getAuthHeaders(), + }); +export const runAdminSchedule = (id: number) => + fetch(`/api/admin/schedules/${id}/run`, { method: 'POST', headers: getAuthHeaders() }); +export const toggleAdminSchedule = (id: number, enabled: boolean) => + fetch(`/api/admin/schedules/${id}/${enabled ? 'enable' : 'disable'}`, { method: 'POST', headers: getAuthHeaders() }); +export const listAdminScheduleRuns = (taskId: number, params?: { status?: string; started_after?: string; started_before?: string }) => { + const sp = new URLSearchParams(); + if (params?.status) sp.set('status', params.status); + if (params?.started_after) sp.set('started_after', params.started_after); + if (params?.started_before) sp.set('started_before', params.started_before); + const qs = sp.toString(); + return getJson(`/api/admin/schedules/${taskId}/runs${qs ? '?' + qs : ''}`); +}; +export const adminRunExcelUrl = (runId: number) => `/api/admin/schedule-runs/${runId}/excel`; + +export const listWorkspaceScheduleRuns = (params?: { status?: string; schedule_name?: string; started_after?: string; started_before?: string }) => { + const sp = new URLSearchParams(); + if (params?.status) sp.set('status', params.status); + if (params?.schedule_name) sp.set('schedule_name', params.schedule_name); + if (params?.started_after) sp.set('started_after', params.started_after); + if (params?.started_before) sp.set('started_before', params.started_before); + const qs = sp.toString(); + return getJson(`/api/workspace/schedule-runs${qs ? '?' + qs : ''}`); +}; +export const workspaceRunExcelUrl = (runId: number) => `/api/workspace/schedule-runs/${runId}/excel`; diff --git a/frontend/src/components/ScheduleRunsPanel.vue b/frontend/src/components/ScheduleRunsPanel.vue new file mode 100644 index 00000000..8ed80383 --- /dev/null +++ b/frontend/src/components/ScheduleRunsPanel.vue @@ -0,0 +1,71 @@ + + + diff --git a/frontend/src/config.ts b/frontend/src/config.ts index 3bc59950..21b7019a 100644 --- a/frontend/src/config.ts +++ b/frontend/src/config.ts @@ -4,7 +4,7 @@ export const config = { // Login mode switch: // - 'casdoor': submit username/password to backend Casdoor password-login API. // - 'password': submit to legacy local /api/user/login. - loginMode: 'casdoor', + loginMode: 'password', casdoor: { enabled: true, authorizeApi: '/api/user/casdoor/authorize-url', diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue index edeeedc3..864cff5b 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -8,7 +8,7 @@ * 逻辑关系: * - 通过 /api/admin/agents 管理 Agent 配置 * - 通过 /api/admin/users 与 /permissions 管理用户可访问的 Agent - * - 这个界面需要优化,进入管理台页面会请求所有接口数据,其实只需要请求dashboard数据 + * - 该页面后续可继续优化按模块懒加载数据 */ import { ref, onMounted, watch, computed } from 'vue'; import { useRouter } from 'vue-router'; @@ -20,6 +20,7 @@ import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useRe import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog'; import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom'; import { getAuthHeaders } from '../utils/auth'; +import { listAdminSchedules, createAdminSchedule, updateAdminSchedule, deleteAdminSchedule, toggleAdminSchedule, runAdminSchedule, listAdminScheduleRuns, adminRunExcelUrl, type ScheduleTask, type ScheduleRun } from '../api/schedule'; import { ArrowLeft, // Save, @@ -44,7 +45,9 @@ import { Link2, Unlink2, RefreshCw, - CircleHelp + CircleHelp, + Pause, + Play } from 'lucide-vue-next'; import * as XLSX from 'xlsx'; @@ -64,6 +67,7 @@ const sidebarItems = computed(() => { { id: 'wecom', icon: Link2, label: t('admin.nav.wecom') }, { id: 'permissions', icon: Users, label: t('admin.nav.permissions') }, { id: 'requests', icon: ShieldCheck, label: t('admin.nav.requests'), badge: permissionRequests.value.filter(r => r.status === 'pending').length }, + { id: 'schedules', icon: Settings2, label: '排程管理' }, ]; return items.filter(item => { @@ -226,7 +230,7 @@ interface WecomIntegrationManifest { const router = useRouter(); // 当前左侧菜单激活的模块:dashboard / agents / permissions -const activeModule = ref<'dashboard' | 'agents' | 'announcements' | 'permissions' | 'requests' | 'reports' | 'approvals' | 'users' | 'departments' | 'questions' | 'wecom'>('dashboard'); +const activeModule = ref<'dashboard' | 'agents' | 'announcements' | 'permissions' | 'requests' | 'reports' | 'approvals' | 'users' | 'departments' | 'questions' | 'wecom' | 'schedules'>('dashboard'); const expandedReports = ref(true); // agents:管理员视角下的所有 Agent 列表 @@ -413,6 +417,444 @@ const wecomSystemSettings = ref({ public_base_url: '', }); const wecomIntegrationManifest = ref(null); +const schedules = ref([]); +const selectedScheduleRuns = ref([]); +const scheduleLoading = ref(false); +const scheduleRunsLoading = ref(false); +const selectedScheduleId = ref(null); +const scheduleRunStatusFilter = ref<'all' | string>('all'); +const scheduleRunStartedAfter = ref(''); +const scheduleRunStartedBefore = ref(''); +const scheduleViewMode = ref<'overview' | 'workbench'>('overview'); +const showScheduleCreateModal = ref(false); +const scheduleCreateSaving = ref(false); +const scheduleEditingId = ref(null); +const scheduleCreateForm = ref({ + name: '', + platform_api_path: '', + dify_agent_id: null as number | null, + owner_user_id: null as number | null, + wait_seconds: 300, + notify_enabled: true, + notify_user_ids_json: [] as number[], + enabled: true, +}); +const scheduleCronDesigner = ref({ + mode: 'every_minutes' as 'every_minutes' | 'hourly' | 'daily' | 'weekly', + every_minutes: 30, + hourly_minute: 0, + daily_hour: 9, + daily_minute: 0, + weekly_day: 1, + weekly_hour: 9, + weekly_minute: 0, +}); +const weeklyDayOptions = [ + { value: 1, label: '周一' }, + { value: 2, label: '周二' }, + { value: 3, label: '周三' }, + { value: 4, label: '周四' }, + { value: 5, label: '周五' }, + { value: 6, label: '周六' }, + { value: 0, label: '周日' }, +]; + +const buildCronExprFromDesigner = () => { + const cfg = scheduleCronDesigner.value; + if (cfg.mode === 'every_minutes') { + const every = Math.max(1, Math.min(59, Number(cfg.every_minutes || 30))); + return `*/${every} * * * *`; + } + if (cfg.mode === 'hourly') { + const minute = Math.max(0, Math.min(59, Number(cfg.hourly_minute || 0))); + return `${minute} * * * *`; + } + if (cfg.mode === 'daily') { + const minute = Math.max(0, Math.min(59, Number(cfg.daily_minute || 0))); + const hour = Math.max(0, Math.min(23, Number(cfg.daily_hour || 0))); + return `${minute} ${hour} * * *`; + } + const minute = Math.max(0, Math.min(59, Number(cfg.weekly_minute || 0))); + const hour = Math.max(0, Math.min(23, Number(cfg.weekly_hour || 0))); + const day = Number(cfg.weekly_day); + return `${minute} ${hour} * * ${Number.isNaN(day) ? 1 : day}`; +}; + +const scheduleCronPreview = computed(() => buildCronExprFromDesigner()); + +const scheduleNextRunPreview = computed(() => { + const expr = scheduleCronPreview.value; + if (!expr) return null; + try { + const parts = expr.trim().split(/\s+/); + if (parts.length !== 5) return null; + const now = new Date(); + const minuteRaw = parts[0]; + const hourRaw = parts[1]; + const dayOfMonth = parts[2]; + const month = parts[3]; + const dayOfWeek = parts[4]; + if (month !== '*') return null; + if (dayOfMonth !== '*' && dayOfWeek !== '*') return null; + const minute = minuteRaw.startsWith('*/') ? undefined : parseInt(minuteRaw, 10); + const hour = hourRaw === '*' ? undefined : parseInt(hourRaw, 10); + if (minuteRaw.startsWith('*/')) { + const every = parseInt(minuteRaw.replace('*/', ''), 10); + const next = new Date(now); + next.setSeconds(0, 0); + const mod = next.getMinutes() % every; + next.setMinutes(next.getMinutes() + (every - mod)); + if (next <= now) next.setMinutes(next.getMinutes() + every); + return next; + } + if (minute !== undefined && hour === undefined) { + const next = new Date(now); + next.setMinutes(minute, 0, 0); + if (next <= now) next.setHours(next.getHours() + 1); + return next; + } + if (minute !== undefined && hour !== undefined) { + const next = new Date(now); + next.setHours(hour, minute, 0, 0); + if (next <= now) { + if (dayOfWeek !== '*') { + const dow = parseInt(dayOfWeek, 10); + const currentDow = next.getDay(); + let diff = dow - currentDow; + if (diff <= 0) diff += 7; + next.setDate(next.getDate() + diff); + } else { + next.setDate(next.getDate() + 1); + } + } else if (dayOfWeek !== '*') { + const dow = parseInt(dayOfWeek, 10); + const target = new Date(next); + const currentDow = target.getDay(); + let diff = dow - currentDow; + if (diff < 0) diff += 7; + if (diff > 0) target.setDate(target.getDate() + diff); + if (target <= now) { + target.setDate(target.getDate() + 7); + } + return target; + } + return next; + } + return null; + } catch { + return null; + } +}); + +const parseCronExprToDesigner = (expr: string | null | undefined) => { + const text = String(expr || '').trim(); + const parts = text.split(/\s+/); + if (parts.length !== 5) { + scheduleCronDesigner.value = { + mode: 'every_minutes', + every_minutes: 30, + hourly_minute: 0, + daily_hour: 9, + daily_minute: 0, + weekly_day: 1, + weekly_hour: 9, + weekly_minute: 0, + }; + return; + } + const m = parts[0] ?? ''; + const h = parts[1] ?? ''; + const dow = parts[4] ?? ''; + if (/^\*\/\d+$/.test(m) && h === '*' && dow === '*') { + scheduleCronDesigner.value.mode = 'every_minutes'; + scheduleCronDesigner.value.every_minutes = Number(m.replace('*/', '')) || 30; + return; + } + if (/^\d+$/.test(m) && h === '*' && dow === '*') { + scheduleCronDesigner.value.mode = 'hourly'; + scheduleCronDesigner.value.hourly_minute = Number(m) || 0; + return; + } + if (/^\d+$/.test(m) && /^\d+$/.test(h) && dow === '*') { + scheduleCronDesigner.value.mode = 'daily'; + scheduleCronDesigner.value.daily_hour = Number(h) || 0; + scheduleCronDesigner.value.daily_minute = Number(m) || 0; + return; + } + if (/^\d+$/.test(m) && /^\d+$/.test(h) && /^\d+$/.test(dow)) { + scheduleCronDesigner.value.mode = 'weekly'; + scheduleCronDesigner.value.weekly_hour = Number(h) || 0; + scheduleCronDesigner.value.weekly_minute = Number(m) || 0; + scheduleCronDesigner.value.weekly_day = Number(dow); + return; + } + scheduleCronDesigner.value.mode = 'every_minutes'; + scheduleCronDesigner.value.every_minutes = 30; +}; + +const resetScheduleCreateForm = () => { + scheduleEditingId.value = null; + scheduleCreateForm.value = { + name: '', + platform_api_path: '', + dify_agent_id: null, + owner_user_id: null, + wait_seconds: 300, + notify_enabled: true, + notify_user_ids_json: [], + enabled: true, + }; + scheduleCronDesigner.value = { + mode: 'every_minutes', + every_minutes: 30, + hourly_minute: 0, + daily_hour: 9, + daily_minute: 0, + weekly_day: 1, + weekly_hour: 9, + weekly_minute: 0, + }; +}; + +const openScheduleCreateModal = async () => { + resetScheduleCreateForm(); + await Promise.all([loadAgents(), loadUsers()]); + showScheduleCreateModal.value = true; +}; + +const openScheduleEditModal = async (task: ScheduleTask) => { + await Promise.all([loadAgents(), loadUsers()]); + scheduleEditingId.value = task.id; + scheduleCreateForm.value = { + name: task.name || '', + platform_api_path: task.platform_api_path || '', + dify_agent_id: task.dify_agent_id || null, + owner_user_id: task.owner_user_id || null, + wait_seconds: task.wait_seconds || 0, + notify_enabled: !!task.notify_enabled, + notify_user_ids_json: task.notify_user_ids_json || [], + enabled: !!task.enabled, + }; + parseCronExprToDesigner(task.cron_expr); + showScheduleCreateModal.value = true; +}; + +const selectedSchedule = computed(() => + schedules.value.find((item) => item.id === selectedScheduleId.value) || null +); + +const scheduleRunStatusOptions = [ + { value: 'all', label: '全部状态' }, + { value: 'success', label: '成功' }, + { value: 'partial_failed', label: '部分成功' }, + { value: 'failed', label: '失败' }, + { value: 'running', label: '执行中' }, +]; + +const getScheduleRunStatusBadge = (status: string) => { + const map: Record = { + success: { cls: 'bg-emerald-100 text-emerald-700', label: '成功' }, + partial_failed: { cls: 'bg-blue-100 text-blue-700', label: '部分成功' }, + failed: { cls: 'bg-rose-100 text-rose-700', label: '失败' }, + running: { cls: 'bg-amber-100 text-amber-700', label: '执行中' }, + queued: { cls: 'bg-slate-100 text-slate-600', label: '排队中' }, + }; + return map[status] || { cls: 'bg-slate-100 text-slate-600', label: status }; +}; + +const formatDateTime = (iso?: string | null) => { + if (!iso) return '-'; + const d = new Date(iso); + if (isNaN(d.getTime())) return iso; + const pad = (n: number) => String(n).padStart(2, '0'); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; +}; + +const filteredScheduleRuns = computed(() => { + if (scheduleRunStatusFilter.value === 'all') return selectedScheduleRuns.value; + return selectedScheduleRuns.value.filter((item) => item.status === scheduleRunStatusFilter.value); +}); + +const selectedScheduleRunMetrics = computed(() => { + const runs = selectedScheduleRuns.value; + return runs.reduce( + (acc, item) => { + acc.total += item.total_count || 0; + acc.success += item.success_count || 0; + acc.failed += item.failed_count || 0; + return acc; + }, + { total: 0, success: 0, failed: 0 } + ); +}); + +const selectedScheduleLatestRunAt = computed( + () => selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at || '-' +); + +const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length); +const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length); +const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length); + +const loadSchedules = async () => { + scheduleLoading.value = true; + try { + schedules.value = await listAdminSchedules(); + if (schedules.value.length === 0) { + selectedScheduleId.value = null; + selectedScheduleRuns.value = []; + scheduleViewMode.value = 'overview'; + return; + } + const exists = selectedScheduleId.value && schedules.value.some((item) => item.id === selectedScheduleId.value); + const nextScheduleId = exists && selectedScheduleId.value ? selectedScheduleId.value : schedules.value[0]?.id ?? null; + if (!exists && nextScheduleId) { + selectedScheduleId.value = nextScheduleId; + } + if (scheduleViewMode.value === 'workbench' && nextScheduleId) { + await viewScheduleRuns(nextScheduleId); + } + } finally { + scheduleLoading.value = false; + } +}; + +const createSchedule = async () => { + if (!scheduleCreateForm.value.name || !scheduleCreateForm.value.owner_user_id) return; + scheduleCreateSaving.value = true; + const payload: Partial = { + name: scheduleCreateForm.value.name, + schedule_type: 'platform_app', + owner_user_id: scheduleCreateForm.value.owner_user_id, + cron_expr: scheduleCronPreview.value, + wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)), + dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined, + platform_api_path: scheduleCreateForm.value.platform_api_path?.trim() || undefined, + notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [], + notify_enabled: scheduleCreateForm.value.notify_enabled, + enabled: scheduleCreateForm.value.enabled, + }; + const res = scheduleEditingId.value + ? await updateAdminSchedule(scheduleEditingId.value, payload) + : await createAdminSchedule(payload); + try { + if (res.ok) { + let createdId: number | null = null; + try { + const payload = await res.clone().json(); + createdId = payload?.id ?? payload?.schedule?.id ?? null; + } catch { + createdId = null; + } + const targetId = scheduleEditingId.value || createdId; + showScheduleCreateModal.value = false; + await loadSchedules(); + if (targetId) { + await viewScheduleRuns(targetId); + } + } + } finally { + scheduleCreateSaving.value = false; + } +}; + +const todayStart = () => { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`; +}; +const todayEnd = () => { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T23:59:59`; +}; + +const resetScheduleRunFilters = () => { + scheduleRunStatusFilter.value = 'all'; + scheduleRunStartedAfter.value = todayStart(); + scheduleRunStartedBefore.value = todayEnd(); +}; + +const viewScheduleRuns = async (taskId: number) => { + selectedScheduleId.value = taskId; + scheduleRunsLoading.value = true; + if (!scheduleRunStartedAfter.value && !scheduleRunStartedBefore.value) { + resetScheduleRunFilters(); + } + try { + const params: { status?: string; started_after?: string; started_before?: string } = {}; + if (scheduleRunStatusFilter.value !== 'all') params.status = scheduleRunStatusFilter.value; + if (scheduleRunStartedAfter.value) params.started_after = scheduleRunStartedAfter.value; + if (scheduleRunStartedBefore.value) params.started_before = scheduleRunStartedBefore.value; + selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params); + } finally { + scheduleRunsLoading.value = false; + } +}; + +const openScheduleRunSubmenu = async (taskId: number) => { + scheduleViewMode.value = 'workbench'; + await viewScheduleRuns(taskId); +}; + +const backToScheduleOverview = () => { + scheduleViewMode.value = 'overview'; +}; + +const runScheduleNow = async (taskId: number) => { + await runAdminSchedule(taskId); + await viewScheduleRuns(taskId); + await loadSchedules(); + + const pollInterval = setInterval(async () => { + await viewScheduleRuns(taskId); + await loadSchedules(); + const target = schedules.value.find((s: ScheduleTask) => s.id === taskId); + if (target && target.last_status && target.last_status !== 'running') { + clearInterval(pollInterval); + } + }, 5000); +}; + +const setScheduleEnabled = async (taskId: number, enabled: boolean) => { + await toggleAdminSchedule(taskId, enabled); + await loadSchedules(); +}; + +const downloadScheduleExcel = async (runId: number) => { + const res = await fetch(`/api/admin/schedule-runs/${runId}/excel`, { headers: getAuthHeaders() }); + if (!res.ok) { + showMessageDialog('error', '下载 Excel 失败'); + return; + } + const blob = await res.blob(); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + const disposition = res.headers.get('content-disposition'); + a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'result.xlsx'; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +}; + +const deleteSchedule = (task: ScheduleTask) => { + openDeleteConfirmDialog( + `确认删除排程「${task.name}」?`, + async () => { + const res = await deleteAdminSchedule(task.id); + if (!res.ok) { + showMessageDialog('error', '删除排程失败'); + return; + } + if (selectedScheduleId.value === task.id) { + selectedScheduleId.value = null; + selectedScheduleRuns.value = []; + } + await loadSchedules(); + }, + '删除排程' + ); +}; // Batch Operation Refs const selectedUserIds = ref([]); @@ -1352,6 +1794,9 @@ watch(activeModule, async (value) => { if (value === 'wecom') { await refreshWecomData(); } + if (value === 'schedules') { + await loadSchedules(); + } }); /** @@ -2192,7 +2637,7 @@ const onReportHeaderClick = (key: string) => { }; const getHeaderSortMark = (key: string) => { if (reportHeaderSort.value?.key !== key) return ''; - return reportHeaderSort.value.direction === 'asc' ? '↑' : '↓'; + return reportHeaderSort.value.direction === 'asc' ? '^' : 'v'; }; const addChatLogsSortRule = () => { const keys = visibleReportKeys.value; @@ -3387,6 +3832,354 @@ const handlePermissionImport = async (event: Event) => { +
+
+
+
+ +
+ +
+
+

+ {{ scheduleViewMode === 'overview' ? '排程管理概览' : '排程管理工作台' }} +

+

+ {{ scheduleViewMode === 'overview' ? '点击排程卡片进入排程工作台。' : '左侧排程列表,右侧执行记录列表。' }} +

+
+
+ +
+
+ + + + +
@@ -4289,6 +5082,200 @@ const handlePermissionImport = async (event: Event) => {
+ +
+
+
+

{{ scheduleEditingId ? '编辑排程' : '新增排程' }}

+ +
+
+
+
+ + +
+
+ + +
+
+ +
+ +
+ +
+
+
+
+ +
+ +
+ +
+
+
+
+ + +
+
+ +
+
+

Cron 图形化设置

+

选择执行频率后自动生成 Cron 表达式。

+
+
+ + + + +
+ +
+ + + + +
+
+ Cron 预览:{{ scheduleCronPreview }} + 下次执行:{{ formatDateTime(scheduleNextRunPreview.toISOString()) }} +
+
+ +
+
+ + +
+
+ +
+ +
+
+
+
+ +
+ + +
+
+
+
@@ -4498,3 +5485,4 @@ const handlePermissionImport = async (event: Event) => { />
+ diff --git a/frontend/src/views/WorkspaceView.vue b/frontend/src/views/WorkspaceView.vue index ae192c45..e709c8ba 100644 --- a/frontend/src/views/WorkspaceView.vue +++ b/frontend/src/views/WorkspaceView.vue @@ -50,6 +50,8 @@ import { } from 'lucide-vue-next'; import KbWorkspaceView from './KbWorkspaceView.vue'; +import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule'; +import { Clock, Download, Search, RefreshCw } from 'lucide-vue-next'; const { t, locale } = useI18n(); const { showMessageDialog } = useGlobalMessageDialog(); @@ -758,7 +760,7 @@ const handleRegister = async () => { } }; -const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base'>('applications'); +const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base' | 'schedule_runs'>('applications'); const isProfileLoading = ref(false); const isProfileSaving = ref(false); const isProfileEditing = ref(false); @@ -982,6 +984,99 @@ const navigateToKnowledgeBase = () => { activeSidebarItem.value = 'knowledge_base'; }; +const navigateToScheduleRuns = () => { + activeSidebarItem.value = 'schedule_runs'; + loadWorkspaceScheduleRuns(); +}; + +const workspaceScheduleRuns = ref([]); +const workspaceScheduleLoading = ref(false); +const wsScheduleStatusFilter = ref('all'); +const wsScheduleNameFilter = ref(''); +const wsScheduleStartedAfter = ref(''); +const wsScheduleStartedBefore = ref(''); + +const wsScheduleStatusOptions = [ + { value: 'all', label: '全部状态' }, + { value: 'success', label: '成功' }, + { value: 'partial_failed', label: '部分成功' }, + { value: 'failed', label: '失败' }, + { value: 'running', label: '执行中' }, +]; + +const getWsScheduleStatusBadge = (status: string) => { + const map: Record = { + success: { cls: 'bg-emerald-100 text-emerald-700', label: '成功' }, + partial_failed: { cls: 'bg-blue-100 text-blue-700', label: '部分成功' }, + failed: { cls: 'bg-rose-100 text-rose-700', label: '失败' }, + running: { cls: 'bg-amber-100 text-amber-700', label: '执行中' }, + queued: { cls: 'bg-slate-100 text-slate-600', label: '排队中' }, + }; + return map[status] || { cls: 'bg-slate-100 text-slate-600', label: status }; +}; + +const formatDateTime = (iso?: string | null) => { + if (!iso) return '-'; + const d = new Date(iso); + if (isNaN(d.getTime())) return iso; + const pad = (n: number) => String(n).padStart(2, '0'); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; +}; + +const todayStart = () => { + const d = new Date(); + d.setHours(0, 0, 0, 0); + return d.toISOString(); +}; + +const todayEnd = () => { + const d = new Date(); + d.setHours(23, 59, 59, 0); + return d.toISOString(); +}; + +const loadWorkspaceScheduleRuns = async () => { + workspaceScheduleLoading.value = true; + try { + const params: { status?: string; schedule_name?: string; started_after?: string; started_before?: string } = {}; + if (wsScheduleStatusFilter.value !== 'all') params.status = wsScheduleStatusFilter.value; + if (wsScheduleNameFilter.value.trim()) params.schedule_name = wsScheduleNameFilter.value.trim(); + if (wsScheduleStartedAfter.value) params.started_after = new Date(wsScheduleStartedAfter.value).toISOString(); + if (wsScheduleStartedBefore.value) params.started_before = new Date(wsScheduleStartedBefore.value).toISOString(); + workspaceScheduleRuns.value = await listWorkspaceScheduleRuns(params); + } catch { + workspaceScheduleRuns.value = []; + } finally { + workspaceScheduleLoading.value = false; + } +}; + +const resetWsScheduleFilters = () => { + wsScheduleStatusFilter.value = 'all'; + wsScheduleNameFilter.value = ''; + wsScheduleStartedAfter.value = todayStart().slice(0, 16); + wsScheduleStartedBefore.value = todayEnd().slice(0, 16); + loadWorkspaceScheduleRuns(); +}; + +const downloadWsScheduleExcel = async (runId: number) => { + const res = await fetch(workspaceRunExcelUrl(runId), { headers: getAuthHeaders() }); + if (!res.ok) { + showMessageDialog('error', '下载 Excel 失败'); + return; + } + const blob = await res.blob(); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + const disposition = res.headers.get('content-disposition'); + a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'result.xlsx'; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +}; + const navigateToGeneralChat = () => { router.push(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`); }; @@ -1397,6 +1492,14 @@ onMounted(async () => { 知识库管理 +