feat(faq): 知识库相对应文档更新,标记关联的问题为待复审状态并暂停缓存命中
This commit is contained in:
1 parent
757231e3d5
commit
0d59b23e0c
16 files changed
+809
-185
No files matched your search
@@ -6,7 +6,7 @@ backend/app/api/admin.py
|
||||
逻辑:供前端 Admin 控制台调用;创建/编辑用户时委托 user._sync_casdoor_* 与 IdP 保持同步。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide, KbDocument
|
||||
from app.services.minio_service import minio_service
|
||||
from app.decorators import require_admin
|
||||
from app.config import Config
|
||||
@@ -840,18 +840,23 @@ def reject_request(id):
|
||||
def list_quick_questions():
|
||||
"""
|
||||
列出全局常用问题(含 FAQ 缓存字段)。
|
||||
@returns JSON 数组,每项含 answer/cache_enabled/hit_count 等扩展字段
|
||||
@query stale_only - 可选,true 时仅返回待复审(stale_at 非空)条目
|
||||
@returns JSON 数组,每项含 answer/cache_enabled/hit_count/stale_* 等扩展字段
|
||||
"""
|
||||
qqs = (
|
||||
stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'}
|
||||
query = (
|
||||
db.session.query(QuickQuestion)
|
||||
.filter(QuickQuestion.user_id.is_(None))
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
.all()
|
||||
)
|
||||
if stale_only:
|
||||
query = query.filter(QuickQuestion.stale_at.isnot(None))
|
||||
qqs = query.all()
|
||||
res = []
|
||||
for q in qqs:
|
||||
agent = db.session.get(Agent, q.agent_id)
|
||||
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown'))
|
||||
stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None
|
||||
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown', stale_doc))
|
||||
return jsonify(res)
|
||||
|
||||
|
||||
@@ -895,11 +900,16 @@ def _parse_expires_at(raw_value) -> datetime | None:
|
||||
raise ValidationError('Invalid expires_at format')
|
||||
|
||||
|
||||
def _serialize_admin_quick_question(q: QuickQuestion, agent_name: str) -> dict:
|
||||
def _serialize_admin_quick_question(
|
||||
q: QuickQuestion,
|
||||
agent_name: str,
|
||||
stale_kb_document: KbDocument | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
序列化全局常用问题供管理端展示。
|
||||
@param q - QuickQuestion 实例
|
||||
@param agent_name - 所属应用名称
|
||||
@param stale_kb_document - 触发待复审的 KB 文档(可选)
|
||||
@returns 可 JSON 化的字典
|
||||
"""
|
||||
return {
|
||||
@@ -916,6 +926,11 @@ def _serialize_admin_quick_question(q: QuickQuestion, agent_name: str) -> dict:
|
||||
'sort_order': q.sort_order,
|
||||
'expires_at': q.expires_at.isoformat() if q.expires_at else None,
|
||||
'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None,
|
||||
'source_kb_document_ids': q.source_kb_document_ids if isinstance(q.source_kb_document_ids, list) else [],
|
||||
'stale_at': q.stale_at.isoformat() if getattr(q, 'stale_at', None) else None,
|
||||
'stale_reason': q.stale_reason,
|
||||
'stale_kb_document_id': q.stale_kb_document_id,
|
||||
'stale_kb_document_title': stale_kb_document.title if stale_kb_document else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -944,6 +959,14 @@ def _apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answ
|
||||
qq.is_enabled = bool(data['is_enabled'])
|
||||
if 'expires_at' in data:
|
||||
qq.expires_at = _parse_expires_at(data['expires_at'])
|
||||
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
if data.get('clear_stale'):
|
||||
from app.services.faq_kb_invalidation import clear_faq_stale
|
||||
|
||||
clear_faq_stale(qq)
|
||||
|
||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||
@@ -961,6 +984,10 @@ def create_quick_question():
|
||||
data = request.get_json() or {}
|
||||
qq = QuickQuestion(user_id=None)
|
||||
_apply_quick_question_payload(qq, data, require_answer=True)
|
||||
if isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
@@ -1063,6 +1090,7 @@ def promote_faq_candidate():
|
||||
|
||||
aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm]
|
||||
|
||||
retriever_resources = candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=int(agent_id),
|
||||
@@ -1072,10 +1100,13 @@ def promote_faq_candidate():
|
||||
aliases=aliases or None,
|
||||
cache_enabled=True,
|
||||
is_enabled=True,
|
||||
retriever_resources=candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None,
|
||||
retriever_resources=retriever_resources,
|
||||
sort_order=int(data.get('sort_order') or 0),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, retriever_resources)
|
||||
db.session.add(qq)
|
||||
db.session.flush()
|
||||
if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id):
|
||||
|
||||
@@ -291,7 +291,11 @@ class QuickQuestion(Base):
|
||||
is_enabled: Mapped[bool] = mapped_column(default=True)
|
||||
hit_count: Mapped[int] = mapped_column(default=0)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
stale_kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
@@ -82,6 +82,7 @@ class FaqCacheService:
|
||||
QuickQuestion.is_enabled.is_(True),
|
||||
QuickQuestion.answer.isnot(None),
|
||||
QuickQuestion.answer != "",
|
||||
QuickQuestion.stale_at.is_(None),
|
||||
)
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
.all()
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
"""
|
||||
backend/app/services/faq_kb_invalidation.py
|
||||
|
||||
用途:知识库文档更新/删除时,标记关联 FAQ 为待复审并暂停 L1 缓存命中。
|
||||
依赖:models.QuickQuestion、KbDifySyncRecord、DifyService._extract_dify_ids、IntegrationApiService。
|
||||
逻辑:dify_sync_service 同步成功后调用 invalidate_faqs_for_kb_document;晋升 FAQ 时写入 source_kb_document_ids。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import KbDifySyncRecord, QuickQuestion, db
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
|
||||
STALE_REASON_KB_UPDATED = 'kb_document_updated'
|
||||
STALE_REASON_KB_DELETED = 'kb_document_deleted'
|
||||
|
||||
|
||||
def extract_dify_id_pairs(retriever_resources: list | None) -> list[tuple[str, str]]:
|
||||
"""
|
||||
从 retriever_resources 提取 (dataset_id, remote_document_id) 对。
|
||||
@param retriever_resources - ChatLog / FAQ 上的引用元数据
|
||||
@returns 去重后的 Dify ID 对列表
|
||||
"""
|
||||
if not isinstance(retriever_resources, list):
|
||||
return []
|
||||
pairs: list[tuple[str, str]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for item in retriever_resources:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
dataset_id, remote_document_id = DifyService._extract_dify_ids(item)
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
key = (str(dataset_id), str(remote_document_id))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
pairs.append(key)
|
||||
return pairs
|
||||
|
||||
|
||||
def resolve_kb_document_ids_from_resources(retriever_resources: list | None) -> list[int]:
|
||||
"""
|
||||
将 retriever_resources 解析为本地 kb_documents.id 列表。
|
||||
核心逻辑:优先 IntegrationApiService 本地映射,失败则查 KbDifySyncRecord。
|
||||
@param retriever_resources - Dify 检索引用列表
|
||||
@returns 去重后的文档主键列表
|
||||
"""
|
||||
doc_ids: list[int] = []
|
||||
seen: set[int] = set()
|
||||
for dataset_id, remote_document_id in extract_dify_id_pairs(retriever_resources):
|
||||
local_doc_id: Optional[int] = None
|
||||
try:
|
||||
payload = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if payload and payload.get('document_id') is not None:
|
||||
local_doc_id = int(payload['document_id'])
|
||||
except Exception:
|
||||
local_doc_id = None
|
||||
if local_doc_id is None:
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord.document_id)
|
||||
.filter(
|
||||
KbDifySyncRecord.dataset_id == str(dataset_id),
|
||||
KbDifySyncRecord.remote_document_id == str(remote_document_id),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if record and record[0] is not None:
|
||||
local_doc_id = int(record[0])
|
||||
if local_doc_id is not None and local_doc_id not in seen:
|
||||
seen.add(local_doc_id)
|
||||
doc_ids.append(local_doc_id)
|
||||
return doc_ids
|
||||
|
||||
|
||||
def merge_source_kb_document_ids(
|
||||
existing: list | None,
|
||||
retriever_resources: list | None,
|
||||
) -> list[int] | None:
|
||||
"""
|
||||
合并已有 source_kb_document_ids 与 retriever_resources 解析结果。
|
||||
@returns 合并去重后的 ID 列表;无有效 ID 时返回 None
|
||||
"""
|
||||
merged: list[int] = []
|
||||
seen: set[int] = set()
|
||||
for raw in (existing if isinstance(existing, list) else []):
|
||||
try:
|
||||
doc_id = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if doc_id not in seen:
|
||||
seen.add(doc_id)
|
||||
merged.append(doc_id)
|
||||
for doc_id in resolve_kb_document_ids_from_resources(retriever_resources):
|
||||
if doc_id not in seen:
|
||||
seen.add(doc_id)
|
||||
merged.append(doc_id)
|
||||
return merged or None
|
||||
|
||||
|
||||
def _faq_links_kb_document(
|
||||
qq: QuickQuestion,
|
||||
document_id: int,
|
||||
dataset_id: str | None,
|
||||
remote_document_id: str | None,
|
||||
) -> bool:
|
||||
"""判断 FAQ 是否关联指定 KB 文档(本地 ID 或 Dify ID 对)。"""
|
||||
source_ids = qq.source_kb_document_ids if isinstance(qq.source_kb_document_ids, list) else []
|
||||
for raw in source_ids:
|
||||
try:
|
||||
if int(raw) == int(document_id):
|
||||
return True
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not dataset_id or not remote_document_id:
|
||||
return False
|
||||
target = (str(dataset_id), str(remote_document_id))
|
||||
return target in extract_dify_id_pairs(
|
||||
qq.retriever_resources if isinstance(qq.retriever_resources, list) else None
|
||||
)
|
||||
|
||||
|
||||
def find_linked_faqs(
|
||||
document_id: int,
|
||||
*,
|
||||
dataset_id: str | None = None,
|
||||
remote_document_id: str | None = None,
|
||||
cache_enabled_only: bool = True,
|
||||
) -> list[QuickQuestion]:
|
||||
"""
|
||||
查找与 KB 文档关联的全局 FAQ。
|
||||
@param cache_enabled_only - True 时仅扫描 cache_enabled 条目
|
||||
@returns 匹配的 QuickQuestion 列表
|
||||
"""
|
||||
query = db.session.query(QuickQuestion).filter(QuickQuestion.user_id.is_(None))
|
||||
if cache_enabled_only:
|
||||
query = query.filter(QuickQuestion.cache_enabled.is_(True))
|
||||
rows = query.all()
|
||||
return [
|
||||
row
|
||||
for row in rows
|
||||
if _faq_links_kb_document(row, document_id, dataset_id, remote_document_id)
|
||||
]
|
||||
|
||||
|
||||
def mark_faq_stale(qq: QuickQuestion, *, document_id: int, reason: str) -> None:
|
||||
"""
|
||||
将 FAQ 标记为待复审并暂停缓存。
|
||||
核心逻辑:写 stale_* 字段,cache_enabled=false,用户提问将回退 Dify。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
qq.stale_at = now
|
||||
qq.stale_reason = reason
|
||||
qq.stale_kb_document_id = document_id
|
||||
qq.cache_enabled = False
|
||||
qq.updated_at = now
|
||||
|
||||
|
||||
def clear_faq_stale(qq: QuickQuestion) -> None:
|
||||
"""清除 FAQ 待复审标记。"""
|
||||
qq.stale_at = None
|
||||
qq.stale_reason = None
|
||||
qq.stale_kb_document_id = None
|
||||
|
||||
|
||||
def invalidate_faqs_for_kb_document(
|
||||
document_id: int,
|
||||
*,
|
||||
reason: str,
|
||||
dataset_id: str | None = None,
|
||||
remote_document_id: str | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
KB 文档变更后,标记所有关联 FAQ 为待复审。
|
||||
@param document_id - kb_documents.id
|
||||
@param reason - stale_reason 枚举值
|
||||
@param dataset_id - 可选,Dify dataset_id
|
||||
@param remote_document_id - 可选,Dify remote document id
|
||||
@returns 标记条数
|
||||
"""
|
||||
if not document_id:
|
||||
return 0
|
||||
try:
|
||||
linked = find_linked_faqs(
|
||||
int(document_id),
|
||||
dataset_id=dataset_id,
|
||||
remote_document_id=remote_document_id,
|
||||
cache_enabled_only=True,
|
||||
)
|
||||
if not linked:
|
||||
return 0
|
||||
for qq in linked:
|
||||
mark_faq_stale(qq, document_id=int(document_id), reason=reason)
|
||||
db.session.commit()
|
||||
return len(linked)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
'[faq-kb-invalidation] invalidate failed document_id=%s: %s',
|
||||
document_id,
|
||||
exc,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def apply_retriever_resources_to_faq(qq: QuickQuestion, retriever_resources: Any) -> None:
|
||||
"""
|
||||
将 retriever_resources 写入 FAQ,并解析 source_kb_document_ids。
|
||||
@param qq - QuickQuestion 实例
|
||||
@param retriever_resources - 引用列表或 None
|
||||
"""
|
||||
if isinstance(retriever_resources, list) and retriever_resources:
|
||||
qq.retriever_resources = retriever_resources
|
||||
qq.source_kb_document_ids = merge_source_kb_document_ids(
|
||||
qq.source_kb_document_ids if isinstance(qq.source_kb_document_ids, list) else None,
|
||||
qq.retriever_resources if isinstance(qq.retriever_resources, list) else None,
|
||||
)
|
||||
@@ -10,6 +10,7 @@ import re
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
@@ -312,6 +313,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
previous_sync_hash = existing_record.sync_hash if existing_record else None
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
@@ -401,6 +403,35 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
content_changed = previous_sync_hash != sync_hash
|
||||
if content_changed:
|
||||
try:
|
||||
from app.services.faq_kb_invalidation import (
|
||||
STALE_REASON_KB_UPDATED,
|
||||
invalidate_faqs_for_kb_document,
|
||||
)
|
||||
|
||||
invalidated = invalidate_faqs_for_kb_document(
|
||||
document.id,
|
||||
reason=STALE_REASON_KB_UPDATED,
|
||||
dataset_id=str(dataset_id),
|
||||
remote_document_id=str(remote_document_id),
|
||||
)
|
||||
if current_app and invalidated:
|
||||
current_app.logger.info(
|
||||
'[faq-kb-invalidation] kb_document_updated id=%s invalidated=%s',
|
||||
document.id,
|
||||
invalidated,
|
||||
)
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
'[faq-kb-invalidation] hook failed document_id=%s: %s',
|
||||
document.id,
|
||||
exc,
|
||||
)
|
||||
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
@@ -445,4 +476,32 @@ def delete_document_from_dify(document_id: int) -> dict:
|
||||
deleted_count += 1
|
||||
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
from app.services.faq_kb_invalidation import (
|
||||
STALE_REASON_KB_DELETED,
|
||||
invalidate_faqs_for_kb_document,
|
||||
)
|
||||
|
||||
latest = records[0] if records else None
|
||||
invalidated = invalidate_faqs_for_kb_document(
|
||||
int(document_id),
|
||||
reason=STALE_REASON_KB_DELETED,
|
||||
dataset_id=str(latest.dataset_id) if latest and latest.dataset_id else None,
|
||||
remote_document_id=str(latest.remote_document_id) if latest and latest.remote_document_id else None,
|
||||
)
|
||||
if current_app and invalidated:
|
||||
current_app.logger.info(
|
||||
'[faq-kb-invalidation] kb_document_deleted id=%s invalidated=%s',
|
||||
document_id,
|
||||
invalidated,
|
||||
)
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
'[faq-kb-invalidation] delete hook failed document_id=%s: %s',
|
||||
document_id,
|
||||
exc,
|
||||
)
|
||||
|
||||
return {'deleted': True, 'remote_document_count': deleted_count}
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
backend/migrations/versions/c6d7e8f9a0b1_add_faq_kb_stale_fields.py
|
||||
|
||||
用途:为 quick_questions 增加 KB 关联与待复审(stale)字段,支持方案 B 失效标记。
|
||||
依赖:alembic.op、sqlalchemy。
|
||||
逻辑:KB sync 成功后按 source_kb_document_ids / retriever_resources 标记 FAQ 待复审。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "c6d7e8f9a0b1"
|
||||
down_revision = "c5d6e7f8a9b0"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("source_kb_document_ids", sa.JSON(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("stale_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("stale_reason", sa.String(length=64), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("stale_kb_document_id", sa.Integer(), nullable=True),
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_quick_questions_stale_kb_document_id",
|
||||
"quick_questions",
|
||||
"kb_documents",
|
||||
["stale_kb_document_id"],
|
||||
["id"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_quick_questions_stale_at",
|
||||
"quick_questions",
|
||||
["stale_at"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index("ix_quick_questions_stale_at", table_name="quick_questions")
|
||||
op.drop_constraint(
|
||||
"fk_quick_questions_stale_kb_document_id",
|
||||
"quick_questions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.drop_column("quick_questions", "stale_kb_document_id")
|
||||
op.drop_column("quick_questions", "stale_reason")
|
||||
op.drop_column("quick_questions", "stale_at")
|
||||
op.drop_column("quick_questions", "source_kb_document_ids")
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
backend/tests/test_faq_kb_invalidation.py
|
||||
|
||||
用途:FAQ 与 KB 文档关联解析及失效标记单元测试。
|
||||
"""
|
||||
from app.services.faq_kb_invalidation import (
|
||||
_faq_links_kb_document,
|
||||
extract_dify_id_pairs,
|
||||
merge_source_kb_document_ids,
|
||||
)
|
||||
from app.models import QuickQuestion
|
||||
|
||||
|
||||
def test_extract_dify_id_pairs_from_retriever_resources():
|
||||
resources = [
|
||||
{'dataset_id': 'ds-1', 'document_id': 'doc-1'},
|
||||
{'metadata': {'dify_dataset_id': 'ds-2', 'remote_document_id': 'doc-2'}},
|
||||
]
|
||||
pairs = extract_dify_id_pairs(resources)
|
||||
assert ('ds-1', 'doc-1') in pairs
|
||||
assert ('ds-2', 'doc-2') in pairs
|
||||
|
||||
|
||||
def test_faq_links_kb_document_by_source_ids():
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=1,
|
||||
title='t',
|
||||
question='q',
|
||||
source_kb_document_ids=[10, 20],
|
||||
)
|
||||
assert _faq_links_kb_document(qq, 10, None, None) is True
|
||||
assert _faq_links_kb_document(qq, 99, None, None) is False
|
||||
|
||||
|
||||
def test_faq_links_kb_document_by_retriever_resources():
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=1,
|
||||
title='t',
|
||||
question='q',
|
||||
retriever_resources=[{'dataset_id': 'ds-a', 'document_id': 'remote-a'}],
|
||||
)
|
||||
assert _faq_links_kb_document(qq, 0, 'ds-a', 'remote-a') is True
|
||||
assert _faq_links_kb_document(qq, 0, 'ds-b', 'remote-a') is False
|
||||
|
||||
|
||||
def test_merge_source_kb_document_ids():
|
||||
merged = merge_source_kb_document_ids([1], None)
|
||||
assert merged == [1]
|
||||
@@ -405,7 +405,31 @@ FAQ_HOT_ENABLED=false
|
||||
|
||||
---
|
||||
|
||||
## 13. 建议运维节奏(参考)
|
||||
## 13. KB 更新与 FAQ 待复审(方案 B)
|
||||
|
||||
知识库文档 sync 到 Dify 且 **sync_hash 变化**(内容真的变了)时,系统自动:
|
||||
|
||||
1. 查找 `source_kb_document_ids` 或 `retriever_resources` 关联的 FAQ
|
||||
2. 设置 `stale_at`、`stale_reason=kb_document_updated`、`stale_kb_document_id`
|
||||
3. **`cache_enabled=false`** — 用户提问立即回退 Dify
|
||||
|
||||
文档从 Dify 删除时同理,reason 为 `kb_document_deleted`。
|
||||
|
||||
### 管理员复审
|
||||
|
||||
路径:**常用问题** → 筛选「仅显示待复审」→ 编辑 → **完成复审并启用缓存**
|
||||
|
||||
API:`PUT /api/admin/quick-questions/:id` body 含 `clear_stale: true` 且 `cache_enabled: true`
|
||||
|
||||
### 部署
|
||||
|
||||
```bash
|
||||
flask --app manage.py db upgrade # c6d7e8f9a0b1_add_faq_kb_stale_fields
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. 建议运维节奏(参考)
|
||||
|
||||
| 频率 | 动作 | 负责人 |
|
||||
| --- | --- | --- |
|
||||
|
||||
@@ -56,6 +56,10 @@ const {
|
||||
|
||||
filterCacheOnly,
|
||||
|
||||
filterStaleOnly,
|
||||
|
||||
staleCount,
|
||||
|
||||
searchKeyword,
|
||||
|
||||
loadAll,
|
||||
@@ -68,6 +72,8 @@ const {
|
||||
|
||||
saveQuestion,
|
||||
|
||||
saveReviewQuestion,
|
||||
|
||||
deleteQuestion,
|
||||
|
||||
closeDeleteConfirm,
|
||||
@@ -144,6 +150,13 @@ onMounted(() => {
|
||||
|
||||
{{ t('admin.question.tabs.manual') }}
|
||||
|
||||
<span
|
||||
v-if="staleCount > 0"
|
||||
class="ml-1.5 inline-flex min-w-[1.25rem] items-center justify-center rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold text-amber-800"
|
||||
>
|
||||
{{ staleCount }}
|
||||
</span>
|
||||
|
||||
</button>
|
||||
|
||||
<button
|
||||
@@ -218,6 +231,14 @@ onMounted(() => {
|
||||
|
||||
</label>
|
||||
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary whitespace-nowrap">
|
||||
|
||||
<input v-model="filterStaleOnly" type="checkbox" class="accent-brand-600" />
|
||||
|
||||
<span>{{ t('admin.question.filters.staleOnly') }}</span>
|
||||
|
||||
</label>
|
||||
|
||||
</div>
|
||||
|
||||
<p class="text-xs text-muted">
|
||||
@@ -274,6 +295,18 @@ onMounted(() => {
|
||||
|
||||
<div class="font-medium text-primary text-sm">{{ q.title }}</div>
|
||||
|
||||
<span
|
||||
|
||||
v-if="q.stale_at"
|
||||
|
||||
class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium bg-amber-50 text-amber-800 border border-amber-100"
|
||||
|
||||
>
|
||||
|
||||
{{ t('admin.question.badges.stale') }}
|
||||
|
||||
</span>
|
||||
|
||||
<span
|
||||
|
||||
v-if="!q.is_enabled"
|
||||
@@ -416,21 +449,23 @@ onMounted(() => {
|
||||
|
||||
|
||||
|
||||
<QuestionFormModal
|
||||
<QuestionFormModal
|
||||
|
||||
:visible="showFormModal"
|
||||
:visible="showFormModal"
|
||||
|
||||
:form="form"
|
||||
:form="form"
|
||||
|
||||
:agents="agents"
|
||||
:agents="agents"
|
||||
|
||||
:is-saving="isSaving"
|
||||
:is-saving="isSaving"
|
||||
|
||||
@close="closeFormModal"
|
||||
@close="closeFormModal"
|
||||
|
||||
@save="saveQuestion"
|
||||
@save="saveQuestion"
|
||||
|
||||
/>
|
||||
@review="saveReviewQuestion"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,160 +1,199 @@
|
||||
/**␍
|
||||
* features/admin/modules/questions/components/QuestionFormModal.vue␍
|
||||
* 常用问题 / FAQ 缓存创建与编辑居中弹窗。␍
|
||||
* 依赖:QuestionFormState、admin 通用 modal 样式。␍
|
||||
* 逻辑:QuestionsPage 打开本组件;提交时 emit save,由 composable 调 API。␍
|
||||
*/␍
|
||||
<script setup lang="ts">␍
|
||||
import { computed } from 'vue';␍
|
||||
import { useI18n } from 'vue-i18n';␍
|
||||
import type { AdminAgentOption } from '@/features/admin/types/admin.types';␍
|
||||
import type { QuestionFormState } from '@/features/admin/types/question.types';␍
|
||||
␍
|
||||
const props = defineProps<{␍
|
||||
visible: boolean;␍
|
||||
form: QuestionFormState;␍
|
||||
agents: AdminAgentOption[];␍
|
||||
isSaving: boolean;␍
|
||||
}>();␍
|
||||
␍
|
||||
const emit = defineEmits<{␍
|
||||
close: [];␍
|
||||
save: [];␍
|
||||
}>();␍
|
||||
␍
|
||||
const { t } = useI18n();␍
|
||||
␍
|
||||
/** 启用 FAQ 缓存时标准答案为必填。 */␍
|
||||
const answerRequired = computed(() => props.form.cache_enabled);␍
|
||||
</script>␍
|
||||
␍
|
||||
<template>␍
|
||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">␍
|
||||
<div class="admin-modal-panel max-w-3xl max-h-[92vh] scale-100">␍
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">␍
|
||||
<h3 class="section-title">␍
|
||||
{{ form.id ? t('admin.question.edit') : t('admin.question.add') }}␍
|
||||
</h3>␍
|
||||
<p class="text-sm text-muted mt-1">{{ t('admin.question.formHint') }}</p>␍
|
||||
</div>␍
|
||||
␍
|
||||
<div class="px-5 sm:px-8 py-5 space-y-6 overflow-y-auto">␍
|
||||
<section class="space-y-4">␍
|
||||
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">␍
|
||||
{{ t('admin.question.sections.basic') }}␍
|
||||
</h4>␍
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">␍
|
||||
<div class="space-y-1.5 md:col-span-2">␍
|
||||
<label class="label-field">{{ t('admin.question.fields.title') }}</label>␍
|
||||
<input␍
|
||||
v-model="form.title"␍
|
||||
type="text"␍
|
||||
class="input-field text-sm"␍
|
||||
:placeholder="t('admin.question.fields.titlePlaceholder')"␍
|
||||
/>␍
|
||||
</div>␍
|
||||
<div class="space-y-1.5">␍
|
||||
<label class="label-field">{{ t('admin.question.fields.targetAgent') }}</label>␍
|
||||
<select v-model="form.agent_id" class="input-field text-sm">␍
|
||||
<option :value="undefined" disabled>{{ t('admin.perm.batchModal.selectAgents') }}</option>␍
|
||||
<option v-for="agent in agents" :key="agent.id" :value="agent.id">␍
|
||||
{{ agent.name }}␍
|
||||
</option>␍
|
||||
</select>␍
|
||||
</div>␍
|
||||
<div class="space-y-1.5">␍
|
||||
<label class="label-field">{{ t('admin.question.fields.sortOrder') }}</label>␍
|
||||
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" />␍
|
||||
</div>␍
|
||||
<div class="md:col-span-2 flex flex-wrap gap-6">␍
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">␍
|
||||
<input v-model="form.is_enabled" type="checkbox" class="accent-brand-600" />␍
|
||||
<span>{{ t('admin.question.fields.isEnabled') }}</span>␍
|
||||
</label>␍
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">␍
|
||||
<input v-model="form.cache_enabled" type="checkbox" class="accent-brand-600" />␍
|
||||
<span>{{ t('admin.question.fields.cacheEnabled') }}</span>␍
|
||||
</label>␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
</section>␍
|
||||
␍
|
||||
<section class="space-y-4">␍
|
||||
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">␍
|
||||
{{ t('admin.question.sections.matching') }}␍
|
||||
</h4>␍
|
||||
<div class="space-y-1.5">␍
|
||||
<label class="label-field">{{ t('admin.question.fields.content') }}</label>␍
|
||||
<textarea␍
|
||||
v-model="form.question"␍
|
||||
rows="3"␍
|
||||
class="input-field text-sm resize-y min-h-[88px]"␍
|
||||
:placeholder="t('admin.question.fields.contentPlaceholder')"␍
|
||||
/>␍
|
||||
<p class="text-xs text-muted">{{ t('admin.question.fields.contentHelp') }}</p>␍
|
||||
</div>␍
|
||||
<div class="space-y-1.5">␍
|
||||
<label class="label-field">{{ t('admin.question.fields.aliases') }}</label>␍
|
||||
<textarea␍
|
||||
v-model="form.aliasesText"␍
|
||||
rows="3"␍
|
||||
class="input-field text-sm resize-y min-h-[88px] font-mono"␍
|
||||
:placeholder="t('admin.question.fields.aliasesPlaceholder')"␍
|
||||
/>␍
|
||||
<p class="text-xs text-muted">{{ t('admin.question.fields.aliasesHelp') }}</p>␍
|
||||
</div>␍
|
||||
</section>␍
|
||||
␍
|
||||
<section class="space-y-4 rounded-2xl border border-default bg-surface-soft/60 p-4">␍
|
||||
<div class="flex items-start justify-between gap-3">␍
|
||||
<div>␍
|
||||
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">␍
|
||||
{{ t('admin.question.sections.cache') }}␍
|
||||
</h4>␍
|
||||
<p class="text-xs text-muted mt-1">{{ t('admin.question.fields.cacheHelp') }}</p>␍
|
||||
</div>␍
|
||||
<span␍
|
||||
class="inline-flex shrink-0 items-center rounded-full px-2.5 py-0.5 text-xs font-medium"␍
|
||||
:class="form.cache_enabled ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-surface-soft text-muted border border-default'"␍
|
||||
>␍
|
||||
{{ form.cache_enabled ? t('admin.question.badges.cacheOn') : t('admin.question.badges.cacheOff') }}␍
|
||||
</span>␍
|
||||
</div>␍
|
||||
␍
|
||||
<div class="space-y-1.5">␍
|
||||
<label class="label-field">␍
|
||||
{{ t('admin.question.fields.answer') }}␍
|
||||
<span v-if="answerRequired" class="text-red-500">*</span>␍
|
||||
</label>␍
|
||||
<textarea␍
|
||||
v-model="form.answer"␍
|
||||
rows="6"␍
|
||||
class="input-field text-sm resize-y min-h-[140px]"␍
|
||||
:placeholder="t('admin.question.fields.answerPlaceholder')"␍
|
||||
/>␍
|
||||
</div>␍
|
||||
␍
|
||||
<div class="space-y-1.5">␍
|
||||
<label class="label-field">{{ t('admin.question.fields.expiresAt') }}</label>␍
|
||||
<input v-model="form.expires_at" type="datetime-local" class="input-field text-sm" />␍
|
||||
<p class="text-xs text-muted">{{ t('admin.question.fields.expiresAtHelp') }}</p>␍
|
||||
</div>␍
|
||||
</section>␍
|
||||
</div>␍
|
||||
␍
|
||||
<div class="admin-modal-footer">␍
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>␍
|
||||
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">␍
|
||||
{{␍
|
||||
isSaving␍
|
||||
? t('admin.save') + '...'␍
|
||||
: form.id␍
|
||||
? t('admin.update')␍
|
||||
: t('admin.add')␍
|
||||
}}␍
|
||||
</button>␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
</template>␍
|
||||
␍
|
||||
/**
|
||||
* features/admin/modules/questions/components/QuestionFormModal.vue
|
||||
* 常用问题 / FAQ 缓存创建与编辑居中弹窗。
|
||||
* 依赖:QuestionFormState、admin 通用 modal 样式。
|
||||
* 逻辑:QuestionsPage 打开本组件;提交时 emit save,由 composable 调 API。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
|
||||
import type { QuestionFormState } from '@/features/admin/types/question.types';
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
form: QuestionFormState;
|
||||
agents: AdminAgentOption[];
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
save: [];
|
||||
review: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/** 启用 FAQ 缓存时标准答案为必填。 */
|
||||
const answerRequired = computed(() => props.form.cache_enabled);
|
||||
|
||||
/** 是否处于 KB 更新后的待复审状态。 */
|
||||
const isStale = computed(() => Boolean(props.form.stale_at));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
||||
<div class="admin-modal-panel max-w-3xl max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">
|
||||
{{ form.id ? t('admin.question.edit') : t('admin.question.add') }}
|
||||
</h3>
|
||||
<p class="text-sm text-muted mt-1">{{ t('admin.question.formHint') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="px-5 sm:px-8 py-5 space-y-6 overflow-y-auto">
|
||||
<div
|
||||
v-if="isStale"
|
||||
class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900"
|
||||
>
|
||||
<p class="font-medium">{{ t('admin.question.stale.bannerTitle') }}</p>
|
||||
<p class="mt-1 text-xs text-amber-800">
|
||||
{{ t('admin.question.stale.bannerBody', {
|
||||
doc: form.stale_kb_document_title || t('admin.question.stale.unknownDoc'),
|
||||
reason: form.stale_reason === 'kb_document_deleted'
|
||||
? t('admin.question.stale.reasonDeleted')
|
||||
: t('admin.question.stale.reasonUpdated'),
|
||||
}) }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-amber-700">{{ t('admin.question.stale.bannerHint') }}</p>
|
||||
</div>
|
||||
|
||||
<section class="space-y-4">
|
||||
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">
|
||||
{{ t('admin.question.sections.basic') }}
|
||||
</h4>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="space-y-1.5 md:col-span-2">
|
||||
<label class="label-field">{{ t('admin.question.fields.title') }}</label>
|
||||
<input
|
||||
v-model="form.title"
|
||||
type="text"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.question.fields.titlePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.targetAgent') }}</label>
|
||||
<select v-model="form.agent_id" class="input-field text-sm">
|
||||
<option :value="undefined" disabled>{{ t('admin.perm.batchModal.selectAgents') }}</option>
|
||||
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
|
||||
{{ agent.name }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.sortOrder') }}</label>
|
||||
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" />
|
||||
</div>
|
||||
<div class="md:col-span-2 flex flex-wrap gap-6">
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="form.is_enabled" type="checkbox" class="accent-brand-600" />
|
||||
<span>{{ t('admin.question.fields.isEnabled') }}</span>
|
||||
</label>
|
||||
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
|
||||
<input v-model="form.cache_enabled" type="checkbox" class="accent-brand-600" />
|
||||
<span>{{ t('admin.question.fields.cacheEnabled') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="space-y-4">
|
||||
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">
|
||||
{{ t('admin.question.sections.matching') }}
|
||||
</h4>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.content') }}</label>
|
||||
<textarea
|
||||
v-model="form.question"
|
||||
rows="3"
|
||||
class="input-field text-sm resize-y min-h-[88px]"
|
||||
:placeholder="t('admin.question.fields.contentPlaceholder')"
|
||||
/>
|
||||
<p class="text-xs text-muted">{{ t('admin.question.fields.contentHelp') }}</p>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.aliases') }}</label>
|
||||
<textarea
|
||||
v-model="form.aliasesText"
|
||||
rows="3"
|
||||
class="input-field text-sm resize-y min-h-[88px] font-mono"
|
||||
:placeholder="t('admin.question.fields.aliasesPlaceholder')"
|
||||
/>
|
||||
<p class="text-xs text-muted">{{ t('admin.question.fields.aliasesHelp') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="space-y-4 rounded-2xl border border-default bg-surface-soft/60 p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h4 class="text-xs font-bold uppercase tracking-wider text-muted">
|
||||
{{ t('admin.question.sections.cache') }}
|
||||
</h4>
|
||||
<p class="text-xs text-muted mt-1">{{ t('admin.question.fields.cacheHelp') }}</p>
|
||||
</div>
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
|
||||
:class="form.cache_enabled ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-surface-soft text-muted border border-default'"
|
||||
>
|
||||
{{ form.cache_enabled ? t('admin.question.badges.cacheOn') : t('admin.question.badges.cacheOff') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">
|
||||
{{ t('admin.question.fields.answer') }}
|
||||
<span v-if="answerRequired" class="text-red-500">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
v-model="form.answer"
|
||||
rows="6"
|
||||
class="input-field text-sm resize-y min-h-[140px]"
|
||||
:placeholder="t('admin.question.fields.answerPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.question.fields.expiresAt') }}</label>
|
||||
<input v-model="form.expires_at" type="datetime-local" class="input-field text-sm" />
|
||||
<p class="text-xs text-muted">{{ t('admin.question.fields.expiresAtHelp') }}</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
||||
<button
|
||||
v-if="isStale"
|
||||
type="button"
|
||||
class="btn-primary disabled:opacity-70"
|
||||
:disabled="isSaving"
|
||||
@click="emit('review')"
|
||||
>
|
||||
{{
|
||||
isSaving
|
||||
? t('admin.save') + '...'
|
||||
: t('admin.question.stale.completeReview')
|
||||
}}
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="btn-primary disabled:opacity-70"
|
||||
:disabled="isSaving"
|
||||
@click="emit('save')"
|
||||
>
|
||||
{{
|
||||
isSaving
|
||||
? t('admin.save') + '...'
|
||||
: form.id
|
||||
? t('admin.update')
|
||||
: t('admin.add')
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -37,17 +37,21 @@ export function useQuestionsAdmin() {
|
||||
const showFormModal = ref(false);
|
||||
const filterAgentId = ref<number | ''>('');
|
||||
const filterCacheOnly = ref(false);
|
||||
const filterStaleOnly = ref(false);
|
||||
const searchKeyword = ref('');
|
||||
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
const deleteConfirmMessage = ref('');
|
||||
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
const staleCount = computed(() => questions.value.filter((q) => Boolean(q.stale_at)).length);
|
||||
|
||||
const filteredQuestions = computed(() => {
|
||||
const keyword = searchKeyword.value.trim().toLowerCase();
|
||||
return questions.value.filter((q) => {
|
||||
if (filterAgentId.value !== '' && q.agent_id !== filterAgentId.value) return false;
|
||||
if (filterCacheOnly.value && !q.cache_enabled) return false;
|
||||
if (filterStaleOnly.value && !q.stale_at) return false;
|
||||
if (!keyword) return true;
|
||||
const haystack = [q.title, q.question, q.answer, ...(q.aliases || [])]
|
||||
.filter(Boolean)
|
||||
@@ -130,6 +134,9 @@ export function useQuestionsAdmin() {
|
||||
agent_id: q.agent_id,
|
||||
sort_order: q.sort_order,
|
||||
expires_at: q.expires_at ? q.expires_at.slice(0, 16) : '',
|
||||
stale_at: q.stale_at || null,
|
||||
stale_reason: q.stale_reason || null,
|
||||
stale_kb_document_title: q.stale_kb_document_title || null,
|
||||
};
|
||||
showFormModal.value = true;
|
||||
};
|
||||
@@ -191,6 +198,33 @@ export function useQuestionsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 完成 KB 待复审:更新答案、清除 stale 并重新启用缓存。
|
||||
*/
|
||||
const saveReviewQuestion = async (): Promise<void> => {
|
||||
if (!form.value.id) return;
|
||||
if (!form.value.answer.trim()) {
|
||||
msg.warning(t('admin.question.msg.answerRequired'));
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
await saveAdminQuickQuestion(
|
||||
`/api/admin/quick-questions/${form.value.id}`,
|
||||
'PUT',
|
||||
buildQuestionPayload({ ...form.value, cache_enabled: true }, { clearStale: true }),
|
||||
);
|
||||
await loadQuestions();
|
||||
closeFormModal();
|
||||
msg.success(t('admin.question.msg.reviewCompleted'));
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const deleteQuestion = (id: number): void => {
|
||||
openDeleteConfirm(t('admin.question.confirmDelete'), async () => {
|
||||
try {
|
||||
@@ -215,12 +249,15 @@ export function useQuestionsAdmin() {
|
||||
deleteConfirmMessage,
|
||||
filterAgentId,
|
||||
filterCacheOnly,
|
||||
filterStaleOnly,
|
||||
staleCount,
|
||||
searchKeyword,
|
||||
loadAll,
|
||||
openCreateModal,
|
||||
openEditModal,
|
||||
closeFormModal,
|
||||
saveQuestion,
|
||||
saveReviewQuestion,
|
||||
deleteQuestion,
|
||||
closeDeleteConfirm,
|
||||
confirmDelete,
|
||||
|
||||
@@ -17,6 +17,11 @@ export interface AdminQuickQuestionRow {
|
||||
sort_order: number;
|
||||
expires_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
source_kb_document_ids?: number[];
|
||||
stale_at?: string | null;
|
||||
stale_reason?: string | null;
|
||||
stale_kb_document_id?: number | null;
|
||||
stale_kb_document_title?: string | null;
|
||||
}
|
||||
|
||||
export interface QuestionFormState {
|
||||
@@ -30,6 +35,9 @@ export interface QuestionFormState {
|
||||
agent_id?: number;
|
||||
sort_order: number;
|
||||
expires_at: string;
|
||||
stale_at?: string | null;
|
||||
stale_reason?: string | null;
|
||||
stale_kb_document_title?: string | null;
|
||||
}
|
||||
|
||||
export const createEmptyQuestionForm = (): QuestionFormState => ({
|
||||
@@ -63,7 +71,10 @@ export const textToAliases = (text: string): string[] => {
|
||||
};
|
||||
|
||||
/** 构建提交 API 的 payload。 */
|
||||
export const buildQuestionPayload = (form: QuestionFormState): Record<string, unknown> => ({
|
||||
export const buildQuestionPayload = (
|
||||
form: QuestionFormState,
|
||||
options?: { clearStale?: boolean },
|
||||
): Record<string, unknown> => ({
|
||||
title: form.title,
|
||||
question: form.question,
|
||||
answer: form.answer || null,
|
||||
@@ -73,4 +84,5 @@ export const buildQuestionPayload = (form: QuestionFormState): Record<string, un
|
||||
agent_id: form.agent_id,
|
||||
sort_order: form.sort_order,
|
||||
expires_at: form.expires_at || null,
|
||||
...(options?.clearStale ? { clear_stale: true } : {}),
|
||||
});
|
||||
@@ -240,12 +240,14 @@
|
||||
"search": "Search title, query or answer…",
|
||||
"allAgents": "All agents",
|
||||
"cacheOnly": "Cache enabled only",
|
||||
"staleOnly": "Pending review only",
|
||||
"resultCount": "{count} item(s)"
|
||||
},
|
||||
"badges": {
|
||||
"cacheOn": "Cached",
|
||||
"cacheOff": "Not cached",
|
||||
"disabled": "Disabled"
|
||||
"disabled": "Disabled",
|
||||
"stale": "Review"
|
||||
},
|
||||
"labels": {
|
||||
"aliases": "{count} alias(es)"
|
||||
@@ -258,7 +260,17 @@
|
||||
"msg": {
|
||||
"fillAll": "Please fill in title, query and target agent",
|
||||
"answerRequired": "Preset answer is required when FAQ cache is enabled",
|
||||
"saved": "Saved successfully"
|
||||
"saved": "Saved successfully",
|
||||
"reviewCompleted": "Review completed; FAQ cache re-enabled"
|
||||
},
|
||||
"stale": {
|
||||
"bannerTitle": "Linked knowledge base changed — cache paused",
|
||||
"bannerBody": "Triggered by: {doc} ({reason})",
|
||||
"bannerHint": "Update the standard answer from the latest KB, then click Complete review. While stale, users get fresh answers via Dify.",
|
||||
"unknownDoc": "Unknown document",
|
||||
"reasonUpdated": "Document updated",
|
||||
"reasonDeleted": "Document deleted",
|
||||
"completeReview": "Complete review & enable cache"
|
||||
},
|
||||
"tabs": {
|
||||
"manual": "Common Questions",
|
||||
|
||||
@@ -240,12 +240,14 @@
|
||||
"search": "ค้นหาหัวข้อ คำถาม หรือคำตอบ…",
|
||||
"allAgents": "ตัวแทนทั้งหมด",
|
||||
"cacheOnly": "เฉพาะที่เปิด cache",
|
||||
"staleOnly": "รอตรวจสอบเท่านั้น",
|
||||
"resultCount": "{count} รายการ"
|
||||
},
|
||||
"badges": {
|
||||
"cacheOn": "Cache แล้ว",
|
||||
"cacheOff": "ยังไม่ cache",
|
||||
"disabled": "ปิดใช้งาน"
|
||||
"disabled": "ปิดใช้งาน",
|
||||
"stale": "รอตรวจ"
|
||||
},
|
||||
"labels": {
|
||||
"aliases": "{count} คำถามทางเลือก"
|
||||
@@ -258,7 +260,17 @@
|
||||
"msg": {
|
||||
"fillAll": "กรุณากรอกหัวข้อ คำถาม และตัวแทนเป้าหมาย",
|
||||
"answerRequired": "ต้องกรอกคำตอบมาตรฐานเมื่อเปิด FAQ cache",
|
||||
"saved": "บันทึกสำเร็จ"
|
||||
"saved": "บันทึกสำเร็จ",
|
||||
"reviewCompleted": "ตรวจสอบเสร็จแล้ว เปิด FAQ cache อีกครั้ง"
|
||||
},
|
||||
"stale": {
|
||||
"bannerTitle": "ฐานความรู้ที่เชื่อมโยงมีการเปลี่ยนแปลง — หยุด cache ชั่วคราว",
|
||||
"bannerBody": "เอกสารที่ทริกเกอร์: {doc} ({reason})",
|
||||
"bannerHint": "อัปเดตคำตอบมาตรฐานจาก KB ล่าสุด แล้วกดเสร็จสิ้นการตรวจสอบ ระหว่างรอตรวจ ผู้ใช้จะได้คำตอบใหม่ผ่าน Dify",
|
||||
"unknownDoc": "เอกสารไม่ทราบ",
|
||||
"reasonUpdated": "อัปเดตเอกสารแล้ว",
|
||||
"reasonDeleted": "ลบเอกสารแล้ว",
|
||||
"completeReview": "เสร็จสิ้นการตรวจสอบและเปิด cache"
|
||||
},
|
||||
"tabs": {
|
||||
"manual": "คำถามทั่วไป",
|
||||
|
||||
@@ -241,12 +241,14 @@
|
||||
"search": "搜索标题、问句或答案…",
|
||||
"allAgents": "全部应用",
|
||||
"cacheOnly": "仅显示已启用缓存",
|
||||
"staleOnly": "仅显示待复审",
|
||||
"resultCount": "共 {count} 条"
|
||||
},
|
||||
"badges": {
|
||||
"cacheOn": "已缓存",
|
||||
"cacheOff": "未缓存",
|
||||
"disabled": "已停用"
|
||||
"disabled": "已停用",
|
||||
"stale": "待复审"
|
||||
},
|
||||
"labels": {
|
||||
"aliases": "{count} 条同义问法"
|
||||
@@ -259,7 +261,17 @@
|
||||
"msg": {
|
||||
"fillAll": "请填写标题、问句和目标应用",
|
||||
"answerRequired": "启用 FAQ 缓存时必须填写标准答案",
|
||||
"saved": "保存成功"
|
||||
"saved": "保存成功",
|
||||
"reviewCompleted": "复审完成,FAQ 缓存已重新启用"
|
||||
},
|
||||
"stale": {
|
||||
"bannerTitle": "关联知识库已更新,缓存已暂停",
|
||||
"bannerBody": "触发文档:{doc}({reason})",
|
||||
"bannerHint": "请对照最新知识库更新标准答案,完成后点击「完成复审并启用缓存」。失效期间用户提问将走 Dify 获取新答案。",
|
||||
"unknownDoc": "未知文档",
|
||||
"reasonUpdated": "文档内容已更新",
|
||||
"reasonDeleted": "文档已删除",
|
||||
"completeReview": "完成复审并启用缓存"
|
||||
},
|
||||
"tabs": {
|
||||
"manual": "常用问题",
|
||||
|
||||
@@ -240,12 +240,14 @@
|
||||
"search": "搜尋標題、問句或答案…",
|
||||
"allAgents": "全部應用",
|
||||
"cacheOnly": "僅顯示已啟用快取",
|
||||
"staleOnly": "僅顯示待複審",
|
||||
"resultCount": "共 {count} 條"
|
||||
},
|
||||
"badges": {
|
||||
"cacheOn": "已快取",
|
||||
"cacheOff": "未快取",
|
||||
"disabled": "已停用"
|
||||
"disabled": "已停用",
|
||||
"stale": "待複審"
|
||||
},
|
||||
"labels": {
|
||||
"aliases": "{count} 條同義問法"
|
||||
@@ -258,7 +260,17 @@
|
||||
"msg": {
|
||||
"fillAll": "請填寫標題、問句和目標應用",
|
||||
"answerRequired": "啟用 FAQ 快取時必須填寫標準答案",
|
||||
"saved": "儲存成功"
|
||||
"saved": "儲存成功",
|
||||
"reviewCompleted": "複審完成,FAQ 快取已重新啟用"
|
||||
},
|
||||
"stale": {
|
||||
"bannerTitle": "關聯知識庫已更新,快取已暫停",
|
||||
"bannerBody": "觸發文件:{doc}({reason})",
|
||||
"bannerHint": "請對照最新知識庫更新標準答案,完成後點擊「完成複審並啟用快取」。失效期間使用者提問將走 Dify 取得新答案。",
|
||||
"unknownDoc": "未知文件",
|
||||
"reasonUpdated": "文件內容已更新",
|
||||
"reasonDeleted": "文件已刪除",
|
||||
"completeReview": "完成複審並啟用快取"
|
||||
},
|
||||
"tabs": {
|
||||
"manual": "常用問題",
|
||||
|
||||
Reference in new issue
Block a user