排程管理及排程记录查看功能
This commit is contained in:
1 parent
3b31867319
commit
08776feef2
28 files changed
+3040
-8
No files matched your search
@@ -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
|
||||
@@ -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():
|
||||
|
||||
@@ -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/<int:task_id>', 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/<int:task_id>', 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/<int:task_id>', 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/<int:task_id>/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/<int:task_id>/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/<int:task_id>/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/<int:task_id>/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/<int:run_id>', 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/<int:run_id>/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')
|
||||
@@ -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/<int:run_id>', 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/<int:run_id>/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')
|
||||
+24
-2
@@ -30,7 +30,7 @@ def _load_environment_files() -> str:
|
||||
1. .env.shared
|
||||
2. .env.<ENV_NAME>
|
||||
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 = {
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -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):
|
||||
"""
|
||||
|
||||
@@ -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"]
|
||||
@@ -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)
|
||||
@@ -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 (
|
||||
"<html><body>"
|
||||
"<h3>排程执行结果</h3>"
|
||||
"<table border='1' cellspacing='0' cellpadding='6'>"
|
||||
f"<tr><th>排程</th><td>{schedule_name}</td></tr>"
|
||||
f"<tr><th>执行单号</th><td>{run_no}</td></tr>"
|
||||
f"<tr><th>状态</th><td>{status}</td></tr>"
|
||||
f"<tr><th>总数</th><td>{total}</td></tr>"
|
||||
f"<tr><th>成功</th><td>{success}</td></tr>"
|
||||
f"<tr><th>失败</th><td>{failed}</td></tr>"
|
||||
"</table></body></html>"
|
||||
)
|
||||
@@ -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()}
|
||||
@@ -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()
|
||||
@@ -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
|
||||
Binary file not shown.
Binary file not shown.
@@ -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
|
||||
@@ -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')
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
+25
@@ -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')
|
||||
@@ -34,3 +34,4 @@ python-pptx==1.0.2
|
||||
beautifulsoup4==4.14.2
|
||||
lxml==6.0.2
|
||||
typer==0.17.4
|
||||
croniter
|
||||
@@ -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
|
||||
Vendored
+5
@@ -10,8 +10,13 @@
|
||||
<meta name="apple-mobile-web-app-title" content="AI工作台" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<title>AI工作台</title>
|
||||
<<<<<<< Updated upstream
|
||||
<script type="module" crossorigin src="/assets/index-grYi-CaK.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DvLiupE9.css">
|
||||
=======
|
||||
<script type="module" crossorigin src="/assets/index-DOCtY95c.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-BL1tdy0j.css">
|
||||
>>>>>>> Stashed changes
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>␍
|
||||
|
||||
@@ -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<string, any> | null;
|
||||
api_response_json?: Record<string, any> | null;
|
||||
response_summary_json?: Record<string, any> | 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<T>(url: string): Promise<T> {
|
||||
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<ScheduleTask[]>('/api/admin/schedules');
|
||||
export const createAdminSchedule = (payload: Partial<ScheduleTask>) =>
|
||||
fetch('/api/admin/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask>) =>
|
||||
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<ScheduleRun[]>(`/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<ScheduleRun[]>(`/api/workspace/schedule-runs${qs ? '?' + qs : ''}`);
|
||||
};
|
||||
export const workspaceRunExcelUrl = (runId: number) => `/api/workspace/schedule-runs/${runId}/excel`;
|
||||
@@ -0,0 +1,71 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule';
|
||||
|
||||
const isLoading = ref(false);
|
||||
const error = ref('');
|
||||
const runs = ref<ScheduleRun[]>([]);
|
||||
|
||||
const loadRuns = async () => {
|
||||
isLoading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
runs.value = await listWorkspaceScheduleRuns();
|
||||
} catch (e: any) {
|
||||
error.value = e?.message || '加载排程记录失败';
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
void loadRuns();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mt-6 rounded-2xl border border-slate-200 bg-white p-5">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h3 class="text-lg font-semibold text-slate-900">排程记录</h3>
|
||||
<button class="rounded-lg border border-slate-300 px-3 py-1.5 text-sm text-slate-700 hover:bg-slate-50" @click="loadRuns">
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
<p class="mb-3 text-xs text-slate-500">仅展示你是 owner 或在通知名单中的记录</p>
|
||||
<div v-if="isLoading" class="py-6 text-sm text-slate-500">加载中...</div>
|
||||
<div v-else-if="error" class="py-6 text-sm text-rose-500">{{ error }}</div>
|
||||
<div v-else-if="runs.length === 0" class="py-6 text-sm text-slate-400">暂无可见记录</div>
|
||||
<div v-else class="overflow-x-auto">
|
||||
<table class="w-full min-w-[920px] text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-slate-200 text-left text-slate-500">
|
||||
<th class="px-2 py-2">执行单号</th>
|
||||
<th class="px-2 py-2">排程</th>
|
||||
<th class="px-2 py-2">开始</th>
|
||||
<th class="px-2 py-2">结束</th>
|
||||
<th class="px-2 py-2">状态</th>
|
||||
<th class="px-2 py-2">处理</th>
|
||||
<th class="px-2 py-2">成功</th>
|
||||
<th class="px-2 py-2">失败</th>
|
||||
<th class="px-2 py-2">Excel</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="run in runs" :key="run.id" class="border-b border-slate-100 text-slate-700">
|
||||
<td class="px-2 py-2">{{ run.run_no }}</td>
|
||||
<td class="px-2 py-2">{{ run.schedule_name || '-' }}</td>
|
||||
<td class="px-2 py-2">{{ run.started_at || '-' }}</td>
|
||||
<td class="px-2 py-2">{{ run.finished_at || '-' }}</td>
|
||||
<td class="px-2 py-2">{{ run.status }}</td>
|
||||
<td class="px-2 py-2">{{ run.total_count }}</td>
|
||||
<td class="px-2 py-2">{{ run.success_count }}</td>
|
||||
<td class="px-2 py-2">{{ run.failed_count }}</td>
|
||||
<td class="px-2 py-2">
|
||||
<a class="text-brand-600 hover:underline" :href="workspaceRunExcelUrl(run.id)" target="_blank">查看Excel</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -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',
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<ScheduleRun[]>([]);
|
||||
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<string, { cls: string; label: string }> = {
|
||||
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 () => {
|
||||
<FileText class="h-4 w-4" />
|
||||
<span>知识库管理</span>
|
||||
</button>
|
||||
<button
|
||||
@click="navigateToScheduleRuns"
|
||||
class="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all"
|
||||
:class="activeSidebarItem === 'schedule_runs' ? 'bg-brand-50 text-brand-700 shadow-sm' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'"
|
||||
>
|
||||
<Clock class="h-4 w-4" />
|
||||
<span>排程记录</span>
|
||||
</button>
|
||||
<button
|
||||
@click="openGeneralFeedback"
|
||||
class="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all"
|
||||
@@ -1616,6 +1719,109 @@ onMounted(async () => {
|
||||
<KbWorkspaceView :embedded="true" />
|
||||
</template>
|
||||
|
||||
<template v-else-if="activeSidebarItem === 'schedule_runs'">
|
||||
<div class="space-y-5 animate-fade-in-up">
|
||||
<div class="flex items-center justify-between">
|
||||
<h2 class="text-2xl font-bold text-slate-900">排程记录</h2>
|
||||
<button
|
||||
@click="loadWorkspaceScheduleRuns"
|
||||
class="inline-flex items-center gap-1.5 rounded-xl border border-slate-200 px-3 py-1.5 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-slate-200 bg-slate-50/40 px-4 py-3">
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-medium text-slate-500">排程名称</label>
|
||||
<input type="text" v-model="wsScheduleNameFilter" placeholder="输入排程名称" class="!w-[150px] !py-1 !px-2 !text-xs rounded-lg border border-slate-200 bg-white" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-medium text-slate-500">开始时间</label>
|
||||
<input type="datetime-local" step="1" v-model="wsScheduleStartedAfter" class="!w-[170px] !py-1 !px-2 !text-xs rounded-lg border border-slate-200 bg-white" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-medium text-slate-500">结束时间</label>
|
||||
<input type="datetime-local" step="1" v-model="wsScheduleStartedBefore" class="!w-[170px] !py-1 !px-2 !text-xs rounded-lg border border-slate-200 bg-white" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-xs font-medium text-slate-500">状态</label>
|
||||
<select v-model="wsScheduleStatusFilter" class="!w-[120px] !py-1 !px-2 !text-xs rounded-lg border border-slate-200 bg-white">
|
||||
<option v-for="o in wsScheduleStatusOptions" :key="o.value" :value="o.value">{{ o.label }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<button
|
||||
@click="loadWorkspaceScheduleRuns"
|
||||
class="inline-flex items-center gap-1 rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-brand-700"
|
||||
>
|
||||
<Search class="h-3.5 w-3.5" />
|
||||
查询
|
||||
</button>
|
||||
<button
|
||||
@click="resetWsScheduleFilters"
|
||||
class="rounded-xl border border-slate-200 px-3 py-1.5 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50"
|
||||
>
|
||||
重置
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="workspaceScheduleLoading" class="py-10 text-center text-sm text-slate-400">正在加载...</div>
|
||||
<div v-else-if="workspaceScheduleRuns.length === 0" class="py-10 text-center text-sm text-slate-400">暂无排程记录</div>
|
||||
<div v-else class="overflow-hidden rounded-2xl border border-slate-200 bg-white">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-slate-100 bg-slate-50/60">
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">排程名称</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">运行编号</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">触发方式</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">开始时间</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">结束时间</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">耗时</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">状态</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">处理笔数</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">成功笔数</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">失败笔数</th>
|
||||
<th class="px-4 py-3 text-left font-semibold text-slate-600">明细</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="r in workspaceScheduleRuns" :key="r.id" class="border-b border-slate-50 transition-colors hover:bg-slate-50/50">
|
||||
<td class="px-4 py-3 font-medium text-slate-900">{{ r.schedule_name || '-' }}</td>
|
||||
<td class="px-4 py-3 text-slate-500 font-mono text-xs">{{ r.run_no }}</td>
|
||||
<td class="px-4 py-3 text-slate-500">{{ r.trigger_type === 'manual' ? '手动' : '定时' }}</td>
|
||||
<td class="px-4 py-3 text-slate-500 whitespace-nowrap">{{ formatDateTime(r.started_at) }}</td>
|
||||
<td class="px-4 py-3 text-slate-500 whitespace-nowrap">{{ formatDateTime(r.finished_at) }}</td>
|
||||
<td class="px-4 py-3 text-slate-500 whitespace-nowrap">{{ r.duration_ms != null ? (r.duration_ms >= 1000 ? (r.duration_ms / 1000).toFixed(1) + 's' : r.duration_ms + 'ms') : '-' }}</td>
|
||||
<td class="px-4 py-3">
|
||||
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold" :class="getWsScheduleStatusBadge(r.status).cls">
|
||||
{{ getWsScheduleStatusBadge(r.status).label }}
|
||||
</span>
|
||||
<span v-if="r.error_message && r.error_message !== '无待处理数据'" class="ml-1 text-xs text-slate-400" :title="r.error_message">...</span>
|
||||
<span v-else-if="r.error_message === '无待处理数据'" class="ml-1 text-xs text-slate-400">(无待处理数据)</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-slate-500">{{ r.total_count || 0 }}</td>
|
||||
<td class="px-4 py-3 text-emerald-600 font-medium">{{ r.success_count ?? 0 }}</td>
|
||||
<td class="px-4 py-3 text-rose-600 font-medium">{{ r.failed_count ?? 0 }}</td>
|
||||
<td class="px-4 py-3">
|
||||
<a
|
||||
v-if="r.total_count > 0 && r.excel_file_name"
|
||||
href="#"
|
||||
@click.prevent="downloadWsScheduleExcel(r.id)"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-2 py-1 text-xs font-medium text-slate-600 transition-colors hover:bg-slate-50"
|
||||
>
|
||||
<Download class="h-3 w-3" />
|
||||
下载
|
||||
</a>
|
||||
<span v-else class="text-xs text-slate-300">-</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div v-if="wecomEntryHint" class="rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
|
||||
{{ wecomEntryHint }}
|
||||
|
||||
Reference in new issue
Block a user