feat(admin): 排程管理触发热点问题离线聚合
This commit is contained in:
1 parent
cdd227d550
commit
82ad4323f8
11 files changed
+348
-39
No files matched your search
@@ -38,6 +38,49 @@ def run_internal_job(name: str):
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
if key in {'faq-aggregate-hot', 'faq_hot_aggregate', 'faq-hot-aggregate'}:
|
||||||
|
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||||
|
|
||||||
|
schedule_task_id = data.get('schedule_task_id')
|
||||||
|
agent_id = data.get('agent_id')
|
||||||
|
if schedule_task_id:
|
||||||
|
task = db.session.get(ScheduleTask, int(schedule_task_id))
|
||||||
|
if task and task.dify_agent_id:
|
||||||
|
agent_id = task.dify_agent_id
|
||||||
|
result = HotFaqAggregator.aggregate_hot_faq_candidates(
|
||||||
|
agent_id=int(agent_id) if agent_id else None,
|
||||||
|
dry_run=False,
|
||||||
|
)
|
||||||
|
if not result.get('enabled'):
|
||||||
|
message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
|
||||||
|
return jsonify({
|
||||||
|
'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 1},
|
||||||
|
'details': [],
|
||||||
|
'errors': [message],
|
||||||
|
'step_logs': [{'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}}],
|
||||||
|
})
|
||||||
|
promoted = int(result.get('promoted_count') or 0)
|
||||||
|
skipped = int(result.get('skipped_count') or 0)
|
||||||
|
total = max(promoted + skipped, 1)
|
||||||
|
return jsonify({
|
||||||
|
'summary': {
|
||||||
|
'total_count': total,
|
||||||
|
'success_count': promoted,
|
||||||
|
'failed_count': 0,
|
||||||
|
'skipped_count': skipped,
|
||||||
|
},
|
||||||
|
'details': (result.get('candidates') or [])[:20],
|
||||||
|
'errors': [],
|
||||||
|
'step_logs': [{
|
||||||
|
'step': 'faq_hot_aggregate',
|
||||||
|
'status': 'success',
|
||||||
|
'detail': {
|
||||||
|
'scanned_logs': result.get('scanned_logs'),
|
||||||
|
'promoted_count': promoted,
|
||||||
|
'skipped_count': skipped,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
})
|
||||||
run_no = str(data.get('run_no') or '').strip()
|
run_no = str(data.get('run_no') or '').strip()
|
||||||
schedule_task_id = data.get('schedule_task_id')
|
schedule_task_id = data.get('schedule_task_id')
|
||||||
task = None
|
task = None
|
||||||
|
|||||||
@@ -334,11 +334,14 @@ def post_schedule():
|
|||||||
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
|
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
|
||||||
raw_kb_group_id = data.get('kb_group_id')
|
raw_kb_group_id = data.get('kb_group_id')
|
||||||
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
|
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
|
||||||
|
if data_source_type == 'faq_hot_aggregate':
|
||||||
|
task.platform_api_path = 'faq-aggregate-hot'
|
||||||
|
else:
|
||||||
task.platform_api_path = f'/{task.id}'
|
task.platform_api_path = f'/{task.id}'
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
db.session.refresh(task)
|
db.session.refresh(task)
|
||||||
config_data = data.get('config')
|
config_data = data.get('config')
|
||||||
if config_data:
|
if config_data and data_source_type != 'faq_hot_aggregate':
|
||||||
upsert_schedule_task_config(task.id, config_data)
|
upsert_schedule_task_config(task.id, config_data)
|
||||||
if not task.dify_agent_id:
|
if not task.dify_agent_id:
|
||||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||||
|
|||||||
@@ -273,6 +273,9 @@ def list_registered_api_paths() -> list[dict[str, str]]:
|
|||||||
|
|
||||||
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
|
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
|
||||||
dst = getattr(task, "data_source_type", None) or "database"
|
dst = getattr(task, "data_source_type", None) or "database"
|
||||||
|
if dst == "faq_hot_aggregate":
|
||||||
|
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
|
||||||
|
return run_faq_hot_aggregate_schedule
|
||||||
if dst in ("database", "external_api"):
|
if dst in ("database", "external_api"):
|
||||||
return _run_generic_check_job
|
return _run_generic_check_job
|
||||||
return _run_common_executor
|
return _run_common_executor
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/schedule/faq_hot_aggregate_job.py
|
||||||
|
|
||||||
|
用途:排程管理触发的 FAQ 热点离线聚合执行器。
|
||||||
|
依赖:HotFaqAggregator、ScheduleTask、ScheduleRun。
|
||||||
|
逻辑:data_source_type=faq_hot_aggregate 时由 resolve_schedule_executor 调用。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||||
|
|
||||||
|
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||||
|
|
||||||
|
|
||||||
|
def run_faq_hot_aggregate_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||||
|
"""
|
||||||
|
执行 FAQ 热点离线聚合(等同 flask faq-aggregate-hot,非 dry-run)。
|
||||||
|
核心逻辑:委托 HotFaqAggregator;可选 dify_agent_id 限定 Agent。
|
||||||
|
@param task - 排程任务;dify_agent_id 可选作 agent_id 过滤
|
||||||
|
@param run - 当前执行批次(未写入 run 字段,由 scheduler_service 汇总)
|
||||||
|
@returns ScheduleExecuteResult 元组
|
||||||
|
"""
|
||||||
|
agent_id = int(task.dify_agent_id) if task.dify_agent_id else None
|
||||||
|
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=False)
|
||||||
|
|
||||||
|
step_logs: list[dict[str, Any]] = [
|
||||||
|
{
|
||||||
|
'step': 'faq_hot_aggregate',
|
||||||
|
'status': 'started',
|
||||||
|
'detail': {'schedule_task_id': task.id, 'agent_id': agent_id},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
if not result.get('enabled'):
|
||||||
|
message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
|
||||||
|
step_logs.append({'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}})
|
||||||
|
return 0, 0, 0, 1, [], [message], step_logs
|
||||||
|
|
||||||
|
promoted = int(result.get('promoted_count') or 0)
|
||||||
|
skipped = int(result.get('skipped_count') or 0)
|
||||||
|
scanned = int(result.get('scanned_logs') or 0)
|
||||||
|
total = max(promoted + skipped, 1)
|
||||||
|
|
||||||
|
step_logs.append({
|
||||||
|
'step': 'faq_hot_aggregate',
|
||||||
|
'status': 'success',
|
||||||
|
'detail': {
|
||||||
|
'scanned_logs': scanned,
|
||||||
|
'promoted_count': promoted,
|
||||||
|
'skipped_count': skipped,
|
||||||
|
'group_count': result.get('group_count'),
|
||||||
|
'agent_id': agent_id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
details = [
|
||||||
|
{
|
||||||
|
'canonical_query': item.get('canonical_query'),
|
||||||
|
'ask_count_7d': item.get('ask_count_7d'),
|
||||||
|
'user_count_7d': item.get('user_count_7d'),
|
||||||
|
'answer_dominance': item.get('answer_dominance'),
|
||||||
|
}
|
||||||
|
for item in (result.get('candidates') or [])[:20]
|
||||||
|
if isinstance(item, dict)
|
||||||
|
]
|
||||||
|
|
||||||
|
return total, promoted, 0, skipped, details, [], step_logs
|
||||||
@@ -226,7 +226,10 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
|
|||||||
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
|
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):
|
if not normalize_platform_api_path(task.platform_api_path):
|
||||||
|
dst = str(getattr(task, "data_source_type", None) or "database")
|
||||||
|
if dst != "faq_hot_aggregate":
|
||||||
raise ValueError("platform_api_path is required for platform_app")
|
raise ValueError("platform_api_path is required for platform_app")
|
||||||
|
task.platform_api_path = "faq-aggregate-hot"
|
||||||
task.schedule_type = "platform_app"
|
task.schedule_type = "platform_app"
|
||||||
|
|
||||||
if task.enabled and task.cron_expr:
|
if task.enabled and task.cron_expr:
|
||||||
|
|||||||
@@ -17,6 +17,142 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 1.1 架构总览
|
||||||
|
|
||||||
|
### 整体分层
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TB
|
||||||
|
subgraph online["在线对话(用户提问)"]
|
||||||
|
Q[用户问句] --> Match{FaqCacheService.try_match}
|
||||||
|
Match -->|命中 L1| SSE[SSE 直答预置答案]
|
||||||
|
Match -->|未命中| Dify[调用 Dify / HR / PLM 等]
|
||||||
|
Dify --> Log[写入 ChatLog]
|
||||||
|
SSE --> Log
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph offline["离线聚合(定时 / 手动)"]
|
||||||
|
Log --> Agg[HotFaqAggregator]
|
||||||
|
Agg --> PG[(faq_hot_candidates)]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph admin["管理端审核"]
|
||||||
|
PG --> UI[热点发现 Tab]
|
||||||
|
UI -->|晋升| QQ[(quick_questions)]
|
||||||
|
UI -->|忽略| Deny[dismissed + deny_until]
|
||||||
|
QQ --> Match
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph kb["知识库更新(方案 B)"]
|
||||||
|
KBDoc[KB 文档 sync / 删除] --> Hook[faq_kb_invalidation]
|
||||||
|
Hook --> Stale[FAQ 待复审 stale_*<br/>cache_enabled=false]
|
||||||
|
Stale --> UI2[常用问题 · 待复审]
|
||||||
|
UI2 -->|完成复审| QQ
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
| 层级 | 名称 | 存储 | 在线生效 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| L1 | 人工 FAQ | `quick_questions` | ✅ 命中即 SSE 直答 |
|
||||||
|
| L2 | 热点候选 | `faq_hot_candidates` | ❌ 须晋升后才进 L1 |
|
||||||
|
| L3 | Dify 实时问答 | `chat_logs` | ✅ 默认兜底 |
|
||||||
|
|
||||||
|
### 在线命中流程
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A[用户发消息 chat.py] --> B{有附件?}
|
||||||
|
B -->|是| Z[跳过 FAQ,走业务路由]
|
||||||
|
B -->|否| C[FaqCacheService.try_match]
|
||||||
|
C --> D{agent 全局 FAQ<br/>cache_enabled=true<br/>is_enabled=true<br/>stale_at 为空<br/>未过期?}
|
||||||
|
D -->|否| E[未命中 → Dify 等]
|
||||||
|
D -->|是| F{归一化问句匹配<br/>question / title / aliases?}
|
||||||
|
F -->|否| E
|
||||||
|
F -->|是| G[SSE 直答 stream_chat]
|
||||||
|
G --> H[ChatLog: tokens=0<br/>payload.source=faq_cache]
|
||||||
|
E --> I[ChatLog: tokens>0]
|
||||||
|
```
|
||||||
|
|
||||||
|
**匹配规则**:`normalize_faq_query` 归一化后精确匹配(见 `faq_text_utils.py`)。
|
||||||
|
|
||||||
|
### 离线热点发现流程
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
T[定时 cron / 管理端刷新] --> P[purge_expired 清理过期 candidate]
|
||||||
|
P --> S[扫描近 N 天 ChatLog]
|
||||||
|
S --> F1{tokens>0 且非 faq_cache 来源?}
|
||||||
|
F1 -->|否| Skip[跳过]
|
||||||
|
F1 -->|是| G[按 agent_id + q_norm 分组]
|
||||||
|
G --> F2{频次 / 用户数 / deny / 已有 FAQ?}
|
||||||
|
F2 -->|否| Skip
|
||||||
|
F2 -->|是| A[答案聚类 + 选最佳答案]
|
||||||
|
A --> F3{dominance ≥ 60%?}
|
||||||
|
F3 -->|否| Skip
|
||||||
|
F3 -->|是| U[UPSERT faq_hot_candidates]
|
||||||
|
U --> Admin[管理员审核]
|
||||||
|
Admin -->|晋升| QQ[quick_questions + cache_enabled]
|
||||||
|
Admin -->|忽略| D[dismissed + deny_until]
|
||||||
|
```
|
||||||
|
|
||||||
|
### KB 更新 → FAQ 待复审(方案 B)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
participant Admin as 管理员
|
||||||
|
participant KB as 知识库
|
||||||
|
participant Sync as dify_sync_service
|
||||||
|
participant Hook as faq_kb_invalidation
|
||||||
|
participant QQ as quick_questions
|
||||||
|
participant User as 用户
|
||||||
|
participant Dify as Dify
|
||||||
|
|
||||||
|
Note over Admin,QQ: 已晋升 FAQ 正常运行
|
||||||
|
User->>QQ: 提问
|
||||||
|
QQ->>User: L1 SSE 直答
|
||||||
|
|
||||||
|
Admin->>KB: 编辑文档并 sync
|
||||||
|
KB->>Sync: sync_hash 变化
|
||||||
|
Sync->>Hook: invalidate_faqs_for_kb_document
|
||||||
|
Hook->>QQ: stale_at=now, cache_enabled=false
|
||||||
|
|
||||||
|
User->>Dify: 再问同类问题(FAQ 不命中)
|
||||||
|
Dify->>User: 基于新 KB 回答
|
||||||
|
|
||||||
|
Admin->>QQ: 待复审 → 更新 answer → 完成复审
|
||||||
|
Note over QQ: clear_stale + cache_enabled=true
|
||||||
|
User->>QQ: 再问
|
||||||
|
QQ->>User: L1 直答新答案
|
||||||
|
```
|
||||||
|
|
||||||
|
### 数据表关系(简图)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
erDiagram
|
||||||
|
chat_logs ||--o{ faq_hot_candidates : "source_chat_log_id"
|
||||||
|
faq_hot_candidates ||--o| quick_questions : "promoted_quick_question_id"
|
||||||
|
quick_questions }o--|| agents : "agent_id"
|
||||||
|
kb_documents ||--o{ kb_dify_sync_records : "document_id"
|
||||||
|
quick_questions }o--o| kb_documents : "stale_kb_document_id"
|
||||||
|
quick_questions {
|
||||||
|
int id
|
||||||
|
text answer
|
||||||
|
bool cache_enabled
|
||||||
|
json retriever_resources
|
||||||
|
json source_kb_document_ids
|
||||||
|
datetime stale_at
|
||||||
|
string stale_reason
|
||||||
|
}
|
||||||
|
faq_hot_candidates {
|
||||||
|
int id
|
||||||
|
string q_norm
|
||||||
|
string status
|
||||||
|
datetime expires_at
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 2. 首次部署 Checklist
|
## 2. 首次部署 Checklist
|
||||||
|
|
||||||
### 2.1 数据库迁移
|
### 2.1 数据库迁移
|
||||||
@@ -34,6 +170,8 @@ docker compose exec -T hxops-backend flask --app manage.py db upgrade
|
|||||||
|
|
||||||
- `a1b2c3d4e5f7` — 扩展 `quick_questions`(answer、aliases、cache_enabled 等)
|
- `a1b2c3d4e5f7` — 扩展 `quick_questions`(answer、aliases、cache_enabled 等)
|
||||||
- `b2c3d4e5f6a8` — 新建 `faq_hot_candidates`
|
- `b2c3d4e5f6a8` — 新建 `faq_hot_candidates`
|
||||||
|
- `c5d6e7f8a9b0` — 合并迁移 head(无 DDL)
|
||||||
|
- `c6d7e8f9a0b1` — FAQ 待复审字段(`stale_*`、`source_kb_document_ids`)
|
||||||
|
|
||||||
### 2.2 环境变量
|
### 2.2 环境变量
|
||||||
|
|
||||||
@@ -73,16 +211,33 @@ flask --app manage.py faq-aggregate-hot
|
|||||||
|
|
||||||
## 3. 定时任务(推荐)
|
## 3. 定时任务(推荐)
|
||||||
|
|
||||||
热点发现 **无内置 cron**;过期 `candidate` 的物理清理也发生在聚合开始时。建议至少 **每天 1 次** 跑聚合。
|
热点发现可通过 **排程管理** 配置 Cron,无需宿主机 crontab。
|
||||||
|
|
||||||
### 3.1 Docker 环境(宿主机 crontab)
|
### 3.1 排程管理(推荐)
|
||||||
|
|
||||||
|
路径:**管理后台 → 排程管理 → 新增排程**
|
||||||
|
|
||||||
|
| 配置项 | 建议值 |
|
||||||
|
| --- | --- |
|
||||||
|
| 数据源类型 | **FAQ 热点聚合** |
|
||||||
|
| Cron | 例如每天 02:30(`0 2 * * *`) |
|
||||||
|
| 限定应用 | 可选;留空=全部 Agent |
|
||||||
|
| 所有者 | 必填 |
|
||||||
|
|
||||||
|
创建并 **启用** 后,后端 `schedule-worker` 会按 Cron 自动执行,等同 `flask faq-aggregate-hot`。执行记录在排程工作台可查看(处理数 = 本次产出候选 + 跳过组数)。
|
||||||
|
|
||||||
|
**前提**:`SCHEDULE_WORKER_ENABLED=true`(默认开启),后端进程需正常运行。
|
||||||
|
|
||||||
|
### 3.2 Docker 环境(宿主机 crontab,备选)
|
||||||
|
|
||||||
|
若不用排程管理,仍可用 crontab:
|
||||||
|
|
||||||
```cron
|
```cron
|
||||||
# 每天 02:30 聚合热点 FAQ(stdout 追加到日志)
|
# 每天 02:30 聚合热点 FAQ(stdout 追加到日志)
|
||||||
30 2 * * * cd /path/to/hxops && docker compose exec -T hxops-backend flask --app manage.py faq-aggregate-hot >> /var/log/hxops/faq-aggregate-hot.log 2>&1
|
30 2 * * * cd /path/to/hxops && docker compose exec -T hxops-backend flask --app manage.py faq-aggregate-hot >> /var/log/hxops/faq-aggregate-hot.log 2>&1
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3.2 裸机 / systemd timer
|
### 3.3 裸机 / systemd timer
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 手动试跑
|
# 手动试跑
|
||||||
@@ -120,7 +275,7 @@ WantedBy=timers.target
|
|||||||
sudo systemctl enable --now hxops-faq-aggregate.timer
|
sudo systemctl enable --now hxops-faq-aggregate.timer
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3.3 按 Agent 拆分(可选)
|
### 3.4 按 Agent 拆分(可选)
|
||||||
|
|
||||||
大租户可分开跑,减轻单次扫描量:
|
大租户可分开跑,减轻单次扫描量:
|
||||||
|
|
||||||
@@ -128,9 +283,12 @@ sudo systemctl enable --now hxops-faq-aggregate.timer
|
|||||||
flask --app manage.py faq-aggregate-hot --agent-id 12
|
flask --app manage.py faq-aggregate-hot --agent-id 12
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3.4 与「排程管理」的关系
|
### 3.5 与 SQL 检核排程的区别
|
||||||
|
|
||||||
管理端 **排程(Schedule)** 用于 Dify Workflow / 文件检核等,**不能**直接触发 `faq-aggregate-hot`。FAQ 聚合请用 crontab / systemd / CI 定时 Job。
|
| 类型 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| 数据库直联 / 外部 API | SQL 拉数 + Dify 检核等业务排程 |
|
||||||
|
| **FAQ 热点聚合** | ChatLog → `faq_hot_candidates`,无需 SQL/Dify Agent 配置 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -397,6 +555,7 @@ FAQ_HOT_ENABLED=false
|
|||||||
| L1 在线匹配 | `backend/app/services/faq_cache.py` |
|
| L1 在线匹配 | `backend/app/services/faq_cache.py` |
|
||||||
| 离线聚合 | `backend/app/services/hot_faq_aggregator.py` |
|
| 离线聚合 | `backend/app/services/hot_faq_aggregator.py` |
|
||||||
| PG 候选存储 | `backend/app/services/hot_faq_candidate_store.py` |
|
| PG 候选存储 | `backend/app/services/hot_faq_candidate_store.py` |
|
||||||
|
| KB 失效标记 | `backend/app/services/faq_kb_invalidation.py` |
|
||||||
| CLI | `backend/app/cli/faq_commands.py` |
|
| CLI | `backend/app/cli/faq_commands.py` |
|
||||||
| 管理 API | `backend/app/api/admin.py` |
|
| 管理 API | `backend/app/api/admin.py` |
|
||||||
| 对话入口 | `backend/app/api/chat.py`(Dify 前 `try_match`) |
|
| 对话入口 | `backend/app/api/chat.py`(Dify 前 `try_match`) |
|
||||||
|
|||||||
+36
-26
@@ -66,31 +66,26 @@ const showCreateModal = useScheduleCreateModalOpen();
|
|||||||
</div>
|
</div>
|
||||||
<!-- SQL Config Panel -->
|
<!-- SQL Config Panel -->
|
||||||
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4">
|
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4">
|
||||||
<div class="mb-3 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
<div class="mb-3 space-y-3">
|
||||||
<h4 class="text-base font-bold text-primary shrink-0">{{ $t('admin.schedule.form.dataSourceConfig') }}</h4>
|
<h4 class="text-base font-bold text-primary">{{ $t('admin.schedule.form.dataSourceConfig') }}</h4>
|
||||||
<div class="flex flex-wrap items-center gap-2">
|
<div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||||
<div
|
<div class="w-full sm:max-w-sm">
|
||||||
class="segment-control segment-control--fit segment-control--sm shrink-0"
|
<label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-muted">
|
||||||
role="radiogroup"
|
{{ $t('admin.schedule.form.dataSourceType') }}
|
||||||
:aria-label="$t('admin.schedule.form.dataSourceConfig')"
|
</label>
|
||||||
|
<select
|
||||||
|
v-model="admin.scheduleCreateForm.data_source_type"
|
||||||
|
class="input-field w-full !text-sm !leading-5"
|
||||||
>
|
>
|
||||||
<button
|
<option value="database">{{ $t('admin.schedule.form.databaseDirect') }}</option>
|
||||||
type="button"
|
<option value="external_api">{{ $t('admin.schedule.form.externalApi') }}</option>
|
||||||
role="radio"
|
<option value="faq_hot_aggregate">{{ $t('admin.schedule.form.faqHotAggregate') }}</option>
|
||||||
:aria-checked="admin.scheduleCreateForm.data_source_type === 'database'"
|
</select>
|
||||||
class="segment-item"
|
|
||||||
:class="admin.scheduleCreateForm.data_source_type === 'database' ? 'segment-item--active' : ''"
|
|
||||||
@click="admin.scheduleCreateForm.data_source_type = 'database'"
|
|
||||||
>{{ $t('admin.schedule.form.databaseDirect') }}</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
role="radio"
|
|
||||||
:aria-checked="admin.scheduleCreateForm.data_source_type === 'external_api'"
|
|
||||||
class="segment-item"
|
|
||||||
:class="admin.scheduleCreateForm.data_source_type === 'external_api' ? 'segment-item--active' : ''"
|
|
||||||
@click="admin.scheduleCreateForm.data_source_type = 'external_api'"
|
|
||||||
>{{ $t('admin.schedule.form.externalApi') }}</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="admin.scheduleCreateForm.data_source_type !== 'faq_hot_aggregate'"
|
||||||
|
class="flex flex-wrap items-center gap-2 sm:shrink-0"
|
||||||
|
>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap disabled:cursor-not-allowed disabled:opacity-60"
|
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
@@ -110,7 +105,22 @@ const showCreateModal = useScheduleCreateModalOpen();
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-show="!admin.scheduleConfigCollapsed" class="space-y-3">
|
</div>
|
||||||
|
<div v-show="!admin.scheduleConfigCollapsed || admin.scheduleCreateForm.data_source_type === 'faq_hot_aggregate'" class="space-y-3">
|
||||||
|
<div
|
||||||
|
v-if="admin.scheduleCreateForm.data_source_type === 'faq_hot_aggregate'"
|
||||||
|
class="rounded-xl border border-amber-200 bg-amber-50/60 p-4 space-y-3"
|
||||||
|
>
|
||||||
|
<p class="text-sm text-amber-900">{{ $t('admin.schedule.form.faqHotAggregateHint') }}</p>
|
||||||
|
<div>
|
||||||
|
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.faqHotAgentFilter') }}</label>
|
||||||
|
<select v-model="admin.scheduleCreateForm.dify_agent_id" class="input-field !text-sm !leading-5" :disabled="admin.agents.length === 0">
|
||||||
|
<option :value="null">{{ $t('admin.schedule.form.faqHotAllAgents') }}</option>
|
||||||
|
<option v-for="agent in admin.agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
|
||||||
|
</select>
|
||||||
|
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.faqHotAgentFilterHelp') }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<!-- 数据库直联模式 -->
|
<!-- 数据库直联模式 -->
|
||||||
<template v-if="admin.scheduleCreateForm.data_source_type === 'database'">
|
<template v-if="admin.scheduleCreateForm.data_source_type === 'database'">
|
||||||
<!-- 数据源配置 -->
|
<!-- 数据源配置 -->
|
||||||
@@ -301,7 +311,7 @@ const showCreateModal = useScheduleCreateModalOpen();
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
<div v-if="admin.scheduleCreateForm.data_source_type !== 'faq_hot_aggregate'" class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||||
<div>
|
<div>
|
||||||
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.agentLabel') }}</label>
|
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.agentLabel') }}</label>
|
||||||
<div class="relative">
|
<div class="relative">
|
||||||
@@ -320,7 +330,7 @@ const showCreateModal = useScheduleCreateModalOpen();
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
|
<div v-if="admin.scheduleCreateForm.data_source_type !== 'faq_hot_aggregate'" class="rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
|
||||||
<label class="flex items-center gap-2 text-sm font-semibold text-secondary">
|
<label class="flex items-center gap-2 text-sm font-semibold text-secondary">
|
||||||
<input v-model="admin.scheduleCreateForm.kb_sync_enabled" type="checkbox" class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-300" />
|
<input v-model="admin.scheduleCreateForm.kb_sync_enabled" type="checkbox" class="h-4 w-4 rounded border-default text-emerald-600 focus:ring-emerald-300" />
|
||||||
{{ $t('admin.schedule.form.kbSyncEnabled') }}
|
{{ $t('admin.schedule.form.kbSyncEnabled') }}
|
||||||
|
|||||||
+11
-5
@@ -16,6 +16,7 @@ import { useMessage } from '@/shared/composables/useMessage';
|
|||||||
import {
|
import {
|
||||||
createDefaultScheduleCreateForm,
|
createDefaultScheduleCreateForm,
|
||||||
createDefaultScheduleSqlEditForm,
|
createDefaultScheduleSqlEditForm,
|
||||||
|
type ScheduleCreateForm,
|
||||||
} from '../../types/schedule-admin.types';
|
} from '../../types/schedule-admin.types';
|
||||||
import { buildScheduleConfigPayload } from '../../utils/schedule-form-payload.utils';
|
import { buildScheduleConfigPayload } from '../../utils/schedule-form-payload.utils';
|
||||||
import { useScheduleCronDesigner } from '../useScheduleCronDesigner';
|
import { useScheduleCronDesigner } from '../useScheduleCronDesigner';
|
||||||
@@ -106,7 +107,7 @@ export function useScheduleAdminForm(
|
|||||||
result: Awaited<ReturnType<typeof getAdminScheduleTaskConfig>>,
|
result: Awaited<ReturnType<typeof getAdminScheduleTaskConfig>>,
|
||||||
): void => {
|
): void => {
|
||||||
const cfg = result.config;
|
const cfg = result.config;
|
||||||
scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as 'database' | 'external_api';
|
scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as ScheduleCreateForm['data_source_type'];
|
||||||
if (!cfg) return;
|
if (!cfg) return;
|
||||||
scheduleSqlEditForm.value = {
|
scheduleSqlEditForm.value = {
|
||||||
base_fetch_sql: cfg.base_fetch_sql || '',
|
base_fetch_sql: cfg.base_fetch_sql || '',
|
||||||
@@ -179,7 +180,7 @@ export function useScheduleAdminForm(
|
|||||||
kb_sync_enabled: !!task.kb_sync_enabled,
|
kb_sync_enabled: !!task.kb_sync_enabled,
|
||||||
kb_group_id: task.kb_group_id || null,
|
kb_group_id: task.kb_group_id || null,
|
||||||
enabled: !!task.enabled,
|
enabled: !!task.enabled,
|
||||||
data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
|
data_source_type: (task.data_source_type || 'database') as ScheduleCreateForm['data_source_type'],
|
||||||
};
|
};
|
||||||
scheduleSqlEditForm.value = createDefaultScheduleSqlEditForm();
|
scheduleSqlEditForm.value = createDefaultScheduleSqlEditForm();
|
||||||
scheduleTestResult.value = null;
|
scheduleTestResult.value = null;
|
||||||
@@ -278,21 +279,24 @@ export function useScheduleAdminForm(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const dst = scheduleCreateForm.value.data_source_type;
|
const dst = scheduleCreateForm.value.data_source_type;
|
||||||
|
const isFaqHot = dst === 'faq_hot_aggregate';
|
||||||
const hasAgent = !!scheduleCreateForm.value.dify_agent_id;
|
const hasAgent = !!scheduleCreateForm.value.dify_agent_id;
|
||||||
const hasSql = dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
|
const hasSql = dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.trim();
|
||||||
const hasApi = dst === 'external_api' && !!scheduleSqlEditForm.value.api_url.trim();
|
const hasApi = dst === 'external_api' && !!scheduleSqlEditForm.value.api_url.trim();
|
||||||
if (!hasAgent && !hasSql && !hasApi) {
|
if (!isFaqHot && !hasAgent && !hasSql && !hasApi) {
|
||||||
msg.error(t('admin.schedule.msg.configRequired'));
|
msg.error(t('admin.schedule.msg.configRequired'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let headerLabels: Record<string, string> = {};
|
let headerLabels: Record<string, string> = {};
|
||||||
|
if (!isFaqHot) {
|
||||||
try {
|
try {
|
||||||
headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
|
headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
|
||||||
} catch {
|
} catch {
|
||||||
msg.error(t('admin.schedule.msg.headerLabelsJsonInvalid'));
|
msg.error(t('admin.schedule.msg.headerLabelsJsonInvalid'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
let apiHeaders: Record<string, string> = {};
|
let apiHeaders: Record<string, string> = {};
|
||||||
if (dst === 'external_api') {
|
if (dst === 'external_api') {
|
||||||
try {
|
try {
|
||||||
@@ -303,13 +307,15 @@ export function useScheduleAdminForm(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let configPayload: Record<string, unknown>;
|
let configPayload: Record<string, unknown> | undefined;
|
||||||
|
if (!isFaqHot) {
|
||||||
configPayload = buildScheduleConfigPayload(
|
configPayload = buildScheduleConfigPayload(
|
||||||
scheduleSqlEditForm.value,
|
scheduleSqlEditForm.value,
|
||||||
hasAgent,
|
hasAgent,
|
||||||
headerLabels,
|
headerLabels,
|
||||||
apiHeaders,
|
apiHeaders,
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
scheduleCreateSaving.value = true;
|
scheduleCreateSaving.value = true;
|
||||||
try {
|
try {
|
||||||
@@ -326,7 +332,7 @@ export function useScheduleAdminForm(
|
|||||||
kb_group_id: scheduleCreateForm.value.kb_sync_enabled ? scheduleCreateForm.value.kb_group_id : null,
|
kb_group_id: scheduleCreateForm.value.kb_sync_enabled ? scheduleCreateForm.value.kb_group_id : null,
|
||||||
enabled: scheduleCreateForm.value.enabled,
|
enabled: scheduleCreateForm.value.enabled,
|
||||||
data_source_type: dst,
|
data_source_type: dst,
|
||||||
config: configPayload,
|
...(configPayload ? { config: configPayload } : {}),
|
||||||
};
|
};
|
||||||
let resultData: { id?: number; schedule?: { id?: number } } | null = null;
|
let resultData: { id?: number; schedule?: { id?: number } } | null = null;
|
||||||
if (scheduleEditingId.value) {
|
if (scheduleEditingId.value) {
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ export interface ScheduleCronDesigner {
|
|||||||
/** 创建/编辑定时任务主表单 */
|
/** 创建/编辑定时任务主表单 */
|
||||||
export interface ScheduleCreateForm {
|
export interface ScheduleCreateForm {
|
||||||
name: string;
|
name: string;
|
||||||
data_source_type: 'database' | 'external_api';
|
data_source_type: 'database' | 'external_api' | 'faq_hot_aggregate';
|
||||||
dify_agent_id: number | null;
|
dify_agent_id: number | null;
|
||||||
owner_user_id: number | null;
|
owner_user_id: number | null;
|
||||||
wait_seconds: number;
|
wait_seconds: number;
|
||||||
|
|||||||
@@ -827,8 +827,14 @@
|
|||||||
"noUsers": "No users available",
|
"noUsers": "No users available",
|
||||||
"selectOwner": "Select an owner",
|
"selectOwner": "Select an owner",
|
||||||
"dataSourceConfig": "Data source & execution config",
|
"dataSourceConfig": "Data source & execution config",
|
||||||
|
"dataSourceType": "Data source type",
|
||||||
"databaseDirect": "Database",
|
"databaseDirect": "Database",
|
||||||
"externalApi": "External API",
|
"externalApi": "External API",
|
||||||
|
"faqHotAggregate": "FAQ hot aggregate",
|
||||||
|
"faqHotAggregateHint": "Runs ChatLog hot-FAQ discovery on schedule and writes to faq_hot_candidates — same as Admin → Common Questions → Hot Discovery → Refresh.",
|
||||||
|
"faqHotAgentFilter": "Limit to agent (optional)",
|
||||||
|
"faqHotAllAgents": "All agents",
|
||||||
|
"faqHotAgentFilterHelp": "Leave empty to aggregate all agents; pick one to scope ChatLog to that agent.",
|
||||||
"querying": "Querying...",
|
"querying": "Querying...",
|
||||||
"testQuery": "Test query",
|
"testQuery": "Test query",
|
||||||
"expandConfig": "Expand config",
|
"expandConfig": "Expand config",
|
||||||
|
|||||||
@@ -807,8 +807,14 @@
|
|||||||
"noUsers": "暂无可用用户",
|
"noUsers": "暂无可用用户",
|
||||||
"selectOwner": "请选择所有者",
|
"selectOwner": "请选择所有者",
|
||||||
"dataSourceConfig": "数据源与执行配置",
|
"dataSourceConfig": "数据源与执行配置",
|
||||||
|
"dataSourceType": "数据源类型",
|
||||||
"databaseDirect": "数据库直联",
|
"databaseDirect": "数据库直联",
|
||||||
"externalApi": "外部API",
|
"externalApi": "外部API",
|
||||||
|
"faqHotAggregate": "FAQ 热点聚合",
|
||||||
|
"faqHotAggregateHint": "按 Cron 自动执行 ChatLog 热点发现,结果写入 faq_hot_candidates 表;与「常用问题 → 热点发现 → 刷新聚合」相同。",
|
||||||
|
"faqHotAgentFilter": "限定应用(可选)",
|
||||||
|
"faqHotAllAgents": "全部应用",
|
||||||
|
"faqHotAgentFilterHelp": "留空则聚合所有 Agent;选定后仅统计该应用的 ChatLog。",
|
||||||
"querying": "查询中...",
|
"querying": "查询中...",
|
||||||
"testQuery": "测试查询",
|
"testQuery": "测试查询",
|
||||||
"expandConfig": "展开配置",
|
"expandConfig": "展开配置",
|
||||||
|
|||||||
Reference in new issue
Block a user