排程管理及排程记录查看功能
This commit is contained in:
1 parent
3b31867319
commit
08776feef2
28 files changed
+3040
-8
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user