Merge branch 'dev' into hugo

This commit is contained in:
hugo committed 2026-06-23 11:22:39 +08:00
commit d5928b42f3
63 files changed
+5759 -1493

No files matched your search

+2 -2
View File
@@ -136,7 +136,7 @@ FAQ_HOT_MAX_QUERY_LEN=200 # 问句最大字符数,过长跳过
FAQ_HOT_MIN_QUERY_LEN=4 # 问句最短字符数,过短跳过
FAQ_HOT_MIN_ANSWER_LEN=8 # 答案最短字符数,过短跳过
FAQ_HOT_TTL_SECONDS=604800 # 候选/忽略黑名单有效期(秒),默认 7 天
FAQ_HOT_ANSWER_SIMILARITY=0.95 # 答案聚类相似度阈值(0~1),RAG 长文可适当调低至 0.80~0.85
FAQ_HOT_ANSWER_DOMINANCE=0.6 # 最大答案簇占比下限(0~1),分歧过大则跳过;可降至 0.4 便于测试
FAQ_HOT_ANSWER_SIMILARITY=0.95 # (聚类已关闭)答案聚类相似度阈值,恢复聚类时生效
FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇占比下限,恢复聚类时生效
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
+16 -4
View File
@@ -43,14 +43,23 @@ backend/app/
response_utils.py / errors.py / decorators.py # 统一返回、异常、权限装饰器
backend/migrations/ # Alembic 迁移文件
frontend/src/
features/ # 按业务域组织(admin / auth / chat)
composables/# Hooks(如 useChat.ts)
views/ components/ i18n.ts
main.ts · App.vue · i18n.ts · config.ts # Vite 入口(保留 src 根)
app/ # 应用基础设施:router/(routes/* · guards)、plugins/pinia
shared/ # 跨域共享(无业务语义)
# api/client · composables · components · layouts · utils · styles
features/ # 业务域垂直切分(新代码主要落在这里)
# auth · workspace · chat · admin · kb
# 域内:api/ · composables/ · views/ · stores/ · components/
# admin 子模块:modules/<name>/*Page.vue + use*Admin.ts
locales/ # i18n 四语言 JSON(zh-CN / zh-TW / en / th),按域拆分
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
docs/ # 权威文档(规范、上下文、流程、发布说明)
```
**约定**:新逻辑优先放入对应 `services/`(后端)或 `features/composables/`(前端),复用既有 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
**约定**:
- **后端**:新逻辑优先放入 `services/`,复用 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
- **前端**:Feature-Module + Composables + Pinia;新功能放入 `features/<domain>/`(`api/` · `composables/` · `views/` 等),跨域通用代码放 `shared/`;HTTP 统一 `@/shared/api/client`。**禁止**在已废弃的 `src/api/`、`src/views/`、`src/composables/` 等路径新增代码。完整规范见 **[docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md)**。
---
@@ -143,6 +152,7 @@ docker compose logs -f hxops-backend
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
- 📝 **注释两层标准(强制)**:新建或调整代码须满足 §5 文件层 + 函数层注释;AI 生成/重构代码同样适用,不得省略。
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
@@ -183,3 +193,5 @@ docker compose logs -f hxops-backend
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
+2
View File
@@ -91,6 +91,8 @@ def create_app(config_name='default'):
_apply_persisted_settings(app)
from app.services.schedule.scheduler_service import start_scheduler
start_scheduler(app)
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
FixedAssetsSnapshotService.start_worker(app)
from app.cli.faq_commands import init_app as init_faq_cli
init_faq_cli(app)
+203 -25
View File
@@ -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
@@ -18,6 +18,7 @@ from sqlalchemy.orm import joinedload
from datetime import datetime, timedelta
import csv
import io
import math
import re
import requests
import uuid
@@ -41,6 +42,29 @@ def _raise_user_integrity_conflict(exc: IntegrityError) -> None:
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS')
raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT')
def _assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None:
"""
校验用户唯一字段(邮箱、工号、手机号)不与其它账号冲突。
核心逻辑:对传入的非 None 字段查询 User 表;编辑时 exclude_user_id 排除当前用户。
@param exclude_user_id: 编辑场景传当前用户 id;创建场景传 None
@param fields: email / employee_id / phone_number 等待校验值
@raises ConflictError: 唯一字段已被占用
"""
checks = (
('email', 'USER.EMAIL_EXISTS', 'Email already exists'),
('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'),
('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'),
)
for field, code, message in checks:
value = fields.get(field)
if value is None:
continue
query = db.session.query(User.id).filter(getattr(User, field) == value)
if exclude_user_id is not None:
query = query.filter(User.id != exclude_user_id)
if query.first():
raise ConflictError(message, code=code, details={'field': field})
def _empty_to_none(value):
if value is None:
return None
@@ -564,13 +588,19 @@ def create_user():
email = _empty_to_none(data.get('email'))
if not _is_valid_email(email):
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
_assert_user_unique_fields(
None,
email=email,
employee_id=_empty_to_none(data.get('employee_id')),
phone_number=_empty_to_none(data.get('phone_number')),
)
user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number')))
user.set_password(data['password'])
if data.get('agent_ids'):
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
db.session.add(user)
try:
if data.get('agent_ids'):
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
user_api._sync_casdoor_create_user(
username=user.username,
password=data['password'],
@@ -597,7 +627,7 @@ def create_user():
def update_user(id):
"""
管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。
核心逻辑:应用本地字段 →(有 new_password 时)_sync_casdoor_update_user → commit。
核心逻辑:唯一字段预校验 → 应用本地字段与 agent_ids →(有 new_password 时)_sync_casdoor_update_user → commit。
Request JSON: email, department, role, status, password 等;password 为空表示不改密
Returns:
{ status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError
@@ -611,19 +641,25 @@ def update_user(id):
email = _empty_to_none(data.get('email'))
if email is not None and (not _is_valid_email(email)):
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
unique_updates = {
field: _empty_to_none(data[field])
for field in ('email', 'employee_id', 'phone_number')
if field in data
}
_assert_user_unique_fields(id, **unique_updates)
new_password = _empty_to_none(data.get('password'))
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
if k in data:
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
setattr(user, k, _empty_to_none(data[k]))
else:
setattr(user, k, data[k])
if new_password:
user.set_password(new_password)
if 'agent_ids' in data:
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
try:
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
if k in data:
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
setattr(user, k, _empty_to_none(data[k]))
else:
setattr(user, k, data[k])
if new_password:
user.set_password(new_password)
if 'agent_ids' in data:
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
if new_password:
user_api._sync_casdoor_update_user(user, new_password=new_password)
db.session.commit()
@@ -804,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)
@@ -859,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 {
@@ -880,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,
}
@@ -908,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 缓存时必须填写标准答案')
@@ -925,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()
@@ -1027,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),
@@ -1036,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):
@@ -1070,13 +1137,59 @@ def dismiss_faq_candidate():
return jsonify({'status': 'ok'})
USAGE_BY_USER_TOP_LIMIT = 50
@admin_bp.route('/reports/usage', methods=['GET'])
@require_admin
def usage_report():
"""
聊天使用分析:按应用汇总全部;按用户仅 TOP N(默认 50)并支持分页。
Query: user_page(默认 1)、user_page_size(默认 10,最大 50)
"""
total = db.session.query(ChatLog).count()
by_user = db.session.query(User.username, func.count(ChatLog.id)).join(ChatLog).group_by(User.username).all()
by_agent = db.session.query(Agent.name, func.count(ChatLog.id)).join(ChatLog).group_by(Agent.name).all()
return jsonify({'total': total, 'by_user': [{'username': u, 'count': c} for u, c in by_user], 'by_agent': [{'agent': a, 'count': c} for a, c in by_agent]})
by_agent = (
db.session.query(Agent.name, func.count(ChatLog.id))
.join(ChatLog)
.group_by(Agent.name)
.order_by(desc(func.count(ChatLog.id)), Agent.name)
.all()
)
try:
user_page = int(request.args.get('user_page', 1))
except (TypeError, ValueError):
user_page = 1
try:
user_page_size = int(request.args.get('user_page_size', 10))
except (TypeError, ValueError):
user_page_size = 10
user_page = max(1, user_page)
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
by_user_top = (
db.session.query(User.username, func.count(ChatLog.id))
.join(ChatLog)
.group_by(User.username)
.order_by(desc(func.count(ChatLog.id)), User.username)
.limit(USAGE_BY_USER_TOP_LIMIT)
.all()
)
user_total = len(by_user_top)
user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1
user_page = min(user_page, user_pages)
offset = (user_page - 1) * user_page_size
by_user_page = by_user_top[offset:offset + user_page_size]
return jsonify({
'total': total,
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
'user_total': user_total,
'user_page': user_page,
'user_page_size': user_page_size,
'user_pages': user_pages,
'user_top_limit': USAGE_BY_USER_TOP_LIMIT,
})
@admin_bp.route('/reports/feedback', methods=['GET'])
@require_admin
@@ -1151,9 +1264,74 @@ def count_general_feedbacks_report():
total = query.count()
return jsonify({'table': 'general_feedbacks', 'total': int(total)})
def _chat_logs_report_query():
"""
聊天日志报表查询:关联用户与应用,供管理后台数据报表展示。
核心逻辑:ChatLog JOIN User、Agent,按创建时间倒序。
"""
return (
db.session.query(
ChatLog,
User.username.label('username'),
Agent.name.label('agent_name'),
)
.join(User, User.id == ChatLog.user_id)
.join(Agent, Agent.id == ChatLog.agent_id)
)
def _serialize_chat_log_report_row(log: ChatLog, username: str | None, agent_name: str | None) -> dict:
"""
将 ChatLog 及关联字段序列化为报表行(隐藏 run_id / 原始 ID 类外键列)。
保留 id 供前端批量删除使用,默认不在表格列中展示。
"""
created_at = log.created_at.isoformat() if log.created_at else None
return {
'id': log.id,
'agent_name': agent_name or '',
'username': username or '',
'created_at': created_at,
'query': log.query,
'answer': log.answer,
'session_id': log.session_id,
'tokens_used': log.tokens_used,
'message_type': log.message_type,
}
def _apply_chat_logs_report_filters(query):
"""
对聊天日志报表查询应用列筛选(支持展示列名与 ChatLog 字段名)。
"""
reserved = {'limit', 'offset', 'page', 'page_size'}
for key, value in request.args.items():
if key in reserved or not value:
continue
if key == 'agent_name':
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
elif key == 'username':
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
elif hasattr(ChatLog, key):
col = getattr(ChatLog, key)
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
return query
def _list_chat_logs_report():
"""管理后台聊天日志报表数据列表(最多 100 条,支持列筛选)。"""
query = _apply_chat_logs_report_filters(_chat_logs_report_query())
query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
items = query.limit(100).all()
rows = [_serialize_chat_log_report_row(log, username, agent_name) for log, username, agent_name in items]
return jsonify(rows)
@admin_bp.route('/database/<table>', methods=['GET'])
@require_admin
def get_table_data(table):
if table == 'chat_logs':
return _list_chat_logs_report()
model_map = {'users': User, 'agents': Agent, 'chat_logs': ChatLog, 'feedbacks': Feedback, 'permission_requests': PermissionRequest, 'departments': Department, 'quick_questions': QuickQuestion, 'user_homepage_configs': UserHomepageConfig, 'user_favorite_agents': UserFavoriteAgent, 'user_default_agents': UserDefaultAgent}
model = model_map.get(table)
if not model:
+1
View File
@@ -1031,6 +1031,7 @@ def get_chat_query_preview(chat_log_id: int):
page_size=page_size,
agent=g.current_agent,
total_count=total_count,
user_context=Text2SQLService._normalize_user_context(g.current_user),
)
if columns == ["Error"]:
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
+69 -1
View File
@@ -13,6 +13,74 @@ internal_jobs_bp = Blueprint('internal_jobs', __name__)
def run_internal_job(name: str):
key = name.strip().lower()
data = request.get_json(silent=True) or {}
if key in {'fixed-assets-snapshot', 'fixed_assets_snapshot', 'fixedassets'}:
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
summary = FixedAssetsSnapshotService.sync_once(reason='internal_api', attempt=1)
row_count = int(summary.get('row_count') or 0)
return jsonify({
'summary': {
'total_count': row_count,
'success_count': row_count,
'failed_count': 0,
'skipped_count': 0,
},
'details': [summary],
'errors': [],
'step_logs': [
{
'step': 'fixed_assets_snapshot_sync',
'status': 'success',
'detail': {
'version': summary.get('current_version'),
'row_count': row_count,
},
}
],
})
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()
schedule_task_id = data.get('schedule_task_id')
task = None
@@ -53,4 +121,4 @@ def run_internal_job(name: str):
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
run.step_logs = step_logs if step_logs else None
db.session.commit()
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
+5 -2
View File
@@ -334,11 +334,14 @@ def post_schedule():
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
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.platform_api_path = f'/{task.id}'
if data_source_type == 'faq_hot_aggregate':
task.platform_api_path = 'faq-aggregate-hot'
else:
task.platform_api_path = f'/{task.id}'
db.session.commit()
db.session.refresh(task)
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)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
+25
View File
@@ -257,6 +257,29 @@ class Config:
SMTP_FROM = os.getenv('SMTP_FROM', '')
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
)
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
)
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
str(_ROOT_DIR / 'docs'),
)
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
# MinIO 配置
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
@@ -283,6 +306,8 @@ class TestingConfig(Config):
WTF_CSRF_ENABLED = False
SQLALCHEMY_ENGINE_OPTIONS = {}
SCHEDULE_WORKER_ENABLED = False
FIXED_ASSETS_SYNC_ENABLED = False
FIXED_ASSETS_EXPORT_TO_DOCS = False
config = {
+4
View File
@@ -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)
+81 -2
View File
@@ -8,6 +8,7 @@ It is responsible for:
1) Forwarding chat requests from this system to Dify in streaming mode.
2) Relaying Dify SSE events to the frontend.
3) Aggregating answer text and metadata (retriever resources / attribution).
Chatflow 模式下来源在 knowledge-retrieval 的 node_finished.outputs.result。
4) Enriching retriever resources with original source-file download URLs via
the integration API mapping (dataset_id + remote_document_id).
5) Persisting chat logs to the local database.
@@ -623,7 +624,9 @@ class DifyService:
app_obj = current_app._get_current_object() if current_app else None
persist_data = json.loads(json.dumps(data, ensure_ascii=False, default=str))
resources_snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
# 优先使用已 enrich 并挂到 event 上的 retriever_resources(与 SSE 下发一致)
resources_for_persist = data.get('retriever_resources') or retriever_resources
resources_snapshot = json.loads(json.dumps(resources_for_persist, ensure_ascii=False, default=str))
attribution_snapshot = list(attribution_parts)
answer_snapshot = build_final_answer_text(persist_data, event_name)
latency_snapshot = int((time.time() - start_time) * 1000)
@@ -742,7 +745,11 @@ class DifyService:
data.get('conversation_id') or normalized_conversation_id,
)
if event == 'message':
if event == 'node_finished':
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
elif event == 'message':
message_count += 1
if data.get('answer'):
has_sent_answer = True
@@ -770,6 +777,7 @@ class DifyService:
data['replace_answer'] = True
if event in ('message_end', 'workflow_finished'):
DifyService._attach_retriever_resources_to_event(data, retriever_resources)
persist_stream_chat(data, event)
if chat_perf_enabled():
perf_summary = perf.log_summary(current_app.logger if current_app else None)
@@ -1116,6 +1124,77 @@ class DifyService:
DifyService._merge_attribution_parts(attribution_parts, event_data.get('citation'))
DifyService._merge_attribution_parts(attribution_parts, metadata.get('citation'))
@staticmethod
def _normalize_knowledge_retrieval_result(item: Any) -> dict | None:
"""
将 Chatflow 知识检索节点的单条 result 规范化为 retriever_resource 结构。
核心逻辑:合并 metadata 中的 dataset/document/segment 字段到顶层,供前后端统一解析。
"""
if not isinstance(item, dict):
return None
metadata = item.get('metadata') if isinstance(item.get('metadata'), dict) else {}
document_name = (
item.get('document_name')
or metadata.get('document_name')
or item.get('title')
or metadata.get('title')
)
resource = {
**item,
'document_name': document_name,
'content': item.get('content') or metadata.get('content') or '',
'metadata': dict(metadata),
}
for key in ('dataset_id', 'dataset_name', 'document_id', 'segment_id', 'score'):
value = metadata.get(key) if metadata.get(key) not in (None, '') else item.get(key)
if value not in (None, '') and resource.get(key) in (None, ''):
resource[key] = value
return resource
@staticmethod
def _collect_knowledge_retrieval_from_node(retriever_resources: List[Any], event_data: dict):
"""
从 knowledge-retrieval 节点的 node_finished 事件提取检索来源。
核心逻辑:读取 data.outputs.result 列表,规范化后合并进 retriever_resources accumulator。
"""
if event_data.get('event') != 'node_finished':
return
node = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
if node.get('node_type') != 'knowledge-retrieval':
return
if node.get('status') not in (None, 'succeeded'):
return
outputs = node.get('outputs') if isinstance(node.get('outputs'), dict) else {}
results = outputs.get('result')
if not isinstance(results, list):
return
normalized: List[Any] = []
for item in results:
resource = DifyService._normalize_knowledge_retrieval_result(item)
if resource:
normalized.append(resource)
DifyService._merge_retriever_resources(retriever_resources, normalized)
@staticmethod
def _attach_retriever_resources_to_event(event_data: dict, retriever_resources: List[Any]):
"""
在 message_end / workflow_finished 下发前,把检索来源挂到 SSE 事件体。
核心逻辑:深拷贝 accumulator → enrich 源文件下载链接 → 写入 retriever_resources 与 metadata。
"""
if not retriever_resources:
return
snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
DifyService._enrich_retriever_resources_with_source_urls(snapshot)
event_data['retriever_resources'] = snapshot
metadata = event_data.get('metadata') if isinstance(event_data.get('metadata'), dict) else {}
metadata['retriever_resources'] = snapshot
event_data['metadata'] = metadata
@staticmethod
def _extract_dify_ids(resource: dict):
"""
+1
View File
@@ -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()
+224
View File
@@ -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,
)
@@ -0,0 +1,863 @@
"""
backend/app/services/fixed_assets_snapshot.py
用途:提供固定资产快照同步、本地结构化落地、Excel 导出与本地查询能力。
依赖:Flask current_app、openpyxl、sqlite3、Text2SQLService(延迟导入)、ERP Oracle。
逻辑关系:该服务负责将 ERP 固资实时查询能力沉淀为本地快照,供 text2sql 在固资场景下优先查询。
"""
from __future__ import annotations
import json
import os
import re
import shutil
import sqlite3
import threading
import time
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from zoneinfo import ZoneInfo
from flask import current_app, has_app_context
from openpyxl import Workbook
from app.path_utils import backend_dir
_worker_started = False
_worker_lock = threading.Lock()
_sync_lock = threading.Lock()
class FixedAssetsSnapshotService:
"""固定资产快照同步与本地查询服务。"""
SNAPSHOT_SQL_MARKER = "SNAPSHOT://FIXED_ASSETS"
SNAPSHOT_KIND = "fixed_assets_snapshot_preview"
VISIBLE_COLUMNS = (
"资产编号",
"资产名称",
"规格型号",
"保管人姓名",
"保管部门名称",
"存放位置名称",
"资产状态",
"预留残值",
"供应厂商",
"资产性质",
"本币单价",
"数量",
"计量单位",
"取得日期",
"入账日期",
)
NATURE_MAP = {
"1": "有形资产",
"2": "无形资产",
"3": "土地",
"4": "递耗资产",
"5": "费用",
}
STATUS_MAP = {
"0": "取得",
"1": "资本化",
"2": "折旧中",
"3": "外送",
"4": "折毕",
"5": "出售",
"6": "销账",
"7": "折旧再提",
"8": "改良",
"9": "重估",
"X": "被资本",
"Z": "停用",
}
STOPWORDS_PATTERN = re.compile(
r"(固定资产|固资|资产编号|财产编号|资产编码|编号|资产名称|设备名称|资产|设备|请问|帮我|看下|查下|查询|统计|核对|看看|我想知道|有多少台?|有多少|多少台?|多少|明细|列表|数据|结果|并且|以及|还有|和|按|根据|生成图表|生成excel|生成表单|导出excel|导出表单|导出)",
re.IGNORECASE,
)
@classmethod
def _storage_root(cls) -> Path:
path_value = current_app.config.get("FIXED_ASSETS_STORAGE_ROOT")
return Path(str(path_value)).resolve()
@classmethod
def _docs_export_root(cls) -> Path:
path_value = current_app.config.get("FIXED_ASSETS_DOCS_EXPORT_ROOT")
return Path(str(path_value)).resolve()
@classmethod
def _snapshots_dir(cls) -> Path:
return cls._storage_root() / "snapshots"
@classmethod
def _latest_dir(cls) -> Path:
return cls._storage_root() / "latest"
@classmethod
def _manifest_path(cls) -> Path:
return cls._storage_root() / "manifest.json"
@classmethod
def _ensure_storage_dirs(cls) -> None:
for path in (cls._storage_root(), cls._snapshots_dir(), cls._latest_dir()):
path.mkdir(parents=True, exist_ok=True)
@classmethod
def _latest_db_path(cls) -> Path:
return cls._latest_dir() / "FixedAssets_latest.db"
@classmethod
def _latest_xlsx_path(cls) -> Path:
return cls._latest_dir() / "FixedAssets_latest.xlsx"
@staticmethod
def _stringify(value: Any) -> str:
if value is None:
return ""
return str(value).strip()
@classmethod
def _normalize_search_text(cls, text: str) -> str:
cleaned = str(text or "").upper()
cleaned = re.sub(r"[\s\-_|,::;;,。()()/\\]+", "", cleaned)
return cleaned
@classmethod
def _build_remark(cls, row: dict[str, str]) -> str:
parts = [
f"资产编号:{row.get('资产编号', '')}",
f"资产名称:{row.get('资产名称', '')}",
f"规格型号:{row.get('规格型号', '')}",
f"保管人姓名:{row.get('保管人姓名', '')}",
f"保管部门名称:{row.get('保管部门名称', '')}",
f"存放位置名称:{row.get('存放位置名称', '')}",
f"资产状态:{row.get('资产状态', '')}",
f"供应厂商:{row.get('供应厂商', '')}",
f"资产性质:{row.get('资产性质', '')}",
]
return " | ".join(parts)
@classmethod
def _snapshot_identity_key(cls, row: dict[str, str], fallback_index: int) -> str:
"""生成快照去重键,优先使用资产编号。"""
asset_no = cls._stringify(row.get("资产编号"))
if asset_no:
return asset_no.upper()
return f"__ROW_{fallback_index}"
@classmethod
def _snapshot_row_score(cls, row: dict[str, str]) -> tuple[int, int]:
"""为重复资产选择信息更完整的一条记录。"""
preferred_fields = (
"资产名称",
"规格型号",
"保管人姓名",
"保管部门名称",
"存放位置名称",
"资产状态",
"供应厂商",
"资产性质",
"本币单价",
"数量",
"计量单位",
"取得日期",
"入账日期",
)
filled_count = sum(1 for key in preferred_fields if cls._stringify(row.get(key)))
text_length = sum(len(cls._stringify(row.get(key))) for key in preferred_fields)
return filled_count, text_length
@classmethod
def _dedupe_snapshot_rows(cls, rows: list[dict[str, str]]) -> list[dict[str, str]]:
"""按资产编号对快照结果去重,避免联表重复导致同一资产多次入库。"""
deduped: dict[str, dict[str, str]] = {}
for index, row in enumerate(rows):
dedupe_key = cls._snapshot_identity_key(row, index)
existing = deduped.get(dedupe_key)
if existing is None:
deduped[dedupe_key] = row
continue
if cls._snapshot_row_score(row) > cls._snapshot_row_score(existing):
deduped[dedupe_key] = row
return list(deduped.values())
@classmethod
def _snapshot_sql(cls) -> str:
return """
SELECT DISTINCT
faj.faj02 AS "资产编号",
faj.faj06 AS "资产名称",
faj.faj061 AS "资产名称2",
faj.faj08 AS "规格型号",
gen.gen01 AS "保管人工号",
gen.gen02 AS "保管人姓名",
gem.gem01 AS "保管部门编号",
gem.gem02 AS "保管部门名称",
faf.faf02 AS "存放位置名称",
faj.faj43 AS "资产状态代码",
faj.faj31 AS "预留残值",
pmc.pmc03 AS "供应厂商",
faj.faj09 AS "资产性质代码",
faj.faj13 AS "本币单价",
faj.faj17 AS "数量",
faj.faj18 AS "计量单位",
TO_CHAR(faj.faj25, 'YYYY-MM-DD HH24:MI:SS') AS "取得日期",
TO_CHAR(faj.faj26, 'YYYY-MM-DD HH24:MI:SS') AS "入账日期",
TRIM(NVL(faj.faj22, '')) AS "营运中心代码",
TRIM(NVL(faj.site, '')) AS "站点代码"
FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj
LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen
ON gen.gen01 = faj.faj19
AND gen.site = faj.site
LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem
ON gem.gem01 = faj.faj20
AND gem.site = faj.site
LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
ON faf.faf01 = faj.faj21
AND faf.site = faj.site
LEFT JOIN ERP_VIEW_USER.ERP_PMC_FILE_V pmc
ON pmc.pmc01 = faj.faj10
AND pmc.site = faj.site
WHERE UPPER(TRIM(NVL(faj.faj22, ''))) IN ('HXJM', 'HTT', 'HTE')
ORDER BY faj.faj02
""".strip()
@classmethod
def _oracle_credentials(cls) -> tuple[str, str, str]:
username = str(current_app.config.get("FIXED_ASSETS_ERP_USERNAME") or "EXT_VIEW_USER").strip()
password = str(current_app.config.get("FIXED_ASSETS_ERP_PASSWORD") or "extviewuser").strip()
dsn = str(current_app.config.get("FIXED_ASSETS_ERP_DSN") or os.getenv("ERP_DB_DSN") or "192.168.8.24:1521/topprod").strip()
return username, password, dsn
@classmethod
def _fetch_snapshot_rows(cls, timeout_seconds: int) -> list[dict[str, str]]:
"""从 ERP Oracle 拉取固定资产全量快照。"""
import oracledb
from app.services.text2sql import Text2SQLService
username, password, dsn = cls._oracle_credentials()
Text2SQLService._init_oracle_client(oracledb)
connection = None
cursor = None
try:
connection = oracledb.connect(user=username, password=password, dsn=dsn)
connection.call_timeout = max(1, int(timeout_seconds)) * 1000
cursor = connection.cursor()
cursor.execute(cls._snapshot_sql())
columns = [str(col[0] or "").strip() for col in cursor.description]
rows = cursor.fetchall()
normalized_rows: list[dict[str, str]] = []
for raw_row in rows:
item = {
columns[idx]: cls._stringify(value)
for idx, value in enumerate(raw_row)
}
item["资产状态"] = cls.STATUS_MAP.get(item.get("资产状态代码", "").upper(), item.get("资产状态代码", ""))
item["资产性质"] = cls.NATURE_MAP.get(item.get("资产性质代码", ""), item.get("资产性质代码", ""))
item["备注"] = cls._build_remark(item)
item["备注标准化"] = cls._normalize_search_text(item["备注"])
normalized_rows.append(item)
return cls._dedupe_snapshot_rows(normalized_rows)
finally:
if cursor is not None:
try:
cursor.close()
except Exception:
pass
if connection is not None:
try:
connection.close()
except Exception:
pass
@classmethod
def _snapshot_db_schema_sql(cls) -> list[str]:
return [
"""
CREATE TABLE IF NOT EXISTS fixed_assets (
asset_no TEXT,
asset_name TEXT,
asset_name2 TEXT,
specification TEXT,
custodian_id TEXT,
custodian_name TEXT,
department_code TEXT,
department_name TEXT,
location_name TEXT,
asset_status TEXT,
asset_status_code TEXT,
residual_value TEXT,
vendor_name TEXT,
asset_nature TEXT,
asset_nature_code TEXT,
unit_price TEXT,
quantity TEXT,
unit TEXT,
acquisition_date TEXT,
accounting_date TEXT,
operating_center_code TEXT,
site_code TEXT,
remark TEXT,
remark_normalized TEXT,
snapshot_version TEXT,
snapshot_date TEXT
)
""".strip(),
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_no ON fixed_assets(asset_no)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_name ON fixed_assets(asset_name)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_name2 ON fixed_assets(asset_name2)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_spec ON fixed_assets(specification)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_custodian ON fixed_assets(custodian_name)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_department ON fixed_assets(department_name)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_location ON fixed_assets(location_name)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_status ON fixed_assets(asset_status)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_vendor ON fixed_assets(vendor_name)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_nature ON fixed_assets(asset_nature)",
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_remark_norm ON fixed_assets(remark_normalized)",
]
@classmethod
def _write_snapshot_db(cls, db_path: Path, rows: list[dict[str, str]], version: str, snapshot_date: str) -> None:
"""将快照数据写入 SQLite。"""
if db_path.exists():
db_path.unlink()
conn = sqlite3.connect(db_path)
try:
cursor = conn.cursor()
for statement in cls._snapshot_db_schema_sql():
cursor.execute(statement)
insert_sql = """
INSERT INTO fixed_assets (
asset_no, asset_name, asset_name2, specification, custodian_id, custodian_name,
department_code, department_name, location_name, asset_status, asset_status_code,
residual_value, vendor_name, asset_nature, asset_nature_code, unit_price, quantity,
unit, acquisition_date, accounting_date, operating_center_code, site_code, remark,
remark_normalized, snapshot_version, snapshot_date
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""".strip()
payload = []
for item in rows:
payload.append(
(
item.get("资产编号", ""),
item.get("资产名称", ""),
item.get("资产名称2", ""),
item.get("规格型号", ""),
item.get("保管人工号", ""),
item.get("保管人姓名", ""),
item.get("保管部门编号", ""),
item.get("保管部门名称", ""),
item.get("存放位置名称", ""),
item.get("资产状态", ""),
item.get("资产状态代码", ""),
item.get("预留残值", ""),
item.get("供应厂商", ""),
item.get("资产性质", ""),
item.get("资产性质代码", ""),
item.get("本币单价", ""),
item.get("数量", ""),
item.get("计量单位", ""),
item.get("取得日期", ""),
item.get("入账日期", ""),
item.get("营运中心代码", ""),
item.get("站点代码", ""),
item.get("备注", ""),
item.get("备注标准化", ""),
version,
snapshot_date,
)
)
cursor.executemany(insert_sql, payload)
conn.commit()
finally:
conn.close()
@classmethod
def _export_snapshot_excel(cls, excel_path: Path, rows: list[dict[str, str]]) -> None:
"""导出快照 Excel 文件。"""
workbook = Workbook()
sheet = workbook.active
sheet.title = "FixedAssets"
header = list(cls.VISIBLE_COLUMNS) + ["备注"]
sheet.append(header)
for item in rows:
sheet.append([
item.get("资产编号", ""),
item.get("资产名称", ""),
item.get("规格型号", ""),
item.get("保管人姓名", ""),
item.get("保管部门名称", ""),
item.get("存放位置名称", ""),
item.get("资产状态", ""),
item.get("预留残值", ""),
item.get("供应厂商", ""),
item.get("资产性质", ""),
item.get("本币单价", ""),
item.get("数量", ""),
item.get("计量单位", ""),
item.get("取得日期", ""),
item.get("入账日期", ""),
item.get("备注", ""),
])
workbook.save(excel_path)
@classmethod
def _write_manifest(cls, payload: dict[str, Any]) -> None:
cls._ensure_storage_dirs()
cls._manifest_path().write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
@classmethod
def _load_manifest(cls) -> dict[str, Any]:
path = cls._manifest_path()
if not path.exists():
return {}
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {}
@classmethod
def _promote_snapshot(cls, version: str, db_path: Path, excel_path: Path) -> dict[str, str]:
cls._ensure_storage_dirs()
latest_db = cls._latest_db_path()
latest_xlsx = cls._latest_xlsx_path()
shutil.copy2(db_path, latest_db)
shutil.copy2(excel_path, latest_xlsx)
docs_exports: dict[str, str] = {}
if current_app.config.get("FIXED_ASSETS_EXPORT_TO_DOCS", True):
docs_root = cls._docs_export_root()
docs_root.mkdir(parents=True, exist_ok=True)
docs_latest = docs_root / "FixedAssets_latest.xlsx"
docs_versioned = docs_root / f"FixedAssets_{version}.xlsx"
shutil.copy2(excel_path, docs_latest)
shutil.copy2(excel_path, docs_versioned)
docs_exports = {
"docs_latest_xlsx": str(docs_latest),
"docs_versioned_xlsx": str(docs_versioned),
}
return {
"latest_db": str(latest_db),
"latest_xlsx": str(latest_xlsx),
**docs_exports,
}
@classmethod
def _cleanup_temp_snapshot_files(cls, directory: Path) -> None:
"""清理 Excel 打开时遗留的临时锁文件。"""
if not directory.exists():
return
for temp_file in directory.glob("~$FixedAssets*.xlsx"):
try:
temp_file.unlink()
except OSError as exc:
cls._log("warning", f"Failed to remove temp snapshot file {temp_file}: {exc}")
@classmethod
def _cleanup_history_snapshots(cls, keep_count: int | None = None) -> None:
"""仅保留最新 N 份历史快照,额外旧文件自动清理。"""
cls._ensure_storage_dirs()
snapshots_dir = cls._snapshots_dir()
cls._cleanup_temp_snapshot_files(snapshots_dir)
safe_keep_count = max(1, int(keep_count or current_app.config.get("FIXED_ASSETS_HISTORY_KEEP_COUNT", 3) or 3))
version_files: dict[str, list[Path]] = {}
for pattern in ("FixedAssets_*.db", "FixedAssets_*.xlsx"):
for file_path in snapshots_dir.glob(pattern):
if file_path.name.startswith("~$"):
continue
version_key = file_path.stem
version_files.setdefault(version_key, []).append(file_path)
version_keys = sorted(version_files.keys(), reverse=True)
obsolete_keys = version_keys[safe_keep_count:]
for version_key in obsolete_keys:
for file_path in version_files.get(version_key, []):
try:
file_path.unlink()
except OSError as exc:
cls._log("warning", f"Failed to remove obsolete snapshot file {file_path}: {exc}")
@classmethod
def is_snapshot_available(cls) -> bool:
return cls._latest_db_path().exists()
@classmethod
def sync_once(cls, *, reason: str = "manual", attempt: int = 1) -> dict[str, Any]:
"""执行一次固资快照同步。"""
with _sync_lock:
cls._ensure_storage_dirs()
timeout_seconds = int(current_app.config.get("FIXED_ASSETS_SYNC_TIMEOUT_SECONDS", 600) or 600)
started_at = datetime.utcnow()
version = started_at.strftime("%Y%m%d_%H%M%S")
snapshot_date = started_at.strftime("%Y-%m-%d")
version_db = cls._snapshots_dir() / f"FixedAssets_{version}.db"
version_xlsx = cls._snapshots_dir() / f"FixedAssets_{version}.xlsx"
try:
rows = cls._fetch_snapshot_rows(timeout_seconds)
cls._write_snapshot_db(version_db, rows, version, snapshot_date)
cls._export_snapshot_excel(version_xlsx, rows)
promoted_paths = cls._promote_snapshot(version, version_db, version_xlsx)
cls._cleanup_history_snapshots()
manifest = {
"status": "success",
"last_reason": reason,
"last_attempt": attempt,
"last_started_at": started_at.isoformat(),
"last_finished_at": datetime.utcnow().isoformat(),
"last_success_at": datetime.utcnow().isoformat(),
"current_version": version,
"snapshot_date": snapshot_date,
"row_count": len(rows),
"files": {
"versioned_db": str(version_db),
"versioned_xlsx": str(version_xlsx),
**promoted_paths,
},
}
cls._write_manifest(manifest)
cls._log("info", f"Fixed assets snapshot synced successfully version={version} row_count={len(rows)}")
return manifest
except Exception as exc:
manifest = cls._load_manifest()
manifest.update({
"status": "failed",
"last_reason": reason,
"last_attempt": attempt,
"last_started_at": started_at.isoformat(),
"last_finished_at": datetime.utcnow().isoformat(),
"last_error": str(exc),
})
cls._write_manifest(manifest)
cls._log("warning", f"Fixed assets snapshot sync failed attempt={attempt}: {exc}")
raise
@classmethod
def sync_with_retry(cls, *, reason: str = "schedule") -> dict[str, Any]:
"""按配置执行同步与重试。"""
max_attempts = max(1, int(current_app.config.get("FIXED_ASSETS_SYNC_MAX_ATTEMPTS", 4) or 4))
retry_interval_seconds = max(
60,
int(current_app.config.get("FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES", 30) or 30) * 60,
)
last_error: Exception | None = None
for attempt in range(1, max_attempts + 1):
try:
return cls.sync_once(reason=reason, attempt=attempt)
except Exception as exc: # pragma: no cover - runtime branch
last_error = exc
if attempt >= max_attempts:
break
cls._log(
"warning",
f"Fixed assets snapshot will retry after {retry_interval_seconds}s, attempt={attempt}, error={exc}",
)
time.sleep(retry_interval_seconds)
if last_error is not None:
raise last_error
raise RuntimeError("Fixed assets snapshot sync failed without explicit error")
@classmethod
def _tokenize_query(cls, query: str) -> list[str]:
cleaned = cls.STOPWORDS_PATTERN.sub(" ", str(query or ""))
tokens = re.findall(r"[A-Za-z0-9\u4e00-\u9fff()()_-]{2,40}", cleaned)
normalized_tokens: list[str] = []
for token in tokens:
normalized = cls._normalize_search_text(token)
if normalized and normalized not in normalized_tokens:
normalized_tokens.append(normalized)
return normalized_tokens[:5]
@classmethod
def _build_where_clause(cls, query: str, user_context: dict[str, Any] | None = None) -> tuple[str, list[str]]:
"""根据用户问句生成本地快照过滤条件。"""
from app.services.text2sql import Text2SQLService
clauses: list[str] = []
params: list[str] = []
advanced_conds = Text2SQLService._extract_advanced_asset_conditions(query)
asset_code = advanced_conds.get("asset_code") or Text2SQLService._extract_asset_code(query)
asset_name = advanced_conds.get("asset_name") or Text2SQLService._extract_asset_name_keyword(query)
asset_nature_code = Text2SQLService._extract_asset_nature_code(query)
explicit_scope = Text2SQLService._extract_asset_scope(query)
has_explicit_location = bool(advanced_conds.get("location"))
has_explicit_vendor = bool(advanced_conds.get("vendor"))
has_explicit_spec = bool(advanced_conds.get("spec"))
has_explicit_status = bool(advanced_conds.get("status"))
has_explicit_person = bool(explicit_scope.get("person"))
has_explicit_department = bool(explicit_scope.get("department"))
should_use_generic_keyword_search = bool(
asset_name
and not asset_code
and not has_explicit_location
and not has_explicit_vendor
and not has_explicit_spec
and not has_explicit_status
and not has_explicit_person
and not has_explicit_department
and not asset_nature_code
)
if asset_code:
clauses.append("UPPER(COALESCE(asset_no, '')) LIKE ?")
params.append(f"%{asset_code.upper()}%")
if asset_name and not should_use_generic_keyword_search:
clauses.append("(UPPER(COALESCE(asset_name, '')) LIKE ? OR UPPER(COALESCE(asset_name2, '')) LIKE ?)")
params.extend([f"%{asset_name.upper()}%", f"%{asset_name.upper()}%"])
if "spec" in advanced_conds:
clauses.append("UPPER(COALESCE(specification, '')) LIKE ?")
params.append(f"%{advanced_conds['spec'].upper()}%")
if "status" in advanced_conds:
clauses.append("UPPER(COALESCE(asset_status, '')) LIKE ?")
params.append(f"%{advanced_conds['status'].upper()}%")
if "vendor" in advanced_conds:
clauses.append("UPPER(COALESCE(vendor_name, '')) LIKE ?")
params.append(f"%{advanced_conds['vendor'].upper()}%")
if "location" in advanced_conds:
clauses.append("UPPER(COALESCE(location_name, '')) LIKE ?")
params.append(f"%{advanced_conds['location'].upper()}%")
if asset_nature_code:
asset_nature = cls.NATURE_MAP.get(asset_nature_code, asset_nature_code)
clauses.append("UPPER(COALESCE(asset_nature, '')) = ?")
params.append(asset_nature.upper())
explicit_person = explicit_scope.get("person")
if explicit_person:
clauses.append("UPPER(COALESCE(custodian_name, '')) LIKE ?")
params.append(f"%{explicit_person.upper()}%")
explicit_department = explicit_scope.get("department")
if explicit_department:
clauses.append("UPPER(COALESCE(department_name, '')) LIKE ?")
params.append(f"%{explicit_department.upper()}%")
if should_use_generic_keyword_search:
normalized_keyword = cls._normalize_search_text(asset_name)
clauses.append(
"("
"UPPER(COALESCE(asset_name, '')) LIKE ? "
"OR UPPER(COALESCE(asset_name2, '')) LIKE ? "
"OR UPPER(COALESCE(specification, '')) LIKE ? "
"OR UPPER(COALESCE(location_name, '')) LIKE ? "
"OR UPPER(COALESCE(custodian_name, '')) LIKE ? "
"OR UPPER(COALESCE(department_name, '')) LIKE ? "
"OR UPPER(COALESCE(vendor_name, '')) LIKE ? "
"OR UPPER(COALESCE(remark_normalized, '')) LIKE ?"
")"
)
params.extend(
[
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{normalized_keyword}%",
]
)
normalized_user = user_context or {}
if Text2SQLService._is_self_asset_query(query):
self_clauses = []
for candidate in (normalized_user.get("employee_id"), normalized_user.get("username")):
value = cls._stringify(candidate)
if not value:
continue
self_clauses.append("UPPER(COALESCE(custodian_id, '')) = ?")
params.append(value.upper())
real_name = cls._stringify(normalized_user.get("real_name"))
if real_name:
self_clauses.append("UPPER(COALESCE(custodian_name, '')) = ?")
params.append(real_name.upper())
if self_clauses:
clauses.append("(" + " OR ".join(self_clauses) + ")")
if not clauses and not Text2SQLService._is_company_asset_detail_query(query):
tokens = cls._tokenize_query(query)
for token in tokens:
clauses.append("UPPER(COALESCE(remark_normalized, '')) LIKE ?")
params.append(f"%{token}%")
where_sql = " AND ".join(clauses) if clauses else "1=1"
return where_sql, params
@classmethod
def query_assets(
cls,
query: str,
*,
limit: int = 10,
offset: int = 0,
user_context: dict[str, Any] | None = None,
) -> tuple[list[str], list[tuple], int]:
"""查询最新固资快照。"""
if not cls.is_snapshot_available():
return ["Error"], [("固定资产快照尚未生成,请稍后重试。",)], 0
where_sql, params = cls._build_where_clause(query, user_context=user_context)
deduped_assets_cte = """
WITH deduped_assets AS (
SELECT *
FROM (
SELECT
fixed_assets.*,
ROW_NUMBER() OVER (
PARTITION BY CASE
WHEN TRIM(COALESCE(asset_no, '')) = '' THEN '__ROW_' || rowid
ELSE UPPER(TRIM(asset_no))
END
ORDER BY rowid
) AS dedupe_rn
FROM fixed_assets
)
WHERE dedupe_rn = 1
)
""".strip()
visible_select = """
asset_no AS "资产编号",
asset_name AS "资产名称",
specification AS "规格型号",
custodian_name AS "保管人姓名",
department_name AS "保管部门名称",
location_name AS "存放位置名称",
asset_status AS "资产状态",
residual_value AS "预留残值",
vendor_name AS "供应厂商",
asset_nature AS "资产性质",
unit_price AS "本币单价",
quantity AS "数量",
unit AS "计量单位",
acquisition_date AS "取得日期",
accounting_date AS "入账日期"
""".strip()
list_sql = f"""
{deduped_assets_cte}
SELECT {visible_select}
FROM deduped_assets
WHERE {where_sql}
ORDER BY asset_no
LIMIT ? OFFSET ?
""".strip()
count_sql = f"""
{deduped_assets_cte}
SELECT COUNT(*) FROM deduped_assets WHERE {where_sql}
""".strip()
conn = sqlite3.connect(cls._latest_db_path())
try:
cursor = conn.cursor()
cursor.execute(count_sql, params)
total_count = int(cursor.fetchone()[0] or 0)
cursor.execute(list_sql, [*params, max(1, int(limit)), max(0, int(offset))])
columns = [str(item[0] or "").strip() for item in cursor.description]
rows = [tuple(row) for row in cursor.fetchall()]
return columns, rows, total_count
finally:
conn.close()
@classmethod
def get_snapshot_preview_payload(
cls,
query: str,
columns: list[str],
rows: list[tuple],
total_count: int,
) -> dict[str, Any]:
return {
"kind": "text2sql_result_preview",
"previewable": total_count > len(rows or []),
"query": query,
"sql": cls.SNAPSHOT_SQL_MARKER,
"total_count": total_count,
"preview_row_count": len(rows or []),
"display_columns": list(columns or []),
"data_source": cls.SNAPSHOT_KIND,
}
@classmethod
def is_snapshot_sql(cls, sql: str) -> bool:
return str(sql or "").strip().startswith(cls.SNAPSHOT_SQL_MARKER)
@classmethod
def snapshot_sql_label(cls) -> str:
manifest = cls._load_manifest()
version = str(manifest.get("current_version") or "").strip()
if version:
return f"固定资产快照查询(版本 {version})"
return "固定资产快照查询"
@classmethod
def _should_run_bootstrap(cls) -> bool:
return bool(current_app.config.get("FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING", True)) and not cls.is_snapshot_available()
@classmethod
def _local_now(cls, timezone_name: str) -> datetime:
return datetime.now(ZoneInfo(timezone_name))
@classmethod
def _next_run_at(cls, now_local: datetime, hour: int, minute: int) -> datetime:
scheduled = now_local.replace(hour=hour, minute=minute, second=0, microsecond=0)
if now_local >= scheduled:
scheduled = scheduled + timedelta(days=1)
return scheduled
@classmethod
def _worker_loop(cls, app) -> None:
with app.app_context():
timezone_name = str(app.config.get("FIXED_ASSETS_SYNC_TIMEZONE") or "Asia/Shanghai").strip()
schedule_hour = int(app.config.get("FIXED_ASSETS_SYNC_HOUR", 3) or 3)
schedule_minute = int(app.config.get("FIXED_ASSETS_SYNC_MINUTE", 0) or 0)
poll_seconds = max(30, int(app.config.get("FIXED_ASSETS_SYNC_POLL_SECONDS", 60) or 60))
if cls._should_run_bootstrap():
try:
cls.sync_with_retry(reason="bootstrap")
except Exception as exc: # pragma: no cover - runtime branch
cls._log("warning", f"Bootstrap fixed assets snapshot failed: {exc}")
next_run = cls._next_run_at(cls._local_now(timezone_name), schedule_hour, schedule_minute)
while True: # pragma: no cover - runtime branch
now_local = cls._local_now(timezone_name)
if now_local >= next_run:
try:
cls.sync_with_retry(reason="schedule")
except Exception as exc:
cls._log("warning", f"Scheduled fixed assets snapshot failed: {exc}")
next_run = cls._next_run_at(cls._local_now(timezone_name), schedule_hour, schedule_minute)
time.sleep(poll_seconds)
@classmethod
def start_worker(cls, app) -> None:
"""启动固定资产快照后台同步线程。"""
global _worker_started
if not bool(app.config.get("FIXED_ASSETS_SYNC_ENABLED", True)):
app.logger.info("Fixed assets snapshot worker disabled by config")
return
with _worker_lock:
if _worker_started:
return
thread = threading.Thread(
target=cls._worker_loop,
args=(app,),
name="fixed-assets-snapshot-worker",
daemon=True,
)
thread.start()
_worker_started = True
app.logger.info("Fixed assets snapshot worker started")
@staticmethod
def _log(level: str, message: str) -> None:
if has_app_context():
getattr(current_app.logger, level, current_app.logger.info)(message)
+34 -52
View File
@@ -22,21 +22,19 @@ backend/app/services/hot_faq_aggregator.py
## 最佳答案选取规则(HOT_FAQ_ANSWER_RULES)
1. **答案聚类**:对组内每条 ChatLog 的 answer 做相似度聚类(SequenceMatcher ≥ FAQ_HOT_ANSWER_SIMILARITY,默认 0.95)。
2. **一致性门槛**:最大簇占比 ≥ FAQ_HOT_ANSWER_DOMINANCE(默认 0.6);否则视为答案分歧过大,整组跳过。
3. **在最大簇内选代表答案**,优先级:
1. ~~**答案聚类**~~(已暂时关闭):原按 FAQ_HOT_ANSWER_SIMILARITY 对 answer 聚类。
2. ~~**一致性门槛**~~(已暂时关闭):原要求最大簇占比 ≥ FAQ_HOT_ANSWER_DOMINANCE。
3. **在组内选代表答案**,优先级:
a. Feedback.score ≥ FAQ_HOT_GOOD_SCORE(默认 4)的记录中,取 created_at 最新;
b. 否则排除 Feedback.score ≤ FAQ_HOT_BAD_SCORE(默认 2)的记录,取 created_at 最新;
c. 否则取簇内 created_at 最新的 answer。
c. 否则取组内 created_at 最新的 answer。
4. **canonical_query**:取该组内出现次数最多的原始 query 文本(非归一化,便于人工阅读)。
"""
from __future__ import annotations
import re
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from difflib import SequenceMatcher
from typing import Any, Optional
from flask import current_app
@@ -73,8 +71,7 @@ HOT_FAQ_AGGREGATOR_DOC_SELECTION = (
)
HOT_FAQ_AGGREGATOR_DOC_ANSWER = (
'答案按相似度聚类,最大簇占比需≥dominance 阈值;'
'在最大簇内优先选好评最新,其次无差评最新,最后取最新记录。'
'答案聚类与一致性门槛已暂时关闭;在组内按反馈优先级选代表答案。'
)
@@ -161,8 +158,10 @@ class HotFaqAggregator:
'description': HOT_FAQ_AGGREGATOR_DOC_SELECTION,
},
'answer': {
# 答案聚类 / 一致性门槛已暂时关闭,以下配置保留供日后恢复
'answer_similarity': float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95)),
'answer_dominance': float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6)),
'answer_clustering_enabled': False,
'good_feedback_score': int(cls._cfg('FAQ_HOT_GOOD_SCORE', 4)),
'bad_feedback_score': int(cls._cfg('FAQ_HOT_BAD_SCORE', 2)),
'description': HOT_FAQ_AGGREGATOR_DOC_ANSWER,
@@ -332,17 +331,19 @@ class HotFaqAggregator:
rows: list[_LogRow],
) -> tuple[Optional[HotFaqCandidate], Optional[str]]:
"""从一组 ChatLog 构建热点候选;失败时返回 skip reason。"""
dominance_threshold = float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6))
clusters = cls._cluster_answers(rows)
if not clusters:
return None, 'empty_answer_clusters'
# [DISABLED] 答案聚类 + 一致性门槛(answer_divergence)已暂时关闭,直接在整组内选代表答案。
# dominance_threshold = float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6))
# similarity_threshold = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95))
# largest_rows = cls._largest_similarity_cluster(rows, similarity_threshold)
# dominance = len(largest_rows) / len(rows) if rows else 0.0
# if dominance < dominance_threshold:
# relaxed = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY_RELAXED', 0.70))
# ...
# if dominance < dominance_threshold:
# return None, f'answer_divergence:{dominance:.2f}'
largest = max(clusters, key=lambda c: len(c['rows']))
dominance = len(largest['rows']) / len(rows)
if dominance < dominance_threshold:
return None, f'answer_divergence:{dominance:.2f}'
rep = cls._pick_representative_answer(largest['rows'])
dominance = 1.0
rep = cls._pick_representative_answer(rows)
if not rep:
return None, 'no_representative_answer'
@@ -371,44 +372,25 @@ class HotFaqAggregator:
retriever_resources=rep.retriever_resources,
), None
@classmethod
def _cluster_answers(cls, rows: list[_LogRow]) -> list[dict[str, Any]]:
"""
将 answer 按相似度聚类(贪心:与簇代表相似度 ≥ 阈值则归入)。
@returns [{'representative': str, 'rows': [_LogRow, ...]}, ...]
"""
threshold = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95))
clusters: list[dict[str, Any]] = []
for row in rows:
answer = row.answer.strip()
if not answer:
continue
placed = False
for cluster in clusters:
rep = cluster['representative']
if cls._answer_similarity(rep, answer) >= threshold:
cluster['rows'].append(row)
placed = True
break
if not placed:
clusters.append({'representative': answer, 'rows': [row]})
return clusters
@staticmethod
def _answer_similarity(a: str, b: str) -> float:
"""计算两段答案文本相似度(0~1)。"""
left = re.sub(r'\s+', ' ', a.strip())
right = re.sub(r'\s+', ' ', b.strip())
if not left or not right:
return 0.0
return SequenceMatcher(None, left, right).ratio()
# [DISABLED] 答案聚类相关方法(恢复 FAQ_HOT_ANSWER_SIMILARITY / DOMINANCE 检查时可启用)
#
# @classmethod
# def _largest_similarity_cluster(cls, rows: list[_LogRow], threshold: float) -> list[_LogRow]:
# ...
#
# @classmethod
# def _cluster_answers(cls, rows: list[_LogRow], *, threshold: float | None = None) -> list[dict[str, Any]]:
# ...
#
# @staticmethod
# def _answer_similarity(a: str, b: str) -> float:
# ...
@classmethod
def _pick_representative_answer(cls, rows: list[_LogRow]) -> Optional[_LogRow]:
"""
在 dominant 簇内按反馈优先级选取最佳 ChatLog 行。
优先级:好评最新 > 无差评最新 > 簇内最新。
在组内按反馈优先级选取最佳 ChatLog 行。
优先级:好评最新 > 无差评最新 > 组内最新。
"""
good_score = int(cls._cfg('FAQ_HOT_GOOD_SCORE', 4))
bad_score = int(cls._cfg('FAQ_HOT_BAD_SCORE', 2))
@@ -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}
@@ -273,6 +273,9 @@ def list_registered_api_paths() -> list[dict[str, str]]:
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
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"):
return _run_generic_check_job
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
if not normalize_platform_api_path(task.platform_api_path):
raise ValueError("platform_api_path is required for platform_app")
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")
task.platform_api_path = "faq-aggregate-hot"
task.schedule_type = "platform_app"
if task.enabled and task.cron_expr:
+377 -34
View File
@@ -76,6 +76,23 @@ class Text2SQLService:
"GEM01": "部门编号",
"GEM02": "部门名称",
}
_ASSET_DISPLAY_COLUMN_ORDER = (
"资产编号",
"资产名称",
"规格型号",
"保管人姓名",
"保管部门名称",
"存放位置名称",
"资产状态",
"预留残值",
"供应厂商",
"资产性质",
"本币单价",
"数量",
"计量单位",
"取得日期",
"入账日期",
)
_ASSET_VALUE_MAPPINGS = {
"资产性质": {
"1": "有形资产",
@@ -460,6 +477,58 @@ class Text2SQLService:
def _is_asset_management_agent(cls, agent) -> bool:
return cls._agent_name(agent) in cls._ASSET_AGENT_NAMES
@classmethod
def _refine_asset_query(cls, query: str, agent=None) -> str:
"""使用固资查询提炼 Agent 清洗用户问句。
AI 触发时机:当用户在固资查询中夹带“生成图表、生成 Excel、生成表单”等
与数据筛选无关的诉求时,先提炼出纯查询文字,再交给现有固资规则和 Text2SQL 流程。
Args:
query: 用户原始问题,允许同时包含查询、统计、导出或展示诉求。
agent: 当前会话 Agent,仅固资管理 Agent 进入该提炼流程。
Returns:
str: 提炼后的查询文字;若不属于固资 Agent、模型调用失败或结果无效,则回退原问题。
"""
original_query = str(query or "").strip()
if not original_query:
return ""
if not cls._is_asset_management_agent(agent):
return original_query
system_prompt = """你是一位文字提炼专家。
# 角色
你是一位文字提炼专家
# 任务
负责把用户的查询数据需求进行提炼和总结,抓取关键数据查询文字,去掉和数据查询无关的内容,比如生成图表、生成Excel、生成表单等和数据查询无关的内容,只保留提炼查询数据的文字。
# 约束
- 只保留与固定资产数据查询直接相关的文字。
- 保留用户的筛选条件、模糊查询关键词、统计意图,例如“有多少”“多少台”“明细”“列表”。
- 删除生成图表、生成 Excel、生成表单、导出、汇报、分析结论、排版等与查询无关的内容。
- 用户在查询设备固资时可按:资产编号、资产名称、规格型号、资产性质、保管人、保管部门、存放位置、资产状态、供应厂商进行模糊查询。
- 像“线切割机”“线切割机有多少”“400吨冲床有多少台”这类表达属于有效查询意图,必须保留。
- 如果原问题已经是纯查询表达,直接原样输出。
- 不要补充不存在的筛选条件,不要解释,不要加引号,不要输出多段内容。
# 输出
只输出你提炼后的结果,无需其他言语。"""
user_prompt = f"用户原始问题:{original_query}"
try:
refined_query = cls._chat_completion(system_prompt, user_prompt, temperature=0)
except Exception as exc:
cls._log("warning", f"Asset query refine failed, fallback to original query: {exc}")
return original_query
refined_query = re.sub(r"\s+", " ", str(refined_query or "")).strip().strip("`'\"")
if len(refined_query) < 2:
return original_query
return refined_query
@classmethod
def _looks_like_asset_query(cls, query: str, sql: str = "") -> bool:
query_text = str(query or "")
@@ -494,6 +563,84 @@ class Text2SQLService:
text = re.sub(r"(?:的|下)?(?:有哪些|有多少|多少|名下|资产|固定资产|固资|列表|明细|电脑|设备|机|工装|模具|车辆).*$", "", text)
return text.strip(" ::,,。.??")
@classmethod
def _clean_asset_keyword_value(cls, value: str | None) -> str:
"""清洗固资名称/规格等自由输入关键词,尽量保留设备名原词。"""
text = cls._strip_asset_query_prefix(value)
text = re.sub(r"(?:有多少台?|有多少|多少台?|多少|有哪些|有什么|明细|列表|数据|结果).*$", "", text)
text = re.sub(r"^(?:请问|帮我|看下|查下|查询|统计|核对|看看|我想知道)\s*", "", text)
return text.strip(" ::,,。.??;;")
@classmethod
def _extract_explicit_asset_name(cls, query: str) -> str:
"""抽取用户显式声明的资产名称。"""
text = cls._strip_asset_query_prefix(query)
if not text:
return ""
patterns = [
r"(?:资产名称|设备名称|固定资产名称|固资名称)\s*(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40})",
r"^\s*([A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40})\s*(?:的)?\s*(?:规格型号|规格|型号)",
]
for pattern in patterns:
match = re.search(pattern, text)
if not match:
continue
candidate = cls._clean_asset_keyword_value(match.group(1))
if not candidate:
continue
if cls._looks_like_asset_code_token(candidate):
continue
if cls._ASSET_SUFFIX_DEPARTMENT_PATTERN.fullmatch(candidate):
continue
if cls._looks_like_person_name(candidate):
continue
return candidate
return ""
@classmethod
def _extract_asset_name_combo_keyword(cls, query: str) -> str:
"""在“资产名称/编号 + 规格型号”等组合问句中补抽资产名称。"""
text = cls._strip_asset_query_prefix(query)
if not text:
return ""
stripped = text
patterns_to_strip = [
r"(?:规格型号|规格|型号)(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
r"(?:资产类型|类型)(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
r"(?:资产状态|状态)(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
r"(?:存放位置|位置)(?:在|为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
r"(?:供应商|供应厂商|厂商)(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
r"(?:资产名称|设备名称|固定资产名称|固资名称)\s*(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
]
for pattern in patterns_to_strip:
stripped = re.sub(pattern, " ", stripped)
asset_code = cls._extract_asset_code(text)
if asset_code:
stripped = re.sub(re.escape(asset_code), " ", stripped, flags=re.IGNORECASE)
stripped = re.sub(
r"(?:固定资产|固资|资产编号|财产编号|资产编码|编号|资产名称|设备名称|资产|设备|请问|帮我|看下|查下|查询|统计|核对|看看|我想知道|有多少台?|有多少|多少台?|多少|明细|列表|数据|结果|并且|且|以及|还有|和|按|根据)",
" ",
stripped,
)
candidates = re.findall(r"[A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40}", stripped)
for candidate in sorted(candidates, key=len, reverse=True):
cleaned = cls._clean_asset_keyword_value(candidate)
if not cleaned:
continue
if cleaned in {"公司", "全部", "所有", "当前", "目前"}:
continue
if cls._looks_like_asset_code_token(cleaned):
continue
if cls._ASSET_SUFFIX_DEPARTMENT_PATTERN.fullmatch(cleaned):
continue
if cls._looks_like_person_name(cleaned):
continue
return cleaned
return ""
@classmethod
def _extract_advanced_asset_conditions(cls, query: str) -> dict[str, str]:
conds = {}
@@ -522,7 +669,20 @@ class Text2SQLService:
if m:
val = cls._clean_asset_scope_value(m.group(1))
if val: conds["vendor"] = val
explicit_asset_name = cls._extract_explicit_asset_name(query)
if explicit_asset_name:
conds["asset_name"] = explicit_asset_name
asset_code = cls._extract_asset_code(query)
if asset_code and conds:
conds["asset_code"] = asset_code
if conds and "asset_name" not in conds:
combo_asset_name = cls._extract_asset_name_combo_keyword(query)
if combo_asset_name:
conds["asset_name"] = combo_asset_name
return conds
@staticmethod
@@ -639,7 +799,7 @@ class Text2SQLService:
match = re.search(pattern, text)
if not match:
continue
keyword = cls._clean_asset_scope_value(match.group("keyword"))
keyword = cls._clean_asset_keyword_value(match.group("keyword"))
if not keyword:
continue
if keyword in {"公司", "全部", "所有", "当前", "目前"}:
@@ -653,7 +813,7 @@ class Text2SQLService:
return keyword
if re.fullmatch(r"^\s*[A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40}\s*$", text):
cleaned = cls._clean_asset_scope_value(text)
cleaned = cls._clean_asset_keyword_value(text)
if cleaned and cleaned not in {"公司", "全部", "所有", "当前", "目前", "你好", "在吗", "是谁", "是什么", "固定资产", "固资", "资产", "设备"}:
if not cls._looks_like_person_name(cleaned) and not cls._ASSET_SUFFIX_DEPARTMENT_PATTERN.fullmatch(cleaned):
return cleaned
@@ -957,6 +1117,17 @@ ORDER BY faj.faj02
nature_sql = f"\n AND {nature_condition}" if nature_condition else ""
where_clauses = []
if "asset_code" in conds:
literal = cls._escape_sql_literal(conds["asset_code"])
where_clauses.append(f"UPPER(NVL(faj.faj02, ' ')) LIKE '%' || UPPER('{literal}') || '%'")
if "asset_name" in conds:
literal = cls._escape_sql_literal(conds["asset_name"])
where_clauses.append(
"("
f"UPPER(NVL(faj.faj06, ' ')) LIKE '%' || UPPER('{literal}') || '%' "
f"OR UPPER(NVL(faj.faj061, ' ')) LIKE '%' || UPPER('{literal}') || '%'"
")"
)
if "spec" in conds:
literal = cls._escape_sql_literal(conds["spec"])
where_clauses.append(f"UPPER(NVL(faj.faj08, ' ')) LIKE '%' || UPPER('{literal}') || '%'")
@@ -1088,7 +1259,7 @@ ORDER BY faj.faj02
"- 固资相关联表必须同时补齐 `site` 条件,例如 `gen.site = faj.site`、`gem.site = faj.site`、`faf.site = faj.site`、`fab.site = faj.site`、`pmc.site = faj.site`,避免同编码跨营运中心造成重复记录。",
"- 固资数据只允许保留 `faj22`(存放营运中心)属于 `HXJM`、`HTT`、`HTE` 的记录;生成 SQL 时必须显式加上 `UPPER(TRIM(NVL(faj.faj22, ''))) IN ('HXJM', 'HTT', 'HTE')` 过滤。",
"- 查询固定资产明细列表时优先使用 `SELECT DISTINCT`;如果是统计资产数量,优先使用 `COUNT(DISTINCT faj.faj02)`。",
"- 当查询固定资产明细时,返回结果必须且只能包含以下列并使用严格对应的中文别名:faj.faj02 AS \"资产编号\"、faj.faj06 AS \"资产名称\"、faj.faj08 AS \"规格型号\"、faj.faj09 AS \"资产性质\"、faj.faj13 AS \"本币单价\"、faj.faj17 AS \"数量\"、faj.faj18 AS \"计量单位\"、TO_CHAR(faj.faj25, YYYY-MM-DD HH24:MI:SS) AS \"取得日期\"、TO_CHAR(faj.faj26, YYYY-MM-DD HH24:MI:SS) AS \"入账日期\"、gen.gen02 AS \"保管人姓名\"、gem.gem02 AS \"保管部门名称\"、faf.faf02 AS \"存放位置名称\"、faj.faj43 AS \"资产状态\"、faj.faj31 AS \"预留残值\"、pmc.pmc03 AS \"供应厂商\"。",
"- 当查询固定资产明细时,返回结果必须且只能包含以下列并使用严格对应的中文别名,顺序必须为:faj.faj02 AS \"资产编号\"、faj.faj06 AS \"资产名称\"、faj.faj08 AS \"规格型号\"、gen.gen02 AS \"保管人姓名\"、gem.gem02 AS \"保管部门名称\"、faf.faf02 AS \"存放位置名称\"、faj.faj43 AS \"资产状态\"、faj.faj31 AS \"预留残值\"、pmc.pmc03 AS \"供应厂商\"、faj.faj09 AS \"资产性质\"、faj.faj13 AS \"本币单价\"、faj.faj17 AS \"数量\"、faj.faj18 AS \"计量单位\"、TO_CHAR(faj.faj25, YYYY-MM-DD HH24:MI:SS) AS \"取得日期\"、TO_CHAR(faj.faj26, YYYY-MM-DD HH24:MI:SS) AS \"入账日期\"。",
"- 日期时间字段展示时不要去掉时分秒;若使用 TO_CHAR 格式化,必须保留为 `YYYY-MM-DD HH24:MI:SS`,不能只输出日期。",
*filters,
]
@@ -1098,12 +1269,36 @@ ORDER BY faj.faj02
def _localize_asset_columns(cls, columns, query: str, sql: str, agent=None):
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
return columns
localized = cls._map_asset_column_names(columns)
order = cls._get_asset_display_order(columns, query, sql, agent=agent)
return [localized[idx] for idx in order]
@classmethod
def _map_asset_column_names(cls, columns):
localized = []
for name in columns or []:
raw_name = str(name or "").strip().strip('"')
localized.append(cls._ASSET_COLUMN_LABELS.get(raw_name.upper(), raw_name))
return localized
@classmethod
def _get_asset_display_order(cls, columns, query: str, sql: str, agent=None) -> list[int]:
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
return list(range(len(columns or [])))
localized = cls._map_asset_column_names(columns)
normalized_target_order = {
cls._normalize_result_column_name(name): position
for position, name in enumerate(cls._ASSET_DISPLAY_COLUMN_ORDER)
}
indexed_columns = list(enumerate(localized))
indexed_columns.sort(
key=lambda item: (
normalized_target_order.get(cls._normalize_result_column_name(item[1]), len(normalized_target_order) + item[0]),
item[0],
)
)
return [idx for idx, _ in indexed_columns]
@classmethod
def _translate_asset_display_value(cls, display_name: str, value) -> str:
text = cls._stringify_value(value)
@@ -1118,7 +1313,7 @@ ORDER BY faj.faj02
@classmethod
def _find_result_column_index(cls, columns, query: str, sql: str, agent, candidate_names: set[str]) -> int | None:
localized_columns = cls._localize_asset_columns(columns, query, sql, agent=agent)
localized_columns = cls._map_asset_column_names(columns)
for idx, raw_name in enumerate(columns or []):
normalized_raw = cls._normalize_result_column_name(raw_name)
normalized_localized = cls._normalize_result_column_name(localized_columns[idx] if idx < len(localized_columns) else "")
@@ -1191,11 +1386,13 @@ ORDER BY faj.faj02
def _localize_asset_rows(cls, columns, rows, query: str, sql: str, agent=None):
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
return rows
display_order = cls._get_asset_display_order(columns, query, sql, agent=agent)
display_columns = cls._localize_asset_columns(columns, query, sql, agent=agent)
index_map = {str(name or "").strip(): idx for idx, name in enumerate(display_columns)}
localized_rows = []
for row in rows or []:
row_values = list(row)
source_row_values = list(row)
row_values = [source_row_values[idx] if idx < len(source_row_values) else None for idx in display_order]
display_values = []
for idx, display_name in enumerate(display_columns):
raw_value = row_values[idx] if idx < len(row_values) else None
@@ -1269,9 +1466,39 @@ ORDER BY faj.faj02
)
@classmethod
def _query_asset_total_count(cls, query: str, sql: str, agent=None) -> int | None:
def _can_use_fixed_assets_snapshot(cls, query: str, agent=None) -> bool:
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, "")):
return False
try:
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
return FixedAssetsSnapshotService.is_snapshot_available()
except Exception:
return False
@classmethod
def _is_fixed_assets_snapshot_sql(cls, sql: str) -> bool:
try:
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
return FixedAssetsSnapshotService.is_snapshot_sql(sql)
except Exception:
return False
@classmethod
def _query_asset_total_count(cls, query: str, sql: str, agent=None, user_context: dict | None = None) -> int | None:
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
return None
if cls._is_fixed_assets_snapshot_sql(sql):
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
_, _, total_count = FixedAssetsSnapshotService.query_assets(
query,
limit=1,
offset=0,
user_context=user_context,
)
return total_count
count_sql = cls._build_asset_total_count_sql(sql)
if not count_sql:
return None
@@ -1466,8 +1693,7 @@ ORDER BY faj.faj02
@classmethod
def summarize_result(cls, query: str, columns, rows, total_count: int | None = None) -> str:
if columns == ["Error"]:
error_message = rows[0][0] if rows and rows[0] else "未知错误"
return f"- 直击答案:查询执行失败,当前无法返回结果。\n- 异常提醒:数据库返回错误 `{error_message}`,请检查筛选条件、表名或字段名。"
return "- 直击答案:查询执行失败,当前无法返回结果。"
if not rows:
return "- 直击答案:当前未查询到符合条件的数据。\n- 趋势发现:当前结果未体现明显趋势。\n- 异常提醒:当前结果未体现明显异常,建议调整筛选条件后重试。"
@@ -1516,12 +1742,17 @@ ORDER BY faj.faj02
@classmethod
def generate_sql(cls, query: str, user_context: dict | None = None, agent=None) -> str:
special_sql = cls._build_special_asset_sql(query, agent=agent)
if cls._can_use_fixed_assets_snapshot(query, agent=agent):
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
return FixedAssetsSnapshotService.SNAPSHOT_SQL_MARKER
effective_query = cls._refine_asset_query(query, agent=agent)
special_sql = cls._build_special_asset_sql(effective_query, agent=agent)
if special_sql:
return cls._rewrite_asset_sql(special_sql, query, agent=agent, user_context=user_context)
return cls._rewrite_asset_sql(special_sql, effective_query, agent=agent, user_context=user_context)
schema = cls.get_schema()
asset_constraints = cls._build_asset_prompt_constraints(query, user_context, agent)
asset_constraints = cls._build_asset_prompt_constraints(effective_query, user_context, agent)
try:
system_prompt = f"""你是一个专业的 Oracle SQL 专家和数据分析助手。你的任务是将用户的自然语言转换为准确的 Oracle 查询语句。
@@ -1542,10 +1773,10 @@ ORDER BY faj.faj02
- 如果问题无法仅依据当前 Schema 回答,请输出安全的 SELECT 语句说明原因,例如 SELECT '无法根据当前表结构回答该问题' AS message FROM DUAL。
{asset_constraints}"""
user_prompt = f"用户问题:{query}"
user_prompt = f"用户问题:{effective_query}"
sql = cls._chat_completion(system_prompt, user_prompt, temperature=0)
sql = sql.rstrip(";")
sql = cls._rewrite_asset_sql(sql, query, agent=agent, user_context=user_context)
sql = cls._rewrite_asset_sql(sql, effective_query, agent=agent, user_context=user_context)
if not cls._is_safe_query(sql):
return "SELECT 'Generated SQL was blocked because it is not a safe read-only SELECT query' AS error FROM DUAL"
@@ -1556,14 +1787,19 @@ ORDER BY faj.faj02
@classmethod
def repair_sql(cls, query: str, failed_sql: str, error_message: str, user_context: dict | None = None, agent=None) -> str:
special_sql = cls._build_special_asset_sql(query, agent=agent)
if cls._can_use_fixed_assets_snapshot(query, agent=agent):
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
return FixedAssetsSnapshotService.SNAPSHOT_SQL_MARKER
effective_query = cls._refine_asset_query(query, agent=agent)
special_sql = cls._build_special_asset_sql(effective_query, agent=agent)
if special_sql:
return cls._rewrite_asset_sql(special_sql, query, agent=agent, user_context=user_context)
return cls._rewrite_asset_sql(special_sql, effective_query, agent=agent, user_context=user_context)
schema = cls.get_schema()
invalid_identifier = cls._extract_invalid_identifier(error_message)
invalid_hint = f"本次报错的非法字段/标识符是:{invalid_identifier}。" if invalid_identifier else ""
asset_constraints = cls._build_asset_prompt_constraints(query, user_context, agent)
asset_constraints = cls._build_asset_prompt_constraints(effective_query, user_context, agent)
system_prompt = f"""你是一个专业的 Oracle SQL 修复助手。你的任务是根据执行失败的 SQL、数据库报错和当前 Schema,修复成一条可执行的 Oracle 查询语句。
@@ -1579,7 +1815,7 @@ ORDER BY faj.faj02
- 严禁输出任何非 SELECT / WITH 语句。
{asset_constraints}"""
user_prompt = f"""用户问题:{query}
user_prompt = f"""用户问题:{effective_query}
执行失败的 SQL:
```sql
{failed_sql}
@@ -1593,7 +1829,7 @@ ORDER BY faj.faj02
try:
sql = cls._chat_completion(system_prompt, user_prompt, temperature=0)
sql = sql.rstrip(";")
sql = cls._rewrite_asset_sql(sql, query, agent=agent, user_context=user_context)
sql = cls._rewrite_asset_sql(sql, effective_query, agent=agent, user_context=user_context)
if not cls._is_safe_query(sql):
return "SELECT 'Generated SQL was blocked because it is not a safe read-only SELECT query' AS error FROM DUAL"
return sql
@@ -1601,7 +1837,17 @@ ORDER BY faj.faj02
return f"SELECT '{cls._escape_sql_message(f'SQL Repair Error: {e}')}' AS error FROM DUAL"
@classmethod
def execute_sql(cls, sql: str, *, query: str = "", agent=None, limit: int | None = None):
def execute_sql(cls, sql: str, *, query: str = "", agent=None, limit: int | None = None, user_context: dict | None = None):
if cls._is_fixed_assets_snapshot_sql(sql):
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
columns, rows, _ = FixedAssetsSnapshotService.query_assets(
query,
limit=limit or cls._ASSET_CHAT_RESULT_LIMIT,
offset=0,
user_context=user_context,
)
return columns, rows
connection, cursor, columns, error_rows = cls._execute_sql_internal(sql)
if columns == ["Error"]:
return columns, error_rows
@@ -1626,9 +1872,29 @@ ORDER BY faj.faj02
connection.close()
@classmethod
def execute_sql_page(cls, sql: str, *, query: str = "", page: int = 1, page_size: int = 100, agent=None):
def execute_sql_page(
cls,
sql: str,
*,
query: str = "",
page: int = 1,
page_size: int = 100,
agent=None,
user_context: dict | None = None,
):
safe_page = max(1, int(page or 1))
safe_page_size = max(1, min(200, int(page_size or 100)))
if cls._is_fixed_assets_snapshot_sql(sql):
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
offset = (safe_page - 1) * safe_page_size
columns, rows, _ = FixedAssetsSnapshotService.query_assets(
query,
limit=safe_page_size,
offset=offset,
user_context=user_context,
)
return columns, rows
is_asset_detail = (
not cls._is_aggregate_sql(sql)
and (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql))
@@ -1664,9 +1930,19 @@ ORDER BY faj.faj02
connection.close()
@classmethod
def get_total_count_for_sql(cls, sql: str) -> int | None:
def get_total_count_for_sql(cls, sql: str, *, query: str = "", user_context: dict | None = None) -> int | None:
if cls._is_fixed_assets_snapshot_sql(sql):
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
_, _, total_count = FixedAssetsSnapshotService.query_assets(
query,
limit=1,
offset=0,
user_context=user_context,
)
return total_count
count_sql = cls._build_generic_total_count_sql(sql)
columns, rows = cls.execute_sql_page(count_sql, page=1, page_size=1)
columns, rows = cls.execute_sql_page(count_sql, query=query, page=1, page_size=1, user_context=user_context)
if columns == ["Error"] or not rows or not rows[0]:
return None
try:
@@ -1675,10 +1951,20 @@ ORDER BY faj.faj02
return None
@classmethod
def format_result(cls, columns, rows, sql, original_query, agent=None):
total_count = cls._query_asset_total_count(original_query, sql, agent=agent)
def format_result(cls, columns, rows, sql, original_query, agent=None, user_context: dict | None = None):
total_count = cls._query_asset_total_count(original_query, sql, agent=agent, user_context=user_context)
summary_text = cls.summarize_result(original_query, columns, rows, total_count=total_count)
sql_details = f"<details>\n<summary class=\"cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300 mb-2\">执行的SQL</summary>\n\n```sql\n{sql}\n```\n</details>"
if cls._is_fixed_assets_snapshot_sql(sql):
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
sql_details = (
"<details>\n"
"<summary class=\"cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300 mb-2\">数据来源</summary>\n\n"
f"{FixedAssetsSnapshotService.snapshot_sql_label()}\n"
"\n</details>"
)
else:
sql_details = f"<details>\n<summary class=\"cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300 mb-2\">执行的SQL</summary>\n\n```sql\n{sql}\n```\n</details>"
if columns == ["Error"]:
error_message = rows[0][0] if rows and rows[0] else "未知错误"
@@ -1701,10 +1987,26 @@ ORDER BY faj.faj02
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
@classmethod
def build_query_preview_payload(cls, columns, rows, sql, original_query, agent=None):
def build_query_preview_payload(cls, columns, rows, sql, original_query, agent=None, user_context: dict | None = None):
if columns == ["Error"] or not columns:
return None
total_count = cls._query_asset_total_count(original_query, sql, agent=agent)
if cls._is_fixed_assets_snapshot_sql(sql):
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
_, _, total_count = FixedAssetsSnapshotService.query_assets(
original_query,
limit=max(1, len(rows or [])),
offset=0,
user_context=user_context,
)
return FixedAssetsSnapshotService.get_snapshot_preview_payload(
original_query,
cls._localize_asset_columns(columns, original_query, sql, agent=agent),
rows,
total_count,
)
total_count = cls._query_asset_total_count(original_query, sql, agent=agent, user_context=user_context)
if total_count is None:
total_count = len(rows or [])
preview_row_count = len(rows or [])
@@ -1720,11 +2022,32 @@ ORDER BY faj.faj02
}
@classmethod
def get_preview_page(cls, *, sql: str, query: str, page: int = 1, page_size: int = 100, agent=None, total_count: int | None = None):
raw_columns, raw_rows = cls.execute_sql_page(sql, query=query, page=page, page_size=page_size, agent=agent)
def get_preview_page(
cls,
*,
sql: str,
query: str,
page: int = 1,
page_size: int = 100,
agent=None,
total_count: int | None = None,
user_context: dict | None = None,
):
raw_columns, raw_rows = cls.execute_sql_page(
sql,
query=query,
page=page,
page_size=page_size,
agent=agent,
user_context=user_context,
)
if raw_columns == ["Error"]:
return raw_columns, raw_rows, total_count
resolved_total = total_count if total_count is not None else cls.get_total_count_for_sql(sql)
resolved_total = total_count if total_count is not None else cls.get_total_count_for_sql(
sql,
query=query,
user_context=user_context,
)
display_columns = cls._localize_asset_columns(raw_columns, query, sql, agent=agent)
display_rows = cls._localize_asset_rows(raw_columns, raw_rows, query, sql, agent=agent)
return display_columns, display_rows, resolved_total
@@ -1753,7 +2076,13 @@ ORDER BY faj.faj02
# 2. Execute SQL
stage_start = time.time()
columns, rows = Text2SQLService.execute_sql(sql, query=query, agent=agent, limit=Text2SQLService._ASSET_CHAT_RESULT_LIMIT)
columns, rows = Text2SQLService.execute_sql(
sql,
query=query,
agent=agent,
limit=Text2SQLService._ASSET_CHAT_RESULT_LIMIT,
user_context=user_context,
)
execute_sql_ms = int((time.time() - stage_start) * 1000)
if current_app:
current_app.logger.info(
@@ -1794,8 +2123,22 @@ ORDER BY faj.faj02
# 3. Format result
yield f"data: {json.dumps({'event': 'message', 'answer': '📝 数据检索完成,正在生成最终业务报告...\n'})}\n\n"
stage_start = time.time()
result_text = Text2SQLService.format_result(columns, rows, sql, query, agent=agent)
result_preview_payload = Text2SQLService.build_query_preview_payload(columns, rows, sql, query, agent=agent)
result_text = Text2SQLService.format_result(
columns,
rows,
sql,
query,
agent=agent,
user_context=user_context,
)
result_preview_payload = Text2SQLService.build_query_preview_payload(
columns,
rows,
sql,
query,
agent=agent,
user_context=user_context,
)
format_result_ms = int((time.time() - stage_start) * 1000)
latency = int((time.time() - start_time) * 1000)
if current_app:
@@ -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")
+5
View File
@@ -267,6 +267,11 @@ def test_reports(client, admin_headers):
assert 'total' in data
assert 'by_user' in data
assert 'by_agent' in data
assert 'user_total' in data
assert 'user_page' in data
assert 'user_page_size' in data
assert 'user_pages' in data
assert 'user_top_limit' in data
response = client.get('/api/admin/reports/feedback', headers=admin_headers)
assert response.status_code == 200
+92 -1
View File
@@ -127,5 +127,96 @@ def test_update_chat_log_tokens_backfills_after_message_end(app):
assert updated is True
assert db.session.get(ChatLog, chat_log_id).tokens_used == 3068
# 不应被更小的值覆盖
def test_collect_knowledge_retrieval_from_node_finished():
"""Chatflow:知识检索来源应从 node_finished.outputs.result 提取。"""
retriever_resources: list = []
event_data = {
'event': 'node_finished',
'data': {
'node_type': 'knowledge-retrieval',
'status': 'succeeded',
'outputs': {
'result': [
{
'metadata': {
'dataset_id': 'ac0cf595-ca91-4f48-a0d1-0d31544c4136',
'dataset_name': '4.人事规章',
'document_id': '94b7246a-4daa-4dff-bdef-01510848f985',
'document_name': '员工入职须4',
'segment_id': '9d10e131-bf02-4add-8ef1-d3098a2ab7a4',
'score': 0.8577696681022644,
},
'title': '员工入职须4',
'files': None,
'content': '员工入职须知4\n2.上班时间',
},
{
'metadata': {
'dataset_id': 'ac0cf595-ca91-4f48-a0d1-0d31544c4136',
'document_id': '97eab330-d658-4f9e-aa7f-a24423234ee5',
'document_name': '考勤-公司班次信息',
},
'title': '考勤-公司班次信息',
'content': '考勤-公司班次信息',
},
],
},
},
}
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, event_data)
assert len(retriever_resources) == 2
assert retriever_resources[0]['document_id'] == '94b7246a-4daa-4dff-bdef-01510848f985'
assert retriever_resources[0]['document_name'] == '员工入职须4'
assert retriever_resources[0]['dataset_id'] == 'ac0cf595-ca91-4f48-a0d1-0d31544c4136'
assert retriever_resources[1]['document_id'] == '97eab330-d658-4f9e-aa7f-a24423234ee5'
def test_attach_retriever_resources_to_workflow_finished_event():
"""workflow_finished 下发前应携带 retriever_resources 供前端展示源文件。"""
resources = [
{
'dataset_id': 'ds-1',
'document_id': 'doc-1',
'document_name': '员工入职须知.pdf',
'content': '上班时间 8:00',
},
]
event_data = {'event': 'workflow_finished', 'metadata': {}}
DifyService._attach_retriever_resources_to_event(event_data, resources)
assert len(event_data['retriever_resources']) == 1
assert event_data['retriever_resources'][0]['document_name'] == '员工入职须知.pdf'
assert event_data['metadata']['retriever_resources'][0]['document_id'] == 'doc-1'
def test_update_chat_log_tokens_does_not_decrease(app):
"""已写入更大 token 后,不应被更小的值覆盖。"""
with app.app_context():
user = User(username='u3', role='user', email='u3@example.com')
agent = Agent(name='wf_agent3', dify_app_id='wf-3')
db.session.add_all([user, agent])
db.session.commit()
first = DifyService._persist_stream_chat_record(
data={'event': 'message_end', 'conversation_id': 'conv-wf-3', 'metadata': {}},
event_name='message_end',
request_id='req-wf-3',
user_id=user.id,
agent=agent,
session_id='sess-wf-3',
hxops_turn_id=None,
normalized_conversation_id='conv-wf-3',
query='test',
answer_text='answer',
latency=1000,
retriever_resources=[],
attribution_parts=[],
)
chat_log_id = first['chat_log_id']
DifyService._update_chat_log_tokens(chat_log_id, 500)
assert DifyService._update_chat_log_tokens(chat_log_id, 100) is False
+50
View File
@@ -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]
+113
View File
@@ -0,0 +1,113 @@
"""
backend/tests/test_fixed_assets_snapshot.py
用途:验证固定资产快照查询服务的核心过滤行为。
依赖:pytest、Flask app fixture、FixedAssetsSnapshotService。
逻辑关系:覆盖“资产名称+规格型号组合查询”和“本人名下资产查询”两个高频场景。
"""
from __future__ import annotations
from pathlib import Path
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
def _seed_latest_snapshot(root: Path) -> None:
"""写入一份最小可用的 latest 快照,供查询服务读取。"""
rows = [
{
"资产编号": "A0827011",
"资产名称": "线切割机",
"资产名称2": "",
"规格型号": "DK7732",
"保管人工号": "E1001",
"保管人姓名": "张三",
"保管部门编号": "D01",
"保管部门名称": "制造部",
"存放位置名称": "一厂机加区",
"资产状态": "折旧中",
"资产状态代码": "2",
"预留残值": "1000",
"供应厂商": "华东设备",
"资产性质": "有形资产",
"资产性质代码": "1",
"本币单价": "60000",
"数量": "1",
"计量单位": "台",
"取得日期": "2024-01-01 00:00:00",
"入账日期": "2024-01-10 00:00:00",
"营运中心代码": "HXJM",
"站点代码": "JM",
"备注": "资产编号:A0827011 | 资产名称:线切割机 | 规格型号:DK7732 | 保管人姓名:张三 | 保管部门名称:制造部 | 存放位置名称:一厂机加区 | 资产状态:折旧中 | 供应厂商:华东设备 | 资产性质:有形资产",
"备注标准化": "资产编号A0827011资产名称线切割机规格型号DK7732保管人姓名张三保管部门名称制造部存放位置名称一厂机加区资产状态折旧中供应厂商华东设备资产性质有形资产",
},
{
"资产编号": "A0827012",
"资产名称": "400吨冲床",
"资产名称2": "",
"规格型号": "JH21-400",
"保管人工号": "E1002",
"保管人姓名": "李四",
"保管部门编号": "D02",
"保管部门名称": "冲压部",
"存放位置名称": "二厂冲压区",
"资产状态": "折旧中",
"资产状态代码": "2",
"预留残值": "2000",
"供应厂商": "华南设备",
"资产性质": "有形资产",
"资产性质代码": "1",
"本币单价": "200000",
"数量": "1",
"计量单位": "台",
"取得日期": "2023-01-01 00:00:00",
"入账日期": "2023-01-10 00:00:00",
"营运中心代码": "HTT",
"站点代码": "TT",
"备注": "资产编号:A0827012 | 资产名称:400吨冲床 | 规格型号:JH21-400 | 保管人姓名:李四 | 保管部门名称:冲压部 | 存放位置名称:二厂冲压区 | 资产状态:折旧中 | 供应厂商:华南设备 | 资产性质:有形资产",
"备注标准化": "资产编号A0827012资产名称400吨冲床规格型号JH21400保管人姓名李四保管部门名称冲压部存放位置名称二厂冲压区资产状态折旧中供应厂商华南设备资产性质有形资产",
},
]
root.mkdir(parents=True, exist_ok=True)
latest_dir = root / "latest"
latest_dir.mkdir(parents=True, exist_ok=True)
FixedAssetsSnapshotService._write_snapshot_db(
latest_dir / "FixedAssets_latest.db",
rows,
version="20260622_030000",
snapshot_date="2026-06-22",
)
def test_query_assets_supports_name_and_spec_combo(app, tmp_path):
app.config["FIXED_ASSETS_STORAGE_ROOT"] = str(tmp_path / "fixed_assets")
with app.app_context():
_seed_latest_snapshot(tmp_path / "fixed_assets")
columns, rows, total = FixedAssetsSnapshotService.query_assets("查询线切割机 规格型号 DK7732")
# 断言:组合查询应命中同一台设备,且返回预期中文列头。
assert columns[:3] == ["资产编号", "资产名称", "规格型号"]
assert total == 1
assert rows[0][0] == "A0827011"
assert rows[0][1] == "线切割机"
assert rows[0][2] == "DK7732"
def test_query_assets_supports_self_scope(app, tmp_path):
app.config["FIXED_ASSETS_STORAGE_ROOT"] = str(tmp_path / "fixed_assets")
with app.app_context():
_seed_latest_snapshot(tmp_path / "fixed_assets")
columns, rows, total = FixedAssetsSnapshotService.query_assets(
"查询我名下固定资产",
user_context={"employee_id": "E1001", "real_name": "张三", "username": "zhangsan"},
)
# 断言:本人查询必须按当前用户身份过滤,不能返回其他人的资产。
assert columns[0] == "资产编号"
assert total == 1
assert len(rows) == 1
assert rows[0][0] == "A0827011"
assert rows[0][3] == "张三"
+14 -25
View File
@@ -1,10 +1,9 @@
"""
backend/tests/test_hot_faq_aggregator.py
测试热点 FAQ 离线聚合的核心规则:问句归一化、答案聚类与代表答案选取。
测试热点 FAQ 离线聚合的核心规则:问句归一化、代表答案选取。
"""
from datetime import datetime
from types import SimpleNamespace
from app.services.faq_text_utils import normalize_faq_query
from app.services.hot_faq_aggregator import HotFaqAggregator, _LogRow
@@ -15,15 +14,19 @@ def test_normalize_faq_query_strips_punctuation_and_space():
assert normalize_faq_query('公司几点上班?') == normalize_faq_query('公司 几点上班')
def test_answer_cluster_merges_similar_answers():
"""相似度≥阈值的答案应归入同一簇。"""
rows = [
_LogRow(1, 1, 1, 'q', '工作日8:30到17:30', 100, 10, datetime.utcnow()),
_LogRow(2, 2, 1, 'q', '工作日 8:30 到 17:30', 100, 10, datetime.utcnow()),
]
clusters = HotFaqAggregator._cluster_answers(rows)
assert len(clusters) == 1
assert len(clusters[0]['rows']) == 2
def test_build_candidate_accepts_divergent_answers_when_clustering_disabled(app, monkeypatch):
"""答案聚类关闭时,即使答案分歧较大也应生成热点候选。"""
monkeypatch.setenv('FAQ_HOT_ANSWER_DOMINANCE', '0.6')
with app.app_context():
now = datetime.utcnow()
rows = [
_LogRow(i, i, 1, '上班时间', f'answer variant {i % 3}', 200, 100, now)
for i in range(6)
]
candidate, reason = HotFaqAggregator._build_candidate(1, 'Agent', '上班时间', rows)
assert candidate is not None
assert reason is None
assert candidate.ask_count_7d == 6
def test_pick_representative_prefers_good_feedback():
@@ -37,17 +40,3 @@ def test_pick_representative_prefers_good_feedback():
assert picked is not None
assert picked.chat_log_id == 2
assert picked.answer == 'answer B'
def test_build_candidate_rejects_divergent_answers(app, monkeypatch):
"""答案分歧过大时应跳过该热点组。"""
monkeypatch.setenv('FAQ_HOT_ANSWER_DOMINANCE', '0.6')
with app.app_context():
now = datetime.utcnow()
rows = [
_LogRow(i, i, 1, '上班时间', f'answer variant {i % 3}', 200, 100, now)
for i in range(6)
]
candidate, reason = HotFaqAggregator._build_candidate(1, 'Agent', '上班时间', rows)
assert candidate is None
assert reason and reason.startswith('answer_divergence')
+59 -6
View File
@@ -1,7 +1,21 @@
import pytest
from app.models import User
from app.models import User, Agent
from app import db
def _error_message(response):
body = response.get_json() or {}
error = body.get('error')
if isinstance(error, dict):
return str(error.get('message') or '')
return str(error or '')
def _error_code(response):
body = response.get_json() or {}
error = body.get('error')
if isinstance(error, dict):
return str(error.get('code') or '')
return ''
def test_register_fields_validation(client):
"""
Test user registration field validation
@@ -40,7 +54,7 @@ def test_register_fields_validation(client):
}
response = client.post('/api/user/register', json=dup_user)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
assert "Employee ID already exists" in _error_message(response)
def test_admin_duplicate_employee_id(client, admin_headers):
"""
@@ -68,8 +82,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
"phone_number": "13800000012"
}
response = client.post('/api/admin/users', json=u2, headers=admin_headers)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
assert response.status_code == 409
assert "Employee ID already exists" in _error_message(response)
# 3. Update user to duplicate ID
# Create u3 with valid ID
@@ -86,5 +100,44 @@ def test_admin_duplicate_employee_id(client, admin_headers):
# Update u3 to ADM001 (which exists)
res = client.put(f'/api/admin/users/{u3_id}', json={"employee_id": "ADM001"}, headers=admin_headers)
assert res.status_code == 400
assert "Employee ID already exists" in res.json['error']
assert res.status_code == 409
assert "Employee ID already exists" in _error_message(res)
assert _error_code(res) == 'USER.EMPLOYEE_ID_EXISTS'
def test_admin_duplicate_phone_on_update_with_agent_ids(client, admin_headers):
"""
编辑用户时若手机号重复且同时提交 agent_ids,应在 autoflush 前返回冲突而非 500。
"""
existing = {
"username": "phone_owner",
"password": "pwd",
"email": "phone_owner@e.com",
"real_name": "Phone Owner",
"employee_id": "PHN001",
"phone_number": "123456",
}
target = {
"username": "phone_target",
"password": "pwd",
"email": "phone_target@e.com",
"real_name": "Phone Target",
"employee_id": "PHN002",
"phone_number": "13800009999",
}
assert client.post('/api/admin/users', json=existing, headers=admin_headers).status_code == 201
target_res = client.post('/api/admin/users', json=target, headers=admin_headers)
assert target_res.status_code == 201
target_id = target_res.json['id']
agent = Agent(name='Dup Phone Agent', dify_app_id='dup-phone-agent', type='chat')
db.session.add(agent)
db.session.commit()
res = client.put(
f'/api/admin/users/{target_id}',
json={'phone_number': '123456', 'agent_ids': [agent.id]},
headers=admin_headers,
)
assert res.status_code == 409
assert _error_code(res) == 'USER.PHONE_EXISTS'
assert "Phone number already exists" in _error_message(res)
+211
View File
@@ -0,0 +1,211 @@
# 错误处理规范
> 更新时间:2026-06-22
> 适用范围:HXOPS 前后端 API 与 UI 错误反馈
> 读者:组内同事、AI 编程助手
> 文档定位:**错误契约、分层职责与禁止项**的权威说明。`AGENTS.md` §8 仅保留强约束摘要,细则以本文为准。
---
## 1. 统一错误契约
前后端 JSON API 采用 **Envelope** 结构(由 `ENABLE_API_ENVELOPE` 与全局 handler 保证)。
**成功:**
```json
{
"success": true,
"data": { },
"request_id": "req_abc123",
"timestamp": "2026-06-22T08:00:00Z"
}
```
**失败:**
```json
{
"success": false,
"error": {
"code": "USER.EMAIL_EXISTS",
"message": "Email already exists",
"details": { "field": "email" },
"retryable": false
},
"request_id": "req_abc123",
"timestamp": "2026-06-22T08:00:00Z"
}
```
| 字段 | 说明 |
|------|------|
| `error.code` | 机器可读错误码,格式 `DOMAIN.SUBTYPE`(如 `AUTH.UNAUTHORIZED`) |
| `error.message` | 英文或简短说明,供日志与 fallback;**前端优先用 i18n 映射** |
| `error.details` | 可选结构化信息(字段名、冲突项等),供前端分支逻辑 |
| `error.retryable` | 是否建议用户重试(503 等) |
| `request_id` | 与 `X-Request-Id` 对齐,便于排障 |
---
## 2. 后端规范
### 2.1 分层职责
| 层 | 职责 |
|----|------|
| **Route(`api/`)** | 参数读取、权限装饰器、调用 service;**不**手写 `jsonify({"error": ...})` |
| **Service(`services/`)** | 业务校验失败 `raise AppError` 子类;不构造 HTTP Response |
| **全局 handler(`app/__init__.py`)** | 捕获 `AppError` / `HTTPException` / 未预期异常 → `error_payload` |
### 2.2 使用 `app/errors.py`
优先使用已有子类,语义不明确时再 `raise AppError(...)`:
| 异常 | 典型 HTTP | 默认 code |
|------|-----------|-----------|
| `ValidationError` | 400 | `VALIDATION.INVALID_PARAM` |
| `UnauthorizedError` | 401 | `AUTH.UNAUTHORIZED` |
| `ForbiddenError` | 403 | `AUTH.FORBIDDEN` |
| `NotFoundError` | 404 | `RESOURCE.NOT_FOUND` |
| `ConflictError` | 409 | `RESOURCE.CONFLICT`(可自定义 code) |
| `ServiceUnavailableError` | 503 | `SYSTEM.SERVICE_UNAVAILABLE` |
**示例(service / route):**
```python
from app.errors import ValidationError, NotFoundError, ConflictError
if not name:
raise ValidationError("Name is required")
if not row:
raise NotFoundError("Agent not found")
if email_exists:
raise ConflictError("Email already exists", code="USER.EMAIL_EXISTS", details={"field": "email"})
```
**成功响应:** 使用 `app.response_utils.ok(data)`,或在 envelope 开启时返回 plain dict(由 `@app.after_request` 包装)。
### 2.3 错误码命名
- 格式:`<域>.<语义>`,全大写,点号分隔。
- 域示例:`AUTH`、`USER`、`RESOURCE`、`VALIDATION`、`KB`、`WECOM`、`SYSTEM`。
- **新增 code 必须同步前端四语言** `locales/*/errors.json` → `errors.codes.<CODE_WITH_UNDERSCORES>`(`.` 换 `_`)。
### 2.4 禁止项(后端)
| ❌ 不要 | ✅ 应该 |
|---------|---------|
| `return jsonify({"error": "Not found"}), 404` | `raise NotFoundError(...)` |
| `return jsonify({"ok": False, "error": "..."}), 400` | `raise ValidationError(...)` |
| 在 service 里 `return (jsonify(...), 4xx)` | `raise AppError` 交给 handler |
| 500 时把堆栈/ SQL 返回给客户端 | 日志记录细节;客户端仅 `SYSTEM.INTERNAL_ERROR` |
| 随意字符串作 code(`"not_found"`) | `RESOURCE.NOT_FOUND` 等规范 code |
> 历史路由(如部分 `workspace_shipping_notice.py`)仍有 legacy `{"error": "..."}` 写法;**新接口与改动处须改为 `AppError`**,逐步收敛。
---
## 3. 前端规范
### 3.1 分层职责
| 层 | 职责 |
|----|------|
| **`shared/api/client.ts`** | 唯一 JSON 客户端:`requestJson` 解析 envelope,失败抛 `BusinessError`(含 `code` / `message` / `details` / `status` / `requestId`) |
| **`features/*/api/*.api.ts`** | 只组装 URL 与 body,调用 `requestJson`;**不** catch 后改写成字符串 |
| **Composables / Views** | catch `BusinessError`,用 `useMessage()` 或域内 resolver 展示;按 `status` / `code` 做分支(401 跳登录等) |
| **Components** | 一般不 catch API;由父级注入错误状态或回调 |
### 3.2 `BusinessError` 与 i18n
`requestJson` 抛出前已通过 `resolveLocalizedErrorMessage` 将 `error.code` 映射到 `errors.codes.*`(四语言 `errors.json`)。
**Composable 中展示错误(推荐):**
```typescript
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
const msg = useMessage();
try {
await saveProfile(payload);
msg.success(t('workspace.profile.msg.saved'));
} catch (e) {
const message = e instanceof BusinessError
? e.message
: t('workspace.profile.msg.saveFailed');
msg.error(message);
}
```
**按状态分支:**
```typescript
catch (e) {
if (e instanceof BusinessError && e.status === 401) {
msg.error(t('login.loginRequired'));
return;
}
if (e instanceof BusinessError && e.status === 403) {
msg.error(e.message);
return;
}
msg.error(e instanceof Error ? e.message : t('errors.generic'));
}
```
**域内复杂映射**(如 Casdoor 登录):在 `shared/utils/` 或 feature `utils/` 提供 `resolveXxxErrorMessage(err: BusinessError, t)`,避免 View 内重复 if-else。
### 3.3 表单校验 vs 服务端错误
| 类型 | 处理方式 |
|------|----------|
| 前端必填 / 格式 | 提交前校验,`msg.warning(t('...'))`,不发起请求 |
| 服务端业务拒绝 | API 抛 `BusinessError`,展示 `e.message`(已 i18n) |
| 字段级错误 | 读 `e.details.field`,高亮对应表单项 |
### 3.4 SSE / 流式对话
对话流式接口**不走** `requestJson`,错误处理在 `features/chat/composables/useChat.ts` 内完成(解析 SSE event、断线重试等)。勿用 Axios 替代。
### 3.5 禁止项(前端)
| ❌ 不要 | ✅ 应该 |
|---------|---------|
| 在组件里直接 `fetch('/api/...')` | `features/*/api/*.api.ts` + `requestJson` |
| `(e as Error).message` 且不判断类型 | 优先 `instanceof BusinessError` |
| catch 后静默吞掉(无 UI、无日志) | `msg.error` 或向上抛出 |
| catch 里硬编码中文 | `e.message`(已映射)或 `t('errors....')` |
| 在 `*.api.ts` 里 `msg.error` | API 层只抛错,UI 层负责展示 |
| 新增后端 code 却不加 `errors.json` | 四语言同步 `errors.codes.*` |
---
## 4. 新增错误码检查清单
1. 后端:在 `app/errors.py` 选用或新增语义明确的 `code`。
2. 前端:在 `locales/{zh-CN,zh-TW,en,th}/errors.json` 的 `codes` 下增加键(`USER.EMAIL_EXISTS` → `USER_EMAIL_EXISTS`)。
3. 若需按 `details` 分支,在 composable 文档注释中说明字段约定。
4. 自测:触发该错误,确认四语言文案与 HTTP 状态码正确。
---
## 5. 相关文件
| 文件 | 说明 |
|------|------|
| `backend/app/errors.py` | 业务异常类型 |
| `backend/app/response_utils.py` | `ok()`、`error_payload()` |
| `backend/app/__init__.py` | 全局 errorhandler、envelope 包装 |
| `frontend/src/shared/api/client.ts` | `requestJson`、`BusinessError` |
| `frontend/src/locales/*/errors.json` | 错误码 i18n |
| `frontend/src/shared/composables/useMessage.ts` | 全局 error/success 弹窗 |
---
## 6. 相关文档
- [AGENTS.md](../../AGENTS.md) §8 — 红线摘要
- [frontend_architecture_refactor.md](../refactor/frontend_architecture_refactor.md) — 前端分层与 API 层约束
+8
View File
@@ -30,6 +30,14 @@
- 检核成功或部分成功并生成 Excel 报告后,可按配置自动同步到指定知识库分组;Chatflow 历史分支按 `task_id` 选择知识库 Dataset。
- Dify Chatflow 编排与 OpenAPI 导入见 [docs/file_check.md](file_check.md)(第二部分)。
### 3.x 固资快照查询补充需求
- **核心目标**:固资管理从“实时 ERP Text2SQL 查询”为主,逐步演进为“每天定时同步全量固资快照 + 本地结构化查询”为主。
- **同步要求**:系统每天早上 03:00 自动从 ERP Oracle 拉取公司全量固定资产,生成 `FixedAssets` 导出文件,并写入本地结构化快照。
- **备注要求**:同步时为每条资产生成 `备注` 字段,拼接“资产编号、资产名称、规格型号、保管人姓名、保管部门名称、存放位置名称、资产状态、供应厂商、资产性质”等描述,供模糊检索兜底使用。
- **可靠性要求**:单次同步必须设置超时;超时或短时失败后,每隔 30 分钟自动重试 1 次,累计最多重试 3 次;若全部失败,继续保留上一版快照对外服务。
- **查询要求**:用户在 `固资管理` Agent 中发起查询时,优先查询本地快照;字段级条件优先匹配,`备注` 作为模糊检索补充;极少数无法覆盖的复杂场景可再回退实时 ERP 查询。
### 3.1 本期范围
- 查询员工本人假期余额
+190 -7
View File
@@ -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.1 数据库迁移
@@ -34,6 +170,8 @@ docker compose exec -T hxops-backend flask --app manage.py db upgrade
- `a1b2c3d4e5f7` — 扩展 `quick_questions`(answer、aliases、cache_enabled 等)
- `b2c3d4e5f6a8` — 新建 `faq_hot_candidates`
- `c5d6e7f8a9b0` — 合并迁移 head(无 DDL)
- `c6d7e8f9a0b1` — FAQ 待复审字段(`stale_*`、`source_kb_document_ids`)
### 2.2 环境变量
@@ -73,16 +211,33 @@ flask --app manage.py faq-aggregate-hot
## 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
# 每天 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
```
### 3.2 裸机 / systemd timer
### 3.3 裸机 / systemd timer
```bash
# 手动试跑
@@ -120,7 +275,7 @@ WantedBy=timers.target
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
```
### 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` |
| 离线聚合 | `backend/app/services/hot_faq_aggregator.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` |
| 管理 API | `backend/app/api/admin.py` |
| 对话入口 | `backend/app/api/chat.py`(Dify 前 `try_match`) |
@@ -405,7 +564,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. 建议运维节奏(参考)
| 频率 | 动作 | 负责人 |
| --- | --- | --- |
+594
View File
@@ -0,0 +1,594 @@
# 固资快照同步与本地查询技术方案
## 1. 文档目的
本文档用于将“固资管理从实时 ERP 查询逐步演进为定时快照同步 + 本地结构化查询”的需求拆解为可执行设计稿,并给出详细技术方案、实施边界、风险与阶段任务。
本文档当前处于“方案评估 / 设计阶段”,暂不涉及代码开发与数据库迁移执行。
---
## 2. 背景与问题
当前固资查询主要依赖 `backend/app/services/text2sql.py` 在聊天过程中实时访问 ERP Oracle,并结合规则与 LLM 生成 SQL。该方案已经支持资产编号、资产名称、规格型号、保管人、保管部门、存放位置、资产状态、供应厂商、资产性质等维度的查询,但在客户个性化问法持续增加后,逐渐暴露出以下问题:
- 用户自然语言问法复杂且频繁变化,实时 Text2SQL 可控性不足。
- 每次查询依赖 ERP Oracle 在线可用,链路长、故障点多。
- 查询与预览均是运行时临时执行,对性能、稳定性与可运维性不友好。
- 当前固资查询规则在不断补强,后续维护成本较高。
- 结果准确性与实时性高度依赖 ERP 连接状态、LLM 生成质量与联表稳定性。
因此,需要将固资管理从“实时直连 ERP 查询”为主,调整为“每天定时生成固资快照,本地查询为主,ERP 实时查询为辅”的稳定架构。
---
## 3. 目标
### 3.1 核心目标
- 每天早上 3 点自动从 ERP Oracle 拉取公司全量固资快照。
- 生成命名为 `FixedAssets` 的可下载导出文件,供人工核查与运维使用。
- 在快照数据中增加 `备注` 字段,将常用资产描述信息合并存储,辅助模糊检索。
- 对同步任务增加超时控制、失败重试、版本切换与运行审计能力。
- 用户查询固资时,优先查询本地快照数据,降低实时 ERP 查询依赖。
### 3.2 业务目标
- 提升固资查询稳定性与响应速度。
- 降低客户个性化复杂问法对实时 SQL 生成的影响。
- 保留模糊检索体验,同时增强字段级可控查询能力。
- 支持预览、分页、明细展示等现有聊天体验。
### 3.3 非目标
- 本阶段不直接替换全部 ERP 实时查询能力。
- 本阶段不把 Excel 文件本身作为唯一主查询源。
- 本阶段不开发新的前端页面。
- 本阶段不引入新的大型外部中间件。
---
## 4. 现状评估
### 4.1 现有固资查询现状
当前固资查询能力集中在 `backend/app/services/text2sql.py`,具备以下特点:
- 已支持固资专用字段映射、值翻译、结果重排与预览。
- 已支持资产编号、资产名称、规格型号等组合查询。
- 已支持固资管理 Agent 的问句提炼、规则 SQL、LLM 兜底、SQL 修复。
- 预览与全量数据查看当前仍依赖底层 SQL 再次执行。
### 4.2 现有调度能力现状
项目已具备定时任务基础设施,可用于承载“每天 3 点同步一次”的任务外壳,已有能力包括:
- Cron 表达式与时区配置。
- 任务运行记录与步骤日志。
- Excel 结果导出能力。
- 本地文件落地与知识库同步能力。
但仍存在限制:
- 当前排程配置层未直接支持 ERP Oracle 作为标准数据源。
- 当前重试机制未形成统一的“超时后 30 分钟重试,最多 3 次”的通用策略。
- 当前调度执行更偏进程内 worker,不是完整的独立任务执行体系。
### 4.3 结论
结论是:该需求在当前项目基础上“可行”,但不适合简单做成“每天导一个 Excel 到 `docs`,后续所有查询只扫文件中的 `备注` 字段”。
更合理的实现方式应为:
- `docs` 目录只保留可下载导出副本。
- 系统内部使用本地结构化快照作为主查询源。
- `备注` 字段作为辅助模糊检索字段,而不是唯一查询字段。
---
## 5. 推荐总体方案
### 5.1 总体架构
```text
ERP Oracle 固资视图
-> 固资快照同步任务(每天 03:00)
-> 超时控制
-> 失败重试(30 分钟间隔,最多 3 次)
-> 结构化快照落地(SQLite / 本地缓存表)
-> 导出文件落地(FixedAssets.xlsx / csv)
-> 版本切换(latest)
聊天固资查询
-> 固资查询意图识别
-> 优先查本地快照
-> 字段级查询
-> 备注模糊检索
-> 分页/预览
-> 极少数复杂场景保留 ERP 实时查询兜底
```
### 5.2 核心设计原则
- 同步与查询解耦:同步任务负责产出数据,查询服务只读快照。
- 文件与查询解耦:导出文件用于查看与留档,结构化数据用于系统查询。
- 版本切换安全:新快照成功后再切换为有效版本,失败不影响旧版本可用。
- 模糊与结构结合:结构化字段优先,`备注` 模糊匹配兜底。
- 逐步迁移:先并行验证,再切换固资主查询链路。
---
## 6. 数据同步方案设计
### 6.1 数据来源
建议复用当前固资查询逻辑中已验证过的 ERP 视图组合,从 Oracle 中拉取扁平化固资快照。
建议主查询来源:
- `ERP_VIEW_USER.ERP_FAJ_FILE_V faj`
- `ERP_VIEW_USER.ERP_GEN_FILE_V gen`
- `ERP_VIEW_USER.ERP_GEM_FILE_V gem`
- `ERP_VIEW_USER.ERP_FAF_FILE_V faf`
- `ERP_VIEW_USER.ERP_PMC_FILE_V pmc`
- `ERP_VIEW_USER.ERP_FAB_FILE_V fab`
建议同步时直接查询出扁平结果,避免落地后再做复杂联表。
### 6.2 快照字段
建议快照至少包含以下字段:
- `asset_no` / `资产编号`
- `asset_name` / `资产名称`
- `specification` / `规格型号`
- `custodian_name` / `保管人姓名`
- `department_name` / `保管部门名称`
- `location_name` / `存放位置名称`
- `asset_status` / `资产状态`
- `vendor_name` / `供应厂商`
- `asset_nature` / `资产性质`
- `unit_price` / `本币单价`
- `quantity` / `数量`
- `unit` / `计量单位`
- `acquisition_date` / `取得日期`
- `accounting_date` / `入账日期`
- `residual_value` / `预留残值`
- `site_code` / `营运中心代码`
- `site_name` / `营运中心名称`
- `snapshot_version`
- `snapshot_date`
- `remark`
- `remark_normalized`
### 6.3 备注字段设计
`备注` 字段用于汇总常用资产描述,建议由以下字段按固定顺序拼接:
- 资产编号
- 资产名称
- 规格型号
- 保管人姓名
- 保管部门名称
- 存放位置名称
- 资产状态
- 供应厂商
- 资产性质
示例:
```text
资产编号:A0827011 | 资产名称:线切割机 | 规格型号:DK7732 | 保管人姓名:张三 | 保管部门名称:制造部 | 存放位置名称:一厂机加区 | 资产状态:折旧中 | 供应厂商:某某设备厂 | 资产性质:有形资产
```
同时建议生成 `remark_normalized`:
- 去空格
- 转大写
- 去掉全角/半角干扰符号
该字段专用于模糊检索与关键词召回。
### 6.4 同步结果导出文件
建议每次同步成功后生成两类文件:
- 历史版本文件:
- `FixedAssets_YYYYMMDD_HHMMSS.xlsx`
- 当前有效版本别名:
- `FixedAssets_latest.xlsx`
如果业务强制要求在 `docs` 目录保留文件,则建议仅将“导出副本”保存到:
- `docs/FixedAssets_latest.xlsx`
- `docs/FixedAssets_YYYYMMDD_HHMMSS.xlsx`
但运行时主数据源不要直接使用 `docs` 中的 Excel 文件。
---
## 7. 本地存储方案设计
### 7.1 推荐方案
推荐使用本地结构化快照存储,优先选择:
- 方案 A:SQLite
- 方案 B:CSV/Excel 导出 + SQLite 索引
推荐优先使用 SQLite,原因如下:
- 支持字段级过滤、模糊查询、分页与排序。
- 便于承接现有查询结果预览能力。
- 方便版本化管理与原子切换。
- 比直接扫描 Excel/CSV 更适合高频查询。
### 7.2 建议目录
建议新增运行时目录:
```text
backend/data/fixed_assets/
├─ snapshots/
│ ├─ FixedAssets_20260622_030000.db
│ ├─ FixedAssets_20260622_030000.xlsx
│ └─ ...
├─ latest/
│ ├─ FixedAssets_latest.db
│ └─ FixedAssets_latest.xlsx
└─ manifest.json
```
其中:
- `snapshots/` 存历史版本
- `latest/` 存当前有效版本
- `manifest.json` 记录当前有效版本、生成时间、记录数、状态
- `snapshots/` 建议增加自动清理机制,仅保留最近 3 份有效历史快照,超出的旧版 `db/xlsx` 自动删除,并同时清理 `~$FixedAssets*.xlsx` 这类临时锁文件
### 7.3 版本切换
建议流程:
1. 先生成临时快照文件。
2. 完成数据校验与记录数校验。
3. 校验通过后再原子替换 `latest` 版本。
4. 若本次失败,则保留旧版 `latest` 不变。
这样可避免同步失败导致固资查询整体不可用。
---
## 8. 定时任务设计
### 8.1 调度规则
- Cron:`0 3 * * *`
- 时区:`Asia/Shanghai`
- 触发频率:每天 03:00 执行一次
### 8.2 任务类型
建议新增“固资快照同步任务”,不要复用聊天 Text2SQL 逻辑。
建议新增独立服务:
- `FixedAssetsSnapshotService`
建议职责:
- 连接 ERP Oracle
- 拉取全量固资
- 生成备注字段
- 写入本地结构化快照
- 导出文件
- 更新 manifest
- 输出运行日志与错误信息
### 8.3 超时控制
建议增加两层超时:
- Oracle 查询超时:`300 ~ 600 秒`
- 任务总执行超时:`600 ~ 900 秒`
超时后必须:
- 主动断开数据库连接
- 标记本次 run 为 timeout
- 写入失败原因
- 触发延迟重试调度
### 8.4 重试策略
针对“超时 / 网络异常 / Oracle 短暂不可用”场景,建议重试:
- 间隔:每隔 30 分钟
- 最大次数:3 次
推荐执行节奏:
- 第 1 次:03:00
- 第 2 次:03:30
- 第 3 次:04:00
- 第 4 次:04:30
说明:
- 若 03:00 为首次执行,则后续 3 次为补偿重试。
- 若任意一次成功,则终止剩余重试。
- 若全部失败,则继续使用上一版快照。
### 8.5 幂等要求
同一天内重复执行同步任务时,必须满足幂等:
- 以 `snapshot_date + version` 唯一标识一次运行产物。
- 同一版本写入前先使用临时文件。
- 只有成功校验后才更新 `latest`。
- 不允许半成品覆盖生效版本。
---
## 9. 查询链路改造设计
### 9.1 总体思路
当前固资查询入口不需要大改前端交互,后端改为:
1. 用户进入 `固资管理` Agent。
2. 继续做问句提炼。
3. 优先走“本地快照查询服务”。
4. 命中结果后直接返回。
5. 少数极复杂或无法覆盖的场景,保留 ERP 实时查询兜底。
### 9.2 新查询服务
建议新增:
- `FixedAssetsQueryService`
职责:
- 加载当前有效快照
- 解析用户查询条件
- 执行字段级过滤
- 执行 `remark_normalized` 模糊检索
- 返回结构化结果、预览分页与统计信息
### 9.3 查询优先级
建议查询优先级如下:
1. 资产编号
2. 资产名称
3. 规格型号
4. 保管人姓名
5. 保管部门名称
6. 存放位置名称
7. 资产状态
8. 供应厂商
9. 资产性质
10. `备注` / `remark_normalized` 模糊兜底
### 9.4 为什么不能只查备注
如果所有问题都只查 `备注`,会有以下问题:
- 匹配精度不稳定
- 组合查询表达能力不足
- 后续统计口径难以保证准确
- 用户问题越复杂,误命中越多
因此建议:
- 结构化字段过滤作为主链路
- `备注` 只作为召回与兜底补充
### 9.5 预览与分页
当前项目已有查询结果预览能力,因此快照查询必须支持:
- 按页读取
- 返回总数
- 返回显示列顺序
- 与聊天结果表格展示一致
预览链路建议直接查 SQLite 当前快照,不再重新连接 ERP。
---
## 10. 返回字段展示规则
建议固资查询结果与预览继续统一使用当前约定顺序:
1. 资产编号
2. 资产名称
3. 规格型号
4. 保管人姓名
5. 保管部门名称
6. 存放位置名称
7. 资产状态
8. 预留残值
9. 供应厂商
10. 资产性质
11. 本币单价
12. 数量
13. 计量单位
14. 取得日期
15. 入账日期
该顺序与当前 `text2sql.py` 中已调整后的固资展示顺序保持一致,避免用户体验发生跳变。
---
## 11. 失败处理与运维设计
### 11.1 失败分级
建议把同步失败分为三类:
- 连接失败
- 查询超时
- 落地失败
### 11.2 失败后系统行为
- 不覆盖当前有效快照
- 写入运行日志
- 按重试策略补偿执行
- 达到上限后产生日志告警
### 11.3 运维可见性
建议同步 run 至少记录:
- 开始时间
- 结束时间
- 耗时
- 同步记录数
- 失败原因
- 重试次数
- 最终状态
- 当前生效版本
### 11.4 建议告警
建议增加以下告警场景:
- 当日首次同步失败
- 连续重试 3 次后仍失败
- 快照记录数异常降低
- 生成文件成功但结构化快照失败
---
## 12. 安全与合规建议
- ERP Oracle 账号密码必须从环境变量读取,不应继续写死在业务代码中。
- 固资快照文件默认不进入 Git 管理。
- 导出文件如含敏感资产信息,应控制下载权限与保存周期。
- 聊天态查询仍需走用户权限控制,不因快照本地化而放宽权限。
---
## 13. 实施阶段划分
### 阶段一:方案验证
目标:
- 验证 ERP 固资全量导出 SQL
- 验证 `备注` 字段设计
- 验证快照文件体量
- 验证单次同步耗时
产出:
- 样例快照
- 记录数字段覆盖率
- 导出耗时评估
### 阶段二:同步任务建设
目标:
- 实现 `FixedAssetsSnapshotService`
- 接入定时任务
- 完成超时、重试、版本切换
产出:
- 每天 3 点自动同步能力
- 本地快照文件
- 运行日志
### 阶段三:查询链路切换
目标:
- 新增 `FixedAssetsQueryService`
- 将固资常见查询切到本地快照
- 保留 ERP 实时查询兜底
产出:
- 固资聊天查询默认走本地快照
- 预览分页能力稳定可用
### 阶段四:灰度与收敛
目标:
- 对比快照查询与 ERP 实时查询结果
- 观察稳定性与准确率
- 根据数据决定是否进一步收缩实时 Text2SQL 使用范围
---
## 14. 可执行任务拆解
### 14.1 后端任务
1. 设计固资快照导出 SQL。
2. 抽离 ERP Oracle 连接配置到独立服务。
3. 新增 `FixedAssetsSnapshotService`。
4. 实现快照落地、导出文件与版本切换。
5. 实现超时控制与重试逻辑。
6. 新增 `FixedAssetsQueryService`。
7. 调整固资聊天查询优先查快照。
8. 接入预览与分页查询链路。
9. 增加运行日志与告警字段。
### 14.2 文档与配置任务
1. 补充环境变量文档。
2. 补充固资快照运行手册。
3. 补充调度配置说明。
4. 更新需求文档 / 技术文档 / 功能清单。
### 14.3 测试任务
1. 验证全量同步成功。
2. 验证超时自动中断。
3. 验证 30 分钟间隔重试,最多 3 次。
4. 验证旧版本快照在同步失败时仍可查询。
5. 验证资产编号、资产名称、规格型号、备注模糊查询。
6. 验证结果表与预览全量数据顺序一致。
---
## 15. 验收标准
满足以下条件可判定方案落地成功:
- 每天 03:00 可自动触发固资快照同步。
- 同步结果可生成 `FixedAssets` 导出文件。
- 快照中包含 `备注` 字段,且字段拼接规则稳定。
- 同步任务支持超时中断。
- 超时后按 30 分钟间隔自动重试,最多 3 次。
- 用户查询固资时,系统优先查本地快照。
- 快照查询支持模糊检索与分页预览。
- 同步失败时旧版快照仍可继续服务。
---
## 16. 最终建议
本需求建议按“快照主查 + ERP 兜底”的方案推进,而不是直接演变为“扫 `docs/FixedAssets` 文件备注字段”。
推荐结论如下:
- 可以做定时同步。
- 可以做 `FixedAssets` 导出文件。
- 可以做 `备注` 字段。
- 不能把 `备注` 作为唯一查询入口。
- 不建议把 `docs` 作为运行时主数据目录。
- 建议使用本地结构化快照作为主查询源。
如果进入开发阶段,建议下一步先输出:
- 接口与模块改造清单
- 数据结构定义
- 迁移与灰度计划
- 测试清单
+11
View File
@@ -32,6 +32,17 @@
| --- | --- | --- |
| RoHS 排程检核 | 已实现 | 首个文件检核类型实例,复用通用 file_check 域 |
### 固资管理(ERP / 快照)
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| 固资实时查询规则抽取 | 已实现 | `text2sql.py` 已支持资产编号、资产名称、规格型号、状态、供应厂商等多维查询 |
| 固资快照后台同步 | 已实现 | 每天 03:00 自动从 ERP Oracle 同步全量固资到本地快照 |
| 固资同步超时与重试 | 已实现 | 支持同步超时、30 分钟间隔重试、最多 3 次补偿 |
| 固资备注模糊检索 | 已实现 | 同步时生成 `备注` 与标准化备注,查询时作为结构化条件兜底 |
| 固资本地快照查询 | 已实现 | `固资管理` Agent 优先查询 SQLite 最新快照,减少实时 ERP 压力 |
| 固资导出文件 | 已实现 | 同步成功后生成 `FixedAssets_latest.xlsx`,供人工核查与留档 |
### F-01 本人假期查询
#### 目标
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,948 @@
# HXOPS 前端重构 — 分阶段落地记录(附录)
> 更新时间:2026-06-22
> 适用范围:`frontend/` 目录
> 文档定位:**迁移历史与 Phase 0–6 实施细节**;日常开发与 AI 编码请以 **[frontend_architecture_refactor.md](./frontend_architecture_refactor.md)(总览版)** 为准。
---
## 1. 架构选型
在现有技术栈(Vue 3 + TypeScript + Vite + Vue Router + Vue I18n + TailwindCSS)基础上,采用 **Feature-Module 垂直切分 + Composables 逻辑封装 + Pinia 共享状态** 的组合架构。
**选型理由:**
- 与 Vue 3 Composition API 天然契合,学习成本低
- 业务域清晰(聊天 / 管理后台 / 知识库 / 认证),适合按 feature 垂直拆分
- 相比 FSD(Feature-Sliced Design)目录层级更浅,迁移成本可控
- 相比引入 Element Plus 等 UI 库,可继续沿用现有 Tailwind 设计体系(`tokens.css`、`components-ds.css`)
**保持不变的技术栈:**
| 层级 | 选型 |
|------|------|
| 框架 | Vue 3(Composition API + `<script setup>`)+ TypeScript |
| 构建 | Vite |
| 路由 | Vue Router 4(子路由 + 懒加载) |
| 样式 | TailwindCSS + 现有 Design Tokens |
| 国际化 | Vue I18n(messages 外置并按域拆分) |
| 网络 | `fetch` + `requestJson`(`shared/api/client.ts`)+ SSE(`useChat`) |
| 状态 | **新增 Pinia**(替代 localStorage + CustomEvent 为主的跨页状态) |
---
## 2. 目标目录结构
```text
frontend/src/
├── main.ts # Vite 入口(保留在 src 根,不迁入 app/)
├── App.vue # 根组件(保留在 src 根)
├── app/ # 应用基础设施(路由 / 插件)
│ ├── router/
│ │ ├── index.ts # 汇总各域路由
│ │ ├── guards.ts # 认证 / 权限守卫
│ │ └── routes/ # 按业务域拆分路由表
│ │ ├── auth.routes.ts
│ │ ├── chat.routes.ts
│ │ ├── admin.routes.ts
│ │ ├── workspace.routes.ts
│ │ └── kb.routes.ts
│ └── plugins/
│ └── pinia.ts
│
├── shared/ # 跨域共享(无业务语义)
│ ├── api/
│ │ ├── client.ts # requestJson、BusinessError(权威实现)
│ │ └── types.ts # 通用 API 类型(待补充)
│ ├── types/
│ │ └── schedule.types.ts # admin / workspace 共用排程类型
│ ├── composables/ # useTheme、useIsMobile、useMessage 等
│ ├── components/ # 通用 UI:Dialog、DataTable、EmptyState、Pagination
│ ├── layouts/ # AppShell、ChatShell、MinimalShell、MarketingShell
│ ├── utils/ # auth、clipboard、wecom 等纯工具
│ ├── styles/ # tokens.css、components-ds.css、utilities.css
│ └── constants/
│
├── features/ # 按业务域垂直切分(核心)
│ ├── auth/
│ │ ├── api/
│ │ │ └── user.api.ts
│ │ ├── stores/
│ │ │ └── auth.store.ts
│ │ ├── composables/
│ │ │ └── useAuth.ts
│ │ ├── views/
│ │ │ ├── LoginView.vue
│ │ │ └── ResetPasswordView.vue
│ │ └── components/
│ │
│ ├── workspace/ # AI 工作台(自 auth 拆出,2026-06)
│ │ ├── api/
│ │ │ └── schedule.api.ts # 工作台排程记录
│ │ ├── views/
│ │ │ └── WorkspaceLayout.vue
│ │ ├── pages/ # HomePage、ProfilePage、ScheduleRunsPage 等
│ │ ├── composables/
│ │ └── components/
│ │
│ ├── chat/
│ │ ├── api/
│ │ │ ├── chat.api.ts
│ │ │ └── shipping.api.ts # 货代发货(/api/workspace/shipping-tasks)
│ │ ├── types/
│ │ │ └── chat.types.ts
│ │ ├── stores/
│ │ │ └── chat.store.ts # 会话列表、当前 agent 等
│ │ ├── composables/
│ │ │ ├── useChat.ts # SSE 流式对话(保留并增强)
│ │ │ ├── useChatSessions.ts
│ │ │ └── useSourceFiles.ts # 源文件 / 检索来源逻辑
│ │ ├── page/ # useChatPage 编排子模块(composable,非路由页)
│ │ ├── history/ # 跨 Agent 历史(HistoryPage.vue)
│ │ ├── views/
│ │ │ └── ChatView.vue # 页面编排,目标 < 300 行
│ │ └── components/
│ │ ├── ChatSidebar.vue
│ │ ├── ChatMessageList.vue
│ │ ├── ChatInputBar.vue
│ │ ├── MessageBubble.vue
│ │ ├── SourceFilePanel.vue
│ │ └── AgentSwitcher.vue
│ │
│ ├── admin/
│ │ ├── api/
│ │ │ ├── admin.api.ts
│ │ │ └── schedule.api.ts # 管理后台定时任务
│ │ ├── stores/
│ │ │ └── admin-nav.store.ts
│ │ ├── views/
│ │ │ └── AdminLayout.vue # 壳层 + 侧边栏,子路由出口
│ │ ├── modules/ # 原 AdminView activeModule 各拆独立模块
│ │ │ ├── dashboard/
│ │ │ ├── agents/
│ │ │ ├── users/
│ │ │ ├── departments/
│ │ │ ├── permissions/
│ │ │ ├── requests/
│ │ │ ├── reports/
│ │ │ ├── approvals/
│ │ │ ├── announcements/
│ │ │ ├── questions/
│ │ │ ├── wecom/
│ │ │ ├── schedules/ # types/utils + context + panel/overlays(见 §10.5)
│ │ │ └── knowledge-base/
│ │ └── components/
│ │ └── AdminNav.vue
│ │
│ └── kb/
│ ├── api/
│ │ └── kb.api.ts
│ ├── types/
│ │ └── kb-workspace.types.ts
│ ├── utils/ # 列表/展示/工作流/路径上传纯函数
│ ├── composables/
│ │ ├── useKbWorkspace.ts # 编排入口
│ │ └── kb-workspace/ # state / computed / data / pathUpload / documents / modals
│ ├── views/
│ │ ├── KbWorkspaceView.vue # 作业面主内容壳
│ │ └── components/KbWorkspaceOverlays.vue # 弹窗层
│ └── components/ # 治理面:KbAdminPanel、Dify*Dialog
│
├── locales/ # i18n 按语言 + 业务域拆分
│ ├── zh-CN/
│ │ ├── common.json
│ │ ├── auth.json
│ │ ├── chat.json
│ │ ├── admin.json
│ │ ├── kb.json
│ │ └── errors.json
│ ├── zh-TW/
│ ├── en/
│ ├── th/
│ └── index.ts # 按需加载、合并 messages
│
└── config.ts # 应用级开关(loginMode、admin.modules 等)
```
### 2.1 与现有目录的映射关系
| 现有路径 | 目标路径 | 说明 |
|----------|----------|------|
| `src/main.ts`、`src/App.vue` | **保留 `src/` 根目录** | Vite 入口约定;不迁入 `app/` |
| `src/router/index.ts` | `app/router/` | 路由表与守卫拆分 |
| `src/api/client.ts` | `shared/api/client.ts` | 权威实现;`src/api/client.ts` deprecated 转发 |
| `src/api/*.ts` | `features/*/api/` | 按业务域归属(KB 已迁入,见 §16) |
| `src/composables/`(通用) | `shared/composables/` | useTheme、useMessage 等 |
| `src/composables/useChat.ts` | `features/chat/composables/` | 聊天域专属 |
| `src/components/`(通用 Dialog 等) | `shared/components/` | 跨域复用 UI |
| `src/components/kb/` | `features/kb/components/` | ✅ 已迁入(2026-06-11) |
| `src/layouts/` | `shared/layouts/` | 页面壳层 |
| `src/utils/` | `shared/utils/` | 纯工具函数 |
| `src/styles/` | `shared/styles/` | 设计 token 与全局样式 |
| `src/views/AdminView.vue` | `features/admin/modules/*/` | 拆为 12+ 子模块页面 |
| `src/views/ChatView.vue` | `features/chat/` | View + 多个子组件 |
| `src/views/WorkspaceView.vue` | `features/workspace/` + `features/auth/views/LoginView.vue` | 登录与工作台分离 |
| `src/i18n.ts` | `locales/` | 按语言、域拆分 JSON |
---
## 3. 分层职责
各层职责边界如下,**上层可依赖下层,下层不得反向依赖上层**。
```mermaid
flowchart TB
subgraph Views["Views(页面编排层)"]
V1["布局组合、路由参数解析、模块装配"]
end
subgraph Components["Components(展示层)"]
C1["纯 UI:props / emits,不直接调用 API"]
end
subgraph Composables["Composables(逻辑层)"]
CO1["SSE 流、表单、分页、副作用封装"]
end
subgraph Stores["Pinia Stores(共享状态层)"]
S1["跨组件 / 跨页面需共享的可变状态"]
end
subgraph API["API Layer(数据访问层)"]
A1["requestJson 封装 + 领域 API 函数"]
end
Views --> Components
Views --> Composables
Composables --> Stores
Composables --> API
Stores --> API
Components --> Composables
```
### 3.1 Views(页面编排层)
- **职责**:路由入口、Layout 组合、将 composable / store 的数据传给子组件
- **约束**:单个 View 文件目标 **< 300 行**;不写复杂业务算法、不直接写大段 `fetch`
- **示例**:`ChatView.vue` 只负责组装 `ChatSidebar` + `ChatMessageList` + `ChatInputBar`
### 3.2 Components(展示层)
- **职责**:可复用的 UI 单元,通过 `props` / `emits` 与外部通信
- **约束**:不直接 import 领域 API;需要数据时由父组件或 composable 注入
- **划分**:
- `shared/components/`:Dialog、DataTable、EmptyState 等无业务语义组件
- `features/*/components/`:MessageBubble、AdminNav 等领域组件
### 3.3 Composables(逻辑层)
- **职责**:封装可复用的响应式逻辑、副作用(SSE、语音识别、会话管理)
- **约束**:可调用 API 与 Store;返回 ref / computed / 方法供 View / Component 使用
- **示例**:
- `useChat`:SSE 流式对话(保留现有实现,增强类型)
- `useChatSessions`:会话 CRUD
- `useSourceFiles`:从 ChatView 抽出的源文件 / 检索来源解析
### 3.4 Pinia Stores(共享状态层)
- **职责**:跨页面、跨组件需共享且需响应式更新的状态
- **约束**:Store 可调用 API;View 优先通过 composable 访问 Store,避免在模板中散落 store 调用
| Store | 文件 | 职责 |
|-------|------|------|
| `useAuthStore` | `features/auth/stores/auth.store.ts` | 当前用户、token、login / logout、角色 |
| `useChatStore` | `features/chat/stores/chat.store.ts` | 当前 agent、会话列表、侧边栏折叠状态 |
| `useAppStore` | `app/stores/app.store.ts`(可选) | 全局 locale、theme 同步 |
| `useAdminNavStore` | `features/admin/stores/admin-nav.store.ts` | 当前 admin 模块、报表 tab |
### 3.5 API Layer(数据访问层)
- **职责**:所有 HTTP 请求的统一出口;类型定义与后端契约对齐
- **约束**:
- 仅 `shared/api/client.ts` 处理 envelope 解析与 `BusinessError`
- 领域 API 文件只做 URL 组装与类型标注,不写 UI 逻辑
- **示例**:`features/chat/api/chat.api.ts` 迁移自现有 `src/api/chat.ts`
---
## 4. 各 Feature 模块说明
### 4.1 auth(认证 / 工作台)
| 项 | 说明 |
|----|------|
| 路由 | `/`、`/workspace`、`/casdoor-callback`、`/reset-password` |
| 核心 Store | `authStore`:替代 `utils/auth.ts` 的直接读写 + `hxops:logout` 事件 |
| 页面 | `WorkspaceView`(登录、Agent 列表)、`ResetPasswordView` |
| 迁移来源 | `views/WorkspaceView.vue`、`views/ResetPasswordView.vue`、`utils/auth.ts` |
### 4.2 chat(对话)
| 项 | 说明 |
|----|------|
| 路由 | `/chat/:agentId` |
| 核心 Composable | `useChat`(SSE)、`useChatSessions`、`useSourceFiles` |
| 核心 Store | `chatStore`:当前 agent、会话列表缓存 |
| 组件拆分 | Sidebar / MessageList / InputBar / MessageBubble / SourceFilePanel / AgentSwitcher |
| 迁移来源 | `views/ChatView.vue`(~3400 行)、`composables/useChat.ts` |
### 4.3 admin(管理后台)
| 项 | 说明 |
|----|------|
| 路由 | `/admin/*` 子路由(替代 `?module=xxx` query) |
| 布局 | `AdminLayout.vue`:左侧 `AdminNav` + `<router-view>` |
| 子模块 | 与 `config.admin.modules` 一一对应,每个 module 独立页面 |
| 懒加载 | 各 module 使用 `() => import(...)`,减小首屏体积 |
| 迁移来源 | `views/AdminView.vue`(~6000 行)、`api/admin.ts`、`api/schedule.ts` |
**Admin 子路由示例:**
```typescript
// app/router/routes/admin.routes.ts
{
path: '/admin',
component: () => import('@/features/admin/views/AdminLayout.vue'),
meta: { requiresAdmin: true },
children: [
{ path: '', redirect: '/admin/dashboard' },
{ path: 'dashboard', component: () => import('@/features/admin/modules/dashboard/DashboardPage.vue') },
{ path: 'agents', component: () => import('@/features/admin/modules/agents/AgentsPage.vue') },
{ path: 'users', component: () => import('@/features/admin/modules/users/UsersPage.vue') },
{ path: 'reports/:table?', component: () => import('@/features/admin/modules/reports/ReportsPage.vue') },
{ path: 'knowledge-base', component: () => import('@/features/admin/modules/knowledge-base/KbAdminPage.vue') },
// ... 其余 module
],
}
```
**兼容旧 URL:** `/admin?module=users` → redirect 至 `/admin/users`
### 4.4 kb(知识库)
**职责拆分(治理面 vs 作业面):**
| 入口 | 路由 | 组件 | 职责 |
|------|------|------|------|
| 管理控制台 | `/admin/knowledge-base` | `KbAdminPanel` | 分组 CRUD、Dify 配置、健康检查、任务队列 |
| 工作台 | `/workspace/knowledge-base` | `KbWorkspaceView`(`embedded`) | 只读选分组 → 文档上传/清洗/同步 |
| 兼容 | `/kb/workspace` → `/workspace/knowledge-base` | redirect | 旧书签 |
| 兼容 | `/kb/admin` → `/admin/knowledge-base` | redirect | 旧书签 |
| 项 | 说明 |
|----|------|
| API | `features/kb/api/kb.api.ts`(`src/api/kb.ts` 已删除) |
| 作业面编排 | `useKbWorkspace` + `kb-workspace/*` 子 composable |
| 权限 | `hasKnowledgeBaseAccess` / 作业面批量操作:`role === 'admin'` |
| i18n | `locales/{en,zh-CN,zh-TW,th}/kb.json` |
| 迁移来源 | 原 `views/KbWorkspaceView.vue`(~3000 行 monolith) |
详见 §16。
---
## 5. 共享层(shared)沉淀清单
在重构过程中,以下组件建议优先沉淀到 `shared/components/`,供 admin、chat、kb 共用:
| 组件 | 用途 | 现状 |
|------|------|------|
| `ConfirmDialog` | 删除 / 操作确认 | 现有 `DeleteConfirmDialog.vue` |
| `LevelMessageDialog` | 全局消息弹窗 | 现有,经 `useGlobalMessageDialog` 调用 |
| `DataTable` | 管理后台表格 + 分页 | AdminView 内大量重复表格结构 |
| `FormField` | 统一表单字段样式 | 分散在各 View |
| `Pagination` | 分页控件 | 分散在 AdminView |
| `EmptyState` | 空数据占位 | 分散实现 |
| `LoadingOverlay` | 加载遮罩 | 分散实现 |
样式继续沿用 `shared/styles/tokens.css` 与 `components-ds.css`,**不引入 Element Plus / Naive UI 等重型 UI 库**。
---
## 6. 路径别名与 import 规范
建议在 `vite.config.ts` / `tsconfig.json` 中配置:
```typescript
// vite.config.ts
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
```
**import 规则:**
```text
features/chat/views/ChatView.vue
✅ import { useChat } from '../composables/useChat'
✅ import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'
✅ import { listChatSessions } from '../api/chat.api'
❌ import { listAdminUsers } from '@/features/admin/api/admin.api' // 跨 feature 禁止
```
跨 feature 通信通过:**路由跳转**、**shared 层工具**、或 **Pinia store**(仅全局态如 auth),避免 feature 之间直接 import 页面或 API。
---
## 7. Phase 0 落地说明(已实现)
Phase 0 目标:搭好基础设施,**不迁移现有 views**,旧代码可继续运行。
### 7.1 已完成项
| 项 | 路径 / 说明 |
|----|-------------|
| Pinia | `pinia@^3`,`app/plugins/pinia.ts` |
| `@/` 别名 | `vite.config.ts`、`tsconfig.app.json` |
| 路由拆分 | `app/router/routes/{auth,chat,admin,kb}.routes.ts` |
| 路由守卫 | `app/router/guards.ts`(`setupRouterGuards`) |
| Auth Store | `features/auth/stores/auth.store.ts` |
| Auth Composable | `features/auth/composables/useAuth.ts` |
| Chat Store 骨架 | `features/chat/stores/chat.store.ts` |
| API 转发层 | `shared/api/client.ts` 为权威实现;`src/api/client.ts` deprecated 转发 |
| 路由常量 | `shared/constants/routes.ts` |
| 兼容入口 | `router/index.ts` re-export `app/router` |
### 7.2 启动顺序(`src/main.ts`)
> **约定**:`main.ts` / `App.vue` 留在 `src/` 根目录,与 Vite `index.html` 入口一致;`app/` 仅放 router、plugins 等可拆分的基础设施。
```typescript
app.use(pinia);
bindAuthStoreSync(); // Store 与 utils/auth 跨标签同步
app.use(router);
app.use(i18n);
```
### 7.3 新代码用法
```typescript
// 认证(新代码优先)
import { useAuth } from '@/features/auth';
const { user, isLoggedIn, login, logout } = useAuth();
// 或直接使用 Store
import { useAuthStore } from '@/features/auth/stores/auth.store';
```
### 7.4 兼容策略
- 旧代码仍可使用 `utils/auth` 的 `getStoredAuthUser` / `saveAuthUser`
- 路由守卫在每次导航前调用 `auth.syncFromStorage()`,保证 Store 与 storage 一致
- `utils/auth` 的 `logoutAuth` 触发 `hxops:logout` 后,Store 自动清空 `user`
### 7.5 下一步
Phase 1 已完成,见 §8。
---
## 8. Phase 1 落地说明(已实现,后续全量拆分见 §9)
Phase 1 目标:管理后台嵌套子路由 + 首个独立模块 `agents`。
### 8.1 路由结构(初版)
| URL | 组件 | 说明 |
|-----|------|------|
| `/admin` | redirect → `/admin/dashboard` | |
| `/admin/agents` | `AgentsPage.vue` | **首个独立拆分** |
| `/admin/dashboard` 等 | `AdminLegacyPage.vue` | 内嵌 `AdminView`(content-only,已移除) |
| `/admin?module=xxx` | redirect | 兼容旧链接,跳转至 `/admin/xxx` |
> **2026-06 更新**:全部 admin 子模块已独立,见 §9。
### 8.2 初版新增文件
```text
features/admin/
├── views/AdminLayout.vue
├── modules/agents/ ...
├── stores/admin-nav.store.ts
└── ...
```
### 8.3 构建验证
`npm run build` 通过。
### 8.4 下一步
Admin 全量拆分 → §9;Chat 拆分 → §10。
---
## 9. Phase 1.5 Admin 全量拆分(已实现)
Phase 1.5 目标:移除 `AdminView.vue` / `AdminLegacyPage.vue`,全部 `config.admin.modules` 对应独立页面。
### 9.1 路由结构
| URL | 组件 |
|-----|------|
| `/admin/dashboard` | `DashboardPage.vue` |
| `/admin/agents` | `AgentsPage.vue` |
| `/admin/users` | `UsersPage.vue` |
| `/admin/departments` | `DepartmentsPage.vue` |
| `/admin/permissions` | `PermissionsPage.vue` |
| `/admin/requests` | `RequestsPage.vue` |
| `/admin/approvals` | `ApprovalsPage.vue` |
| `/admin/announcements` | `AnnouncementsPage.vue` |
| `/admin/questions` | `QuestionsPage.vue` |
| `/admin/wecom` | `WecomPage.vue` |
| `/admin/schedules` | `SchedulesPage.vue` |
| `/admin/knowledge-base` | `KnowledgeBasePage.vue` |
| `/admin/platform-apps` | `PlatformAppsPage.vue` |
| `/admin/reports/:table?` | `ReportsPage.vue` |
### 9.2 模块目录
```text
features/admin/modules/
├── dashboard/ ├── agents/ ├── users/
├── departments/ ├── permissions/ ├── requests/
├── approvals/ ├── announcements/├── questions/
├── wecom/ ├── schedules/ ├── knowledge-base/
├── platform-apps/ └── reports/
└── composables/use*Admin.ts + components/
```
**schedules/**(2026-06 瘦身,详见 §10.5):`SchedulesPage.vue` 薄壳 + `useSchedulesAdmin` + `schedule-admin/*` + `schedules.context` + 6 个子组件(Header / Overview / Workbench / Overlays / TestRun / CreateEdit)。
### 9.3 构建验证
`npm run build` 通过;`AdminView.vue` 已删除。
---
## 10. Phase 2 Chat 域落地说明(已实现)
Phase 2 Chat 目标:将原 `views/ChatView.vue`(~5500 行)拆为 feature 模块,页面壳层 < 50 行。
### 10.1 已完成项
| 项 | 路径 / 说明 |
|----|-------------|
| 页面壳层 | `features/chat/views/ChatView.vue`(~19 行:`useChatPage()` + `provide` + `ChatViewContent` / `ChatViewOverlays`) |
| 主编排 | `composables/useChatPage.ts`(~400 行,组合 `page/*` 子模块与各域 composable) |
| 页面子模块 | `features/chat/page/*`:用户、本地消息、弹窗、语音、Markdown、会话、发送、handlers 打包 |
| 出货子模块 | `features/chat/shipping/*`:纯函数 + `useChatShippingRefresh` / Menu / Upload / Send handler 工厂;`useChatShipping.ts` ~360 行 |
| 请假子模块 | `features/chat/leave/*`:意图解析、OA 登录、代理人选择、表单提交、流程拦截;`useChatLeave.ts` ~130 行 |
| 子 composable | `useChatAgent`、`useChatAttachments`、`useChatRouteSync`、`useChatBrowserPanel`、`useChatQueryPreview`、`useChatGuides`、`useChatScroll` 等 |
| 子组件 | `ChatSidebar`、`ChatMessageList`、`ChatInputBar`、`ChatMessageBubble`、`ChatViewContent`、`ChatViewOverlays`、弹窗等 |
| 路由 lazy | `app/router/routes/chat.routes.ts` → `features/chat/views/ChatView.vue` |
| API | `features/chat/api/chat.api.ts`(`src/api/chat.ts` deprecated 转发) |
| 货代 API | `features/chat/api/shipping.api.ts`(`src/api/shippingNotice.ts` deprecated 转发) |
| 跨 Agent 历史 | `features/chat/history/HistoryPage.vue` + `useChatHistory` |
| Pinia 接入 | `chat.store`:`currentAgentId`(路由同步)、`sidebarCollapsed`、`sessionHistoryByAgent` 缓存 |
| 内置浏览器 | 输入栏「打开/收起浏览器」按钮已恢复,逻辑在 `useChatBrowserPanel` |
| provide/inject | `chat.context.ts`:`CHAT_PAGE_KEY` + `useChatPageContext()`;`reactive(useChatPage())` 解包嵌套 Ref;`markRaw` 保留 template ref holder |
### 10.2 构建验证
历次拆分后 `npm run build` 通过。
### 10.3 待办(Chat 域内)
| 优先级 | 项 | 状态 |
|--------|-----|------|
| 中 | `chat.context` + provide/inject(`ChatViewContent` / `ChatViewOverlays` inject) | ✅ |
| 中 | `ChatViewOverlays.vue` 抽出全部弹窗 | ✅ |
| 中 | `chat.store` 按 Agent 缓存侧栏会话列表 | ✅ |
| 中 | 瘦身 `useChatPage` → `page/*` 子模块 | ✅ |
| 中 | 瘦身 `useChatShipping` → `shipping/*` 子模块 | ✅ |
| 中 | 瘦身 `useChatLeave` → `leave/*` 子模块 | ✅ |
| 低 | `LeaveAgentOption` 等类型已统一至 `leave.types.ts` 并 re-export | ✅ |
| 低 | `chat.context` 完善类型(`ChatPageContextProvided` + `useChatPageContext()`) | ✅ |
| 低 | `shipping/*`、`leave/*` 纯函数单元测试 | 待做 |
### 10.4 下一步
- ~~Admin 模块独立~~ → 见 §9
- Workspace 壳层 → 见 §11
- ~~API 按 feature 归属~~ → 见 §12
- ~~`shared/` composables/components/layouts/utils/styles 迁移~~ → 见 §14
- ~~KB 域收口~~ → 见 §16
- ~~`locales/` 按域拆分~~ → 见 §15.2
### 10.5 Admin Schedules 模块瘦身(2026-06,已实现)
参照 KB 作业面模式,将原 `SchedulesPage.vue`(~1200 行)与 `useSchedulesAdmin.ts`(~1100 行)拆为薄壳 + provide/inject 子组件。
| 项 | 路径 / 约行数 |
|----|---------------|
| 页面壳层 | `SchedulesPage.vue`(~26 行:`reactive(useSchedulesAdmin())` + `provide` + 4 子组件) |
| 编排入口 | `composables/useSchedulesAdmin.ts`(~28 行,组合子模块) |
| 子 composable | `composables/schedule-admin/`:`state`(~145)、`useScheduleAdminLookups`(~40)、`useScheduleAdminList`(~124)、`useScheduleAdminRuns`(~196)、`useScheduleAdminForm`(~329)、`useScheduleAdminTestRun`(~95) |
| provide/inject | `composables/schedules.context.ts`(~26 行) |
| 类型与默认工厂 | `types/schedule-admin.types.ts`(~127 行) |
| 纯函数 | `utils/schedule-cron.utils.ts`、`utils/schedule-format.utils.ts`、`utils/schedule-form-payload.utils.ts` |
| 子组件 | `SchedulePageHeader`(~44)、`ScheduleOverviewPanel`(~146)、`ScheduleWorkbenchPanel`(~329)、`SchedulesPageOverlays`(~24)、`ScheduleTestRunDialog`(~175)、`ScheduleCreateEditModal`(~525) |
子 panel / overlays 通过 `useSchedulesAdminContext()` inject,无 props 透传。`npm run build` 通过。
**i18n(2026-06)**:`ScheduleCreateEditModal`、`ScheduleTestRunDialog`、`ScheduleWorkbenchPanel`(Dify 快照区)硬编码中文已外置至 `locales/*/admin.json`(`schedule.form.*`、`schedule.difySnapshot.*`、`schedule.testRun.*`);合并脚本 `frontend/scripts/merge-schedule-form-i18n.mjs`。顺带修复创建按钮误用 `admin.schedule.form.admin.createSchedule` 键。
---
## 11. Phase 3 Workspace 模块(已实现)
Phase 3 目标:将原 `WorkspaceView.vue` 拆为独立 feature,路由 `/workspace/*`。
### 11.1 已完成项
| 项 | 路径 / 说明 |
|----|-------------|
| 布局壳 | `features/workspace/views/WorkspaceLayout.vue` + `provide/inject` |
| 子页面 | `HomePage`(应用管理)、`ProfilePage`、`ScheduleRunsPage`、`FeedbackPage` |
| 路由 | `app/router/routes/workspace.routes.ts` |
| Composable | `useWorkspace`、`useWorkspaceHome`、`useWorkspaceNavigation` 等 |
| 排程 API | `features/workspace/api/schedule.api.ts` |
| 历史页 | 复用 `features/chat/history/HistoryPage.vue` |
### 11.2 薄包装页
| 页面 | 现状 |
|------|------|
| `KnowledgeBasePage.vue` | ✅ 嵌入 `features/kb/views/KbWorkspaceView.vue`(`embedded`) |
| `ShippingNoticePage.vue` | ✅ 嵌入 `features/workspace/views/ShippingNoticeView.vue`(`embedded`) |
### 11.3 路由
```text
/workspace/applications → HomePage
/workspace/profile → ProfilePage
/workspace/schedule-runs → ScheduleRunsPage
/workspace/shipping-notice → ShippingNoticePage(嵌入 ShippingNoticeView)
/workspace/knowledge-base → KnowledgeBasePage(legacy 嵌入)
/workspace/history → chat/history/HistoryPage
```
---
## 12. Phase 4 API 按 Feature 归属(已实现)
Phase 4 目标:领域 HTTP 请求迁入对应 `features/*/api/`,`shared/api/client.ts` 作为唯一 JSON 客户端。
### 12.1 迁移对照
| 原路径 | 新路径 | 状态 |
|--------|--------|------|
| `src/api/client.ts` | `shared/api/client.ts` | ✅ 权威实现;旧路径 deprecated 转发 |
| `src/api/user.ts` | `features/auth/api/user.api.ts` | ✅(Phase 0 已完成) |
| `src/api/chat.ts` | `features/chat/api/chat.api.ts` | ✅(Phase 2 已完成) |
| `src/api/admin.ts` | `features/admin/api/admin.api.ts` | ✅ |
| `src/api/schedule.ts`(admin 部分) | `features/admin/api/schedule.api.ts` | ✅ |
| `src/api/schedule.ts`(workspace 部分) | `features/workspace/api/schedule.api.ts` | ✅ |
| 排程共用类型 | `shared/types/schedule.types.ts` | ✅ |
| `src/api/shippingNotice.ts` | `features/chat/api/shipping.api.ts` | ✅ |
| 货代类型 | `features/chat/types/shipping.api.types.ts` | ✅ |
| `src/api/toolRunProgress.ts` | `features/chat/api/toolRunProgress.api.ts` | ✅ |
| 工具进度类型 | `features/chat/types/tool-run-progress.types.ts` | ✅ |
| `src/api/kb.ts` | `features/kb/api/kb.api.ts` | ✅(deprecated 转发已删除) |
### 12.2 新代码 import 规范
```typescript
// 共享 HTTP 客户端
import { requestJson, BusinessError } from '@/shared/api/client';
// 各域 API
import { listAdminUsers } from '@/features/admin/api/admin.api';
import { listAdminSchedules } from '@/features/admin/api/schedule.api';
import { listWorkspaceScheduleRuns } from '@/features/workspace/api/schedule.api';
import { listChatSessions } from '@/features/chat/api/chat.api';
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
import { getUserProfile } from '@/features/auth/api/user.api';
import { getKbGroupsSafe } from '@/features/kb/api/kb.api';
```
或通过 feature 入口 re-export:
```typescript
import { listAdminUsers } from '@/features/admin';
import { listWorkspaceScheduleRuns } from '@/features/workspace';
import { getWorkspaceShippingTask } from '@/features/chat';
```
### 12.3 兼容策略
- ~~`src/api/{client,admin,schedule,shippingNotice,chat,user,toolRunProgress,kb}.ts` deprecated 转发~~ → **已全部删除**(2026-06-11)
- **`src/api/` 目录已清空**;新代码必须使用 `@/features/*/api/*` 或 `@/shared/api/client`
### 12.4 构建验证
迁移后 `npm run build` 须通过。
### 12.5 下一步
- ~~KB API 迁入 `features/kb/api/kb.api.ts`~~ → 已完成(见 §16)
- ~~清理 deprecated `src/api/*` 转发~~ → 已完成(`src/api/` 已清空)
- `locales/` 按域拆分 → 见 §15
---
## 14. Phase 5 Shared 共享层迁移(已实现)
Phase 5 目标:将原 `src/` 根目录下的跨域代码迁入 `src/shared/`,与 `features/` 划清边界。
### 14.1 迁移对照
| 原路径 | 新路径 | 状态 |
|--------|--------|------|
| `src/composables/*` | `shared/composables/*` | ✅ |
| `src/components/*` | `shared/components/*` | ✅(`kb/` 已迁 `features/kb/components/`) |
| `src/layouts/*` | `shared/layouts/*` | ✅ |
| `src/utils/*` | `shared/utils/*` | ✅ |
| `src/styles/*` | `shared/styles/*` | ✅ |
| `style.css` 引用 | `@import './shared/styles/...'` | ✅ |
### 14.2 目录结构
```text
shared/
├── index.ts # 统一导出入口
├── api/client.ts
├── composables/ # useTheme、useMessage、useIsMobile 等
├── components/ # Dialog、LocaleToggle 等(无 kb 子目录)
├── layouts/ # AppShell、ChatShell、MarketingShell 等
├── utils/ # auth、clipboard、wecom 等
├── styles/ # tokens.css、components-ds.css、utilities.css
├── constants/routes.ts
└── types/ # auth.types、schedule.types
```
### 14.3 新代码 import 规范
```typescript
import { useTheme, useMessage } from '@/shared/composables/useTheme';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import ChatShell from '@/shared/layouts/ChatShell.vue';
import { getAuthHeaders } from '@/shared/utils/auth';
// 或按需从入口导入
import { useTheme, requestJson } from '@/shared';
```
### 14.4 兼容策略
- ~~`src/composables/`、`src/utils/`、`src/styles/` deprecated 转发~~ → **已删除**(2026-06-11)
- `src/components/`、`src/layouts/` **已删除**(全仓 import 已切换)
- **新代码必须使用 `@/shared/*` 路径**
- ~~`shared/components/kb/*`~~ → 已迁入 `features/kb/components/`
### 14.5 构建验证
迁移后 `npm run build` 须通过。
### 14.6 下一步
- ~~KB 组件/API 迁入 `features/kb/`~~ → 已完成(见 §16)
- ~~清理 deprecated 转发~~ → 已完成
- `locales/` 按域拆分 → 见 §15
---
## 15. 架构对齐清理清单
> 目标:与 Vite/Vue 默认约定及本文档目标结构对齐。
> 状态更新时间:2026-06-11
### 15.1 已完成 ✅
| 项 | 说明 |
|----|------|
| 删除 `src/composables/` | 7 个 deprecated 转发已移除 |
| 删除 `src/utils/` | 6 个 deprecated 转发已移除 |
| 删除 `src/styles/` | 3 个 CSS 转发已移除 |
| 删除 `src/api/*` | 全部转发已移除,`src/api/` 目录已清空 |
| 移除 `axios` 依赖 | 代码未使用,已从 `package.json` 删除 |
| `main.ts` / `App.vue` | 保留在 `src/` 根(见 §7.2 约定) |
### 15.2 i18n 按域拆分(已完成)
**现状**:`src/i18n.ts` 仅保留 `createI18n` 注册与空 locale 骨架;**全部** messages 均已外置 JSON。
**已完成 ✅**
| 域 | 路径 |
|----|------|
| `errors` | `locales/{en,zh-CN,zh-TW,th}/errors.json` |
| `auth` | `locales/{en,zh-CN,zh-TW,th}/auth.json`(展平合并:`login.*` 等) |
| `workspace` | `locales/{en,zh-CN,zh-TW,th}/workspace.json` |
| `chat` | `locales/{en,zh-CN,zh-TW,th}/chat.json` |
| `admin` | `locales/{en,zh-CN,zh-TW,th}/admin.json` |
| `kb` | `locales/{en,zh-CN,zh-TW,th}/kb.json`(展平合并:`kbDifySettings.*` 等) |
| `common` / `scheduleRuns` / `filePreview` / `profile` / `feedback` / `theme` | 同上四语言 JSON |
| 合并入口 | `locales/index.ts` → `mergeExternalLocales()` |
`i18n.ts` 在 `createI18n` 前调用 `mergeExternalLocales(messages)`,四语言外置域与拆分前行为一致。
**目标结构**(已达成):
```text
src/locales/
├── index.ts # mergeExternalLocales + 导出
├── zh-CN/ zh-TW/ en/ th/
│ ├── errors.json
│ ├── auth.json
│ ├── workspace.json
│ ├── chat.json
│ ├── admin.json
│ ├── kb.json
│ ├── common.json
│ ├── scheduleRuns.json
│ ├── filePreview.json
│ ├── profile.json
│ ├── feedback.json
│ └── theme.json
```
**迁移步骤**(均已完成):
1. ~~拆 `errors.*` → `errors.json`~~ ✅
2. ~~拆 `auth.*` → `auth.json`~~ ✅
3. ~~拆 `workspace.*` → `workspace.json`~~ ✅
4. ~~拆 `chat.*` → `chat.json`~~ ✅
5. ~~拆 `admin.*` → `admin.json`~~ ✅
6. ~~拆 `kb.*` → `kb.json`(四语言)~~ ✅
7. ~~拆共享域 `common` / `scheduleRuns` / `filePreview` / `profile` / `feedback` / `theme`~~ ✅
8. 每步 `npm run build` + 四语言 spot check
9. `i18n.ts` 仅保留 `createI18n` 注册与 locale 骨架
**注意**:AGENTS.md 要求四语言同步;拆分时用脚本或 CI 校验 key 对齐。
### 15.3 清理 `src/views/`(已完成 ✅)
| 文件 | 状态 |
|------|------|
| ~~`KbWorkspaceView.vue`~~ | ✅ 已迁入 `features/kb/views/`(见 §16) |
| ~~`ShippingNoticeView.vue`~~ | ✅ 已迁入 `features/workspace/views/` |
`src/views/`、`src/api/` 空目录已删除。
### 15.4 deprecated 遗留清理(已完成 ✅)
| 项 | 状态 |
|----|------|
| `shared/components/kb/*` | 已删除(canonical:`features/kb/components/*`) |
| `shared/composables/useChat.ts` | 已删除(canonical:`features/chat/composables/useChat`) |
| `features/workspace/pages/HistoryPage.vue` | 已删除(canonical:`chat/history/HistoryPage`) |
| `features/workspace/composables/useWorkspaceHistory.ts` | 已删除 |
| `src/api/toolRunProgress.ts` | 已迁入 `features/chat/api/toolRunProgress.api.ts` |
| `src/api/kb.ts` | 已删除 |
### 15.5 KB 域收口(已实现,见 §16)
- ~~`src/api/kb.ts` → `features/kb/api/kb.api.ts`~~ ✅
- ~~`shared/components/kb/*` → `features/kb/components/*`~~ ✅
- ~~路由收敛:`/kb/workspace` redirect → `/workspace/knowledge-base`~~ ✅
- ~~作业面 monolith 拆分:`useKbWorkspace` + `kb-workspace/*`~~ ✅
### 15.6 可选优化(非必须)
| 项 | 说明 |
|----|------|
| ~~`index.html` `lang="zh-CN"`~~ | ✅ |
| ~~`App.vue` 文件头注释~~ | ✅ |
| `frontend/.env.development` | 若需纯前端多环境 API 地址,再用 `VITE_*` |
| Vite 8 beta → stable | 关注正式版发布后升级 |
### 15.7 推荐执行顺序
```text
✅ Phase A:删 deprecated 转发 + 去 axios
✅ Phase B:i18n 拆 locales/(errors → auth → workspace → chat → admin → kb)
✅ Phase C:ShippingNoticeView 迁入 workspace
✅ Phase E:API 遗留清理 + deprecated 文件删除 + i18n 共享域外置
```
---
## 16. Phase 6 KB 域落地说明(已实现)
Phase 6 目标:知识库从 monolith 迁入 `features/kb/`,治理面与作业面职责分离,作业面逻辑 composable 化。
### 16.1 职责与路由
| 面 | Canonical 路由 | 组件 | 说明 |
|----|----------------|------|------|
| 治理面 | `/admin/knowledge-base` | `KbAdminPanel` | 分组 CRUD、Dify 设置、健康检查、任务队列 |
| 作业面 | `/workspace/knowledge-base` | `KbWorkspaceView`(`embedded`) | 选分组 → 文档上传/清洗/同步(无分组 CRUD) |
| 兼容 | `/kb/workspace` | redirect | → `/workspace/knowledge-base` |
| 兼容 | `/kb/admin` | redirect | → `/admin/knowledge-base` |
权限:`hasKnowledgeBaseAccess`(工作台入口)与作业面批量操作均收敛为 `role === 'admin'`。
### 16.2 目录结构
```text
features/kb/
├── api/kb.api.ts
├── types/kb-workspace.types.ts
├── utils/
│ ├── kb-list.utils.ts
│ ├── kb-display.utils.ts
│ ├── kb-workflow.utils.ts
│ └── kb-path-upload.utils.ts
├── composables/
│ ├── useKbWorkspace.ts # 编排入口(~160 行)
│ └── kb-workspace/
│ ├── kb-workspace.state.ts # 共享 ref + 删除确认
│ ├── kb-workspace.bridge.ts # pathUpload ↔ data 延迟绑定
│ ├── useKbWorkspaceComputed.ts
│ ├── useKbWorkspaceData.ts
│ ├── useKbWorkspacePathUpload.ts
│ ├── useKbWorkspaceDocuments.ts
│ └── useKbWorkspaceModals.ts
├── views/KbWorkspaceView.vue # 主内容壳(~550 行)
├── components/KbWorkspaceOverlays.vue # 弹窗层(~635 行)
└── components/
├── KbAdminPanel.vue
├── DifySettingsDialog.vue
└── DifyHealthDialog.vue
```
### 16.3 已完成项
| 项 | 说明 |
|----|------|
| API 迁入 | `features/kb/api/kb.api.ts`(`src/api/kb.ts` 已删除) |
| 组件迁入 | `KbAdminPanel`、`DifySettingsDialog`、`DifyHealthDialog` |
| 作业面拆分 | 类型/纯函数 utils + `useKbWorkspace` 子 composable |
| 视图薄壳 | `KbWorkspaceView.vue` script 仅 `useKbWorkspace({ embedded })` |
| 工作台嵌入 | `workspace/pages/KnowledgeBasePage.vue` → `KbWorkspaceView` |
| i18n | `locales/*/kb.json` 四语言外置 |
| 路由收敛 | `app/router/routes/kb.routes.ts` 仅保留 redirect |
### 16.4 构建验证
拆分后 `npm run build` 通过。
### 16.5 待办(KB 域内,优先级低)
| 项 | 说明 |
|----|------|
| 作业面 View 继续瘦身 | ✅ 弹窗已抽至 `KbWorkspaceOverlays.vue`(View ~550 行 → 主内容壳;Overlays ~620 行);文档列表区可继续拆 panel |
| 作业面 i18n 全覆盖 | ✅ 模板 + utils/composable 运行时文案已迁入 `kb.json`(`kbWorkspace.*` 四语言);`kb.api.ts` 错误 fallback 仍为中文(低优先级) |
| 删除 `src/api/kb.ts` | ✅ 全仓已无 `@/api/kb` import,deprecated 转发已移除 |
### 16.6 下一步(全项目)
- ~~`ShippingNoticeView` 迁入 workspace~~ → §15.3 ✅
- Chat / admin 域内低优先级待办 → §10.3
---
---
## 相关文档
- **[前端架构规范(总览版)](./frontend_architecture_refactor.md)** — 日常开发与 AI 编码权威入口
- [项目上下文与技术栈](../project_context.md)
- [UI 设计系统](../ui/DESIGN_SYSTEM.md)
- [UI 编码规范](../ui/UI_CODING_GUIDELINES.md)
- [后端重构架构方案](./backend_architecture_refactor.md)
+18
View File
@@ -40,6 +40,14 @@
- 已有最小 worker 轮询模式
- 可复用于“请假状态同步”任务
### 2.x 已有固资查询与快照演进能力
- `backend/app/services/text2sql.py` 已具备固资管理专用规则抽取、字段映射、结果预览与分页能力。
- 新增 `backend/app/services/fixed_assets_snapshot.py` 后,可承接“ERP 固资全量同步 -> SQLite 本地快照 -> Excel 导出 -> 聊天查询优先走快照”的闭环。
- 后端应用启动时可拉起固定资产快照后台线程,按配置在 `Asia/Shanghai` 时区每天 03:00 执行同步任务。
- 同步结果默认落到 `backend/data/fixed_assets/`,并可额外导出 `FixedAssets_latest.xlsx` 到 `docs/` 目录供人工核查。
- 历史快照目录默认仅保留最近 3 份有效版本,额外旧版文件与 `~$` 临时锁文件会在同步成功后自动清理。
## 3. 目标架构总览
```text
@@ -57,6 +65,16 @@
-> OA SQL Server 状态表/视图
-> 本地状态日志
-> 企微通知服务
固定资产数据链路
-> ERP Oracle 固资视图
-> FixedAssetsSnapshotService
-> 超时控制 / 30 分钟重试 / 最多 3 次
-> SQLite 最新快照 + 历史版本
-> FixedAssets Excel 导出
-> Text2SQLService
-> 固资管理 Agent 优先查本地快照
-> 预览分页直接读取最新快照
```
## 4. 组件设计
+16 -1
View File
@@ -7,6 +7,7 @@ import { requestJson } from '@/shared/api/client';
import type { AdminUserRow } from '../types/admin.types';
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
import type { PaginatedResult } from '@/shared/types/pagination.types';
import type { UsageReport } from '../types/report.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
@@ -161,7 +162,21 @@ export const getAdminDashboardBadges = () =>
requestJson<AdminDashboardBadges>('/api/admin/dashboard/badges', auth());
// Reports
export const getAdminUsageReport = () => requestJson<any>('/api/admin/reports/usage', auth());
export interface AdminUsageReportParams {
user_page?: number;
user_page_size?: number;
}
export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
const qs = new URLSearchParams();
if (params.user_page != null) qs.set('user_page', String(params.user_page));
if (params.user_page_size != null) qs.set('user_page_size', String(params.user_page_size));
const query = qs.toString();
return requestJson<UsageReport>(
`/api/admin/reports/usage${query ? `?${query}` : ''}`,
auth(),
);
};
export const getAdminFeedbackReport = () => requestJson<any>('/api/admin/reports/feedback', auth());
export const getAdminReportTable = (url: string) => requestJson<any[]>(url, auth());
export const getAdminReportTableCount = (url: string) => requestJson<{ total: number }>(url, auth());
@@ -1,18 +1,19 @@
/**
* features/admin/modules/agents/AgentsPage.vue
*
* Agent 管理独立页面(Phase 1 首个拆分模块)。
* 路由:/admin/agents
* 用途:管理控制台的应用管理页,提供应用列表、创建/编辑弹窗、测试与授权入口。
* 依赖:useAgentsAdmin 业务编排、AgentFormModal/AgentTestModal/AgentPermissionModal 弹窗。
* 逻辑:页面加载后拉取应用/用户/排程数据;主区域展示应用列表,新增和编辑通过弹窗表单完成。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Bot, Plus, Trash2, Users } from 'lucide-vue-next';
import { Bot, Plus, SquarePen, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import AgentFormModal from './components/AgentFormModal.vue';
import AgentPermissionModal from './components/AgentPermissionModal.vue';
import AgentTestModal from './components/AgentTestModal.vue';
import AgentToolRunProgressConfig from './components/AgentToolRunProgressConfig.vue';
import { useAgentsAdmin } from './composables/useAgentsAdmin';
const { t } = useI18n();
@@ -51,6 +52,35 @@ const {
confirmDelete,
} = useAgentsAdmin();
const showFormDialog = ref(false);
/**
* 打开新建应用弹窗并重置表单状态。
* 核心逻辑:先调用 resetForm 清空编辑上下文,再展示表单弹窗,避免继承上一次选中应用的数据。
*/
const openCreateDialog = (): void => {
resetForm();
showFormDialog.value = true;
};
/**
* 打开编辑应用弹窗并载入当前行数据。
* 核心逻辑:复用 selectAgent 的表单映射逻辑,确保列表行、权限弹窗和保存接口使用同一份状态。
*/
const openEditDialog = (agent: Parameters<typeof selectAgent>[0]): void => {
selectAgent(agent);
showFormDialog.value = true;
};
/**
* 保存应用表单,成功后关闭弹窗。
* 核心逻辑:submitAgent 会处理校验、接口调用和列表刷新;仅在返回 true 时收起弹窗。
*/
const saveAgentForm = async (): Promise<void> => {
const saved = await submitAgent();
if (saved) showFormDialog.value = false;
};
onMounted(() => {
void loadAll();
});
@@ -68,163 +98,32 @@ onMounted(() => {
<h2 class="section-title">{{ t('admin.agent.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.agent.subtitle') }}</p>
</div>
<button type="button" class="btn-primary" @click="resetForm">
<button type="button" class="btn-primary" @click="openCreateDialog">
<Plus class="w-5 h-5" />
<span class="font-medium">{{ t('admin.agent.new') }}</span>
</button>
</div>
<div class="admin-form-panel">
<h3 class="section-title mb-6">{{ isEditing ? t('admin.agent.edit') : t('admin.agent.create') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.name') }}</label>
<input
v-model="form.name"
type="text"
class="w-full border-default rounded-xl px-4 py-3 text-base focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm"
:placeholder="t('admin.agent.fields.namePlaceholder')"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.type') }}</label>
<select v-model="form.type" class="w-full input-field">
<option value="api">{{ t('admin.agent.fields.types.api') }}</option>
<option value="iframe">{{ t('admin.agent.fields.types.iframe') }}</option>
</select>
</div>
<template v-if="form.type === 'api'">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">Dify应用类型</label>
<select v-model="form.dify_app_type" class="w-full input-field text-sm focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm">
<option value="chatflow">Chatflow</option>
<option value="workflow">Workflow</option>
</select>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.appId') }}</label>
<input v-model="form.dify_app_id" type="text" class="w-full input-field text-sm font-mono focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm" />
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">API 基础 URL</label>
<input
v-model="form.api_base_url"
type="text"
class="w-full input-field text-sm font-mono focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm"
:placeholder="t('admin.agent.fields.baseUrlPlaceholder')"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.apiKey') }}</label>
<input v-model="form.dify_api_key" type="password" class="w-full input-field text-sm font-mono focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm" />
</div>
</template>
<template v-if="form.type === 'iframe'">
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.iframeUrl') }}</label>
<input v-model="form.iframe_url" type="text" class="w-full input-field text-sm font-mono focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm" placeholder="https://..." />
</div>
</template>
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.description') }}</label>
<input
v-model="form.description"
type="text"
class="w-full input-field focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm"
:placeholder="t('admin.agent.fields.descPlaceholder')"
/>
</div>
<div class="col-span-1 md:col-span-2 space-y-3">
<div class="flex items-center justify-between gap-3">
<label class="text-xs font-bold text-muted uppercase tracking-wider">常见问题</label>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="addSuggestedQuestion"
>
<Plus class="h-4 w-4" />
添加问题
</button>
</div>
<div class="flex items-center gap-3 text-sm">
<label class="inline-flex items-center gap-2 text-secondary">
<input v-model="form.suggested_questions_style" type="radio" value="plain" class="accent-brand-600" />
<span>无样式</span>
</label>
<label class="inline-flex items-center gap-2 text-secondary">
<input v-model="form.suggested_questions_style" type="radio" value="styled" class="accent-brand-600" />
<span>有样式</span>
</label>
</div>
<div v-if="form.suggested_questions.length === 0" class="rounded-xl border border-dashed border-default px-4 py-5 text-sm text-muted">
暂未配置常见问题,点击“添加问题”后会同步到对应 Agent 的 Chat 欢迎页。
</div>
<div v-else class="space-y-3">
<div
v-for="(item, index) in form.suggested_questions"
:key="index"
class="rounded-2xl border border-default bg-surface-soft/50 p-4"
>
<div class="grid grid-cols-1 gap-3 md:grid-cols-[1fr_220px_auto]">
<input
v-model="item.question"
type="text"
class="w-full input-field"
placeholder="请输入常见问题,例如:查询我有多少假期?"
/>
<input
v-model="item.group"
type="text"
class="w-full input-field"
:disabled="form.suggested_questions_style !== 'styled'"
:placeholder="form.suggested_questions_style === 'styled' ? '可选:分组标题,例如:考勤与休假' : '无样式下无需分组'"
/>
<button
type="button"
class="inline-flex items-center justify-center rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-red-600 transition-colors hover:bg-red-100"
@click="removeSuggestedQuestion(index)"
>
<Trash2 class="h-4 w-4" />
</button>
</div>
</div>
</div>
</div>
<AgentToolRunProgressConfig
v-if="form.type === 'api' && form.dify_app_type !== 'workflow'"
:form="form"
:schedule-tasks="scheduleTasks"
/>
</div>
<div class="flex justify-end">
<button type="button" class="btn-primary btn-lg" @click="submitAgent">
<Plus v-if="!isEditing" class="w-5 h-5" />
{{ isEditing ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
<div class="admin-table-wrap">
<div v-if="agents.length === 0" class="admin-table-empty">
<Bot class="w-12 h-12 mx-auto text-muted mb-3" />
<p class="text-lg text-secondary">{{ t('admin.agent.noAgents') }}</p>
</div>
<table v-else class="admin-table">
<table v-else class="admin-table table-fixed w-full">
<colgroup>
<col class="w-72" />
<col class="w-[4.5rem]" />
<col class="w-32" />
<col class="w-[5.5rem]" />
<col />
</colgroup>
<thead>
<tr>
<th class="px-8 py-4 text-sm">{{ t('admin.agent.headers.name') }}</th>
<th class="px-8 py-4 text-sm">{{ t('admin.agent.headers.type') }}</th>
<th class="px-8 py-4 text-sm">{{ t('admin.agent.headers.config') }}</th>
<th class="px-8 py-4 text-sm">{{ t('admin.agent.headers.status') }}</th>
<th class="px-8 py-4 text-sm text-right">{{ t('admin.agent.headers.actions') }}</th>
<th class="px-4 py-4 text-sm">{{ t('admin.agent.headers.name') }}</th>
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.type') }}</th>
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.config') }}</th>
<th class="px-2 py-4 text-sm">{{ t('admin.agent.headers.status') }}</th>
<th class="px-4 py-4 text-sm text-right">{{ t('admin.agent.headers.actions') }}</th>
</tr>
</thead>
<tbody>
@@ -233,59 +132,70 @@ onMounted(() => {
:key="agent.id"
class="group cursor-pointer"
:class="{ 'bg-blue-50/50': selectedAgentId === agent.id }"
@click="selectAgent(agent)"
@click="openEditDialog(agent)"
>
<td class="px-8 py-5">
<div class="font-bold text-primary text-base">{{ agent.name }}</div>
<div class="section-desc mt-1">{{ agent.description }}</div>
<td class="px-4 py-5 max-w-72">
<div class="font-bold text-primary text-base truncate" :title="agent.name">{{ agent.name }}</div>
<div class="section-desc mt-1 truncate" :title="agent.description">{{ agent.description }}</div>
</td>
<td class="px-8 py-5">
<span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-surface-soft text-primary uppercase tracking-wide">
<td class="px-2 py-5 whitespace-nowrap">
<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-surface-soft text-primary uppercase tracking-wide">
{{ agent.type }}
</span>
</td>
<td class="px-8 py-5 font-mono text-xs text-muted max-w-xs truncate">
<span v-if="agent.type === 'api'" class="flex items-center gap-1">
<td class="px-2 py-5 font-mono text-xs text-muted max-w-32 truncate">
<span v-if="agent.type === 'api'" class="truncate" :title="String(agent.dify_app_id)">
<span class="text-muted">{{ t('admin.agent.idLabel') }}:</span> {{ agent.dify_app_id }}
</span>
<span v-else class="flex items-center gap-1" :title="String(agent.extra_config?.iframe_url || '')">
<span v-else class="truncate block" :title="String(agent.extra_config?.iframe_url || '')">
<span class="text-muted">{{ t('admin.agent.urlLabel') }}:</span> {{ agent.extra_config?.iframe_url }}
</span>
</td>
<td class="px-8 py-5">
<td class="px-2 py-5 whitespace-nowrap">
<span
class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium border"
class="inline-flex shrink-0 items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border whitespace-nowrap"
:class="agent.is_active ? 'bg-green-50 text-green-700 border-green-100' : 'bg-surface-soft text-secondary border-default'"
>
<span class="w-2 h-2 rounded-full" :class="agent.is_active ? 'bg-green-500' : 'bg-surface-strong'" />
<span class="w-2 h-2 shrink-0 rounded-full" :class="agent.is_active ? 'bg-green-500' : 'bg-surface-strong'" />
{{ agent.is_active ? t('admin.status.active') : t('admin.status.disabled') }}
</span>
</td>
<td class="px-8 py-5 text-right flex justify-end gap-2">
<button
type="button"
class="p-2 text-emerald-600 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-all"
:title="t('admin.agent.test')"
@click.stop="openTestModal(agent)"
>
{{ t('admin.agent.test') }}
</button>
<button
type="button"
class="p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-all"
:title="t('admin.agent.manageAccess')"
@click.stop="openPermissionModal(agent)"
>
<Users class="w-5 h-5" />
</button>
<button
type="button"
class="p-2 text-muted hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
:title="t('admin.agent.delete')"
@click.stop="deleteAgent(agent.id)"
>
<Trash2 class="w-5 h-5" />
</button>
<td class="px-4 py-5 text-right whitespace-nowrap">
<div class="inline-flex items-center justify-end gap-2">
<button
type="button"
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-lg bg-blue-50 px-3 py-2 text-sm font-medium text-blue-600 transition-all hover:bg-blue-100"
:title="t('admin.edit')"
@click.stop="openEditDialog(agent)"
>
<SquarePen class="w-4 h-4 shrink-0" />
{{ t('admin.edit') }}
</button>
<button
type="button"
class="inline-flex shrink-0 items-center justify-center p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-all"
:title="t('admin.agent.manageAccess')"
@click.stop="openPermissionModal(agent)"
>
<Users class="w-5 h-5 shrink-0" />
</button>
<button
type="button"
class="inline-flex shrink-0 items-center whitespace-nowrap p-2 text-emerald-600 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-all"
:title="t('admin.agent.test')"
@click.stop="openTestModal(agent)"
>
{{ t('admin.agent.test') }}
</button>
<button
type="button"
class="inline-flex shrink-0 items-center justify-center p-2 text-muted hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
:title="t('admin.agent.delete')"
@click.stop="deleteAgent(agent.id)"
>
<Trash2 class="w-5 h-5 shrink-0" />
</button>
</div>
</td>
</tr>
</tbody>
@@ -302,6 +212,18 @@ onMounted(() => {
@retest="runAgentTest()"
/>
<AgentFormModal
:visible="showFormDialog"
:is-editing="isEditing"
:is-saving="isSaving"
:form="form"
:schedule-tasks="scheduleTasks"
@close="showFormDialog = false"
@save="saveAgentForm"
@add-suggested-question="addSuggestedQuestion"
@remove-suggested-question="removeSuggestedQuestion"
/>
<AgentPermissionModal
:visible="showPermissionModal"
:agent="permissionAgent"
@@ -0,0 +1,189 @@
/**
* features/admin/modules/agents/components/AgentFormModal.vue
*
* 用途:应用管理新增/编辑弹窗,集中承载 Agent 基础信息、Dify/Iframe 配置和常见问题表单。
* 依赖:agent.types AgentFormState、schedule.types ScheduleTask、AgentToolRunProgressConfig、vue-i18n。
* 逻辑:父组件控制 visible/isEditing/isSaving 与保存;本组件直接编辑传入的 form,并通过事件通知关闭、保存、增删常见问题。
*/
<script setup lang="ts">
import { Plus, Trash2, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import type { AgentFormState } from '@/features/admin/types/agent.types';
import type { ScheduleTask } from '@/shared/types/schedule.types';
import AgentToolRunProgressConfig from './AgentToolRunProgressConfig.vue';
defineProps<{
visible: boolean;
isEditing: boolean;
isSaving: boolean;
form: AgentFormState;
scheduleTasks: ScheduleTask[];
}>();
const emit = defineEmits<{
close: [];
save: [];
addSuggestedQuestion: [];
removeSuggestedQuestion: [index: number];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4 py-6 backdrop-blur-sm">
<div class="flex max-h-[92vh] w-full max-w-5xl flex-col overflow-hidden rounded-2xl border border-default bg-surface shadow-2xl">
<div class="flex items-start justify-between gap-4 border-b border-default px-6 py-5">
<div>
<h3 class="section-title">{{ isEditing ? t('admin.agent.edit') : t('admin.agent.create') }}</h3>
<p class="section-desc mt-1">{{ t('admin.agent.subtitle') }}</p>
</div>
<button type="button" class="btn-icon-ds shrink-0" @click="emit('close')">
<X class="h-5 w-5" />
</button>
</div>
<div class="overflow-y-auto px-6 py-6">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.name') }}</label>
<input
v-model="form.name"
type="text"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.fields.namePlaceholder')"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.type') }}</label>
<select v-model="form.type" class="w-full input-field text-sm">
<option value="api">{{ t('admin.agent.fields.types.api') }}</option>
<option value="iframe">{{ t('admin.agent.fields.types.iframe') }}</option>
</select>
</div>
<template v-if="form.type === 'api'">
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">Dify应用类型</label>
<select v-model="form.dify_app_type" class="w-full input-field text-sm">
<option value="chatflow">Chatflow</option>
<option value="workflow">Workflow</option>
</select>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.appId') }}</label>
<input v-model="form.dify_app_id" type="text" class="w-full input-field text-sm font-mono" />
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.baseUrl') }}</label>
<input
v-model="form.api_base_url"
type="text"
class="w-full input-field text-sm font-mono"
:placeholder="t('admin.agent.fields.baseUrlPlaceholder')"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.apiKey') }}</label>
<input v-model="form.dify_api_key" type="password" class="w-full input-field text-sm font-mono" />
</div>
</template>
<template v-if="form.type === 'iframe'">
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.iframeUrl') }}</label>
<input v-model="form.iframe_url" type="text" class="w-full input-field text-sm font-mono" placeholder="https://..." />
</div>
</template>
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-muted uppercase tracking-wider">{{ t('admin.agent.fields.description') }}</label>
<input
v-model="form.description"
type="text"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.fields.descPlaceholder')"
/>
</div>
<div class="col-span-1 md:col-span-2 space-y-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<label class="text-xs font-bold text-muted uppercase tracking-wider">常见问题</label>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="emit('addSuggestedQuestion')"
>
<Plus class="h-4 w-4" />
添加问题
</button>
</div>
<div class="flex flex-wrap items-center gap-3 text-sm">
<label class="inline-flex items-center gap-2 text-secondary">
<input v-model="form.suggested_questions_style" type="radio" value="plain" class="accent-brand-600" />
<span>无样式</span>
</label>
<label class="inline-flex items-center gap-2 text-secondary">
<input v-model="form.suggested_questions_style" type="radio" value="styled" class="accent-brand-600" />
<span>有样式</span>
</label>
</div>
<div v-if="form.suggested_questions.length === 0" class="rounded-xl border border-dashed border-default px-4 py-5 text-sm text-muted">
暂未配置常见问题,点击“添加问题”后会同步到对应 Agent 的 Chat 欢迎页。
</div>
<div v-else class="space-y-3">
<div
v-for="(item, index) in form.suggested_questions"
:key="index"
class="rounded-2xl border border-default bg-surface-soft/50 p-4"
>
<div class="grid grid-cols-1 gap-3 md:grid-cols-[1fr_220px_auto]">
<input
v-model="item.question"
type="text"
class="w-full input-field text-sm"
placeholder="请输入常见问题,例如:查询我有多少假期?"
/>
<input
v-model="item.group"
type="text"
class="w-full input-field text-sm"
:disabled="form.suggested_questions_style !== 'styled'"
:placeholder="form.suggested_questions_style === 'styled' ? '可选:分组标题,例如:考勤与休假' : '无样式下无需分组'"
/>
<button
type="button"
class="inline-flex h-11 w-full items-center justify-center rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-red-600 transition-colors hover:bg-red-100 md:w-11"
@click="emit('removeSuggestedQuestion', index)"
>
<Trash2 class="h-4 w-4" />
</button>
</div>
</div>
</div>
</div>
<AgentToolRunProgressConfig
v-if="form.type === 'api' && form.dify_app_type !== 'workflow'"
:form="form"
:schedule-tasks="scheduleTasks"
/>
</div>
</div>
<div class="flex flex-col-reverse gap-3 border-t border-default px-6 py-4 sm:flex-row sm:items-center sm:justify-end">
<button type="button" class="btn-secondary" @click="emit('close')">
{{ t('admin.cancel') }}
</button>
<button type="button" class="btn-primary btn-lg disabled:opacity-60" :disabled="isSaving" @click="emit('save')">
<Plus v-if="!isEditing" class="w-5 h-5" />
{{ isEditing ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
</template>
@@ -205,15 +205,20 @@ export function useAgentsAdmin() {
}
};
const submitAgent = async (): Promise<void> => {
/**
* 提交应用创建或编辑表单,并向页面反馈是否成功。
* 核心逻辑:先做必填与能力配置校验,再按编辑态调用新增/更新接口;成功后刷新列表并同步当前表单状态。
* @returns true 表示保存成功,false 表示校验或接口失败,调用方可据此决定是否关闭弹窗。
*/
const submitAgent = async (): Promise<boolean> => {
if (!form.value.name) {
msg.warning(t('admin.dept.msg.nameRequired'));
return;
return false;
}
const supportsToolRunProgress = form.value.type === 'api' && form.value.dify_app_type !== 'workflow';
if (supportsToolRunProgress && form.value.tool_run_progress_enabled && !form.value.schedule_task_id) {
msg.warning(t('admin.agent.toolRunProgress.scheduleTaskRequired'));
return;
return false;
}
isSaving.value = true;
@@ -285,9 +290,11 @@ export function useAgentsAdmin() {
} else {
resetForm();
}
return true;
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
return false;
} finally {
isSaving.value = false;
}
@@ -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,
@@ -13,6 +13,16 @@ const { t } = useI18n();
const {
usageReport,
usageUserPage,
usageUserPageSize,
usageUserPageSizeOptions,
usageUserTotal,
usageUserTotalPages,
usageUserTopLimit,
usageUserPageButtons,
goToUsageUserPage,
prevUsageUserPage,
nextUsageUserPage,
isLoading,
currentTable,
tableData,
@@ -359,15 +369,6 @@ onMounted(() => {
<div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-default pt-10">
<h3 class="section-title text-lg mb-6">{{ t('admin.report.usage') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
<div class="card p-6">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byUser') }}</h4>
<div class="space-y-3">
<div v-for="u in usageReport.by_user" :key="u.username" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
<span class="font-medium text-secondary">{{ u.username }}</span>
<span class="admin-report-badge admin-report-badge--info font-bold">{{ u.count }}</span>
</div>
</div>
</div>
<div class="card p-6">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byAgent') }}</h4>
<div class="space-y-3">
@@ -377,6 +378,71 @@ onMounted(() => {
</div>
</div>
</div>
<div class="card p-6 flex flex-col">
<div class="mb-4">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.byUser') }}</h4>
<p class="mt-1 text-xs text-muted">{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}</p>
</div>
<div class="space-y-3 flex-1">
<div v-for="u in usageReport.by_user" :key="u.username" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
<span class="font-medium text-secondary">{{ u.username }}</span>
<span class="admin-report-badge admin-report-badge--info font-bold">{{ u.count }}</span>
</div>
<div v-if="usageReport.by_user.length === 0" class="text-center text-muted text-sm py-6">
{{ t('admin.report.usageByUserEmpty') }}
</div>
</div>
<div v-if="usageUserTotal > 0" class="mt-4 flex flex-col gap-3 border-t border-default pt-4">
<div class="text-xs text-secondary">
{{ t('admin.report.paginationSummary', { total: usageUserTotal, page: usageUserPage, pages: usageUserTotalPages }) }}
</div>
<div class="flex flex-wrap items-center gap-2">
<label class="flex items-center gap-2 text-xs text-secondary">
<span>{{ t('admin.report.perPage') }}</span>
<span class="relative inline-flex items-center">
<select
v-model.number="usageUserPageSize"
class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5"
>
<option v-for="size in usageUserPageSizeOptions" :key="`usage-user-size-${size}`" :value="size">{{ size }}</option>
</select>
<svg class="pointer-events-none absolute right-2 h-3.5 w-3.5 text-muted" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z" clip-rule="evenodd" />
</svg>
</span>
<span>{{ t('admin.report.itemsUnit') }}</span>
</label>
<button
@click="prevUsageUserPage"
:disabled="usageUserPage <= 1"
class="admin-report-page-btn"
>
{{ t('admin.report.prevPage') }}
</button>
<button
v-for="btn in usageUserPageButtons"
:key="`usage-user-page-btn-${btn}`"
:disabled="btn === -1"
@click="btn !== -1 && goToUsageUserPage(btn)"
class="admin-report-page-btn"
:class="btn === -1
? 'border-transparent text-muted cursor-default opacity-100'
: btn === usageUserPage
? 'admin-report-page-btn--active'
: ''"
>
{{ btn === -1 ? '...' : btn }}
</button>
<button
@click="nextUsageUserPage"
:disabled="usageUserPage >= usageUserTotalPages"
class="admin-report-page-btn"
>
{{ t('admin.report.nextPage') }}
</button>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -24,12 +24,62 @@ import type {
} from '@/features/admin/types/report.types';
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
/** 聊天日志报表固定展示列(顺序与产品约定一致;id 仅用于批量删除) */
const CHAT_LOGS_REPORT_KEYS = [
'agent_name',
'username',
'created_at',
'query',
'answer',
'session_id',
'tokens_used',
'message_type',
] as const;
const CHAT_LOGS_TABLE_KEYS = ['id', ...CHAT_LOGS_REPORT_KEYS] as const;
export function useReportsAdmin() {
const { t, locale } = useI18n();
const msg = useMessage();
const route = useRoute();
const usageReport = ref<UsageReport | null>(null);
const usageUserPage = ref(1);
const usageUserPageSize = ref(10);
const usageUserPageSizeOptions = [5, 10, 20, 50];
const loadUsageReport = async (): Promise<void> => {
try {
usageReport.value = await getAdminUsageReport({
user_page: usageUserPage.value,
user_page_size: usageUserPageSize.value,
});
const pages = usageReport.value?.user_pages ?? 1;
if (usageUserPage.value > pages) {
usageUserPage.value = pages;
}
} catch (e) {
console.error('Error loading usage report:', e);
}
};
const usageUserTotalPages = computed(() => Math.max(1, usageReport.value?.user_pages ?? 1));
const usageUserTotal = computed(() => usageReport.value?.user_total ?? 0);
const usageUserTopLimit = computed(() => usageReport.value?.user_top_limit ?? 50);
const usageUserPageButtons = computed(() =>
buildOffsetPageButtons(usageUserPage.value, usageUserTotalPages.value),
);
const goToUsageUserPage = (page: number): void => {
usageUserPage.value = Math.min(Math.max(1, page), usageUserTotalPages.value);
void loadUsageReport();
};
const prevUsageUserPage = () => goToUsageUserPage(usageUserPage.value - 1);
const nextUsageUserPage = () => goToUsageUserPage(usageUserPage.value + 1);
const loadReports = async (): Promise<void> => {
await loadUsageReport();
};
const isLoading = ref(true);
const showDeleteConfirmDialog = ref(false);
@@ -73,14 +123,6 @@ export function useReportsAdmin() {
},
);
const loadReports = async (): Promise<void> => {
try {
usageReport.value = await getAdminUsageReport();
} catch (e) {
console.error('Error loading reports:', e);
}
};
// 报表相关状态
const tableData = ref<any[]>([]);
const isFullScreen = ref(false);
@@ -117,7 +159,11 @@ const loadTableData = async () => {
try {
tableData.value = await getAdminReportTable(url);
if (tableData.value.length > 0) {
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
const rowKeys = Object.keys(tableData.value[0] || {});
const columnKeys = currentTable.value === 'chat_logs'
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
: rowKeys;
initChatLogsColumns(columnKeys);
}
if (currentTable.value === 'chat_logs') {
const validIds = new Set(
@@ -149,10 +195,11 @@ const saveChatLogsColumns = () => {
const initChatLogsColumns = (keys: string[]) => {
chatLogsWrapEnabled.value = false;
chatLogsWrapMaxHeight.value = 120;
const hideByDefault = currentTable.value === 'chat_logs' && keys.includes('id');
const defaults: ReportColumnConfig[] = keys.map((k) => ({
key: k,
visible: true,
width: k === 'id' ? 90 : 180
visible: hideByDefault ? k !== 'id' : true,
width: k === 'id' ? 90 : k === 'tokens_used' ? 120 : 180,
}));
let merged = defaults;
@@ -165,8 +212,8 @@ const initChatLogsColumns = (keys: string[]) => {
const missing = keys.filter((k) => !order.includes(k));
merged = [...order, ...missing].map((k) => ({
key: k,
visible: savedMap.get(k)?.visible ?? true,
width: savedMap.get(k)?.width ?? (k === 'id' ? 90 : 180),
visible: savedMap.get(k)?.visible ?? (currentTable.value === 'chat_logs' && k === 'id' ? false : true),
width: savedMap.get(k)?.width ?? (k === 'id' ? 90 : k === 'tokens_used' ? 120 : 180),
}));
if (!Array.isArray(parsed)) {
chatLogsWrapEnabled.value = !!parsed.wrapEnabled;
@@ -190,7 +237,11 @@ const resetChatLogsColumns = () => {
chatLogsWrapMaxHeight.value = 120;
chatLogsSortRules.value = [];
reportHeaderSort.value = null;
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
const rowKeys = Object.keys(tableData.value[0] || {});
const columnKeys = currentTable.value === 'chat_logs'
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
: rowKeys;
initChatLogsColumns(columnKeys);
saveChatLogsColumns();
};
@@ -269,7 +320,15 @@ const loadTableCount = async (table: string) => {
const exportToExcel = () => {
if (tableData.value.length === 0) return;
const ws = XLSX.utils.json_to_sheet(tableData.value);
const keys = visibleReportKeys.value;
const rows = tableData.value.map((row) => {
const out: Record<string, unknown> = {};
for (const key of keys) {
out[getReportColumnLabel(key)] = getReportCellValue(row, key);
}
return out;
});
const ws = XLSX.utils.json_to_sheet(rows.length > 0 ? rows : tableData.value);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, currentTable.value);
XLSX.writeFile(wb, `${currentTable.value}_report_${new Date().toISOString().split('T')[0]}.xlsx`);
@@ -309,6 +368,11 @@ const visibleReportKeys = computed(() => {
return feedbackFixedOrder.filter((k) => available.has(k));
}
if (currentTable.value === 'chat_logs') {
const available = new Set(keys);
return CHAT_LOGS_REPORT_KEYS.filter((k) => available.has(k));
}
return keys;
});
@@ -772,6 +836,11 @@ watch(columnFilters, () => {
reportCurrentPage.value = 1;
}, { deep: true });
watch(usageUserPageSize, () => {
usageUserPage.value = 1;
void loadUsageReport();
});
watch([reportPageSize, sortedTableData], () => {
if (reportCurrentPage.value > reportTotalPages.value) {
reportCurrentPage.value = reportTotalPages.value;
@@ -801,6 +870,16 @@ watch([reportPageSize, sortedTableData], () => {
return {
usageReport,
usageUserPage,
usageUserPageSize,
usageUserPageSizeOptions,
usageUserTotal,
usageUserTotalPages,
usageUserTopLimit,
usageUserPageButtons,
goToUsageUserPage,
prevUsageUserPage,
nextUsageUserPage,
isLoading,
currentTable,
tableData,
@@ -66,51 +66,61 @@ const showCreateModal = useScheduleCreateModalOpen();
</div>
<!-- SQL Config Panel -->
<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">
<h4 class="text-base font-bold text-primary shrink-0">{{ $t('admin.schedule.form.dataSourceConfig') }}</h4>
<div class="flex flex-wrap items-center gap-2">
<div
class="segment-control segment-control--fit segment-control--sm shrink-0"
role="radiogroup"
:aria-label="$t('admin.schedule.form.dataSourceConfig')"
>
<button
type="button"
role="radio"
:aria-checked="admin.scheduleCreateForm.data_source_type === 'database'"
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 class="mb-3 space-y-3">
<h4 class="text-base font-bold text-primary">{{ $t('admin.schedule.form.dataSourceConfig') }}</h4>
<div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div class="w-full sm:max-w-sm">
<label class="mb-1.5 block text-xs font-semibold uppercase tracking-wide text-muted">
{{ $t('admin.schedule.form.dataSourceType') }}
</label>
<select
v-model="admin.scheduleCreateForm.data_source_type"
class="input-field w-full !text-sm !leading-5"
>
<option value="database">{{ $t('admin.schedule.form.databaseDirect') }}</option>
<option value="external_api">{{ $t('admin.schedule.form.externalApi') }}</option>
<option value="faq_hot_aggregate">{{ $t('admin.schedule.form.faqHotAggregate') }}</option>
</select>
</div>
<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"
:disabled="admin.scheduleTestLoading || !admin.scheduleEditingId"
@click="admin.handleTestScheduleSql"
<div
v-if="admin.scheduleCreateForm.data_source_type !== 'faq_hot_aggregate'"
class="flex flex-wrap items-center gap-2 sm:shrink-0"
>
{{ admin.scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
</button>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap"
@click="admin.scheduleConfigCollapsed = !admin.scheduleConfigCollapsed"
>
<ChevronDown v-if="admin.scheduleConfigCollapsed" class="h-3.5 w-3.5 shrink-0" />
<ChevronUp v-else class="h-3.5 w-3.5 shrink-0" />
{{ admin.scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
</button>
<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"
:disabled="admin.scheduleTestLoading || !admin.scheduleEditingId"
@click="admin.handleTestScheduleSql"
>
{{ admin.scheduleTestLoading ? $t('admin.schedule.form.querying') : $t('admin.schedule.form.testQuery') }}
</button>
<button
type="button"
class="btn-secondary btn-sm inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap"
@click="admin.scheduleConfigCollapsed = !admin.scheduleConfigCollapsed"
>
<ChevronDown v-if="admin.scheduleConfigCollapsed" class="h-3.5 w-3.5 shrink-0" />
<ChevronUp v-else class="h-3.5 w-3.5 shrink-0" />
{{ admin.scheduleConfigCollapsed ? $t('admin.schedule.form.expandConfig') : $t('admin.schedule.form.collapseConfig') }}
</button>
</div>
</div>
</div>
<div v-show="!admin.scheduleConfigCollapsed" class="space-y-3">
<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'">
<!-- 数据源配置 -->
@@ -301,7 +311,7 @@ const showCreateModal = useScheduleCreateModalOpen();
</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>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.agentLabel') }}</label>
<div class="relative">
@@ -320,7 +330,7 @@ const showCreateModal = useScheduleCreateModalOpen();
</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">
<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') }}
@@ -16,6 +16,7 @@ import { useMessage } from '@/shared/composables/useMessage';
import {
createDefaultScheduleCreateForm,
createDefaultScheduleSqlEditForm,
type ScheduleCreateForm,
} from '../../types/schedule-admin.types';
import { buildScheduleConfigPayload } from '../../utils/schedule-form-payload.utils';
import { useScheduleCronDesigner } from '../useScheduleCronDesigner';
@@ -106,7 +107,7 @@ export function useScheduleAdminForm(
result: Awaited<ReturnType<typeof getAdminScheduleTaskConfig>>,
): void => {
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;
scheduleSqlEditForm.value = {
base_fetch_sql: cfg.base_fetch_sql || '',
@@ -179,7 +180,7 @@ export function useScheduleAdminForm(
kb_sync_enabled: !!task.kb_sync_enabled,
kb_group_id: task.kb_group_id || null,
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();
scheduleTestResult.value = null;
@@ -278,20 +279,23 @@ export function useScheduleAdminForm(
}
const dst = scheduleCreateForm.value.data_source_type;
const isFaqHot = dst === 'faq_hot_aggregate';
const hasAgent = !!scheduleCreateForm.value.dify_agent_id;
const hasSql = dst === 'database' && !!scheduleSqlEditForm.value.base_fetch_sql.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'));
return;
}
let headerLabels: Record<string, string> = {};
try {
headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
} catch {
msg.error(t('admin.schedule.msg.headerLabelsJsonInvalid'));
return;
if (!isFaqHot) {
try {
headerLabels = JSON.parse(scheduleSqlEditForm.value.header_labels_str || '{}');
} catch {
msg.error(t('admin.schedule.msg.headerLabelsJsonInvalid'));
return;
}
}
let apiHeaders: Record<string, string> = {};
if (dst === 'external_api') {
@@ -303,13 +307,15 @@ export function useScheduleAdminForm(
}
}
let configPayload: Record<string, unknown>;
configPayload = buildScheduleConfigPayload(
scheduleSqlEditForm.value,
hasAgent,
headerLabels,
apiHeaders,
);
let configPayload: Record<string, unknown> | undefined;
if (!isFaqHot) {
configPayload = buildScheduleConfigPayload(
scheduleSqlEditForm.value,
hasAgent,
headerLabels,
apiHeaders,
);
}
scheduleCreateSaving.value = true;
try {
@@ -326,7 +332,7 @@ export function useScheduleAdminForm(
kb_group_id: scheduleCreateForm.value.kb_sync_enabled ? scheduleCreateForm.value.kb_group_id : null,
enabled: scheduleCreateForm.value.enabled,
data_source_type: dst,
config: configPayload,
...(configPayload ? { config: configPayload } : {}),
};
let resultData: { id?: number; schedule?: { id?: number } } | null = null;
if (scheduleEditingId.value) {
@@ -23,7 +23,7 @@ export interface ScheduleCronDesigner {
/** 创建/编辑定时任务主表单 */
export interface ScheduleCreateForm {
name: string;
data_source_type: 'database' | 'external_api';
data_source_type: 'database' | 'external_api' | 'faq_hot_aggregate';
dify_agent_id: number | null;
owner_user_id: number | null;
wait_seconds: number;
@@ -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 } : {}),
});
@@ -7,7 +7,12 @@ export interface UsageReport {
total: number;
by_user: { username: string; count: number }[];
by_agent: { agent: string; count: number }[];
by_day: { date: string; count: number }[];
by_day?: { date: string; count: number }[];
user_total: number;
user_page: number;
user_page_size: number;
user_pages: number;
user_top_limit: number;
}
export interface ReportColumnConfig {
@@ -9,7 +9,6 @@ import {
Check,
ChevronDown,
Database,
Globe,
Link2,
Loader2,
Mic,
@@ -44,12 +43,10 @@ const props = defineProps<{
/** 用对象包裹 Ref,避免 template 自动解包 */
shippingPickerRefHolder: { pickerRef: Ref<HTMLInputElement | null> };
getKbLabel: (kb: string) => string;
browserPanelOpen: boolean;
}>();
const emit = defineEmits<{
send: [];
'toggle-browser': [];
'voice-click': [];
'remove-attachment': [id: string];
'local-files-selected': [event: Event];
@@ -312,16 +309,6 @@ onBeforeUnmount(() => {
</button>
</div>
</div>
<button
type="button"
:disabled="isThinking"
class="flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
@click="emit('toggle-browser')"
>
<Globe class="h-3.5 w-3.5 text-brand-500" />
{{ browserPanelOpen ? $t('chat.collapseBrowser') : $t('chat.openBrowser') }}
</button>
</div>
<button
@@ -141,8 +141,6 @@ const page = useChatPageContext();
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
:shipping-picker-ref-holder="page.shippingPickerRefHolder"
:get-kb-label="page.getKbLabel"
:browser-panel-open="page.browserPanelOpen"
@toggle-browser="page.toggleBrowserPanel"
@send="page.handleSend()"
@voice-click="page.handleVoiceFeatureClick"
@remove-attachment="page.removeAttachment"
@@ -3,7 +3,9 @@
* SSE 流式对话核心:消息列表、runs、发送与接收。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { getAuthHeaders } from '@/shared/utils/auth';
import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
const normalizeResources = (resources: unknown) => {
@@ -114,6 +116,7 @@ const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) =>
};
export function useChat() {
const { t } = useI18n();
const messages = ref<ChatMessage[]>([]);
const isThinking = ref(false);
const viewId = ref(0);
@@ -173,6 +176,13 @@ export function useChat() {
return String(message ?? 'Unknown error');
};
const streamErrorLabels = (): StreamErrorLabels => ({
networkDisconnectedEmpty: t('chat.streamError.networkDisconnectedEmpty'),
partialInterrupted: t('chat.streamError.partialInterrupted'),
upstreamDisconnected: t('chat.streamError.upstreamDisconnected'),
generic: t('chat.streamError.generic'),
});
const sendMessage = async (
query: string,
agentId: number,
@@ -320,7 +330,7 @@ export function useChat() {
} else if (eventName === 'error') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += `\n[Error: ${formatStreamError(data.message)}]`;
applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
run.status = 'error';
if (messages.value === runMessages) isThinking.value = false;
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
@@ -342,7 +352,7 @@ export function useChat() {
const botMsg = ensureBotMessage();
if (botMsg) {
const message = e instanceof Error ? e.message : 'Network Issue';
botMsg.content += `\n[Error: ${message}]`;
applyStreamErrorToMessage(botMsg, message, streamErrorLabels());
}
} finally {
if (messages.value === runMessages) {
@@ -1,4 +1,4 @@
/**
/**
* features/chat/composables/useChatAgent.ts
* 当前 Agent 元数据、知识库选项、推荐问题与用户可切换 Agent 列表。
*/
@@ -96,8 +96,9 @@ export function useChatAgent(options: UseChatAgentOptions) {
const kbDropdownDisabled = computed(() => availableKbOptions.value.length <= 1);
watch(canSelectErpKnowledgeBase, (allowed) => {
// 固资管理默认先走企业知识库,用户可手动切换到 ERP 知识库。
if (allowed) {
selectedKb.value = ERP_KB;
selectedKb.value = DEFAULT_KB;
return;
}
if (selectedKb.value === ERP_KB) {
@@ -35,6 +35,8 @@ export interface ChatMessage {
variant?: 'primary' | 'secondary' | 'danger';
}>;
shipping_actions_used?: boolean;
/** 流式对话是否因网络/上游中断而附带错误提示 */
stream_error?: boolean;
}
export type ChatRunStatus = 'running' | 'done' | 'error';
@@ -0,0 +1,88 @@
/**
* features/chat/utils/streamErrorMessage.ts
* 用途:将 SSE / 浏览器流式读错映射为用户可读文案。
* 依赖:vue-i18n chat.streamError 词条。
* 逻辑:useChat 在 catch 与 error 事件中调用 applyStreamErrorToMessage。
*/
import type { ChatMessage } from '../types/chat.types';
const NETWORK_DISCONNECT_PATTERNS = [
'network error',
'failed to fetch',
'load failed',
'networkerror when attempting to fetch resource',
'network issue',
];
const UPSTREAM_DISCONNECT_PATTERNS = [
'response ended prematurely',
'chunkedencodingerror',
];
export interface StreamErrorLabels {
networkDisconnectedEmpty: string;
partialInterrupted: string;
upstreamDisconnected: string;
generic: string;
}
/**
* 判断是否为浏览器侧 SSE / fetch 连接中断类错误。
*/
export function isNetworkDisconnectError(message: string): boolean {
const normalized = message.trim().toLowerCase();
if (!normalized) return false;
return NETWORK_DISCONNECT_PATTERNS.some(
(pattern) => normalized === pattern || normalized.includes(pattern),
);
}
/**
* 判断是否为上游(Dify)流式响应提前结束。
*/
export function isUpstreamDisconnectError(message: string): boolean {
const normalized = message.trim().toLowerCase();
return UPSTREAM_DISCONNECT_PATTERNS.some((pattern) => normalized.includes(pattern));
}
/**
* 将原始错误信息映射为面向用户的提示文案。
*
* @param rawMessage - 浏览器或后端返回的原始错误
* @param hasContent - 是否已有部分回答内容
* @param labels - i18n 文案集合
*/
export function resolveStreamErrorText(
rawMessage: string,
hasContent: boolean,
labels: StreamErrorLabels,
): string {
if (isNetworkDisconnectError(rawMessage)) {
return hasContent ? labels.partialInterrupted : labels.networkDisconnectedEmpty;
}
if (isUpstreamDisconnectError(rawMessage)) {
return hasContent ? labels.partialInterrupted : labels.upstreamDisconnected;
}
if (/[\u4e00-\u9fff]/.test(rawMessage)) {
return rawMessage;
}
return labels.generic;
}
/**
* 把流式错误写入 assistant 消息:无内容时整段替换,有部分内容时在末尾追加提示。
*/
export function applyStreamErrorToMessage(
msg: ChatMessage,
rawMessage: string,
labels: StreamErrorLabels,
): void {
const hasContent = Boolean(msg.content.trim());
const text = resolveStreamErrorText(rawMessage, hasContent, labels);
msg.stream_error = true;
if (hasContent) {
msg.content += `\n\n${text}`;
} else {
msg.content = text;
}
}
@@ -41,6 +41,7 @@ export function resolveMessageAnchorKey(msg: ChatMessage, index: number): string
}
export function assistantMessageHasError(msg: ChatMessage | null | undefined): boolean {
if (msg?.stream_error) return true;
return String(msg?.content || '').includes('[Error:');
}
+23 -2
View File
@@ -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",
@@ -626,6 +638,8 @@
"usage": "Usage Analytics",
"byUser": "Requests by User",
"byAgent": "Requests by Agent",
"usageByUserTopHint": "Top {limit} users by chat volume",
"usageByUserEmpty": "No user chat activity yet",
"columns": {
"id": "ID",
"user_id": "User ID",
@@ -670,6 +684,7 @@
"model": "Model",
"tokens": "Tokens",
"tokens_used": "Tokens Used",
"message_type": "Message Type",
"tokens_prompt": "Prompt Tokens",
"tokens_completion": "Completion Tokens",
"total_tokens": "Total Tokens",
@@ -812,8 +827,14 @@
"noUsers": "No users available",
"selectOwner": "Select an owner",
"dataSourceConfig": "Data source & execution config",
"dataSourceType": "Data source type",
"databaseDirect": "Database",
"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...",
"testQuery": "Test query",
"expandConfig": "Expand config",
+6
View File
@@ -316,6 +316,12 @@
"searchByNameOrEmployeeId": "Search by name or employee ID, press Enter",
"name": "Name",
"employeeIdRequired": "Employee ID is required.",
"streamError": {
"networkDisconnectedEmpty": "Connection lost before a reply was received. Please try again.",
"partialInterrupted": "The reply was interrupted. The content above may be incomplete—please ask again.",
"upstreamDisconnected": "The AI service connection was interrupted. Please try again.",
"generic": "The request failed. Please try again."
},
"actions": {
"copy": "Copy",
"edit": "Edit",
+17 -2
View File
@@ -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": "คำถามทั่วไป",
@@ -631,6 +643,8 @@
"usage": "การวิเคราะห์การใช้งาน",
"byUser": "ตามผู้ใช้",
"byAgent": "ตามตัวแทน",
"usageByUserTopHint": "แสดงผู้ใช้ {limit} อันดับแรกตามปริมาณการสนทนา",
"usageByUserEmpty": "ยังไม่มีบันทึกการสนทนาของผู้ใช้",
"columns": {
"id": "ID",
"user_id": "รหัสผู้ใช้",
@@ -675,6 +689,7 @@
"model": "โมเดล",
"tokens": "โทเค็น",
"tokens_used": "โทเค็นที่ใช้",
"message_type": "Message Type",
"tokens_prompt": "โทเค็นพรอมป์ต์",
"tokens_completion": "โทเค็นผลลัพธ์",
"total_tokens": "โทเค็นรวม",
+6
View File
@@ -316,6 +316,12 @@
"searchByNameOrEmployeeId": "ค้นหาด้วยชื่อหรือรหัสพนักงาน แล้วกด Enter",
"name": "ชื่อ",
"employeeIdRequired": "รหัสพนักงานห้ามว่าง",
"streamError": {
"networkDisconnectedEmpty": "การเชื่อมต่อขาดหายก่อนได้รับคำตอบ โปรดลองใหม่อีกครั้ง",
"partialInterrupted": "การสร้างคำตอบถูกขัดจังหวะ เนื้อหาด้านบนอาจไม่สมบูรณ์ โปรดถามใหม่",
"upstreamDisconnected": "การเชื่อมต่อบริการ AI ขาดหาย โปรดลองใหม่อีกครั้ง",
"generic": "คำขอล้มเหลว โปรดลองใหม่อีกครั้ง"
},
"actions": {
"copy": "คัดลอก",
"edit": "แก้ไข",
+23 -2
View File
@@ -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": "常用问题",
@@ -627,6 +639,8 @@
"usage": "使用分析",
"byUser": "按用户统计",
"byAgent": "按应用统计",
"usageByUserTopHint": "仅显示对话量前 {limit} 名用户",
"usageByUserEmpty": "暂无用户对话记录",
"columns": {
"id": "ID",
"user_id": "用户 ID",
@@ -671,6 +685,7 @@
"model": "模型",
"tokens": "Token 数",
"tokens_used": "已用 Token",
"message_type": "Message Type",
"tokens_prompt": "提示词 Token",
"tokens_completion": "补全 Token",
"total_tokens": "总 Token",
@@ -792,8 +807,14 @@
"noUsers": "暂无可用用户",
"selectOwner": "请选择所有者",
"dataSourceConfig": "数据源与执行配置",
"dataSourceType": "数据源类型",
"databaseDirect": "数据库直联",
"externalApi": "外部API",
"faqHotAggregate": "FAQ 热点聚合",
"faqHotAggregateHint": "按 Cron 自动执行 ChatLog 热点发现,结果写入 faq_hot_candidates 表;与「常用问题 → 热点发现 → 刷新聚合」相同。",
"faqHotAgentFilter": "限定应用(可选)",
"faqHotAllAgents": "全部应用",
"faqHotAgentFilterHelp": "留空则聚合所有 Agent;选定后仅统计该应用的 ChatLog。",
"querying": "查询中...",
"testQuery": "测试查询",
"expandConfig": "展开配置",
+6
View File
@@ -320,6 +320,12 @@
"searchByNameOrEmployeeId": "输入姓名或工号搜索,按回车键查询",
"name": "姓名",
"employeeIdRequired": "工号不能为空。",
"streamError": {
"networkDisconnectedEmpty": "连接中断,未能获取回答,请稍后重试。",
"partialInterrupted": "回答生成中断,以上内容可能不完整,请重新提问。",
"upstreamDisconnected": "AI 服务连接中断,请稍后重试。",
"generic": "请求失败,请稍后重试。"
},
"actions": {
"copy": "复制",
"edit": "编辑",
+17 -2
View File
@@ -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": "常用問題",
@@ -631,6 +643,8 @@
"usage": "使用分析",
"byUser": "按用戶統計",
"byAgent": "按應用統計",
"usageByUserTopHint": "僅顯示對話量前 {limit} 名用戶",
"usageByUserEmpty": "暫無用戶對話記錄",
"columns": {
"id": "ID",
"user_id": "用戶 ID",
@@ -675,6 +689,7 @@
"model": "模型",
"tokens": "Token 數",
"tokens_used": "已用 Token",
"message_type": "Message Type",
"tokens_prompt": "提示詞 Token",
"tokens_completion": "補全 Token",
"total_tokens": "總 Token",
+6
View File
@@ -316,6 +316,12 @@
"searchByNameOrEmployeeId": "輸入姓名或工號搜尋,按 Enter 查詢",
"name": "姓名",
"employeeIdRequired": "工號不能為空。",
"streamError": {
"networkDisconnectedEmpty": "連線中斷,未能取得回答,請稍後重試。",
"partialInterrupted": "回答生成中斷,以上內容可能不完整,請重新提問。",
"upstreamDisconnected": "AI 服務連線中斷,請稍後重試。",
"generic": "請求失敗,請稍後重試。"
},
"actions": {
"copy": "複製",
"edit": "編輯",