feat(rohs-check): 新增 RoHS 检核工具 API 及相关功能

This commit is contained in:
hugo committed 2026-06-10 15:17:09 +08:00
1 parent 8a541211b7
commit 24551e9a9a
39 files changed
+3128 -189

No files matched your search

+252
View File
@@ -0,0 +1,252 @@
"""
backend/app/services/schedule/kb_sync.py
文件用途:把排程运行生成的 Excel 结果注册为知识库文档并触发清洗/同步。
"""
from __future__ import annotations
import hashlib
from pathlib import Path
from flask import current_app
from werkzeug.utils import secure_filename
from app import db
from app.services.db_sequence import add_and_flush_with_sequence_retry
from app.models import KbDocument, KbDocumentVersion, KbGroup, KbJob, ScheduleRun, ScheduleTask
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job
def update_schedule_run_kb_sync_status(
run_id: int | None,
*,
status: str,
error: str | None = None,
) -> None:
"""回写排程运行的知识库同步状态,供 Chatflow 查询。"""
if not run_id:
return
run = db.session.get(ScheduleRun, int(run_id))
if not run:
return
run.kb_sync_status = status
if error is not None:
run.kb_sync_error = error
elif status == "success":
run.kb_sync_error = None
db.session.commit()
def _kb_storage_root() -> Path:
root = Path(current_app.config.get("KB_STORAGE_ROOT")).resolve()
root.mkdir(parents=True, exist_ok=True)
return root
def _next_version_no(document: KbDocument) -> int:
versions = list(getattr(document, "versions", []) or [])
if not versions:
return 1
return max(item.version_no for item in versions) + 1
def _safe_excel_name(raw_name: str) -> str:
name = Path(str(raw_name or "")).name.strip() or "schedule_result.xlsx"
safe_stem = secure_filename(Path(name).stem) or "schedule_result"
suffix = Path(name).suffix or ".xlsx"
return f"{safe_stem}{suffix}"
def _create_kb_document_with_sequence_retry(**fields) -> KbDocument:
document = KbDocument(**fields)
add_and_flush_with_sequence_retry(document, "kb_documents")
return document
def sync_schedule_run_excel_to_kb(
task: ScheduleTask,
run: ScheduleRun,
*,
enabled: bool | None = None,
process_inline: bool = True,
) -> None:
kb_enabled = bool(getattr(task, "kb_sync_enabled", False)) if enabled is None else bool(enabled)
if not kb_enabled:
run.kb_sync_status = "skipped"
run.kb_sync_error = None
if current_app:
current_app.logger.info("[schedule-kb-sync] skipped run=%s: kb sync disabled", run.id)
return
if not task.kb_group_id:
run.kb_sync_status = "failed"
run.kb_sync_error = "未配置目标知识库分组"
if current_app:
current_app.logger.warning("[schedule-kb-sync] failed run=%s: kb_group_id missing", run.id)
return
if run.status not in ("success", "partial_failed"):
run.kb_sync_status = "skipped"
run.kb_sync_error = None
if current_app:
current_app.logger.info(
"[schedule-kb-sync] skipped run=%s: status=%s",
run.id,
run.status,
)
return
if not run.excel_file_data:
run.kb_sync_status = "skipped"
run.kb_sync_error = "未生成 Excel 文件"
if current_app:
current_app.logger.warning(
"[schedule-kb-sync] skipped run=%s: excel_file_data empty (size=%s)",
run.id,
run.excel_file_size,
)
return
group = db.session.get(KbGroup, task.kb_group_id)
if not group or not group.is_active:
run.kb_sync_status = "failed"
run.kb_group_id = task.kb_group_id
run.kb_sync_error = "目标知识库分组不存在或已停用"
return
title = f"{task.name}_{run.run_no}"
actor_id = run.triggered_by_user_id or task.owner_user_id
document = _create_kb_document_with_sequence_retry(
group_id=group.id,
title=title,
description=f"排程 {task.name} 运行结果 {run.run_no}",
status="uploaded",
source_type="schedule",
created_by_id=actor_id,
updated_by_id=actor_id,
)
version_no = _next_version_no(document)
source_file_name = _safe_excel_name(run.excel_file_name or f"{run.run_no}.xlsx")
version_dir = _kb_storage_root() / f"group_{group.id:04d}" / f"document_{document.id:06d}" / f"v{version_no:03d}"
version_dir.mkdir(parents=True, exist_ok=True)
target_path = version_dir / source_file_name
target_path.write_bytes(run.excel_file_data)
sha256 = hashlib.sha256(run.excel_file_data).hexdigest()
file_size = len(run.excel_file_data)
version = KbDocumentVersion(
document_id=document.id,
version_no=version_no,
status="uploaded",
is_current=True,
source_file_name=source_file_name,
source_file_path=str(target_path),
source_file_ext=Path(source_file_name).suffix.lower().lstrip(".") or None,
source_file_size=file_size,
sha256=sha256,
uploaded_by_id=run.triggered_by_user_id or task.owner_user_id,
)
add_and_flush_with_sequence_retry(version, "kb_document_versions")
clean_job = KbJob(
job_type="clean",
status="queued",
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
progress=0,
message="等待清洗排程结果 Excel",
payload_json={
"document_version_id": version.id,
"source_file_name": source_file_name,
"source_type": "schedule_run",
"schedule_run_id": run.id,
"run_no": run.run_no,
"auto_sync_dify": True,
},
created_by_id=run.triggered_by_user_id or task.owner_user_id,
)
add_and_flush_with_sequence_retry(clean_job, "kb_jobs")
run.kb_sync_status = "queued"
run.kb_group_id = group.id
run.kb_document_id = document.id
run.kb_document_version_id = version.id
run.kb_sync_job_id = clean_job.id
run.kb_sync_error = None
db.session.commit()
if current_app:
current_app.logger.info(
"[schedule-kb-sync] registered run=%s document_id=%s clean_job_id=%s",
run.id,
run.kb_document_id,
run.kb_sync_job_id,
)
if process_inline:
db.session.refresh(run)
process_schedule_kb_jobs_inline(run)
else:
enqueue_clean_job(clean_job.id)
def _find_pending_sync_job(run: ScheduleRun) -> KbJob | None:
from app.models import KbJob
if run.kb_sync_job_id:
job = db.session.get(KbJob, int(run.kb_sync_job_id))
if job and job.job_type == "sync_dify" and job.status == "queued":
return job
if not run.kb_document_id:
return None
return (
db.session.query(KbJob)
.filter(
KbJob.job_type == "sync_dify",
KbJob.document_id == run.kb_document_id,
KbJob.status == "queued",
)
.order_by(KbJob.id.desc())
.first()
)
def process_schedule_kb_jobs_inline(run: ScheduleRun) -> None:
"""
同步执行清洗与 Dify 同步。
默认在注册 Excel 后立即执行,避免仅 queued 而 worker_kb 未运行导致知识库看不到文档。
"""
if not run.id:
return
from app.models import KbJob
from app.services.knowledge_cleaning.tasks import run_clean_job, run_sync_job
try:
db.session.refresh(run)
clean_job_id = run.kb_sync_job_id
if not clean_job_id:
return
clean_job = db.session.get(KbJob, int(clean_job_id))
if clean_job and clean_job.job_type == "clean" and clean_job.status == "queued":
run_clean_job(clean_job.id)
db.session.refresh(run)
sync_job = _find_pending_sync_job(run)
if sync_job:
run_sync_job(sync_job.id)
db.session.refresh(run)
if run.kb_sync_status in (None, "queued", "cleaning", "syncing"):
if run.kb_document_id:
run.kb_sync_status = "ready"
run.kb_sync_error = None
db.session.commit()
except Exception as exc:
if current_app:
current_app.logger.error(
"[schedule-kb-sync] inline process failed for run %s: %s",
run.id,
exc,
exc_info=True,
)
run.kb_sync_status = "failed"
run.kb_sync_error = str(exc)
db.session.commit()
+28 -11
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
from datetime import datetime
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy import func
@@ -8,6 +8,15 @@ from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.response_utils import utc_iso
def _as_naive_utc(dt: datetime | None) -> datetime | None:
if dt is None:
return None
if dt.tzinfo is not None:
return dt.astimezone(timezone.utc).replace(tzinfo=None)
return dt
def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dict:
@@ -23,14 +32,16 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
'dify_agent_id': task.dify_agent_id,
'platform_api_path': task.platform_api_path,
'data_source_type': task.data_source_type,
'kb_sync_enabled': bool(getattr(task, 'kb_sync_enabled', False)),
'kb_group_id': getattr(task, 'kb_group_id', None),
'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,
'next_run_at': utc_iso(task.next_run_at),
'last_run_at': utc_iso(task.last_run_at),
'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,
'created_at': utc_iso(task.created_at),
'updated_at': utc_iso(task.updated_at),
}
@@ -42,8 +53,8 @@ def serialize_run(run: ScheduleRun) -> dict:
'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,
'started_at': utc_iso(run.started_at),
'finished_at': utc_iso(run.finished_at),
'duration_ms': run.duration_ms,
'status': run.status,
'total_count': run.total_count,
@@ -58,10 +69,16 @@ def serialize_run(run: ScheduleRun) -> dict:
'error_message': run.error_message,
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
'kb_sync_status': run.kb_sync_status,
'kb_group_id': run.kb_group_id,
'kb_document_id': run.kb_document_id,
'kb_document_version_id': run.kb_document_version_id,
'kb_sync_job_id': run.kb_sync_job_id,
'kb_sync_error': run.kb_sync_error,
'wecom_notified': bool(run.wecom_notified),
'wecom_notified_at': run.wecom_notified_at.isoformat() if run.wecom_notified_at else None,
'wecom_notified_at': utc_iso(run.wecom_notified_at),
'wecom_notify_error': run.wecom_notify_error,
'created_at': run.created_at.isoformat() if run.created_at else None,
'created_at': utc_iso(run.created_at),
}
@@ -104,9 +121,9 @@ def list_runs(
if status:
query = query.filter(ScheduleRun.status == status)
if started_after is not None:
query = query.filter(ScheduleRun.started_at >= started_after)
query = query.filter(ScheduleRun.started_at >= _as_naive_utc(started_after))
if started_before is not None:
query = query.filter(ScheduleRun.started_at < started_before)
query = query.filter(ScheduleRun.started_at < _as_naive_utc(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:
@@ -211,6 +211,11 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
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 "kb_sync_enabled" in payload:
task.kb_sync_enabled = bool(payload.get("kb_sync_enabled"))
if "kb_group_id" in payload:
raw_group_id = payload.get("kb_group_id")
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
if not normalize_platform_api_path(task.platform_api_path):
raise ValueError("platform_api_path is required for platform_app")
@@ -343,6 +348,25 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
run.excel_file_data = file_data
run.excel_file_name = file_name
run.excel_file_size = file_size or 0
task.last_run_at = datetime.utcnow()
db.session.commit()
try:
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
db.session.refresh(task)
db.session.refresh(run)
sync_schedule_run_excel_to_kb(task, run, process_inline=True)
db.session.refresh(run)
except Exception as kb_exc:
db.session.rollback()
db.session.refresh(run)
if current_app:
current_app.logger.error("[schedule-run] kb sync failed: %s", kb_exc, exc_info=True)
run.kb_sync_status = "failed"
run.kb_group_id = getattr(task, "kb_group_id", None)
run.kb_sync_error = str(kb_exc)
db.session.commit()
try:
if task.notify_enabled:
@@ -351,8 +375,6 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
if current_app:
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
task.last_run_at = datetime.utcnow()
db.session.commit()
return run
+25 -50
View File
@@ -5,7 +5,7 @@ from typing import Any, Callable
from flask import current_app
from app.services.dify import DifyService
from app.services.rohs_check import RoHSCheckService
try:
import pyodbc # type: ignore
@@ -235,9 +235,12 @@ def _run_check_job_loop(
dify_inputs["system_prompt"] = prompt
t_dify = _ts()
try:
dify_res = DifyService.run_workflow_streaming(
dify_res = RoHSCheckService.evaluate(
agent=agent,
inputs=dify_inputs,
run_no=run_no,
record=record_text,
attachment_url=attachment_url,
system_prompt=prompt,
user=user,
timeout=(5, max(300, int(wait_seconds))),
)
@@ -251,58 +254,30 @@ def _run_check_job_loop(
}))
raise
dify_status = dify_res.get("status") if isinstance(dify_res, dict) else None
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {})
dify_ok = True
if dify_status == "failed" or (dify_error and not dify_res.get("outputs")):
err_detail = str(dify_error) if dify_error else f"Dify status={dify_status}"
dify_result = "人工判定"
dify_message = f"Dify执行失败:{err_detail}"
if current_app:
current_app.logger.info(
"[%s] %s=%s dify_result=%s dify_message=%s",
log_prefix, log_prefix, row_id_value, dify_result, dify_message,
)
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
"request": {
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
"agent_id": getattr(agent, "id", None),
},
"response": _truncate_str(str(dify_res)),
"workflow_run_id": workflow_run_id,
}))
item.update({
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
"request": {
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
"agent_id": getattr(agent, "id", None),
},
"response": {
"provider": dify_res.get("provider") if isinstance(dify_res, dict) else None,
"dify_result": dify_result,
"dify_message": dify_message,
"writeback_srm": False,
"writeback_err": err_detail,
})
failed_count += 1
all_errors.append(f"Dify {log_prefix}={row_id_value}: {err_detail}")
details.append(item)
continue
else:
outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res
if current_app:
current_app.logger.info(
"[%s] %s=%s dify_result=%s dify_message=%s",
log_prefix, log_prefix, row_id_value,
(outputs.get("dify_result") or outputs.get("result")) if isinstance(outputs, dict) else None,
(outputs.get("dify_message") or outputs.get("message")) if isinstance(outputs, dict) else None,
)
dify_result, dify_message = _derive_dify_result_and_message(outputs if isinstance(outputs, dict) else {})
dify_ok = True
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
"request": {
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
"agent_id": getattr(agent, "id", None),
},
"response": {
"status": dify_status,
"dify_result": dify_result,
"dify_message": _truncate_str(dify_message),
"workflow_run_id": workflow_run_id,
},
}))
"dify_message": _truncate_str(dify_message),
"workflow_run_id": workflow_run_id,
"error": dify_error,
},
}))
else:
dify_result = "人工判定"
dify_message = "未配置 Agent ID,跳过 Dify"