feat: 重构管理后台前端架构并新增完整功能

This commit is contained in:
hugo committed 2026-06-03 11:49:14 +08:00
commit 93304a1803
88 files changed
+9941 -6500

No files matched your search

+87 -14
View File
@@ -154,19 +154,84 @@ def debug_wecom_user_by_code():
payload['match_preview'] = _build_wecom_match_preview(identity, rules, operator)
return jsonify(payload)
def _compute_dashboard_summary():
"""
聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。
返回字段:
- agent_count: 启用中的 Agent 数量
- user_count: 用户总数
- total_conversations: 对话日志总数
- avg_score: 反馈平均分(保留 1 位小数)
"""
total_users = db.session.query(func.count(User.id)).scalar() or 0
active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0
total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0
avg_score = db.session.query(func.avg(Feedback.score)).scalar()
avg_score = round(float(avg_score), 1) if avg_score else 0.0
return {
'agent_count': active_agents,
'user_count': total_users,
'total_conversations': total_conversations,
'avg_score': avg_score,
}
def _compute_dashboard_badges():
"""
聚合侧栏角标所需的待办数量(仅 COUNT,不拉 users / permission_requests 全表)。
返回字段:
- pending_approvals: status=pending 的注册用户数量(「用户审批」角标)
- pending_requests: status=pending 的权限申请数量(「权限申请」角标)
"""
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0
pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0
return {
'pending_approvals': pending_approvals,
'pending_requests': pending_requests,
}
@admin_bp.route('/dashboard/summary', methods=['GET'])
@require_admin
def dashboard_summary():
"""
管理后台仪表盘概览(供 Dashboard 页单次请求)。
GET /api/admin/dashboard/summary
响应示例:{"agent_count": 5, "user_count": 120, "total_conversations": 3000, "avg_score": 4.2}
"""
return jsonify(_compute_dashboard_summary())
@admin_bp.route('/dashboard/badges', methods=['GET'])
@require_admin
def dashboard_badges():
"""
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
GET /api/admin/dashboard/badges
响应示例:{"pending_approvals": 2, "pending_requests": 5}
"""
return jsonify(_compute_dashboard_badges())
@admin_bp.route('/dashboard', methods=['GET'])
@require_admin
def dashboard_stats():
"""
Dashboard statistics
仪表盘统计(遗留接口,字段名与早期前端兼容;新代码请用 /dashboard/summary 与 /dashboard/badges)。
GET /api/admin/dashboard
响应含 summary 四指标 + pending_approvals / pending_requests。
"""
total_users = db.session.query(func.count(User.id)).scalar()
active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar()
total_conversations = db.session.query(func.count(ChatLog.id)).scalar()
avg_score = db.session.query(func.avg(Feedback.score)).scalar()
avg_score = float(avg_score) if avg_score else 0.0
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar()
return jsonify({'total_users': total_users, 'active_agents': active_agents, 'total_conversations': total_conversations, 'avg_score': round(avg_score, 1), 'pending_approvals': pending_approvals})
summary = _compute_dashboard_summary()
badges = _compute_dashboard_badges()
return jsonify({
'total_users': summary['user_count'],
'active_agents': summary['agent_count'],
'total_conversations': summary['total_conversations'],
'avg_score': summary['avg_score'],
'pending_approvals': badges['pending_approvals'],
'pending_requests': badges['pending_requests'],
})
@admin_bp.route('/departments', methods=['GET'])
@require_admin
@@ -303,7 +368,7 @@ def test_agent(id):
payload = {'inputs': {'query': '系统连通性测试,请简短回复OK。'}, 'response_mode': 'blocking', 'user': 'admin_test'}
else:
request_url = DifyService._build_chat_messages_url(base_url)
payload = {'inputs': {}, 'query': '系统连通性测试,请简短回复OK。', 'response_mode': 'blocking', 'conversation_id': '', 'user': 'admin_test'}
payload = {'inputs': {}, 'query': '系统连通性测试,请简短回复OK。', 'response_mode': 'blocking', 'user': 'admin_test'}
headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'}
try:
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
@@ -397,16 +462,24 @@ def list_users():
@require_admin
def create_user():
data = request.get_json() or {}
if not data.get('username'):
raise AppError(code='USER.USERNAME_REQUIRED', message='Username is required', http_status=400, details={'field': 'username'})
required_field_errors = (
('username', 'USER.USERNAME_REQUIRED', 'Username is required'),
('password', 'USER.PASSWORD_REQUIRED', 'Password is required'),
('email', 'USER.EMAIL_REQUIRED', 'Email is required'),
('real_name', 'USER.REAL_NAME_REQUIRED', 'Real name is required'),
('employee_id', 'USER.EMPLOYEE_ID_REQUIRED', 'Employee ID is required'),
('phone_number', 'USER.PHONE_REQUIRED', 'Phone number is required'),
)
for field, code, message in required_field_errors:
if _empty_to_none(data.get(field)) is None:
raise AppError(code=code, message=message, http_status=400, details={'field': field})
if db.session.query(User).filter_by(username=data['username']).first():
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS', details={'field': 'username'})
email = _empty_to_none(data.get('email'))
if email is not None and (not _is_valid_email(email)):
if not _is_valid_email(email):
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
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')))
if data.get('password'):
user.set_password(data['password'])
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
+32 -20
View File
@@ -246,10 +246,13 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first()
if log and log.retriever_resources:
for r in log.retriever_resources:
if not isinstance(r, dict):
continue
source_url = str(r.get('source_download_url') or '')
if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]):
dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip()
remote_document_id = remote_document_id or str(r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or '').strip()
resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r)
dataset_id = dataset_id or str(resolved_dataset_id or '').strip()
remote_document_id = remote_document_id or str(resolved_remote_document_id or '').strip()
if dataset_id and remote_document_id:
break
except Exception as e:
@@ -300,12 +303,26 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower()
if resp.status_code == 401:
return True
if resp.status_code in (403, 404) and 'token=' in file_url:
return True
if ctype == 'application/json':
body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower()
if 'unauthorized' in body or '"error"' in body:
return True
return False
if base_url and file_url.startswith(base_url) and ('token=' in file_url):
def _retry_with_refreshed_url(raw_url: str):
refreshed_url = _resolve_latest_integration_url(raw_url)
if not refreshed_url or refreshed_url == raw_url:
return None, raw_url
retry_headers = _build_headers(refreshed_url)
try:
return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url
except requests.RequestException as e:
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
return None, refreshed_url
if 'token=' in file_url:
try:
parsed = urlparse(file_url)
qs = parse_qs(parsed.query)
@@ -327,18 +344,20 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
except requests.RequestException as e:
current_app.logger.warning('[file-preview] upstream request failed: %s', e)
return (None, None, ('failed to fetch source file', 502))
if base_url and file_url.startswith(base_url) and ('token=' in file_url) and _should_refresh_from_response(upstream):
refreshed_url = _resolve_latest_integration_url(file_url)
if refreshed_url != file_url:
headers = _build_headers(refreshed_url)
try:
upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20))
file_url = refreshed_url
except requests.RequestException as e:
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
return (None, None, ('failed to fetch source file', 502))
if 'token=' in file_url and _should_refresh_from_response(upstream):
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
if refreshed_upstream is not None:
upstream = refreshed_upstream
file_url = refreshed_url
if upstream.status_code != 200:
if 'token=' in file_url:
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
if refreshed_upstream is not None:
upstream = refreshed_upstream
file_url = refreshed_url
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
if upstream.status_code == 404:
return None, None, ('source file not found', 404)
return None, None, (f'upstream returned status {upstream.status_code}', 502)
content = upstream.content or b''
@@ -1411,12 +1430,6 @@ def resolve_source_file():
source_ext = str(payload.get('source_ext') or '').strip().lower()
source_download_url = payload.get('source_download_url')
if source_ext in {'txt', 'md', 'markdown', 'csv', 'vtt', 'properties', 'html', 'htm'}:
current_agent = getattr(g, 'current_agent', None)
source_download_url = (
f"{request.host_url.rstrip('/')}/api/chat/source-file-text"
f"?agent_id={getattr(current_agent, 'id', '')}&dataset_id={dataset_id}&remote_document_id={remote_document_id}"
)
return jsonify({
'dataset_id': dataset_id,
@@ -1649,7 +1662,6 @@ def preview_file_raw():
# 避免在服务端走旧版转换链路导致长时间卡住。
needs_pdf_conversion = (
request.args.get('download') != '1'
and original_ext in ('doc', 'ppt', 'pptx')
and ext in ('doc', 'ppt', 'pptx')
)
if needs_pdf_conversion:
+117 -19
View File
@@ -12,6 +12,95 @@ from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
integration_bp = Blueprint('integration', __name__)
def _integration_token_secret() -> str:
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
return configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
def _decode_integration_token(token: str | None) -> dict | None:
normalized_token = str(token or '').strip()
if not normalized_token:
return None
try:
import jwt
payload = jwt.decode(
normalized_token,
_integration_token_secret(),
algorithms=['HS256'],
)
return payload if isinstance(payload, dict) else None
except Exception as e:
current_app.logger.warning(f"Integration API token validation failed: {e}")
return None
def _build_download_url(document_id: int, *, kind: str, version_id: int | None = None) -> str:
base_url = _integration_base_url()
url = f'{base_url}/api/integration/files/{document_id}/download?kind={kind}'
if version_id is not None:
url += f'&version_id={version_id}'
return url
def _version_query():
return (
db.session.query(KbDocumentVersion)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.filter(KbDocument.is_deleted.is_(False))
)
def _resolve_requested_version(file_id: int) -> tuple[KbDocumentVersion | None, KbDocument | None]:
requested_version_id = request.args.get('version_id', type=int)
token_payload = _decode_integration_token(request.args.get('token'))
if isinstance(token_payload, dict):
token_version_id = token_payload.get('version_id')
if token_version_id is not None:
try:
requested_version_id = int(token_version_id)
except (TypeError, ValueError):
current_app.logger.warning(
'Integration API token carried invalid version_id: %r',
token_version_id,
)
dataset_id = str(token_payload.get('dataset_id') or '').strip()
remote_document_id = str(token_payload.get('remote_document_id') or '').strip()
if dataset_id and remote_document_id:
record = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document))
.filter(
KbDocument.is_deleted.is_(False),
KbDocument.id == file_id,
KbDifySyncRecord.dataset_id == dataset_id,
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
if record and record.document_version and record.document_version.document:
return record.document_version, record.document_version.document
if requested_version_id is not None:
version = (
_version_query()
.filter(
KbDocumentVersion.id == requested_version_id,
KbDocumentVersion.document_id == file_id,
)
.first()
)
if version:
return version, version.document
document = _document_query().filter(KbDocument.id == file_id).first()
if not document:
return None, None
return _current_version(document), document
def _require_integration_key():
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
@@ -24,15 +113,8 @@ def _require_integration_key():
return None
token = request.args.get('token')
if token:
try:
import jwt
secret = configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
jwt.decode(token, secret, algorithms=['HS256'])
return None
except Exception as e:
current_app.logger.warning(f"Integration API token validation failed: {e}")
pass
if token and _decode_integration_token(token):
return None
raise UnauthorizedError('Unauthorized')
@@ -43,6 +125,23 @@ def _integration_base_url() -> str:
return explicit
return request.host_url.rstrip('/')
def _kb_storage_root() -> Path:
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
root.mkdir(parents=True, exist_ok=True)
return root
def _resolve_storage_path(path_value: str | None) -> Path | None:
if not path_value:
return None
raw_path = Path(str(path_value))
candidate = (raw_path if raw_path.is_absolute() else (_kb_storage_root() / raw_path)).resolve()
root = _kb_storage_root()
try:
candidate.relative_to(root)
except ValueError:
return None
return candidate
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
versions = list(getattr(document, 'versions', []) or [])
if not versions:
@@ -57,9 +156,8 @@ def _serialize_integration_document(document: KbDocument, *, version: KbDocument
if not version:
abort(404, description='No current version found.')
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
base_url = _integration_base_url()
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
markdown_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=md' if version.cleaned_file_path or version.cleaned_preview_path else None
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
@@ -86,15 +184,16 @@ def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: in
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
if kind == 'source':
path = Path(version.source_file_path)
path = _resolve_storage_path(version.source_file_path)
if path is None:
raise NotFoundError('File not found on disk.')
filename = version.source_file_name or f'document-{version.document_id}'
return (path, filename)
preferred = version.cleaned_file_path or version.cleaned_preview_path
preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path)
if not preferred:
abort(409, description='Markdown not ready.')
path = Path(preferred)
filename = f'document-{version.document_id}-v{version.version_no}.md'
return (path, filename)
return (preferred, filename)
@integration_bp.before_request
def _verify_integration_access():
@@ -189,13 +288,12 @@ def resolve_files_by_dify():
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
def download_file(file_id: int):
kind = str(request.args.get('kind') or 'md').strip().lower()
document = _document_query().filter(KbDocument.id == file_id).first()
version, document = _resolve_requested_version(file_id)
if not document:
raise NotFoundError('Document not found.')
version = _current_version(document)
if not version:
raise NotFoundError('No version found.')
path, filename = _resolve_download_path(version, kind)
if not path.exists():
raise NotFoundError('File not found on disk.')
return send_file(path, as_attachment=True, download_name=filename)
return send_file(path, as_attachment=True, download_name=filename)
+3 -6
View File
@@ -26,12 +26,9 @@ def _safe_upload_filename(raw_filename: str | None) -> str:
original_name = Path(raw_filename or '').name.strip()
if not original_name:
return 'uploaded_file'
original_path = Path(original_name)
safe_stem = secure_filename(original_path.stem)
suffix = original_path.suffix.lower()
if not safe_stem:
safe_stem = 'uploaded_file'
return f'{safe_stem}{suffix}'
import re
safe_name = re.sub(r'[\\/*?:"<>|]', '_', original_name)
return safe_name or 'uploaded_file'
def _require_user():
user = get_current_user()
+5 -3
View File
@@ -632,15 +632,15 @@ def login():
if not user:
_write_login_audit('password', 'failed', username=username, reason='user_not_found')
db.session.commit()
raise NotFoundError('User not found')
raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
if not user.check_password(password):
_write_login_audit('password', 'failed', user=user, reason='incorrect_password')
db.session.commit()
raise UnauthorizedError('Incorrect password')
raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
if user.status != 'active':
_write_login_audit('password', 'failed', user=user, reason='account_disabled')
db.session.commit()
raise ForbiddenError('Account is disabled')
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
_write_login_audit('password', 'success', user=user)
db.session.commit()
return jsonify(_build_login_payload(user, 'password'))
@@ -662,6 +662,8 @@ def login():
except (OperationalError, DatabaseError) as retry_exc:
current_app.logger.warning('Password login retry failed: %s', retry_exc)
raise ServiceUnavailableError('Database connection failed')
except AppError:
raise
except Exception as e:
db.session.rollback()
current_app.logger.exception('Login error: %s', e)
+7 -5
View File
@@ -525,9 +525,10 @@ class DifyService:
'inputs': {},
'query': query,
'response_mode': 'streaming',
'conversation_id': normalized_conversation_id,
'user': str(user_id),
}
if normalized_conversation_id:
payload['conversation_id'] = normalized_conversation_id
if files:
payload['files'] = files
@@ -866,22 +867,23 @@ class DifyService:
remote_document_id = (
resource.get('remote_document_id')
or resource.get('dify_document_id')
or resource.get('document_id')
or resource.get('source_document_id')
or resource.get('doc_id')
or metadata.get('remote_document_id')
or metadata.get('dify_document_id')
or metadata.get('document_id')
or metadata.get('source_document_id')
or metadata.get('doc_id')
or DifyService._find_first_by_keys(
resource,
[
'remote_document_id',
'dify_document_id',
'document_id',
'doc_id',
'source_document_id',
'doc_id',
],
)
or resource.get('document_id')
or metadata.get('document_id')
)
return dataset_id, remote_document_id
+15 -5
View File
@@ -203,13 +203,19 @@ class IntegrationApiService:
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
normalized_dataset_id = str(dataset_id or '').strip()
normalized_remote_document_id = str(remote_document_id or '').strip()
if not normalized_dataset_id or not normalized_remote_document_id:
return None
record = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.remote_document_id == remote_document_id,
KbDifySyncRecord.dataset_id == normalized_dataset_id,
KbDifySyncRecord.remote_document_id == normalized_remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
@@ -236,13 +242,17 @@ class IntegrationApiService:
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
payload = {
'dataset_id': 'local',
'remote_document_id': remote_document_id,
'dataset_id': normalized_dataset_id,
'remote_document_id': normalized_remote_document_id,
'version_id': version.id,
'exp': exp
}
token = jwt.encode(payload, secret, algorithm='HS256')
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source&token={token}'
source_download_url = (
f'{base_url}/api/integration/files/{document.id}/download'
f'?kind=source&version_id={version.id}&token={token}'
)
return {
"source_download_url": source_download_url,
@@ -266,7 +276,7 @@ class IntegrationApiService:
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return None
return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
url = f"{base_url}/api/integration/dify-file"
headers = {"X-Integration-Key": api_key}
@@ -177,6 +177,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
remote_document_id = None
remote_document_name = None
upload_name = version.source_file_name or document.title
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
try:
payload = service.get_document(
@@ -184,23 +185,23 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
document_id=existing_record.remote_document_id,
)
remote_document_id = payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('name') or existing_record.remote_document_name or document.title
remote_document_name = payload.get('name') or existing_record.remote_document_name or upload_name
except KbDifySyncError as exc:
if not _is_remote_document_missing(str(exc)):
raise
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
name=upload_name,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or document.title
remote_document_name = payload.get('document', {}).get('name') or upload_name
elif existing_record and existing_record.dataset_id == dataset_id:
try:
payload = service.update_document_by_text(
dataset_id=dataset_id,
document_id=existing_record.remote_document_id,
name=document.title,
name=upload_name,
text=text,
)
except KbDifySyncError as exc:
@@ -208,19 +209,19 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
raise
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
name=upload_name,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('document', {}).get('name') or document.title
remote_document_name = payload.get('document', {}).get('name') or upload_name
else:
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
name=upload_name,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or document.title
remote_document_name = payload.get('document', {}).get('name') or upload_name
if not remote_document_id:
raise KbDifySyncError('Dify 未返回远端文档 ID')
+18 -1
View File
@@ -60,7 +60,8 @@ def test_user_management(client, admin_headers):
"role": "user",
"password": "password123",
"real_name": "Test User",
"employee_id": "EMP001"
"employee_id": "EMP001",
"phone_number": "13800000001"
}
response = client.post('/api/admin/users', json=new_user, headers=admin_headers)
assert response.status_code == 201
@@ -180,6 +181,22 @@ def test_reports(client, admin_headers):
"""
Test report endpoints
"""
response = client.get('/api/admin/dashboard/summary', headers=admin_headers)
assert response.status_code == 200
data = response.json
assert set(data.keys()) == {'agent_count', 'user_count', 'total_conversations', 'avg_score'}
assert isinstance(data['agent_count'], int)
assert isinstance(data['user_count'], int)
assert isinstance(data['total_conversations'], int)
assert isinstance(data['avg_score'], (int, float))
response = client.get('/api/admin/dashboard/badges', headers=admin_headers)
assert response.status_code == 200
badges = response.json
assert set(badges.keys()) == {'pending_approvals', 'pending_requests'}
assert isinstance(badges['pending_approvals'], int)
assert isinstance(badges['pending_requests'], int)
response = client.get('/api/admin/reports/usage', headers=admin_headers)
assert response.status_code == 200
data = response.json
+7 -3
View File
@@ -100,8 +100,12 @@ def test_login_success(client):
def test_login_fail(client):
res = client.post('/api/user/login', json={'username': 'test1', 'password': 'wrongpassword'})
assert res.status_code == 401
assert 'Incorrect password' in res.get_json()['error']
body = res.get_json()
assert body['error']['code'] == 'AUTH.INCORRECT_PASSWORD'
assert 'Incorrect password' in body['error']['message']
res = client.post('/api/user/login', json={'username': 'nonexistent', 'password': 'password'})
assert res.status_code == 404
assert 'User not found' in res.get_json()['error']
body = res.get_json()
assert body['error']['code'] == 'AUTH.USER_NOT_FOUND'
assert 'User not found' in body['error']['message']
+6 -3
View File
@@ -52,7 +52,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
"password": "pwd",
"email": "au1@e.com",
"real_name": "Admin User 1",
"employee_id": "ADM001"
"employee_id": "ADM001",
"phone_number": "13800000011"
}
response = client.post('/api/admin/users', json=u1, headers=admin_headers)
assert response.status_code == 201
@@ -63,7 +64,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
"password": "pwd",
"email": "au2@e.com",
"real_name": "Admin User 2",
"employee_id": "ADM001"
"employee_id": "ADM001",
"phone_number": "13800000012"
}
response = client.post('/api/admin/users', json=u2, headers=admin_headers)
assert response.status_code == 400
@@ -76,7 +78,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
"password": "pwd",
"email": "au3@e.com",
"real_name": "Admin User 3",
"employee_id": "ADM003"
"employee_id": "ADM003",
"phone_number": "13800000013"
}
res = client.post('/api/admin/users', json=u3, headers=admin_headers)
u3_id = res.json['id']
+453
View File
@@ -0,0 +1,453 @@
# HXOPS 前端重构架构方案
> 更新时间:2026-06-02
> 适用范围:`frontend/` 目录
> 文档定位:定义推荐的目标架构(Feature-Module + Composables + Pinia),作为后续分阶段重构的基准。
---
## 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/
├── app/ # 应用启动层
│ ├── main.ts
│ ├── App.vue
│ ├── router/
│ │ ├── index.ts # 汇总各域路由
│ │ ├── guards.ts # 认证 / 权限守卫(从 router/index.ts 抽出)
│ │ └── routes/ # 按业务域拆分路由表
│ │ ├── auth.routes.ts
│ │ ├── chat.routes.ts
│ │ ├── admin.routes.ts
│ │ └── kb.routes.ts
│ └── plugins/
│ ├── i18n.ts # 仅注册 i18n 实例,messages 外置
│ └── pinia.ts
│
├── shared/ # 跨域共享(无业务语义)
│ ├── api/
│ │ ├── client.ts # requestJson、BusinessError、响应 envelope 解析
│ │ └── types.ts # 通用 API 类型
│ ├── 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/
│ │ │ ├── WorkspaceView.vue
│ │ │ └── ResetPasswordView.vue
│ │ └── components/
│ │
│ ├── chat/
│ │ ├── api/
│ │ │ └── chat.api.ts
│ │ ├── types/
│ │ │ └── chat.types.ts
│ │ ├── stores/
│ │ │ └── chat.store.ts # 会话列表、当前 agent 等
│ │ ├── composables/
│ │ │ ├── useChat.ts # SSE 流式对话(保留并增强)
│ │ │ ├── useChatSessions.ts
│ │ │ └── useSourceFiles.ts # 源文件 / 检索来源逻辑
│ │ ├── 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/
│ │ │ └── knowledge-base/
│ │ └── components/
│ │ └── AdminNav.vue
│ │
│ └── kb/
│ ├── api/
│ │ └── kb.api.ts
│ ├── views/
│ │ └── KbWorkspaceView.vue
│ └── components/ # 迁移现有 components/kb/*
│
├── 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` | `app/` | 启动与全局插件注册 |
| `src/router/index.ts` | `app/router/` | 路由表与守卫拆分 |
| `src/api/client.ts` | `shared/api/client.ts` | 保持不变,作为统一 HTTP 层 |
| `src/api/*.ts` | `features/*/api/` | 按业务域归属 |
| `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/` | 知识库域 |
| `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/auth/views/` | 登录 / 工作台 |
| `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(知识库)
| 项 | 说明 |
|----|------|
| 路由 | `/kb/workspace`;`/kb/admin` redirect 至 `/admin/knowledge-base` |
| 组件 | 迁移 `components/kb/KbAdminPanel.vue`、`DifyHealthDialog.vue` 等 |
| 迁移来源 | `views/KbWorkspaceView.vue`(~2400 行)、`api/kb.ts` |
---
## 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 { BaseDialog } from '@/shared/components/BaseDialog.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` → 现有 `api/client.ts` |
| 路由常量 | `shared/constants/routes.ts` |
| 兼容入口 | `router/index.ts` re-export `app/router` |
### 7.2 启动顺序(main.ts)
```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 落地说明(已实现)
Phase 1 目标:管理后台嵌套子路由 + 首个独立模块 `agents`。
### 8.1 路由结构
| URL | 组件 | 说明 |
|-----|------|------|
| `/admin` | redirect → `/admin/dashboard` | |
| `/admin/agents` | `AgentsPage.vue` | **已独立拆分** |
| `/admin/dashboard` 等 | `AdminLegacyPage.vue` | 内嵌 `AdminView`(content-only) |
| `/admin/reports/:table?` | `AdminLegacyPage.vue` | 报表模块 |
| `/admin?module=xxx` | redirect | 兼容旧链接,跳转至 `/admin/xxx` |
### 8.2 新增文件(均含文件头注释)
```text
features/admin/
├── views/AdminLayout.vue # 壳层:顶栏 + AdminNav + router-view
├── views/AdminLegacyPage.vue # 未拆分模块的过渡容器
├── components/AdminNav.vue # 子路由导航
├── modules/agents/
│ ├── AgentsPage.vue
│ ├── composables/useAgentsAdmin.ts
│ └── components/{AgentTestModal,AgentPermissionModal}.vue
├── stores/admin-nav.store.ts
├── composables/useAdminNavBadges.ts
├── constants/modules.ts
└── types/{admin,agent}.types.ts
```
### 8.3 构建验证
`npm run build` 通过;`AgentsPage`、`AdminLayout`、`AdminLegacyPage` 已代码分割为独立 chunk。
### 8.4 下一步(Phase 2)
- 继续拆分 `users`、`permissions` 等 admin 模块
- 拆分 `ChatView.vue` 为 `features/chat/components/*`
---
## 9. 相关文档
- [项目上下文与技术栈](./project_context.md)
- [UI 设计系统](./ui/DESIGN_SYSTEM.md)
- [UI 编码规范](./ui/UI_CODING_GUIDELINES.md)
+136
View File
@@ -17,6 +17,7 @@
"highlight.js": "^11.11.1",
"lucide-vue-next": "^0.575.0",
"marked": "^17.0.3",
"pinia": "^3.0.4",
"vue": "^3.5.25",
"vue-i18n": "^11.2.8",
"vue-router": "^4.6.4",
@@ -699,6 +700,30 @@
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
"license": "MIT"
},
"node_modules/@vue/devtools-kit": {
"version": "7.7.9",
"resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.9.tgz",
"integrity": "sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==",
"license": "MIT",
"dependencies": {
"@vue/devtools-shared": "^7.7.9",
"birpc": "^2.3.0",
"hookable": "^5.5.3",
"mitt": "^3.0.1",
"perfect-debounce": "^1.0.0",
"speakingurl": "^14.0.1",
"superjson": "^2.2.2"
}
},
"node_modules/@vue/devtools-shared": {
"version": "7.7.9",
"resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.9.tgz",
"integrity": "sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==",
"license": "MIT",
"dependencies": {
"rfdc": "^1.4.1"
}
},
"node_modules/@vue/language-core": {
"version": "3.2.5",
"resolved": "https://mirrors.tencent.com/npm/@vue/language-core/-/language-core-3.2.5.tgz",
@@ -916,6 +941,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/birpc": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/birpc/-/birpc-2.9.0.tgz",
"integrity": "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/braces": {
"version": "3.0.3",
"resolved": "https://mirrors.tencent.com/npm/braces/-/braces-3.0.3.tgz",
@@ -1084,6 +1118,21 @@
"node": ">= 6"
}
},
"node_modules/copy-anything": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz",
"integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==",
"license": "MIT",
"dependencies": {
"is-what": "^5.2.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://mirrors.tencent.com/npm/crc-32/-/crc-32-1.2.2.tgz",
@@ -1496,6 +1545,12 @@
"node": ">=12.0.0"
}
},
"node_modules/hookable": {
"version": "5.5.3",
"resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz",
"integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==",
"license": "MIT"
},
"node_modules/is-binary-path": {
"version": "2.1.0",
"resolved": "https://mirrors.tencent.com/npm/is-binary-path/-/is-binary-path-2.1.0.tgz",
@@ -1553,6 +1608,18 @@
"node": ">=0.12.0"
}
},
"node_modules/is-what": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz",
"integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/mesqueeb"
}
},
"node_modules/jiti": {
"version": "1.21.7",
"resolved": "https://mirrors.tencent.com/npm/jiti/-/jiti-1.21.7.tgz",
@@ -1944,6 +2011,12 @@
"mini-svg-data-uri": "cli.js"
}
},
"node_modules/mitt": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
"integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
"license": "MIT"
},
"node_modules/muggle-string": {
"version": "0.4.1",
"resolved": "https://mirrors.tencent.com/npm/muggle-string/-/muggle-string-0.4.1.tgz",
@@ -2027,6 +2100,12 @@
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
"license": "MIT"
},
"node_modules/perfect-debounce": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz",
"integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==",
"license": "MIT"
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://mirrors.tencent.com/npm/picocolors/-/picocolors-1.1.1.tgz",
@@ -2054,6 +2133,36 @@
"node": ">=0.10.0"
}
},
"node_modules/pinia": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/pinia/-/pinia-3.0.4.tgz",
"integrity": "sha512-l7pqLUFTI/+ESXn6k3nu30ZIzW5E2WZF/LaHJEpoq6ElcLD+wduZoB2kBN19du6K/4FDpPMazY2wJr+IndBtQw==",
"license": "MIT",
"dependencies": {
"@vue/devtools-api": "^7.7.7"
},
"funding": {
"url": "https://github.com/sponsors/posva"
},
"peerDependencies": {
"typescript": ">=4.5.0",
"vue": "^3.5.11"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/pinia/node_modules/@vue/devtools-api": {
"version": "7.7.9",
"resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.9.tgz",
"integrity": "sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==",
"license": "MIT",
"dependencies": {
"@vue/devtools-kit": "^7.7.9"
}
},
"node_modules/pirates": {
"version": "4.0.7",
"resolved": "https://mirrors.tencent.com/npm/pirates/-/pirates-4.0.7.tgz",
@@ -2301,6 +2410,12 @@
"node": ">=0.10.0"
}
},
"node_modules/rfdc": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
"integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
"license": "MIT"
},
"node_modules/rolldown": {
"version": "1.0.0-rc.5",
"resolved": "https://mirrors.tencent.com/npm/rolldown/-/rolldown-1.0.0-rc.5.tgz",
@@ -2389,6 +2504,15 @@
"node": ">=0.10.0"
}
},
"node_modules/speakingurl": {
"version": "14.0.1",
"resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz",
"integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://mirrors.tencent.com/npm/ssf/-/ssf-0.11.2.tgz",
@@ -2423,6 +2547,18 @@
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/superjson": {
"version": "2.2.6",
"resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.6.tgz",
"integrity": "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==",
"license": "MIT",
"dependencies": {
"copy-anything": "^4"
},
"engines": {
"node": ">=16"
}
},
"node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0",
"resolved": "https://mirrors.tencent.com/npm/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
+1
View File
@@ -18,6 +18,7 @@
"highlight.js": "^11.11.1",
"lucide-vue-next": "^0.575.0",
"marked": "^17.0.3",
"pinia": "^3.0.4",
"vue": "^3.5.25",
"vue-i18n": "^11.2.8",
"vue-router": "^4.6.4",
+10
View File
@@ -1,5 +1,6 @@
import { getAuthHeaders } from '../utils/auth';
import { requestJson } from './client';
import type { AdminDashboardBadges, AdminDashboardSummary } from '@/features/admin/types/dashboard.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
@@ -73,6 +74,15 @@ export const batchUpdateAdminPermissions = (payload: Record<string, unknown>) =>
export const importAdminPermissions = (formData: FormData) =>
requestJson('/api/admin/permissions/import', { method: 'POST', ...auth(), body: formData });
// Dashboard(轻量聚合,避免拉全表)
/** 仪表盘四张卡片:Agent 数、用户数、对话总数、平均评分 */
export const getAdminDashboardSummary = () =>
requestJson<AdminDashboardSummary>('/api/admin/dashboard/summary', auth());
/** 侧栏角标:待审批用户数、待处理权限申请数 */
export const getAdminDashboardBadges = () =>
requestJson<AdminDashboardBadges>('/api/admin/dashboard/badges', auth());
// Reports
export const getAdminUsageReport = () => requestJson<any>('/api/admin/reports/usage', auth());
export const getAdminFeedbackReport = () => requestJson<any>('/api/admin/reports/feedback', auth());
+7
View File
@@ -0,0 +1,7 @@
/**
* app/plugins/pinia.ts
* 创建并导出 Pinia 实例,在 main.ts 中注册。
*/
import { createPinia } from 'pinia';
export const pinia = createPinia();
+49
View File
@@ -0,0 +1,49 @@
/**
* app/router/guards.ts
* 全局路由守卫:认证、权限、旧 URL 兼容、document.title。
*/
import type { Router } from 'vue-router';
import { config } from '@/config';
import { adminModulePath } from '@/features/admin/constants/modules';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { DEFAULT_CHAT_AGENT_ID, isPublicPath } from '@/shared/constants/routes';
export function setupRouterGuards(router: Router): void {
router.beforeEach((to, _from, next) => {
const auth = useAuthStore();
auth.syncFromStorage();
if (to.path === '/admin' && typeof to.query.module === 'string' && to.query.module) {
next(adminModulePath(to.query.module));
return;
}
if (to.matched.some((r) => r.meta.requiresAdmin)) {
if (!auth.isAdmin) {
next('/workspace');
return;
}
}
if (to.path === '/') {
if (auth.isLoggedIn) {
next(`/chat/${DEFAULT_CHAT_AGENT_ID}`);
return;
}
next('/workspace');
return;
}
if (!auth.isLoggedIn && !isPublicPath(to.path)) {
next('/workspace');
return;
}
next();
});
router.afterEach((to) => {
const baseTitle = config.appTitle || 'AI工作台';
document.title = to.meta.title ? `${String(to.meta.title)} - ${baseTitle}` : baseTitle;
});
}
+16
View File
@@ -0,0 +1,16 @@
/**
* app/router/index.ts
* 创建 Vue Router 实例并注册守卫。
*/
import { createRouter, createWebHistory } from 'vue-router';
import { appRoutes } from './routes';
import { setupRouterGuards } from './guards';
const router = createRouter({
history: createWebHistory(),
routes: appRoutes,
});
setupRouterGuards(router);
export default router;
@@ -0,0 +1,110 @@
/**␍
* app/router/routes/admin.routes.ts␍
* 管理后台嵌套路由;全部 admin 模块已独立拆分。␍
*/␍
import type { RouteRecordRaw } from 'vue-router';␍
␍
const AdminLayout = () => import('@/features/admin/views/AdminLayout.vue');␍
const AgentsPage = () => import('@/features/admin/modules/agents/AgentsPage.vue');␍
const UsersPage = () => import('@/features/admin/modules/users/UsersPage.vue');␍
const DepartmentsPage = () => import('@/features/admin/modules/departments/DepartmentsPage.vue');␍
const ApprovalsPage = () => import('@/features/admin/modules/approvals/ApprovalsPage.vue');␍
const AnnouncementsPage = () => import('@/features/admin/modules/announcements/AnnouncementsPage.vue');␍
const QuestionsPage = () => import('@/features/admin/modules/questions/QuestionsPage.vue');␍
const RequestsPage = () => import('@/features/admin/modules/requests/RequestsPage.vue');␍
const PermissionsPage = () => import('@/features/admin/modules/permissions/PermissionsPage.vue');␍
const DashboardPage = () => import('@/features/admin/modules/dashboard/DashboardPage.vue');␍
const SchedulesPage = () => import('@/features/admin/modules/schedules/SchedulesPage.vue');␍
const KnowledgeBasePage = () => import('@/features/admin/modules/knowledge-base/KnowledgeBasePage.vue');␍
const WecomPage = () => import('@/features/admin/modules/wecom/WecomPage.vue');␍
const ReportsPage = () => import('@/features/admin/modules/reports/ReportsPage.vue');␍
␍
export const adminRoutes: RouteRecordRaw[] = [␍
{␍
path: '/admin',␍
component: AdminLayout,␍
meta: { requiresAdmin: true },␍
children: [␍
{ path: '', redirect: '/admin/dashboard' },␍
{␍
path: 'dashboard',␍
name: 'AdminDashboard',␍
component: DashboardPage,␍
meta: { requiresAdmin: true, adminModule: 'dashboard', title: '概览' },␍
},␍
{␍
path: 'schedules',␍
name: 'AdminSchedules',␍
component: SchedulesPage,␍
meta: { requiresAdmin: true, adminModule: 'schedules', title: '定时任务' },␍
},␍
{␍
path: 'knowledge-base',␍
name: 'AdminKnowledgeBase',␍
component: KnowledgeBasePage,␍
meta: { requiresAdmin: true, adminModule: 'knowledge_base', title: '知识库' },␍
},␍
{␍
path: 'wecom',␍
name: 'AdminWecom',␍
component: WecomPage,␍
meta: { requiresAdmin: true, adminModule: 'wecom', title: '企业微信' },␍
},␍
{␍
path: 'approvals',␍
name: 'AdminApprovals',␍
component: ApprovalsPage,␍
meta: { requiresAdmin: true, adminModule: 'approvals', title: '用户审批' },␍
},␍
{␍
path: 'agents',␍
name: 'AdminAgents',␍
component: AgentsPage,␍
meta: { requiresAdmin: true, adminModule: 'agents', title: '应用管理' },␍
},␍
{␍
path: 'users',␍
name: 'AdminUsers',␍
component: UsersPage,␍
meta: { requiresAdmin: true, adminModule: 'users', title: '用户管理' },␍
},␍
{␍
path: 'departments',␍
name: 'AdminDepartments',␍
component: DepartmentsPage,␍
meta: { requiresAdmin: true, adminModule: 'departments', title: '部门管理' },␍
},␍
{␍
path: 'announcements',␍
name: 'AdminAnnouncements',␍
component: AnnouncementsPage,␍
meta: { requiresAdmin: true, adminModule: 'announcements', title: '公告管理' },␍
},␍
{␍
path: 'questions',␍
name: 'AdminQuestions',␍
component: QuestionsPage,␍
meta: { requiresAdmin: true, adminModule: 'questions', title: '常用问题' },␍
},␍
{␍
path: 'requests',␍
name: 'AdminRequests',␍
component: RequestsPage,␍
meta: { requiresAdmin: true, adminModule: 'requests', title: '权限申请' },␍
},␍
{␍
path: 'permissions',␍
name: 'AdminPermissions',␍
component: PermissionsPage,␍
meta: { requiresAdmin: true, adminModule: 'permissions', title: '权限管理' },␍
},␍
{␍
path: 'reports/:table?',␍
name: 'AdminReports',␍
component: ReportsPage,␍
meta: { requiresAdmin: true, adminModule: 'reports', title: '报表' },␍
},␍
],␍
},␍
];␍
␍
@@ -0,0 +1,14 @@
/**
* app/router/routes/auth.routes.ts
* 认证 / 工作台相关路由。
*/
import type { RouteRecordRaw } from 'vue-router';
import WorkspaceView from '@/views/WorkspaceView.vue';
import ResetPasswordView from '@/views/ResetPasswordView.vue';
export const authRoutes: RouteRecordRaw[] = [
{ path: '/', name: 'Home', component: WorkspaceView },
{ path: '/workspace', name: 'Workspace', component: WorkspaceView },
{ path: '/casdoor-callback', name: 'CasdoorCallback', component: WorkspaceView },
{ path: '/reset-password', name: 'ResetPassword', component: ResetPasswordView },
];
@@ -0,0 +1,10 @@
/**
* app/router/routes/chat.routes.ts
* 对话相关路由。
*/
import type { RouteRecordRaw } from 'vue-router';
import ChatView from '@/views/ChatView.vue';
export const chatRoutes: RouteRecordRaw[] = [
{ path: '/chat/:agentId', name: 'Chat', component: ChatView, props: true },
];
+16
View File
@@ -0,0 +1,16 @@
/**
* app/router/routes/index.ts
* 汇总各业务域路由表。
*/
import type { RouteRecordRaw } from 'vue-router';
import { adminRoutes } from './admin.routes';
import { authRoutes } from './auth.routes';
import { chatRoutes } from './chat.routes';
import { kbRoutes } from './kb.routes';
export const appRoutes: RouteRecordRaw[] = [
...authRoutes,
...chatRoutes,
...adminRoutes,
...kbRoutes,
];
@@ -0,0 +1,11 @@
/**
* app/router/routes/kb.routes.ts
* 知识库相关路由。
*/
import type { RouteRecordRaw } from 'vue-router';
import KbWorkspaceView from '@/views/KbWorkspaceView.vue';
export const kbRoutes: RouteRecordRaw[] = [
{ path: '/kb/workspace', name: 'KbWorkspace', component: KbWorkspaceView, meta: { title: '知识库工作台' } },
{ path: '/kb/admin', redirect: { path: '/admin/knowledge-base' } },
];
+42 -11
View File
@@ -129,6 +129,42 @@ const clearOfficeObjectUrl = () => {
officeKind.value = null;
};
const extractErrorMessage = (payload: any, fallback: string) => {
if (!payload) return fallback;
if (typeof payload === 'string' && payload.trim()) return payload.trim();
if (typeof payload?.message === 'string' && payload.message.trim()) return payload.message.trim();
if (typeof payload?.error === 'string' && payload.error.trim()) return payload.error.trim();
if (typeof payload?.error?.message === 'string' && payload.error.message.trim()) return payload.error.message.trim();
if (typeof payload?.detail === 'string' && payload.detail.trim()) return payload.detail.trim();
return fallback;
};
const readErrorMessage = async (res: Response) => {
const fallback = `HTTP ${res.status}`;
const contentType = (res.headers.get('content-type') || '').toLowerCase();
if (contentType.includes('application/json')) {
const payload = await res.json().catch(() => null);
return extractErrorMessage(payload, fallback);
}
const text = await res.text().catch(() => '');
return extractErrorMessage(text, fallback);
};
const extractDownloadFilename = (res: Response) => {
const disposition = res.headers.get('content-disposition') || '';
const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
if (utf8Match?.[1]) {
try {
return decodeURIComponent(utf8Match[1]);
} catch {
return utf8Match[1];
}
}
const asciiMatch = disposition.match(/filename="([^"]+)"/i);
if (asciiMatch?.[1]) return asciiMatch[1];
return '';
};
const applyExcelPreview = (buffer: ArrayBuffer) => {
const workbook = XLSX.read(buffer, { type: 'array' });
if (!workbook.SheetNames.length) {
@@ -182,8 +218,7 @@ const loadSheetPreview = async () => {
headers: props.authHeaders || {},
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data?.error || `HTTP ${res.status}`);
throw new Error(await readErrorMessage(res));
}
excelPreview.value = await res.json();
@@ -202,8 +237,7 @@ const loadOfficeContent = async () => {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
throw new Error(await readErrorMessage(res));
}
const buffer = await res.arrayBuffer();
@@ -238,8 +272,7 @@ const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
throw new Error(await readErrorMessage(res));
}
const blob = await res.blob();
@@ -290,8 +323,7 @@ const loadBinaryContent = async () => {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
throw new Error(await readErrorMessage(res));
}
const blob = await res.blob();
@@ -314,15 +346,14 @@ const downloadFile = async () => {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
throw new Error(await readErrorMessage(res));
}
const blob = await res.blob();
const downloadUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = props.file.name || 'download';
link.download = extractDownloadFilename(res) || props.file.name || 'download';
document.body.appendChild(link);
link.click();
link.remove();
+2
View File
@@ -43,6 +43,7 @@ type RunStatus = 'running' | 'done' | 'error';
interface ChatRun {
runId: number;
agentId: number;
viewId: number;
query: string;
messages: ChatMessage[];
@@ -199,6 +200,7 @@ export function useChat() {
const runMessages = messages.value;
const run: ChatRun = {
runId: ++runSeq,
agentId,
viewId: runViewId,
query,
messages: runMessages,
+1
View File
@@ -61,6 +61,7 @@ export const config = {
permissions: true, // 应用权限
requests: true, // 审批权限
reports: true, // 数据报表
schedules: true, // 定时任务
}
}
};
@@ -0,0 +1,128 @@
/**
* features/admin/components/AdminNav.vue
* 管理后台左侧导航,使用子路由跳转。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import {
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2,
} from 'lucide-vue-next';
import type { Component } from 'vue';
import { config } from '@/config';
import { ADMIN_MODULE_METAS, ADMIN_REPORT_TABLES } from '../constants/modules';
import { useAdminNavStore } from '../stores/admin-nav.store';
import type { AdminModuleId } from '../types/admin.types';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const navStore = useAdminNavStore();
const iconMap: Record<AdminModuleId, Component> = {
dashboard: LayoutDashboard,
approvals: UserPlus,
users: UserCog,
departments: Building,
agents: Bot,
knowledge_base: FileText,
schedules: Settings2,
announcements: Megaphone,
questions: MessageCircleQuestion,
wecom: Link2,
permissions: Users,
requests: ShieldCheck,
reports: BarChart2,
};
const visibleModules = computed(() =>
ADMIN_MODULE_METAS.filter((item) => config.admin.modules[item.configKey] !== false),
);
const isModuleActive = (moduleId: AdminModuleId): boolean =>
route.meta.adminModule === moduleId;
const isReportsActive = computed(() => route.meta.adminModule === 'reports');
const getReportTableLabel = (table: string): string => {
const i18nKey = `admin.report.tables.${table}`;
const translated = t(i18nKey);
if (translated && translated !== i18nKey) return translated;
return table.replace(/_/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase());
};
const navigateModule = (routeName: string): void => {
router.push({ name: routeName });
};
const navigateReport = (table: string): void => {
router.push({ name: 'AdminReports', params: { table } });
};
</script>
<template>
<aside
class="surface-panel rounded-2xl shadow-sm h-fit md:sticky md:top-24 overflow-hidden shrink-0 z-10 transition-all duration-300"
:class="navStore.sidebarCollapsed ? 'w-0 md:w-20' : 'w-full md:w-64'"
>
<nav class="flex md:flex-col p-3 gap-1 overflow-x-auto md:overflow-visible no-scrollbar">
<button
v-for="item in visibleModules"
:key="item.id"
type="button"
class="admin-nav-btn group"
:class="{ 'admin-nav-btn--active': isModuleActive(item.id) }"
:title="navStore.sidebarCollapsed ? t(item.labelKey) : ''"
@click="navigateModule(item.routeName)"
>
<component
:is="iconMap[item.id]"
class="w-5 h-5 transition-transform group-hover:scale-110 flex-shrink-0"
:class="isModuleActive(item.id) ? 'text-brand-600' : 'text-muted group-hover:text-secondary'"
/>
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t(item.labelKey) }}</span>
<span
v-if="navStore.badgeForModule(item.id) && !navStore.sidebarCollapsed"
class="ml-auto bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-sm"
>
{{ navStore.badgeForModule(item.id) }}
</span>
<div
v-if="isModuleActive(item.id)"
class="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-brand-600 rounded-r-full"
/>
</button>
<div v-if="config.admin.modules.reports !== false" class="flex flex-col flex-shrink-0">
<button
type="button"
class="admin-nav-btn group justify-between"
:class="{ 'admin-nav-btn--active': isReportsActive }"
@click="navStore.reportsExpanded = !navStore.reportsExpanded"
>
<div class="flex items-center gap-3">
<BarChart2 class="w-5 h-5 flex-shrink-0" :class="isReportsActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.reports') }}</span>
</div>
</button>
<div
v-if="navStore.reportsExpanded && !navStore.sidebarCollapsed"
class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6"
>
<button
v-for="table in ADMIN_REPORT_TABLES"
:key="table"
type="button"
class="admin-nav-subitem"
:class="{ 'admin-nav-subitem--active': isReportsActive && route.params.table === table }"
@click="navigateReport(table)"
>
{{ getReportTableLabel(table) }}
</button>
</div>
</div>
</nav>
</aside>
</template>
@@ -0,0 +1,12 @@
/**
* features/admin/composables/useAdminNavBadges.ts
* 暴露角标刷新入口;拉取与缓存放 admin-nav.store(不在此 composable 内 onMounted,避免子页面重复请求)。
*/
import { useAdminNavStore } from '../stores/admin-nav.store';
export function useAdminNavBadges() {
const navStore = useAdminNavStore();
return {
refreshBadges: () => navStore.refreshBadges(),
};
}
@@ -0,0 +1,52 @@
/**
* features/admin/constants/modules.ts
* 管理后台模块元数据,AdminNav 与子路由共用。
*/
import type { AdminModuleId, AdminReportTableId } from '../types/admin.types';
export interface AdminModuleMeta {
id: AdminModuleId;
routeName: string;
path: string;
labelKey: string;
configKey: keyof typeof import('@/config').config.admin.modules;
}
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'reports',
]);
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
{ id: 'dashboard', routeName: 'AdminDashboard', path: 'dashboard', labelKey: 'admin.nav.dashboard', configKey: 'dashboard' },
{ id: 'approvals', routeName: 'AdminApprovals', path: 'approvals', labelKey: 'admin.nav.approvals', configKey: 'approvals' },
{ id: 'users', routeName: 'AdminUsers', path: 'users', labelKey: 'admin.nav.users', configKey: 'users' },
{ id: 'departments', routeName: 'AdminDepartments', path: 'departments', labelKey: 'admin.nav.departments', configKey: 'departments' },
{ id: 'agents', routeName: 'AdminAgents', path: 'agents', labelKey: 'admin.nav.agents', configKey: 'agents' },
{ id: 'knowledge_base', routeName: 'AdminKnowledgeBase', path: 'knowledge-base', labelKey: 'admin.nav.knowledgeBase', configKey: 'knowledge_base' },
{ id: 'schedules', routeName: 'AdminSchedules', path: 'schedules', labelKey: 'admin.nav.schedules', configKey: 'schedules' },
{ id: 'announcements', routeName: 'AdminAnnouncements', path: 'announcements', labelKey: 'admin.nav.announcements', configKey: 'announcements' },
{ id: 'questions', routeName: 'AdminQuestions', path: 'questions', labelKey: 'admin.nav.questions', configKey: 'questions' },
{ id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' },
{ id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' },
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
];
export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
'users',
'agents',
'chat_logs',
'permission_requests',
'general_feedbacks',
'feedbacks',
];
export const LEGACY_MODULE_QUERY_TO_PATH: Record<string, string> = {};
export const adminModulePath = (moduleId: AdminModuleId | string): string => {
if (moduleId === 'reports') return '/admin/reports';
const meta = ADMIN_MODULE_METAS.find((m) => m.id === moduleId);
if (meta) return `/admin/${meta.path}`;
return `/admin/${LEGACY_MODULE_QUERY_TO_PATH[moduleId] || moduleId}`;
};
+10
View File
@@ -0,0 +1,10 @@
/**
* features/admin/index.ts
*
* 管理后台 feature 的公共导出入口,便于其他模块按需 import。
*/
export { default as AdminLayout } from './views/AdminLayout.vue';
export { useAdminNavStore } from './stores/admin-nav.store';
export { adminModulePath, ADMIN_MODULE_METAS } from './constants/modules';
export type { AdminModuleId } from './types/admin.types';
@@ -0,0 +1,253 @@
/**
* features/admin/modules/agents/AgentsPage.vue
*
* Agent 管理独立页面(Phase 1 首个拆分模块)。
* 路由:/admin/agents
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Bot, Plus, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import AgentPermissionModal from './components/AgentPermissionModal.vue';
import AgentTestModal from './components/AgentTestModal.vue';
import { useAgentsAdmin } from './composables/useAgentsAdmin';
const { t } = useI18n();
const {
agents,
activeUsers,
isLoading,
isSaving,
isEditing,
selectedAgentId,
form,
showTestModal,
isTesting,
testingAgent,
testResult,
showPermissionModal,
permissionAgent,
permissionUserIds,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
selectAgent,
submitAgent,
deleteAgent,
openTestModal,
runAgentTest,
openPermissionModal,
togglePermissionUser,
savePermissions,
closeDeleteConfirm,
confirmDelete,
} = useAgentsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<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">
<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>
<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">
<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>
</tr>
</thead>
<tbody>
<tr
v-for="agent in agents"
:key="agent.id"
class="group cursor-pointer"
:class="{ 'bg-blue-50/50': selectedAgentId === agent.id }"
@click="selectAgent(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>
<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">
{{ 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">
<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 class="text-muted">{{ t('admin.agent.urlLabel') }}:</span> {{ agent.extra_config?.iframe_url }}
</span>
</td>
<td class="px-8 py-5">
<span
class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium border"
: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'" />
{{ 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>
</tr>
</tbody>
</table>
</div>
</template>
<AgentTestModal
:visible="showTestModal"
:agent="testingAgent"
:result="testResult"
:is-testing="isTesting"
@close="showTestModal = false"
@retest="runAgentTest()"
/>
<AgentPermissionModal
:visible="showPermissionModal"
:agent="permissionAgent"
:users="activeUsers()"
:selected-user-ids="permissionUserIds"
:is-saving="isSaving"
@close="showPermissionModal = false"
@save="savePermissions"
@toggle-user="togglePermissionUser"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
@cancel="closeDeleteConfirm"
/>
</section>
</template>
@@ -0,0 +1,94 @@
/**
* features/admin/modules/agents/components/AgentPermissionModal.vue
*
* 为指定 Agent 批量勾选可访问用户的权限弹窗。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentRow } from '@/features/admin/types/agent.types';
defineProps<{
visible: boolean;
agent: AgentRow | null;
users: AdminUserRow[];
selectedUserIds: number[];
isSaving: boolean;
}>();
const emit = defineEmits<{
close: [];
save: [];
toggleUser: [userId: number];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible && agent" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-2xl max-h-[90vh] animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle flex justify-between items-center">
<div>
<h3 class="text-lg font-bold text-primary">{{ t('admin.perm.agentModal.title') }}</h3>
<p class="text-sm text-muted">
{{ t('admin.perm.agentModal.agent') }}
<span class="font-medium text-blue-600">{{ agent.name }}</span>
</p>
</div>
<button type="button" class="btn-icon-ds rounded-full" @click="emit('close')">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div class="flex-1 overflow-y-auto p-8">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div
v-for="user in users"
:key="user.id"
class="flex items-center gap-3 p-3 rounded-xl border transition-all cursor-pointer"
:class="selectedUserIds.includes(user.id) ? 'border-blue-200 bg-blue-50/50' : 'border-default hover-surface-soft'"
@click="emit('toggleUser', user.id)"
>
<div
class="w-5 h-5 rounded border flex items-center justify-center transition-colors"
:class="selectedUserIds.includes(user.id) ? 'bg-blue-600 border-blue-600' : 'bg-surface border-default'"
>
<svg
v-if="selectedUserIds.includes(user.id)"
xmlns="http://www.w3.org/2000/svg"
class="h-3.5 w-3.5 text-white"
viewBox="0 0 20 20"
fill="currentColor"
>
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
</svg>
</div>
<div>
<div class="font-medium text-primary text-sm">{{ user.username }}</div>
<div class="text-xs text-muted">{{ user.real_name || user.email }}</div>
</div>
</div>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">
{{ t('admin.cancel') }}
</button>
<button
type="button"
:disabled="isSaving"
class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
@click="emit('save')"
>
<div v-if="isSaving" class="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent" />
{{ t('admin.perm.agentModal.save') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,82 @@
/**
* features/admin/modules/agents/components/AgentTestModal.vue
*
* Agent 连通性测试弹窗:展示请求 URL、输出信息与分析结果。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AgentRow, AgentTestResult } from '@/features/admin/types/agent.types';
defineProps<{
visible: boolean;
agent: AgentRow | null;
result: AgentTestResult | null;
isTesting: boolean;
}>();
const emit = defineEmits<{
close: [];
retest: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible && agent" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-3xl max-h-[90vh] animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle flex justify-between items-start">
<div>
<h3 class="text-lg font-bold text-primary">{{ t('admin.agent.testModalTitle') }}</h3>
<p class="section-desc mt-1">
{{ t('admin.agent.testModalAgent') }}:
<span class="font-medium text-blue-600">{{ agent.name }}</span>
</p>
</div>
<button type="button" class="btn-icon-ds rounded-full" @click="emit('close')">✕</button>
</div>
<div class="flex-1 overflow-y-auto p-8 space-y-5">
<div class="flex items-center justify-between">
<div class="text-sm text-secondary">
<span v-if="result?.tested_at">{{ t('admin.agent.testedAt') }}:{{ result.tested_at }}</span>
</div>
<button
type="button"
:disabled="isTesting"
class="btn-primary btn-sm disabled:opacity-50"
@click="emit('retest')"
>
{{ isTesting ? t('admin.agent.testing') : t('admin.agent.retest') }}
</button>
</div>
<div v-if="isTesting" class="text-sm text-muted">{{ t('admin.agent.testingInProgress') }}</div>
<template v-if="result">
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.requestUrl') }}</div>
<div class="admin-code-block">{{ result.request_url || '-' }}</div>
</div>
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.outputInfo') }}</div>
<pre class="admin-code-block max-h-64 overflow-y-auto whitespace-pre-wrap">{{ result.output_info || '-' }}</pre>
</div>
<div>
<div class="text-xs font-semibold text-muted uppercase tracking-wider mb-2">{{ t('admin.agent.analysis') }}</div>
<div
class="p-3 rounded-lg border text-sm"
:class="result.success ? 'bg-green-50 border-green-200 text-green-800' : 'bg-red-50 border-red-200 text-red-800'"
>
{{ result.analysis }}
<span v-if="result.http_status">(HTTP {{ result.http_status }})</span>
</div>
</div>
</template>
</div>
</div>
</div>
</template>
@@ -0,0 +1,305 @@
/**
* features/admin/modules/agents/composables/useAgentsAdmin.ts
*
* Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。
* 从原 AdminView.vue 的 agents 相关 script 抽取,供 AgentsPage 使用。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
createAdminAgent,
deleteAdminAgent,
listAdminAgents,
listAdminUsers,
saveAdminAgentPermissions,
testAdminAgent,
updateAdminAgent,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentFormState, AgentRow, AgentTestResult } from '@/features/admin/types/agent.types';
import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
export function useAgentsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const agents = ref<AgentRow[]>([]);
const users = ref<AdminUserRow[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const isEditing = ref(false);
const selectedAgentId = ref<number | null>(null);
const form = ref<AgentFormState>(createEmptyAgentForm());
const showTestModal = ref(false);
const isTesting = ref(false);
const testingAgent = ref<AgentRow | null>(null);
const testResult = ref<AgentTestResult | null>(null);
const showPermissionModal = ref(false);
const permissionAgent = ref<AgentRow | null>(null);
const permissionUserIds = ref<number[]>([]);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const activeUsers = () => users.value.filter((u) => u.status !== 'pending');
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Error loading agents:', e);
agents.value = [];
}
};
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadAgents(), loadUsers()]);
isLoading.value = false;
};
const resetForm = (): void => {
selectedAgentId.value = null;
form.value = createEmptyAgentForm();
isEditing.value = false;
};
const selectAgent = (agent: AgentRow): void => {
selectedAgentId.value = agent.id;
form.value = {
id: agent.id,
name: agent.name,
dify_app_id: agent.dify_app_id,
dify_api_key: agent.dify_api_key || '',
description: agent.description || '',
type: agent.type,
dify_app_type: agent.extra_config?.dify_app_type === 'workflow' ? 'workflow' : 'chatflow',
api_base_url: agent.api_base_url || '',
iframe_url: String(agent.extra_config?.iframe_url || ''),
is_active: agent.is_active,
};
isEditing.value = true;
};
const openDeleteConfirm = (
message: string,
action: () => Promise<void> | void,
): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const submitAgent = async (): Promise<void> => {
if (!form.value.name) {
msg.warning(t('admin.dept.msg.nameRequired'));
return;
}
isSaving.value = true;
const extra_config: Record<string, unknown> = {};
if (form.value.type === 'iframe' && form.value.iframe_url) {
extra_config.iframe_url = form.value.iframe_url;
}
if (form.value.type === 'api') {
extra_config.dify_app_type = form.value.dify_app_type === 'workflow' ? 'workflow' : 'chatflow';
}
try {
const editingId = isEditing.value ? Number(form.value.id) : null;
if (isEditing.value && form.value.id != null) {
const payload: Record<string, unknown> = {
name: form.value.name,
dify_app_id: form.value.dify_app_id,
description: form.value.description,
type: form.value.type,
api_base_url: form.value.api_base_url,
extra_config,
is_active: form.value.is_active,
};
if (form.value.dify_api_key) {
payload.dify_api_key = form.value.dify_api_key;
}
await updateAdminAgent(form.value.id, payload);
} else {
await createAdminAgent({
name: form.value.name,
dify_app_id: form.value.dify_app_id,
dify_api_key: form.value.dify_api_key,
description: form.value.description,
type: form.value.type,
api_base_url: form.value.api_base_url,
extra_config,
});
}
await loadAgents();
if (editingId) {
const updated = agents.value.find((a) => a.id === editingId);
if (updated) selectAgent(updated);
} else {
resetForm();
}
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const deleteAgent = async (id: number): Promise<void> => {
openDeleteConfirm(t('admin.agent.confirmDelete'), async () => {
try {
await deleteAdminAgent(id);
await loadAgents();
if (selectedAgentId.value === id) {
resetForm();
}
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
const openTestModal = (agent: AgentRow): void => {
testingAgent.value = agent;
testResult.value = null;
showTestModal.value = true;
void runAgentTest(agent);
};
const runAgentTest = async (agent?: AgentRow): Promise<void> => {
const target = agent || testingAgent.value;
if (!target) return;
isTesting.value = true;
try {
const data = await testAdminAgent(target.id);
testResult.value = {
success: !!data.success,
request_url: data.request_url || '',
output_info: data.output_info || '',
analysis: data.analysis || (data.success ? t('admin.agent.testDone') : t('admin.agent.testFailed')),
http_status: data.http_status,
tested_at: data.tested_at,
};
if (data.success) {
const idx = agents.value.findIndex((a) => a.id === target.id);
const row = idx >= 0 ? agents.value[idx] : undefined;
if (row) {
row.is_active = true;
}
if (selectedAgentId.value === target.id) {
form.value.is_active = true;
}
}
} catch (e) {
testResult.value = {
success: false,
request_url: '',
output_info: (e as Error).message || t('admin.agent.networkError'),
analysis: t('admin.agent.testFailedRequestException'),
http_status: 0,
};
} finally {
isTesting.value = false;
}
};
const openPermissionModal = (agent: AgentRow): void => {
permissionAgent.value = agent;
permissionUserIds.value = users.value
.filter((u) => u.agent_ids.includes(agent.id))
.map((u) => u.id);
showPermissionModal.value = true;
};
const togglePermissionUser = (userId: number): void => {
const index = permissionUserIds.value.indexOf(userId);
if (index === -1) {
permissionUserIds.value.push(userId);
} else {
permissionUserIds.value.splice(index, 1);
}
};
const savePermissions = async (): Promise<void> => {
if (!permissionAgent.value) return;
isSaving.value = true;
try {
await saveAdminAgentPermissions(
permissionAgent.value.id,
permissionUserIds.value,
);
await loadUsers();
showPermissionModal.value = false;
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
} finally {
isSaving.value = false;
}
};
return {
agents,
users,
activeUsers,
isLoading,
isSaving,
isEditing,
selectedAgentId,
form,
showTestModal,
isTesting,
testingAgent,
testResult,
showPermissionModal,
permissionAgent,
permissionUserIds,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
selectAgent,
submitAgent,
deleteAgent,
openTestModal,
runAgentTest,
openPermissionModal,
togglePermissionUser,
savePermissions,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,107 @@
/**
* features/admin/modules/announcements/AnnouncementsPage.vue
* 公告管理独立页面。路由:/admin/announcements
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useAnnouncementsAdmin } from './composables/useAnnouncementsAdmin';
const { t } = useI18n();
const {
announcements,
newAnnouncement,
isLoading,
isSaving,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
publishAnnouncement,
deleteAnnouncementItem,
closeDeleteConfirm,
confirmDelete,
} = useAnnouncementsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div>
<h2 class="section-title">{{ t('admin.announcement.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.announcement.subtitle') }}</p>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
<h3 class="font-bold text-primary mb-4">{{ t('admin.announcement.add') }}</h3>
<div class="space-y-4">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.announcement.fields.title') }}</label>
<input v-model="newAnnouncement.title" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.announcement.fields.content') }}</label>
<textarea v-model="newAnnouncement.content" rows="6" class="input-field text-sm" />
</div>
<div class="flex justify-end pt-2">
<button
type="button"
class="btn-primary btn-sm disabled:opacity-50"
:disabled="isSaving"
@click="publishAnnouncement"
>
{{ isSaving ? t('admin.save') + '...' : t('admin.announcement.publish') }}
</button>
</div>
</div>
</div>
<div class="lg:col-span-2 card shadow-sm overflow-hidden">
<div v-if="announcements.length === 0" class="p-8 text-center text-muted">
{{ t('admin.announcement.noData') }}
</div>
<div v-else class="divide-y divide-subtle">
<div
v-for="ann in announcements"
:key="ann.id"
class="p-5 hover-surface-soft transition-colors"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<h4 class="font-semibold text-primary truncate">{{ ann.title }}</h4>
<p class="text-xs text-muted mt-1">{{ new Date(ann.created_at).toLocaleString() }}</p>
</div>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
@click="deleteAnnouncementItem(ann.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
<p class="text-sm text-secondary mt-2 whitespace-pre-wrap">{{ ann.content }}</p>
</div>
</div>
</div>
</div>
</template>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</template>
@@ -0,0 +1,109 @@
/**
* features/admin/modules/announcements/composables/useAnnouncementsAdmin.ts
* 公告管理:列表、发布、删除。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { createAnnouncement, deleteAnnouncement, listAnnouncements } from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminAnnouncementRow } from '@/features/admin/types/admin.types';
import {
createEmptyAnnouncementForm,
type AnnouncementFormState,
} from '@/features/admin/types/announcement.types';
export function useAnnouncementsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const announcements = ref<AdminAnnouncementRow[]>([]);
const newAnnouncement = ref<AnnouncementFormState>(createEmptyAnnouncementForm());
const isLoading = ref(true);
const isSaving = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const loadAnnouncements = async (): Promise<void> => {
try {
announcements.value = await listAnnouncements();
} catch (e) {
console.error('Failed to load announcements', e);
announcements.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadAnnouncements();
isLoading.value = false;
};
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const publishAnnouncement = async (): Promise<void> => {
if (!newAnnouncement.value.title.trim() || !newAnnouncement.value.content.trim()) {
msg.warning(t('admin.announcement.msg.fillAll'));
return;
}
isSaving.value = true;
try {
await createAnnouncement({
title: newAnnouncement.value.title.trim(),
content: newAnnouncement.value.content.trim(),
});
newAnnouncement.value = createEmptyAnnouncementForm();
await loadAnnouncements();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const deleteAnnouncementItem = (id: number): void => {
openDeleteConfirm(t('admin.announcement.confirmDelete'), async () => {
try {
await deleteAnnouncement(id);
await loadAnnouncements();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
announcements,
newAnnouncement,
isLoading,
isSaving,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
publishAnnouncement,
deleteAnnouncementItem,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,108 @@
/**
* features/admin/modules/approvals/ApprovalsPage.vue
* 用户注册审批独立页面。路由:/admin/approvals
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ShieldCheck, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useApprovalsAdmin } from './composables/useApprovalsAdmin';
const { t } = useI18n();
const {
pendingUsers,
isLoading,
showConfirmDialog,
confirmMessage,
loadAll,
approveUser,
rejectUser,
closeConfirm,
confirmActionHandler,
} = useApprovalsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header">
<div>
<h2 class="section-title">{{ t('admin.approval.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.approval.subtitle') }}</p>
</div>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.username') }}</th>
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.nameId') }}</th>
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.contact') }}</th>
<th class="px-8 py-4 text-left text-xs">{{ t('admin.approval.headers.role') }}</th>
<th class="px-8 py-4 text-right text-xs">{{ t('admin.approval.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="pendingUsers.length === 0">
<td colspan="5" class="px-8 admin-table-empty">{{ t('admin.approval.noPending') }}</td>
</tr>
<tr v-for="user in pendingUsers" :key="user.id">
<td class="px-8 py-5 text-sm font-medium text-primary">
<div>{{ user.username }}</div>
<div class="text-xs text-muted font-normal">{{ user.email }}</div>
</td>
<td class="px-8 py-5 text-sm text-muted">
<div>{{ user.real_name || '-' }}</div>
<div class="text-xs text-muted font-mono">{{ user.employee_id || '-' }}</div>
</td>
<td class="px-8 py-5 text-sm text-muted">{{ user.phone_number || '-' }}</td>
<td class="px-8 py-5">
<span
class="px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200"
>
{{ t('admin.role.' + user.role) }}
</span>
</td>
<td class="px-8 py-5 text-right flex items-center justify-end gap-2">
<button
type="button"
class="p-2 text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors"
:title="t('admin.approval.confirmApprove')"
@click="approveUser(user.id)"
>
<ShieldCheck class="w-4 h-4" />
</button>
<button
type="button"
class="p-2 text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
:title="t('admin.approval.confirmReject')"
@click="rejectUser(user.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<DeleteConfirmDialog
v-model="showConfirmDialog"
:message="confirmMessage"
@cancel="closeConfirm"
@confirm="confirmActionHandler"
/>
</section>
</template>
@@ -0,0 +1,98 @@
/**
* features/admin/modules/approvals/composables/useApprovalsAdmin.ts
* 用户注册审批:待审列表、通过、拒绝。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { approveAdminUser, listAdminUsers, rejectAdminUser } from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import { useAdminNavBadges } from '@/features/admin/composables/useAdminNavBadges';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
export function useApprovalsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const { refreshBadges } = useAdminNavBadges();
const users = ref<AdminUserRow[]>([]);
const isLoading = ref(true);
const showConfirmDialog = ref(false);
const confirmMessage = ref('');
let confirmAction: (() => Promise<void> | void) | null = null;
const pendingUsers = computed(() => users.value.filter((u) => u.status === 'pending'));
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadUsers();
isLoading.value = false;
};
const openConfirm = (message: string, action: () => Promise<void> | void): void => {
confirmMessage.value = message;
confirmAction = action;
showConfirmDialog.value = true;
};
const closeConfirm = (): void => {
showConfirmDialog.value = false;
confirmAction = null;
};
const confirmActionHandler = async (): Promise<void> => {
if (!confirmAction) return;
try {
await confirmAction();
} finally {
closeConfirm();
}
};
const approveUser = (userId: number): void => {
openConfirm(t('admin.approval.confirmApprove'), async () => {
try {
await approveAdminUser(userId);
await loadUsers();
await refreshBadges();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
}
});
};
const rejectUser = (userId: number): void => {
openConfirm(t('admin.approval.confirmReject'), async () => {
try {
await rejectAdminUser(userId);
await loadUsers();
await refreshBadges();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
pendingUsers,
isLoading,
showConfirmDialog,
confirmMessage,
loadAll,
approveUser,
rejectUser,
closeConfirm,
confirmActionHandler,
};
}
@@ -0,0 +1,94 @@
/**
* features/admin/modules/dashboard/DashboardPage.vue
* 管理后台仪表盘。路由:/admin/dashboard
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { BarChart2, Bot, MessageSquare, Users } from 'lucide-vue-next';
import { useDashboardAdmin } from './composables/useDashboardAdmin';
const { t } = useI18n();
const router = useRouter();
const {
agentCount,
userCount,
totalConversations,
avgScore,
isLoading,
loadAll,
} = useDashboardAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-6 animate-fade-in">
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminAgents' })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-brand-50 rounded-xl group-hover:bg-brand-100 transition-colors">
<Bot class="w-6 h-6 text-brand-600" />
</div>
<span class="text-xs font-medium text-green-600 bg-green-50 px-2 py-1 rounded-full">
+2 {{ t('admin.dash.new') }}
</span>
</div>
<div class="text-3xl font-bold text-primary mb-1">{{ agentCount }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.activeAgents') }}</div>
</div>
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminPermissions' })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-purple-50 rounded-xl group-hover:bg-purple-100 transition-colors">
<Users class="w-6 h-6 text-purple-600" />
</div>
</div>
<div class="text-3xl font-bold text-primary mb-1">{{ userCount }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.totalUsers') }}</div>
</div>
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminReports', params: { table: 'chat_logs' } })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-indigo-50 rounded-xl group-hover:bg-indigo-100 transition-colors">
<MessageSquare class="w-6 h-6 text-indigo-600" />
</div>
</div>
<div class="text-3xl font-bold text-primary mb-1">{{ totalConversations }}</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.totalConversations') }}</div>
</div>
<div
class="card card-ds-interactive p-6 group cursor-pointer"
@click="router.push({ name: 'AdminReports', params: { table: 'feedbacks' } })"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-orange-50 rounded-xl group-hover:bg-orange-100 transition-colors">
<BarChart2 class="w-6 h-6 text-orange-600" />
</div>
</div>
<div class="text-3xl font-bold text-primary mb-1">
{{ avgScore.toFixed(1) }}
</div>
<div class="text-sm text-muted font-medium">{{ t('admin.dash.avgRating') }}</div>
</div>
</div>
</section>
</template>
@@ -0,0 +1,42 @@
/**
* features/admin/modules/dashboard/composables/useDashboardAdmin.ts
* 仪表盘概览:单次 summary 接口获取四个指标。
*/
import { ref } from 'vue';
import { getAdminDashboardSummary } from '@/api/admin';
export function useDashboardAdmin() {
const agentCount = ref(0);
const userCount = ref(0);
const totalConversations = ref(0);
const avgScore = ref(0);
const isLoading = ref(true);
const loadAll = async (): Promise<void> => {
isLoading.value = true;
try {
const summary = await getAdminDashboardSummary();
agentCount.value = summary.agent_count;
userCount.value = summary.user_count;
totalConversations.value = summary.total_conversations;
avgScore.value = summary.avg_score;
} catch (e) {
console.error('Error loading dashboard:', e);
agentCount.value = 0;
userCount.value = 0;
totalConversations.value = 0;
avgScore.value = 0;
} finally {
isLoading.value = false;
}
};
return {
agentCount,
userCount,
totalConversations,
avgScore,
isLoading,
loadAll,
};
}
@@ -0,0 +1,163 @@
/**
* features/admin/modules/departments/DepartmentsPage.vue
* 部门管理独立页面。路由:/admin/departments
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
const { t } = useI18n();
const {
departments,
editingDept,
isLoading,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
editDepartment,
saveDepartment,
deleteDepartment,
closeDeleteConfirm,
confirmDelete,
} = useDepartmentsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="flex items-center justify-between">
<div>
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
<h3 class="font-bold text-primary mb-4">
{{ editingDept.id ? t('admin.dept.edit') : t('admin.dept.add') }}
</h3>
<div class="form-stack">
<div class="space-y-1.5">
<label class="label-field block">{{ t('admin.dept.fields.name') }}</label>
<input
v-model="editingDept.name"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.namePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.code') }}</label>
<input
v-model="editingDept.code"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.codePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.company') }}</label>
<input
v-model="editingDept.company"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.companyPlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
<textarea
v-model="editingDept.description"
rows="3"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.descriptionPlaceholder')"
/>
</div>
<div class="flex justify-end gap-2 pt-2">
<button
v-if="editingDept.id"
type="button"
class="btn-ghost btn-sm"
@click="resetForm"
>
{{ t('admin.cancel') }}
</button>
<button type="button" class="btn-primary btn-sm" @click="saveDepartment">
{{ editingDept.id ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
<div class="lg:col-span-2 admin-table-section">
<div v-if="departments.length === 0" class="p-8 text-center text-muted">
{{ t('admin.dept.noDepts') }}
</div>
<table v-else class="admin-table">
<thead>
<tr>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.dept.headers.name') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.dept.headers.code') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.dept.headers.company') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase text-right">
{{ t('admin.dept.headers.actions') }}
</th>
</tr>
</thead>
<tbody class="divide-y divide-subtle">
<tr v-for="d in departments" :key="d.id">
<td class="px-6 py-4">
<div class="font-medium text-primary text-sm">{{ d.name }}</div>
<div class="text-xs text-muted truncate max-w-xs mt-0.5">{{ d.description }}</div>
</td>
<td class="px-6 py-4 text-sm text-muted font-mono">{{ d.code || '-' }}</td>
<td class="px-6 py-4 text-sm text-muted">{{ d.company || '-' }}</td>
<td class="px-6 py-4 text-right flex justify-end gap-2">
<button
type="button"
class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
@click="editDepartment(d)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
@click="deleteDepartment(d.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</template>
@@ -0,0 +1,131 @@
/**
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
* 部门管理:列表、创建、编辑、删除。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
createAdminDepartment,
deleteAdminDepartment,
listAdminDepartments,
updateAdminDepartment,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
import {
createEmptyDepartmentForm,
type DepartmentFormState,
} from '@/features/admin/types/department.types';
export function useDepartmentsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const departments = ref<AdminDepartmentRow[]>([]);
const editingDept = ref<DepartmentFormState>(createEmptyDepartmentForm());
const isLoading = ref(true);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const loadDepartments = async (): Promise<void> => {
try {
departments.value = await listAdminDepartments();
} catch (e) {
console.error('Failed to load departments', e);
departments.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadDepartments();
isLoading.value = false;
};
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const resetForm = (): void => {
editingDept.value = createEmptyDepartmentForm();
};
const editDepartment = (dept: AdminDepartmentRow): void => {
editingDept.value = {
id: dept.id,
name: dept.name,
code: dept.code || '',
company: dept.company || '',
description: dept.description || '',
};
};
const saveDepartment = async (): Promise<void> => {
if (!editingDept.value.name?.trim()) {
msg.warning(t('admin.dept.msg.nameRequired'));
return;
}
try {
const payload = {
name: editingDept.value.name,
code: editingDept.value.code,
company: editingDept.value.company,
description: editingDept.value.description,
};
if (editingDept.value.id) {
await updateAdminDepartment(editingDept.value.id, payload);
} else {
await createAdminDepartment(payload);
}
await loadDepartments();
resetForm();
} catch (e) {
msg.error((e as Error).message || t('admin.msg.failed'));
}
};
const deleteDepartment = (id: number): void => {
openDeleteConfirm(t('admin.dept.confirmDelete'), async () => {
try {
await deleteAdminDepartment(id);
await loadDepartments();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
departments,
editingDept,
isLoading,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
editDepartment,
saveDepartment,
deleteDepartment,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,13 @@
/**
* features/admin/modules/knowledge-base/KnowledgeBasePage.vue
* 知识库管理独立页面。路由:/admin/knowledge-base
*/
<script setup lang="ts">
import KbAdminPanel from '@/components/kb/KbAdminPanel.vue';
</script>
<template>
<section class="admin-table-section overflow-hidden animate-fade-in-up">
<KbAdminPanel />
</section>
</template>
@@ -0,0 +1,195 @@
/**
* features/admin/modules/permissions/PermissionsPage.vue
* 用户权限矩阵独立页面。路由:/admin/permissions
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Download, FileText, Users } from 'lucide-vue-next';
import BatchPermissionModal from '@/features/admin/modules/users/components/BatchPermissionModal.vue';
import { usePermissionsAdmin } from './composables/usePermissionsAdmin';
const { t } = useI18n();
const {
agents,
permissionFilters,
selectedUserIds,
filteredUsers,
isLoading,
isSaving,
showBatchPermissionModal,
batchPermissionForm,
loadAll,
toggleUserSelection,
toggleAllUsers,
openBatchPermissionModal,
closeBatchPermissionModal,
submitBatchPermission,
toggleUserAgentPermission,
exportPermissions,
importPermissions,
} = usePermissionsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
<div>
<h2 class="section-title">{{ t('admin.perm.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.perm.subtitle') }}</p>
</div>
<div class="flex gap-3">
<button
v-if="selectedUserIds.length > 0"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-200 active:scale-95"
@click="openBatchPermissionModal"
>
<Users class="w-4 h-4" />
<span class="font-medium">{{ t('admin.perm.batchAssign') }}</span>
</button>
<label
class="flex items-center gap-2 px-4 py-2 btn-secondary cursor-pointer text-sm font-medium transition-all shadow-sm"
>
<input type="file" accept=".csv" class="hidden" @change="importPermissions" />
<FileText class="w-4 h-4" />
{{ t('admin.perm.importCsv') }}
</label>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 btn-secondary text-sm font-medium transition-all shadow-sm"
@click="exportPermissions"
>
<Download class="w-4 h-4" />
{{ t('admin.perm.exportCsv') }}
</button>
</div>
</div>
<div class="admin-table-filters--inline">
<input
v-model="permissionFilters.username"
:placeholder="t('admin.perm.filterName')"
class="admin-table-filter-input w-48"
/>
<input
v-model="permissionFilters.department"
:placeholder="t('admin.perm.filterDept')"
class="admin-table-filter-input w-48"
/>
<select v-model="permissionFilters.role" class="admin-table-filter-input w-32">
<option value="">{{ t('admin.perm.allRoles') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="admin-table-section admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-4 py-4 w-12 text-center sticky left-0 admin-table-sticky-head z-20">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
:checked="selectedUserIds.length > 0 && selectedUserIds.length === filteredUsers.length"
@change="toggleAllUsers"
/>
</th>
<th
class="px-6 py-4 text-left text-sm sticky left-12 admin-table-sticky-head z-20 w-64 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
>
{{ t('admin.perm.headers.user') }}
</th>
<th
class="px-6 py-4 text-left text-sm sticky left-[19rem] admin-table-sticky-head z-20 w-40 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
>
{{ t('admin.perm.headers.dept') }}
</th>
<th
v-for="agent in agents"
:key="agent.id"
class="px-4 py-4 text-center text-sm min-w-[100px]"
>
<div class="flex flex-col items-center gap-1">
<span>{{ agent.name }}</span>
<span class="text-[10px] text-muted font-normal border border-default px-1 rounded">
{{ agent.type }}
</span>
</div>
</th>
</tr>
</thead>
<tbody>
<tr v-for="user in filteredUsers" :key="user.id">
<td class="px-4 py-4 text-center sticky left-0 admin-table-sticky-cell z-20">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500"
:checked="selectedUserIds.includes(user.id)"
@change="toggleUserSelection(user.id)"
/>
</td>
<td class="px-6 py-4 sticky left-12 admin-table-sticky-cell z-20 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]">
<div class="flex items-center gap-3">
<div
class="w-8 h-8 rounded-full bg-gradient-to-br from-brand-100 to-indigo-100 text-brand-600 flex items-center justify-center font-bold text-sm"
>
{{ user.username.charAt(0).toUpperCase() }}
</div>
<div class="truncate max-w-[150px]">
<div class="font-medium text-primary truncate" :title="user.username">
{{ user.username }}
</div>
<div class="text-xs text-muted truncate" :title="user.email">
{{ user.email }}
</div>
</div>
</div>
</td>
<td
class="px-6 py-4 sticky left-[19rem] admin-table-sticky-cell z-20 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]"
>
<div class="text-sm text-muted truncate" :title="user.department">
{{ user.department || '-' }}
</div>
</td>
<td
v-for="agent in agents"
:key="agent.id"
class="px-4 py-4 text-center border-l border-dashed border-subtle"
>
<input
type="checkbox"
class="admin-checkbox-lg"
:checked="user.agent_ids.includes(agent.id)"
@change="toggleUserAgentPermission(user, agent.id)"
/>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<BatchPermissionModal
:visible="showBatchPermissionModal"
:form="batchPermissionForm"
:agents="agents"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="closeBatchPermissionModal"
@save="submitBatchPermission"
/>
</section>
</template>
@@ -0,0 +1,205 @@
/**
* features/admin/modules/permissions/composables/usePermissionsAdmin.ts
* 用户权限矩阵:筛选、单格切换、批量分配、CSV 导入导出。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import * as XLSX from 'xlsx';
import {
batchUpdateAdminPermissions,
importAdminPermissions,
listAdminAgents,
listAdminUsers,
updateAdminUserPermissions,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
import {
createEmptyPermissionFilters,
type PermissionFilters,
} from '@/features/admin/types/permission.types';
import type { BatchPermissionForm } from '@/features/admin/types/user.types';
export function usePermissionsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const users = ref<AdminUserRow[]>([]);
const agents = ref<AdminAgentOption[]>([]);
const permissionFilters = ref<PermissionFilters>(createEmptyPermissionFilters());
const selectedUserIds = ref<number[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const showBatchPermissionModal = ref(false);
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
const activeUsers = computed(() => users.value.filter((u) => u.status !== 'pending'));
const filteredUsers = computed(() =>
activeUsers.value.filter((u) => {
const matchName =
!permissionFilters.value.username ||
u.username.toLowerCase().includes(permissionFilters.value.username.toLowerCase()) ||
(u.real_name &&
u.real_name.toLowerCase().includes(permissionFilters.value.username.toLowerCase()));
const matchDept =
!permissionFilters.value.department ||
(u.department &&
u.department.toLowerCase().includes(permissionFilters.value.department.toLowerCase()));
const matchRole = !permissionFilters.value.role || u.role === permissionFilters.value.role;
return matchName && matchDept && matchRole;
}),
);
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Failed to load agents', e);
agents.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadUsers(), loadAgents()]);
isLoading.value = false;
};
const toggleUserSelection = (userId: number): void => {
const index = selectedUserIds.value.indexOf(userId);
if (index === -1) {
selectedUserIds.value.push(userId);
} else {
selectedUserIds.value.splice(index, 1);
}
};
const toggleAllUsers = (): void => {
if (selectedUserIds.value.length === filteredUsers.value.length) {
selectedUserIds.value = [];
} else {
selectedUserIds.value = filteredUsers.value.map((u) => u.id);
}
};
const openBatchPermissionModal = (): void => {
if (selectedUserIds.value.length === 0) return;
batchPermissionForm.value = { agent_ids: [], action: 'add' };
showBatchPermissionModal.value = true;
};
const closeBatchPermissionModal = (): void => {
showBatchPermissionModal.value = false;
};
const submitBatchPermission = async (): Promise<void> => {
if (batchPermissionForm.value.agent_ids.length === 0) {
msg.warning(t('admin.perm.msg.selectAgent'));
return;
}
isSaving.value = true;
try {
await batchUpdateAdminPermissions({
user_ids: selectedUserIds.value,
agent_ids: batchPermissionForm.value.agent_ids,
action: batchPermissionForm.value.action,
});
await loadUsers();
showBatchPermissionModal.value = false;
selectedUserIds.value = [];
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.batchPermissionUpdateFailed'));
} finally {
isSaving.value = false;
}
};
const toggleUserAgentPermission = async (user: AdminUserRow, agentId: number): Promise<void> => {
const hasPermission = user.agent_ids.includes(agentId);
const newAgentIds = hasPermission
? user.agent_ids.filter((id) => id !== agentId)
: [...user.agent_ids, agentId];
const originalIds = [...user.agent_ids];
user.agent_ids = newAgentIds;
try {
await updateAdminUserPermissions(user.id, newAgentIds);
} catch (e) {
console.error(e);
user.agent_ids = originalIds;
msg.error((e as Error).message || t('admin.msg.failed'));
}
};
const exportPermissions = (): void => {
const data = users.value.map((u) => ({
Username: u.username,
Email: u.email,
Role: u.role,
Allowed_Agents: u.agent_ids.join('|'),
}));
const ws = XLSX.utils.json_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Permissions');
XLSX.writeFile(wb, 'user_permissions.csv');
};
const importPermissions = async (event: Event): Promise<void> => {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
const formData = new FormData();
formData.append('file', file);
isSaving.value = true;
try {
await importAdminPermissions(formData);
await loadUsers();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
input.value = '';
}
};
return {
users,
agents,
permissionFilters,
selectedUserIds,
filteredUsers,
isLoading,
isSaving,
showBatchPermissionModal,
batchPermissionForm,
loadAll,
toggleUserSelection,
toggleAllUsers,
openBatchPermissionModal,
closeBatchPermissionModal,
submitBatchPermission,
toggleUserAgentPermission,
exportPermissions,
importPermissions,
};
}
@@ -0,0 +1,174 @@
/**
* features/admin/modules/questions/QuestionsPage.vue
* 常用问题管理独立页面。路由:/admin/questions
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useQuestionsAdmin } from './composables/useQuestionsAdmin';
const { t } = useI18n();
const {
questions,
agents,
form,
isEditing,
isLoading,
isSaving,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
editQuestion,
saveQuestion,
deleteQuestion,
closeDeleteConfirm,
confirmDelete,
} = useQuestionsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="flex items-center justify-between">
<div>
<h2 class="section-title">{{ t('admin.question.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.question.subtitle') }}</p>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
<h3 class="font-bold text-primary mb-4">
{{ isEditing ? t('admin.question.edit') : t('admin.question.add') }}
</h3>
<div class="space-y-4">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.title') }}</label>
<input
v-model="form.title"
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="space-y-1.5">
<label class="label-field">{{ t('admin.question.fields.content') }}</label>
<textarea
v-model="form.question"
rows="4"
class="input-field text-sm"
:placeholder="t('admin.question.fields.contentPlaceholder')"
/>
</div>
<div class="flex justify-end gap-2 pt-2">
<button
v-if="isEditing"
type="button"
class="btn-ghost btn-sm"
@click="resetForm"
>
{{ t('admin.cancel') }}
</button>
<button
type="button"
class="btn-primary btn-sm disabled:opacity-50"
:disabled="isSaving"
@click="saveQuestion"
>
{{ isSaving ? t('admin.save') + '...' : (isEditing ? t('admin.update') : t('admin.add')) }}
</button>
</div>
</div>
</div>
<div class="lg:col-span-2 admin-table-section">
<div v-if="questions.length === 0" class="p-8 text-center text-muted">
{{ t('admin.question.noData') }}
</div>
<table v-else class="admin-table">
<thead>
<tr>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.question.headers.title') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.question.headers.agent') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
{{ t('admin.question.headers.order') }}
</th>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase text-right">
{{ t('admin.question.headers.actions') }}
</th>
</tr>
</thead>
<tbody class="divide-y divide-subtle">
<tr v-for="q in questions" :key="q.id">
<td class="px-6 py-4">
<div class="font-medium text-primary text-sm">{{ q.title }}</div>
<div class="text-xs text-muted truncate max-w-xs mt-0.5">{{ q.question }}</div>
</td>
<td class="px-6 py-4">
<span
class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 border border-blue-100"
>
{{ q.agent_name || 'Unknown' }}
</span>
</td>
<td class="px-6 py-4 text-sm text-muted">{{ q.sort_order }}</td>
<td class="px-6 py-4 text-right flex justify-end gap-2">
<button
type="button"
class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
@click="editQuestion(q)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
@click="deleteQuestion(q.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</template>
@@ -0,0 +1,149 @@
/**
* features/admin/modules/questions/composables/useQuestionsAdmin.ts
* 常用问题管理:列表、创建、编辑、删除。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
deleteAdminQuickQuestion,
listAdminAgents,
listAdminQuickQuestions,
saveAdminQuickQuestion,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
import {
createEmptyQuestionForm,
type AdminQuickQuestionRow,
type QuestionFormState,
} from '@/features/admin/types/question.types';
export function useQuestionsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const questions = ref<AdminQuickQuestionRow[]>([]);
const agents = ref<AdminAgentOption[]>([]);
const form = ref<QuestionFormState>(createEmptyQuestionForm());
const isEditing = ref(false);
const isLoading = ref(true);
const isSaving = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const loadQuestions = async (): Promise<void> => {
try {
questions.value = await listAdminQuickQuestions();
} catch (e) {
console.error('Failed to load quick questions', e);
questions.value = [];
}
};
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Failed to load agents', e);
agents.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadQuestions(), loadAgents()]);
isLoading.value = false;
};
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const resetForm = (): void => {
form.value = createEmptyQuestionForm();
isEditing.value = false;
};
const editQuestion = (q: AdminQuickQuestionRow): void => {
form.value = {
id: q.id,
title: q.title,
question: q.question,
agent_id: q.agent_id,
sort_order: q.sort_order,
};
isEditing.value = true;
};
const saveQuestion = async (): Promise<void> => {
if (!form.value.title || !form.value.question || !form.value.agent_id) {
msg.warning(t('admin.question.msg.fillAll'));
return;
}
isSaving.value = true;
try {
const url = isEditing.value
? `/api/admin/quick-questions/${form.value.id}`
: '/api/admin/quick-questions';
const method = isEditing.value ? 'PUT' : 'POST';
await saveAdminQuickQuestion(url, method, form.value as Record<string, unknown>);
await loadQuestions();
resetForm();
} 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 {
await deleteAdminQuickQuestion(id);
await loadQuestions();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
questions,
agents,
form,
isEditing,
isLoading,
isSaving,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
resetForm,
editQuestion,
saveQuestion,
deleteQuestion,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,390 @@
/**
* features/admin/modules/reports/ReportsPage.vue
* 管理后台报表独立页面。路由:/admin/reports/:table?
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { BarChart2, Download, Settings2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useReportsAdmin } from './composables/useReportsAdmin';
const { t } = useI18n();
const {
usageReport,
isLoading,
currentTable,
tableData,
isFullScreen,
columnFilters,
selectedReportRowIds,
isDeletingChatLogs,
chatLogsTotal,
showChatLogsColumnPanel,
chatLogsWrapEnabled,
chatLogsWrapMaxHeight,
showChatLogsSelection,
reportCurrentPage,
reportPageSize,
reportPageSizeOptions,
chatLogsColumns,
chatLogsSortRules,
isChatLogsTable,
visibleReportKeys,
allReportRowsSelected,
paginatedSortedTableData,
reportTotalRows,
reportTotalPages,
reportRangeStart,
reportRangeEnd,
reportPageButtons,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
handleFilterChange,
resetChatLogsColumns,
moveChatLogsColumn,
onColumnDragStart,
onColumnDrop,
startResizeColumn,
exportToExcel,
getReportColumnLabel,
getReportTableLabel,
getReportCellValue,
getColumnWidthStyle,
getReportRowId,
getReportCellDisplayStyle,
getReportCellInnerStyle,
getHeaderSortMark,
onReportHeaderClick,
addChatLogsSortRule,
removeChatLogsSortRule,
moveChatLogsSortRule,
toggleReportRowSelection,
toggleAllReportRows,
batchDeleteChatLogs,
goToReportPage,
prevReportPage,
nextReportPage,
confirmDelete,
} = useReportsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<!-- Reports -->
<section
v-else
class="admin-report-section transition-all duration-300"
:class="isFullScreen ? 'fixed inset-0 z-50 m-0 rounded-none h-screen w-screen overflow-auto p-8' : ''"
>
<div class="admin-report-toolbar">
<div class="space-y-2">
<h2 class="section-title text-lg flex items-center gap-3">
<span class="inline-flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-brand-600 to-brand-400 shadow-md shadow-brand-500/25">
<BarChart2 class="w-4 h-4 text-white" />
</span>
{{ t('admin.report.title', { table: getReportTableLabel(currentTable) }) }}
</h2>
<div class="flex flex-wrap items-center gap-2 text-xs">
<span class="admin-report-badge">
{{ t('admin.report.subtitle') }}
</span>
<span v-if="isChatLogsTable" class="admin-report-badge admin-report-badge--info font-semibold">
{{ t('admin.report.totalRows', { total: chatLogsTotal }) }}
</span>
<span class="admin-report-badge admin-report-badge--indigo font-semibold">
{{ t('admin.report.showingRange', { start: reportRangeStart, end: reportRangeEnd, total: reportTotalRows }) }}
</span>
</div>
</div>
<div class="flex flex-wrap items-center gap-2 md:gap-3">
<button
@click="showChatLogsColumnPanel = !showChatLogsColumnPanel"
class="btn-secondary text-sm font-semibold"
:title="t('admin.report.columnSettings')"
>
<Settings2 class="w-4 h-4" />
<span>{{ t('admin.report.columnSettings') }}</span>
</button>
<button
v-if="isChatLogsTable"
@click="showChatLogsSelection = !showChatLogsSelection"
class="btn-secondary text-xs font-medium"
>
{{ showChatLogsSelection ? t('admin.report.hideSelection') : t('admin.report.showSelection') }}
</button>
<button
v-if="isChatLogsTable && showChatLogsSelection"
@click="batchDeleteChatLogs"
:disabled="selectedReportRowIds.length === 0 || isDeletingChatLogs"
class="flex items-center gap-2 px-4 py-2 bg-rose-600 text-white text-sm font-medium rounded-xl hover:bg-rose-700 transition-all shadow-md shadow-rose-200 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ isDeletingChatLogs ? t('admin.report.deleting') : t('admin.report.deleteSelected', { count: selectedReportRowIds.length }) }}
</button>
<button
@click="exportToExcel"
class="flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white text-sm font-medium rounded-xl hover:bg-emerald-700 transition-all shadow-md shadow-emerald-200 active:scale-95"
>
<Download class="w-4 h-4" />
{{ t('admin.report.export') }}
</button>
<button
@click="isFullScreen = !isFullScreen"
class="btn-icon-ds"
:title="isFullScreen ? t('admin.report.exitFullscreen') : t('admin.report.enterFullscreen')"
>
<svg v-if="!isFullScreen" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M16 3h3a2 2 0 0 1 2 2v3"/><path d="M8 21H5a2 2 0 0 1-2-2v-3"/><path d="M16 21h3a2 2 0 0 1 2 2v-3"/></svg>
<svg v-else xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3v3a2 2 0 0 1-2 2H3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/><path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M16 21v-3a2 2 0 0 1 2-2h3"/></svg>
</button>
</div>
</div>
<div class="p-5 md:p-8 space-y-5">
<div
v-if="showChatLogsColumnPanel"
class="admin-report-panel"
>
<div class="flex items-center justify-between mb-3">
<div class="text-sm font-semibold text-primary">{{ t('admin.report.tableSettings') }}</div>
<button
@click="resetChatLogsColumns"
class="btn-secondary text-xs px-3 py-1.5"
>
{{ t('admin.report.resetLayout') }}
</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
<label class="admin-report-setting-chip">
<input type="checkbox" v-model="chatLogsWrapEnabled" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500" />
<span>{{ t('admin.report.wrapText') }}</span>
</label>
<label class="admin-report-setting-chip">
<span>{{ t('admin.report.wrapMaxHeightPx') }}</span>
<input
v-model.number="chatLogsWrapMaxHeight"
type="number"
step="1"
class="admin-table-filter-input w-24 py-1"
/>
</label>
</div>
<div class="mb-3 p-3 rounded-xl border border-default bg-surface-soft">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-semibold text-secondary">{{ t('admin.report.advancedSortRules') }}</span>
<button
@click="addChatLogsSortRule"
class="btn-secondary text-xs px-2 py-1"
>
+ {{ t('admin.report.addRule') }}
</button>
</div>
<div v-if="chatLogsSortRules.length === 0" class="text-xs text-muted">{{ t('admin.report.noAdvancedSort') }}</div>
<div v-else class="space-y-2">
<div
v-for="(rule, ridx) in chatLogsSortRules"
:key="`sort-rule-${ridx}`"
class="admin-report-sort-row"
>
<span class="col-span-1 text-muted">{{ ridx + 1 }}.</span>
<select v-model="rule.key" class="col-span-4 admin-table-filter-input py-1">
<option v-for="k in Object.keys(tableData[0] || {})" :key="`rule-key-${k}`" :value="k">{{ getReportColumnLabel(k) }}</option>
</select>
<select v-model="rule.direction" class="col-span-3 admin-table-filter-input py-1">
<option value="asc">{{ t('admin.report.sortAsc') }}</option>
<option value="desc">{{ t('admin.report.sortDesc') }}</option>
</select>
<div class="col-span-4 flex items-center justify-end gap-1">
<button @click="moveChatLogsSortRule(ridx, -1)" class="btn-secondary text-xs px-2 py-1">{{ t('admin.report.moveUp') }}</button>
<button @click="moveChatLogsSortRule(ridx, 1)" class="btn-secondary text-xs px-2 py-1">{{ t('admin.report.moveDown') }}</button>
<button @click="removeChatLogsSortRule(ridx)" class="btn-danger text-xs px-2 py-1">{{ t('admin.report.remove') }}</button>
</div>
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
<div
v-for="col in chatLogsColumns"
:key="`cfg-${col.key}`"
class="admin-report-col-chip"
>
<label class="flex items-center gap-2 min-w-0">
<input type="checkbox" v-model="col.visible" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500" />
<span class="text-xs text-secondary truncate">{{ getReportColumnLabel(col.key) }}</span>
</label>
<div class="flex items-center gap-1">
<button @click="moveChatLogsColumn(col.key, -1)" class="btn-secondary text-xs px-1.5 py-0.5">&lt;</button>
<button @click="moveChatLogsColumn(col.key, 1)" class="btn-secondary text-xs px-1.5 py-0.5">&gt;</button>
</div>
</div>
</div>
</div>
<div v-if="tableData.length === 0" class="text-center text-muted py-20 bg-surface-soft rounded-2xl border border-dashed border-default">
<p>{{ t('admin.report.noData', { table: getReportTableLabel(currentTable) }) }}</p>
</div>
<div v-else class="admin-report-table-wrap">
<table class="admin-report-table w-full border-collapse">
<thead>
<tr>
<th v-if="isChatLogsTable && showChatLogsSelection" class="px-4 py-4 w-10">
<input
type="checkbox"
:checked="allReportRowsSelected"
@change="toggleAllReportRows"
class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500"
/>
</th>
<th
v-for="key in visibleReportKeys"
:key="key"
class="px-6 py-4 whitespace-nowrap align-top relative"
:style="getColumnWidthStyle(key)"
:draggable="true"
@dragstart="onColumnDragStart(String(key))"
@dragover.prevent
@drop="onColumnDrop(String(key))"
>
<div class="flex flex-col gap-2 min-w-0">
<button
@click="onReportHeaderClick(String(key))"
class="admin-report-header-btn"
>
{{ getReportColumnLabel(String(key)) }} <span class="text-[10px] text-brand-500">{{ getHeaderSortMark(String(key)) }}</span>
</button>
<input
v-model="columnFilters[key]"
@input="handleFilterChange"
type="text"
class="admin-report-filter-input"
:placeholder="t('admin.report.filterPlaceholder')"
/>
</div>
<span
class="absolute right-0 top-0 h-full w-1.5 cursor-col-resize select-none"
@mousedown="startResizeColumn(String(key), $event)"
></span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, idx) in paginatedSortedTableData" :key="idx">
<td v-if="isChatLogsTable && showChatLogsSelection" class="px-4 py-3">
<input
type="checkbox"
:checked="selectedReportRowIds.includes(getReportRowId(row))"
@change="toggleReportRowSelection(getReportRowId(row))"
class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500"
/>
</td>
<td
v-for="key in visibleReportKeys"
:key="`cell-${idx}-${key}`"
class="px-6 py-3 font-mono"
:title="String(getReportCellValue(row, String(key)))"
:style="getReportCellDisplayStyle(String(key))"
>
<div :style="getReportCellInnerStyle()">
{{ getReportCellValue(row, String(key)) }}
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="tableData.length > 0" class="flex flex-col gap-3 rounded-2xl border border-default bg-surface px-4 py-3 md:flex-row md:items-center md:justify-between">
<div class="text-sm text-secondary">
{{ t('admin.report.paginationSummary', { total: reportTotalRows, page: reportCurrentPage, pages: reportTotalPages }) }}
</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="reportPageSize"
class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5"
>
<option v-for="size in reportPageSizeOptions" :key="`page-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="prevReportPage"
:disabled="reportCurrentPage <= 1"
class="admin-report-page-btn"
>
{{ t('admin.report.prevPage') }}
</button>
<button
v-for="btn in reportPageButtons"
:key="`report-page-btn-${btn}`"
:disabled="btn === -1"
@click="btn !== -1 && goToReportPage(btn)"
class="admin-report-page-btn"
:class="btn === -1
? 'border-transparent text-muted cursor-default opacity-100'
: btn === reportCurrentPage
? 'admin-report-page-btn--active'
: ''"
>
{{ btn === -1 ? '...' : btn }}
</button>
<button
@click="nextReportPage"
:disabled="reportCurrentPage >= reportTotalPages"
class="admin-report-page-btn"
>
{{ t('admin.report.nextPage') }}
</button>
</div>
</div>
<!-- Statistics Charts -->
<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">
<div v-for="a in usageReport.by_agent" :key="a.agent" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
<span class="font-medium text-secondary">{{ a.agent }}</span>
<span class="admin-report-badge admin-report-badge--info font-bold">{{ a.count }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
/>
</template>
@@ -0,0 +1,865 @@
/**
* features/admin/modules/reports/composables/useReportsAdmin.ts
* 管理后台报表:多表浏览、筛选、排序、chat_logs 批量删除与用量图表。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import * as XLSX from 'xlsx';
import {
batchDeleteAdminChatLogs,
getAdminReportTable,
getAdminReportTableCount,
getAdminUsageReport,
} from '@/api/admin';
import { loadReportLayoutPref, saveReportLayoutPref } from '@/composables/useReportLayoutStorage';
import { useMessage } from '@/composables/useMessage';
import { ADMIN_REPORT_TABLES } from '@/features/admin/constants/modules';
import type {
ChatLogsLayoutPref,
ReportColumnConfig,
SortRule,
UsageReport,
} from '@/features/admin/types/report.types';
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
export function useReportsAdmin() {
const { t, locale } = useI18n();
const msg = useMessage();
const route = useRoute();
const usageReport = ref<UsageReport | null>(null);
const isLoading = ref(true);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const resolveTableFromRoute = (): AdminReportTableId => {
const table = route.params.table;
if (typeof table === 'string' && (ADMIN_REPORT_TABLES as readonly string[]).includes(table)) {
return table as AdminReportTableId;
}
return 'users';
};
const currentTable = ref<AdminReportTableId>(resolveTableFromRoute());
watch(
() => route.params.table,
() => {
currentTable.value = resolveTableFromRoute();
},
);
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);
const columnFilters = ref<Record<string, string>>({});
const selectedReportRowIds = ref<number[]>([]);
const isDeletingChatLogs = ref(false);
const chatLogsTotal = ref(0);
const showChatLogsColumnPanel = ref(false);
const chatLogsWrapEnabled = ref(false);
const chatLogsWrapMaxHeight = ref(120);
const showChatLogsSelection = ref(false);
const reportCurrentPage = ref(1);
const reportPageSize = ref(20);
const reportPageSizeOptions = [10, 20, 50, 100];
const chatLogsColumns = ref<ReportColumnConfig[]>([]);
const chatLogsSortRules = ref<SortRule[]>([]);
const reportHeaderSort = ref<SortRule | null>(null);
const draggingColumnKey = ref<string | null>(null);
const resizingColumnKey = ref<string | null>(null);
let resizeStartX = 0;
let resizeStartWidth = 0;
const loadTableData = async () => {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(columnFilters.value)) {
if (value) params.append(key, value);
}
const url = currentTable.value === 'general_feedbacks'
? `/api/admin/reports/general-feedbacks?${params.toString()}`
: `/api/admin/database/${currentTable.value}?${params.toString()}`;
try {
tableData.value = await getAdminReportTable(url);
if (tableData.value.length > 0) {
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
}
if (currentTable.value === 'chat_logs') {
const validIds = new Set(
tableData.value
.map((row: any) => Number(row?.id))
.filter((id: number) => Number.isFinite(id))
);
selectedReportRowIds.value = selectedReportRowIds.value.filter(id => validIds.has(id));
} else {
selectedReportRowIds.value = [];
}
} catch {
tableData.value = [];
selectedReportRowIds.value = [];
}
};
const saveChatLogsColumns = () => {
if (chatLogsColumns.value.length === 0) return;
const payload: ChatLogsLayoutPref = {
columns: chatLogsColumns.value,
wrapEnabled: chatLogsWrapEnabled.value,
wrapMaxHeight: chatLogsWrapMaxHeight.value,
sortRules: chatLogsSortRules.value,
};
saveReportLayoutPref(currentTable.value, payload);
};
const initChatLogsColumns = (keys: string[]) => {
chatLogsWrapEnabled.value = false;
chatLogsWrapMaxHeight.value = 120;
const defaults: ReportColumnConfig[] = keys.map((k) => ({
key: k,
visible: true,
width: k === 'id' ? 90 : 180
}));
let merged = defaults;
try {
const parsed = loadReportLayoutPref<ReportColumnConfig[] | ChatLogsLayoutPref>(currentTable.value);
if (parsed) {
const saved = Array.isArray(parsed) ? parsed : (parsed.columns || []);
const savedMap = new Map(saved.map((c) => [c.key, c]));
const order = saved.map((c) => c.key).filter((k) => keys.includes(k));
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),
}));
if (!Array.isArray(parsed)) {
chatLogsWrapEnabled.value = !!parsed.wrapEnabled;
chatLogsWrapMaxHeight.value = Number(parsed.wrapMaxHeight || 120);
chatLogsSortRules.value = Array.isArray(parsed.sortRules)
? parsed.sortRules
.filter((r: any) => r && typeof r.key === 'string' && (r.direction === 'asc' || r.direction === 'desc'))
: [];
}
}
} catch {
merged = defaults;
}
if (!Number.isFinite(chatLogsWrapMaxHeight.value)) chatLogsWrapMaxHeight.value = 120;
chatLogsColumns.value = merged;
};
const resetChatLogsColumns = () => {
if (tableData.value.length === 0) return;
chatLogsWrapEnabled.value = false;
chatLogsWrapMaxHeight.value = 120;
chatLogsSortRules.value = [];
reportHeaderSort.value = null;
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
saveChatLogsColumns();
};
const moveChatLogsColumn = (key: string, direction: -1 | 1) => {
const idx = chatLogsColumns.value.findIndex((c) => c.key === key);
if (idx < 0) return;
const target = idx + direction;
if (target < 0 || target >= chatLogsColumns.value.length) return;
const copy = [...chatLogsColumns.value];
const [item] = copy.splice(idx, 1);
if (!item) return;
copy.splice(target, 0, item);
chatLogsColumns.value = copy;
saveChatLogsColumns();
};
const onColumnDragStart = (key: string) => {
draggingColumnKey.value = key;
};
const onColumnDrop = (targetKey: string) => {
const sourceKey = draggingColumnKey.value;
draggingColumnKey.value = null;
if (!sourceKey || sourceKey === targetKey) return;
const sourceIdx = chatLogsColumns.value.findIndex((c) => c.key === sourceKey);
const targetIdx = chatLogsColumns.value.findIndex((c) => c.key === targetKey);
if (sourceIdx < 0 || targetIdx < 0) return;
const copy = [...chatLogsColumns.value];
const [item] = copy.splice(sourceIdx, 1);
if (!item) return;
copy.splice(targetIdx, 0, item);
chatLogsColumns.value = copy;
saveChatLogsColumns();
};
const onResizeMouseMove = (e: MouseEvent) => {
if (!resizingColumnKey.value) return;
const diff = e.clientX - resizeStartX;
const col = chatLogsColumns.value.find((c) => c.key === resizingColumnKey.value);
if (!col) return;
col.width = Math.max(80, resizeStartWidth + diff);
};
const onResizeMouseUp = () => {
if (!resizingColumnKey.value) return;
resizingColumnKey.value = null;
document.removeEventListener('mousemove', onResizeMouseMove);
document.removeEventListener('mouseup', onResizeMouseUp);
saveChatLogsColumns();
};
const startResizeColumn = (key: string, e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
const col = chatLogsColumns.value.find((c) => c.key === key);
if (!col) return;
resizingColumnKey.value = key;
resizeStartX = e.clientX;
resizeStartWidth = col.width;
document.addEventListener('mousemove', onResizeMouseMove);
document.addEventListener('mouseup', onResizeMouseUp);
};
const loadTableCount = async (table: string) => {
try {
const countUrl = table === 'general_feedbacks'
? '/api/admin/reports/general-feedbacks/count'
: `/api/admin/database/${table}/count`;
const data = await getAdminReportTableCount(countUrl);
return Number(data.total || 0);
} catch {
return 0;
}
};
const exportToExcel = () => {
if (tableData.value.length === 0) return;
const ws = XLSX.utils.json_to_sheet(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`);
};
// Debounce filter input
let debounceTimer: any = null;
const handleFilterChange = () => {
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
loadTableData();
}, 500);
};
const isChatLogsTable = computed(() => currentTable.value === 'chat_logs');
const visibleReportKeys = computed(() => {
let keys: string[];
if (chatLogsColumns.value.length === 0) {
keys = Object.keys(tableData.value[0] || {});
} else {
keys = chatLogsColumns.value.filter((c) => c.visible).map((c) => c.key);
}
if (currentTable.value === 'general_feedbacks') {
const feedbackFixedOrder = [
'created_at',
'source_page',
'feedback_module',
'feedback_type',
'content',
'username',
'real_name',
'department',
'chat_log_id',
];
const available = new Set(keys);
return feedbackFixedOrder.filter((k) => available.has(k));
}
return keys;
});
const resolveReportLang = () => {
const l = String(locale.value || 'en').toLowerCase();
if (l.startsWith('zh-cn')) return 'zh-CN';
if (l.startsWith('zh-tw')) return 'zh-TW';
if (l.startsWith('th')) return 'th';
return 'en';
};
const feedbackReportI18nMap: Record<string, {
columns: Record<string, string>;
types: Record<string, string>;
modules: Record<string, string>;
pages: Record<string, string>;
}> = {
en: {
columns: {
feedback_module: 'Feedback Module',
feedback_type: 'Feedback Type',
source_page: 'Source Page',
real_name: 'Real Name',
department: 'Department',
},
types: {
feature_suggestion: 'Feature Suggestion',
issue_feedback: 'Issue Feedback',
experience_optimization: 'Experience Optimization',
},
modules: {
knowledge_base: 'Knowledge Base',
general: 'General',
workflow: 'Workflow',
account_permission: 'Account & Permissions',
},
pages: {
workspace: 'Workspace',
chat: 'Chat',
unknown: 'Unknown',
},
},
'zh-CN': {
columns: {
feedback_module: '\u53cd\u9988\u6a21\u5757',
feedback_type: '\u53cd\u9988\u7c7b\u578b',
source_page: '\u6765\u6e90\u9875\u9762',
real_name: '\u771f\u5b9e\u59d3\u540d',
department: '\u90e8\u95e8',
},
types: {
feature_suggestion: '\u529f\u80fd\u5efa\u8bae',
issue_feedback: '\u95ee\u9898\u53cd\u9988',
experience_optimization: '\u4f53\u9a8c\u4f18\u5316',
},
modules: {
knowledge_base: '\u77e5\u8bc6\u5e93',
general: '\u901a\u7528',
workflow: '\u5de5\u4f5c\u6d41',
account_permission: '\u8d26\u53f7\u6743\u9650',
},
pages: {
workspace: '\u5de5\u4f5c\u53f0',
chat: '\u5bf9\u8bdd',
unknown: '\u672a\u77e5',
},
},
'zh-TW': {
columns: {
feedback_module: '\u53cd\u994b\u6a21\u7d44',
feedback_type: '\u53cd\u994b\u985e\u578b',
source_page: '\u4f86\u6e90\u9801\u9762',
real_name: '\u771f\u5be6\u59d3\u540d',
department: '\u90e8\u9580',
},
types: {
feature_suggestion: '\u529f\u80fd\u5efa\u8b70',
issue_feedback: '\u554f\u984c\u56de\u994b',
experience_optimization: '\u9ad4\u9a57\u512a\u5316',
},
modules: {
knowledge_base: '\u77e5\u8b58\u5eab',
general: '\u901a\u7528',
workflow: '\u5de5\u4f5c\u6d41',
account_permission: '\u5e33\u865f\u6b0a\u9650',
},
pages: {
workspace: '\u5de5\u4f5c\u53f0',
chat: '\u5c0d\u8a71',
unknown: '\u672a\u77e5',
},
},
th: {
columns: {
feedback_module: '\u0e42\u0e21\u0e14\u0e39\u0e25\u0e02\u0e49\u0e2d\u0e40\u0e2a\u0e19\u0e2d\u0e41\u0e19\u0e30',
feedback_type: '\u0e1b\u0e23\u0e30\u0e40\u0e20\u0e17\u0e02\u0e49\u0e2d\u0e40\u0e2a\u0e19\u0e2d\u0e41\u0e19\u0e30',
source_page: '\u0e2b\u0e19\u0e49\u0e32\u0e15\u0e49\u0e19\u0e17\u0e32\u0e07',
real_name: '\u0e0a\u0e37\u0e48\u0e2d\u0e08\u0e23\u0e34\u0e07',
department: '\u0e41\u0e1c\u0e19\u0e01',
},
types: {
feature_suggestion: '\u0e02\u0e49\u0e2d\u0e40\u0e2a\u0e19\u0e2d\u0e41\u0e19\u0e30\u0e1f\u0e35\u0e40\u0e08\u0e2d\u0e23\u0e4c',
issue_feedback: '\u0e41\u0e08\u0e49\u0e07\u0e1b\u0e31\u0e0d\u0e2b\u0e32',
experience_optimization: '\u0e1b\u0e23\u0e31\u0e1a\u0e1b\u0e23\u0e38\u0e07\u0e1b\u0e23\u0e30\u0e2a\u0e1a\u0e01\u0e32\u0e23\u0e13\u0e4c',
},
modules: {
knowledge_base: '\u0e04\u0e25\u0e31\u0e07\u0e04\u0e27\u0e32\u0e21\u0e23\u0e39\u0e49',
general: '\u0e17\u0e31\u0e48\u0e27\u0e44\u0e1b',
workflow: '\u0e40\u0e27\u0e34\u0e23\u0e4c\u0e01\u0e42\u0e1f\u0e25\u0e27\u0e4c',
account_permission: '\u0e1a\u0e31\u0e0d\u0e0a\u0e35\u0e41\u0e25\u0e30\u0e2a\u0e34\u0e17\u0e18\u0e34\u0e4c',
},
pages: {
workspace: '\u0e40\u0e27\u0e34\u0e23\u0e4c\u0e01\u0e2a\u0e40\u0e1b\u0e0b',
chat: '\u0e41\u0e0a\u0e17',
unknown: '\u0e44\u0e21\u0e48\u0e17\u0e23\u0e32\u0e1a',
},
},
};
const getReportColumnLabel = (key: string) => {
const lang = resolveReportLang();
const enPack = feedbackReportI18nMap['en'] || { columns: {}, types: {}, modules: {}, pages: {} };
const direct = feedbackReportI18nMap[lang]?.columns?.[key] || enPack.columns[key];
if (direct) return direct;
const i18nKey = `admin.report.columns.${key}`;
const translated = t(i18nKey);
if (translated && translated !== i18nKey) return translated;
return key.replace(/_/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase());
};
const getReportTableLabel = (table: string) => {
const i18nKey = `admin.report.tables.${table}`;
const translated = t(i18nKey);
if (translated && translated !== i18nKey) return translated;
return table.replace(/_/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase());
};
const getReportRowId = (row: any) => Number(row?.id);
const allReportRowsSelected = computed(() => {
if (!isChatLogsTable.value || paginatedSortedTableData.value.length === 0) return false;
return paginatedSortedTableData.value.every((row: any) => selectedReportRowIds.value.includes(getReportRowId(row)));
});
const getColumnWidthStyle = (key: string) => {
const col = chatLogsColumns.value.find((c) => c.key === key);
if (!col) return {};
return {
width: `${col.width}px`,
minWidth: `${col.width}px`,
maxWidth: `${col.width}px`,
};
};
// 报表值翻译辅助:优先返回 i18n 文案;若没有配置对应翻译则回退原始值
const getTranslatedValue = (i18nKey: string, fallbackValue: any) => {
const translated = t(i18nKey);
return translated && translated !== i18nKey ? translated : fallbackValue;
};
const normalizeFeedbackKey = (value: any) => {
if (value === null || value === undefined) return '';
const raw = String(value).trim();
if (!raw) return '';
const map: Record<string, string> = {
'\u529f\u80fd\u5efa\u8bae': 'feature_suggestion',
'\u95ee\u9898\u53cd\u9988': 'issue_feedback',
'\u4f53\u9a8c\u4f18\u5316': 'experience_optimization',
'\u77e5\u8bc6\u5e93': 'knowledge_base',
'\u901a\u7528': 'general',
'\u5de5\u4f5c\u6d41': 'workflow',
'\u8d26\u53f7\u6743\u9650': 'account_permission',
workspace: 'workspace',
chat: 'chat',
unknown: 'unknown',
};
const normalized = raw.toLowerCase().replace(/[\s\-]+/g, '_');
return map[raw] || map[normalized] || normalized;
};
const getTranslatedFeedbackValue = (group: 'types' | 'modules' | 'pages', value: any) => {
const normalized = normalizeFeedbackKey(value);
if (!normalized) return value;
const lang = resolveReportLang();
const enPack = feedbackReportI18nMap['en'] || { columns: {}, types: {}, modules: {}, pages: {} };
const dict = feedbackReportI18nMap[lang]?.[group] || enPack[group];
return dict?.[normalized] || value;
};
const formatReportDateTime = (value: any) => {
if (value === null || value === undefined || value === '') return value;
const d = new Date(value);
if (Number.isNaN(d.getTime())) return value;
const localeMap: Record<string, string> = {
'zh-CN': 'zh-CN',
'zh-TW': 'zh-TW',
en: 'en-US',
th: 'th-TH',
};
const lang = resolveReportLang();
const localeName = localeMap[lang] || 'en-US';
return new Intl.DateTimeFormat(localeName, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}).format(d);
};
const getReportCellValue = (row: any, key: string) => {
const value = row?.[key];
if (key === 'is_active') {
const truthy = value === true || value === 1 || value === '1' || value === 'true' || value === 'True';
return truthy ? t('admin.status.active') : t('admin.status.disabled');
}
if (key === 'role' && typeof value === 'string') {
return getTranslatedValue(`admin.role.${value}`, value);
}
if (key === 'status' && typeof value === 'string') {
return getTranslatedValue(`admin.status.${value}`, value);
}
if (key === 'theme_preference' && typeof value === 'string') {
return getTranslatedValue(`theme.${value}`, value);
}
if (key === 'feedback_type') {
return getTranslatedFeedbackValue('types', value);
}
if (key === 'feedback_module') {
return getTranslatedFeedbackValue('modules', value);
}
if (key === 'source_page') {
return getTranslatedFeedbackValue('pages', value);
}
// format datetime fields in report table
if (typeof value === 'string' && (key.endsWith('_at') || key === 'created_at' || key === 'updated_at')) {
return formatReportDateTime(value);
}
if (key === 'language' && typeof value === 'string') {
const languageLabelMap: Record<string, string> = {
'zh-CN': '\u7b80\u4f53\u4e2d\u6587',
'zh-TW': '\u7e41\u9ad4\u4e2d\u6587',
en: 'English',
th: '\u0e44\u0e17\u0e22',
};
return languageLabelMap[value] || value;
}
return value;
};
const normalizeSortValue = (v: any) => {
if (v === null || v === undefined) return null;
if (typeof v === 'number') return v;
if (typeof v === 'boolean') return v ? 1 : 0;
if (typeof v === 'string') {
const n = Number(v);
if (!Number.isNaN(n) && v.trim() !== '') return n;
const d = Date.parse(v);
if (!Number.isNaN(d)) return d;
return v.toLowerCase();
}
return String(v).toLowerCase();
};
const compareByRule = (a: any, b: any, rule: SortRule) => {
const av = normalizeSortValue(getReportCellValue(a, rule.key));
const bv = normalizeSortValue(getReportCellValue(b, rule.key));
if (av === bv) return 0;
if (av === null) return 1;
if (bv === null) return -1;
const dir = rule.direction === 'asc' ? 1 : -1;
return av > bv ? dir : -dir;
};
const sortedTableData = computed(() => {
const list = [...tableData.value];
const advanced = chatLogsSortRules.value.length > 0 ? chatLogsSortRules.value : [];
const rules = advanced.length > 0 ? advanced : (reportHeaderSort.value ? [reportHeaderSort.value] : []);
if (rules.length === 0) return list;
return list.sort((a, b) => {
for (const r of rules) {
const c = compareByRule(a, b, r);
if (c !== 0) return c;
}
return 0;
});
});
// Front-end pagination over the already filtered/sorted dataset.
const reportTotalRows = computed(() => sortedTableData.value.length);
const reportTotalPages = computed(() => {
const size = Math.max(1, Number(reportPageSize.value) || 20);
return Math.max(1, Math.ceil(reportTotalRows.value / size));
});
const paginatedSortedTableData = computed(() => {
const size = Math.max(1, Number(reportPageSize.value) || 20);
// Clamp page number to avoid empty pages after filtering/deletion.
const safePage = Math.min(Math.max(1, reportCurrentPage.value), reportTotalPages.value);
const start = (safePage - 1) * size;
return sortedTableData.value.slice(start, start + size);
});
const reportRangeStart = computed(() => {
if (reportTotalRows.value === 0) return 0;
const safePage = Math.min(Math.max(1, reportCurrentPage.value), reportTotalPages.value);
const size = Math.max(1, Number(reportPageSize.value) || 20);
return (safePage - 1) * size + 1;
});
const reportRangeEnd = computed(() => {
if (reportTotalRows.value === 0) return 0;
const size = Math.max(1, Number(reportPageSize.value) || 20);
return Math.min(reportRangeStart.value + size - 1, reportTotalRows.value);
});
const goToReportPage = (page: number) => {
reportCurrentPage.value = Math.min(Math.max(1, page), reportTotalPages.value);
};
const prevReportPage = () => goToReportPage(reportCurrentPage.value - 1);
const nextReportPage = () => goToReportPage(reportCurrentPage.value + 1);
const reportPageButtons = computed(() => {
const total = reportTotalPages.value;
const current = Math.min(Math.max(1, reportCurrentPage.value), total);
if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
if (current <= 4) return [1, 2, 3, 4, 5, -1, total];
if (current >= total - 3) return [1, -1, total - 4, total - 3, total - 2, total - 1, total];
return [1, -1, current - 1, current, current + 1, -1, total];
});
const onReportHeaderClick = (key: string) => {
// Column-header sorting is the quick mode; clear advanced rules to avoid precedence conflict.
if (chatLogsSortRules.value.length > 0) {
chatLogsSortRules.value = [];
}
if (reportHeaderSort.value?.key === key) {
reportHeaderSort.value = { key, direction: reportHeaderSort.value.direction === 'asc' ? 'desc' : 'asc' };
} else {
reportHeaderSort.value = { key, direction: 'asc' };
}
reportCurrentPage.value = 1;
};
const getHeaderSortMark = (key: string) => {
if (reportHeaderSort.value?.key !== key) return '';
return reportHeaderSort.value.direction === 'asc' ? '^' : 'v';
};
const addChatLogsSortRule = () => {
const keys = visibleReportKeys.value;
const fallback = Object.keys(tableData.value[0] || {});
const key = keys[0] || fallback[0];
if (!key) return;
chatLogsSortRules.value.push({ key, direction: 'asc' });
};
const removeChatLogsSortRule = (idx: number) => {
chatLogsSortRules.value.splice(idx, 1);
};
const moveChatLogsSortRule = (idx: number, direction: -1 | 1) => {
const target = idx + direction;
if (target < 0 || target >= chatLogsSortRules.value.length) return;
const copy = [...chatLogsSortRules.value];
const [item] = copy.splice(idx, 1);
if (!item) return;
copy.splice(target, 0, item);
chatLogsSortRules.value = copy;
};
const getReportCellDisplayStyle = (key: string) => {
// Width is applied on <td>; height clamp is applied to inner block container.
return { ...getColumnWidthStyle(key) } as any;
};
const getReportCellInnerStyle = () => {
const style: Record<string, string> = { display: 'block' };
if (!chatLogsWrapEnabled.value) {
style.whiteSpace = 'nowrap';
style.overflow = 'hidden';
style.textOverflow = 'ellipsis';
return style;
}
const maxH = Number.isFinite(chatLogsWrapMaxHeight.value) ? chatLogsWrapMaxHeight.value : 120;
style.whiteSpace = 'normal';
style.wordBreak = 'break-word';
style.maxHeight = `${maxH}px`;
style.overflow = 'hidden';
return style;
};
const toggleReportRowSelection = (rowId: number) => {
const idx = selectedReportRowIds.value.indexOf(rowId);
if (idx === -1) selectedReportRowIds.value.push(rowId);
else selectedReportRowIds.value.splice(idx, 1);
};
const toggleAllReportRows = () => {
if (!isChatLogsTable.value) return;
const ids = paginatedSortedTableData.value
.map((row: any) => getReportRowId(row))
.filter((id: number) => Number.isFinite(id));
const allSelected = ids.length > 0 && ids.every((id: number) => selectedReportRowIds.value.includes(id));
if (allSelected) {
selectedReportRowIds.value = selectedReportRowIds.value.filter((id) => !ids.includes(id));
return;
}
const merged = new Set([...selectedReportRowIds.value, ...ids]);
selectedReportRowIds.value = Array.from(merged);
};
const batchDeleteChatLogs = async () => {
if (!isChatLogsTable.value) return;
if (selectedReportRowIds.value.length === 0) return;
const targetRowIds = [...selectedReportRowIds.value];
openDeleteConfirm(`Delete ${targetRowIds.length} selected chat logs?`, async () => {
isDeletingChatLogs.value = true;
try {
const data = await batchDeleteAdminChatLogs(targetRowIds);
msg.success(`Deleted ${data.deleted_count ?? 0} chat logs.`);
selectedReportRowIds.value = [];
await loadTableData();
chatLogsTotal.value = await loadTableCount('chat_logs');
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
} finally {
isDeletingChatLogs.value = false;
}
});
};
watch(currentTable, async () => {
columnFilters.value = {}; // Reset filters on table change
selectedReportRowIds.value = [];
showChatLogsColumnPanel.value = false;
showChatLogsSelection.value = false;
reportCurrentPage.value = 1;
await loadTableData();
reportHeaderSort.value = null;
if (currentTable.value === 'chat_logs') {
chatLogsTotal.value = await loadTableCount('chat_logs');
}
});
watch(chatLogsColumns, () => {
saveChatLogsColumns();
}, { deep: true });
watch([chatLogsWrapEnabled, chatLogsWrapMaxHeight], () => {
saveChatLogsColumns();
});
watch(chatLogsSortRules, () => {
// Force row re-evaluation immediately when rule fields/order change.
tableData.value = [...tableData.value];
reportCurrentPage.value = 1;
saveChatLogsColumns();
}, { deep: true });
watch(showChatLogsSelection, (v) => {
if (!v) selectedReportRowIds.value = [];
});
watch(columnFilters, () => {
reportCurrentPage.value = 1;
}, { deep: true });
watch([reportPageSize, sortedTableData], () => {
if (reportCurrentPage.value > reportTotalPages.value) {
reportCurrentPage.value = reportTotalPages.value;
}
if (reportCurrentPage.value < 1) {
reportCurrentPage.value = 1;
}
});
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadReports();
columnFilters.value = {};
selectedReportRowIds.value = [];
showChatLogsColumnPanel.value = false;
showChatLogsSelection.value = false;
reportCurrentPage.value = 1;
reportHeaderSort.value = null;
await loadTableData();
if (currentTable.value === 'chat_logs') {
chatLogsTotal.value = await loadTableCount('chat_logs');
} else {
showChatLogsSelection.value = false;
}
isLoading.value = false;
};
return {
usageReport,
isLoading,
currentTable,
tableData,
isFullScreen,
columnFilters,
selectedReportRowIds,
isDeletingChatLogs,
chatLogsTotal,
showChatLogsColumnPanel,
chatLogsWrapEnabled,
chatLogsWrapMaxHeight,
showChatLogsSelection,
reportCurrentPage,
reportPageSize,
reportPageSizeOptions,
chatLogsColumns,
chatLogsSortRules,
reportHeaderSort,
draggingColumnKey,
isChatLogsTable,
visibleReportKeys,
allReportRowsSelected,
sortedTableData,
paginatedSortedTableData,
reportTotalRows,
reportTotalPages,
reportRangeStart,
reportRangeEnd,
reportPageButtons,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
handleFilterChange,
resetChatLogsColumns,
moveChatLogsColumn,
onColumnDragStart,
onColumnDrop,
startResizeColumn,
exportToExcel,
getReportColumnLabel,
getReportTableLabel,
getReportCellValue,
getColumnWidthStyle,
getReportRowId,
getReportCellDisplayStyle,
getReportCellInnerStyle,
getHeaderSortMark,
onReportHeaderClick,
addChatLogsSortRule,
removeChatLogsSortRule,
moveChatLogsSortRule,
toggleReportRowSelection,
toggleAllReportRows,
batchDeleteChatLogs,
goToReportPage,
prevReportPage,
nextReportPage,
confirmDelete,
};
}
@@ -0,0 +1,100 @@
/**
* features/admin/modules/requests/RequestsPage.vue
* 权限申请管理独立页面。路由:/admin/requests
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ShieldCheck } from 'lucide-vue-next';
import { useRequestsAdmin } from './composables/useRequestsAdmin';
const { t } = useI18n();
const {
requests,
isLoading,
loadAll,
approveRequest,
rejectRequest,
} = useRequestsAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header">
<div>
<h2 class="section-title">{{ t('admin.request.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.request.subtitle') }}</p>
</div>
</div>
<div
v-if="requests.length === 0"
class="flex flex-col items-center justify-center py-16 text-muted"
>
<div class="w-16 h-16 bg-surface-soft rounded-full flex items-center justify-center mb-4">
<ShieldCheck class="w-8 h-8 text-muted" />
</div>
<p>{{ t('admin.request.noPending') }}</p>
</div>
<table v-else class="admin-table">
<thead>
<tr>
<th class="px-8 py-4 text-xs">{{ t('admin.request.headers.userId') }}</th>
<th class="px-8 py-4 text-xs">{{ t('admin.request.headers.targetAgent') }}</th>
<th class="px-8 py-4 text-xs">{{ t('admin.request.headers.reason') }}</th>
<th class="px-8 py-4 text-xs">{{ t('admin.request.headers.status') }}</th>
<th class="px-8 py-4 text-xs text-right">{{ t('admin.request.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="req in requests" :key="req.id">
<td class="px-8 py-4 text-sm font-medium text-primary">{{ req.user_id }}</td>
<td class="px-8 py-4 text-sm text-secondary">{{ req.agent_id }}</td>
<td
class="px-8 py-4 text-sm text-muted max-w-xs truncate"
:title="req.reason"
>
{{ req.reason || '-' }}
</td>
<td class="px-8 py-4">
<span
class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-50 text-yellow-700 border border-yellow-100"
>
{{ t('admin.status.' + req.status) }}
</span>
</td>
<td class="px-8 py-4 text-right">
<div class="flex justify-end gap-3">
<button
type="button"
class="text-green-600 hover:text-green-800 text-sm font-medium hover:underline"
@click="approveRequest(req.id)"
>
{{ t('admin.request.approve') }}
</button>
<button
type="button"
class="text-red-500 hover:text-red-700 text-sm font-medium hover:underline"
@click="rejectRequest(req.id)"
>
{{ t('admin.request.reject') }}
</button>
</div>
</td>
</tr>
</tbody>
</table>
</template>
</section>
</template>
@@ -0,0 +1,68 @@
/**
* features/admin/modules/requests/composables/useRequestsAdmin.ts
* 权限申请管理:列表、通过、拒绝。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
approveAdminPermissionRequest,
listAdminPermissionRequests,
rejectAdminPermissionRequest,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import { useAdminNavBadges } from '@/features/admin/composables/useAdminNavBadges';
import type { AdminPermissionRequestRow } from '@/features/admin/types/request.types';
export function useRequestsAdmin() {
const { t } = useI18n();
const msg = useMessage();
const { refreshBadges } = useAdminNavBadges();
const requests = ref<AdminPermissionRequestRow[]>([]);
const isLoading = ref(true);
const loadRequests = async (): Promise<void> => {
try {
requests.value = await listAdminPermissionRequests();
} catch (e) {
console.error('Error loading permission requests:', e);
requests.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadRequests();
isLoading.value = false;
};
const approveRequest = async (id: number): Promise<void> => {
try {
await approveAdminPermissionRequest(id);
await loadRequests();
await refreshBadges();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
}
};
const rejectRequest = async (id: number): Promise<void> => {
try {
await rejectAdminPermissionRequest(id);
await loadRequests();
await refreshBadges();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
}
};
return {
requests,
isLoading,
loadAll,
approveRequest,
rejectRequest,
};
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,972 @@
/**
* features/admin/modules/schedules/composables/useSchedulesAdmin.ts
* 定时任务管理:概览、工作台、创建/编辑、试运行。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { listAdminAgents, listAdminUsers } from '@/api/admin';
import {
createAdminSchedule,
deleteAdminSchedule,
getAdminScheduleTaskConfig,
listAdminScheduleRuns,
listAdminSchedules,
runAdminSchedule,
testAdminScheduleRun,
testAdminScheduleSql,
toggleAdminSchedule,
updateAdminSchedule,
type ScheduleRun,
type ScheduleTask,
type TestScheduleRunResult,
} from '@/api/schedule';
import { useMessage } from '@/composables/useMessage';
import { getAuthHeaders } from '@/utils/auth';
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
export function useSchedulesAdmin() {
const { t, locale } = useI18n();
const msg = useMessage();
const agents = ref<AdminAgentOption[]>([]);
const users = ref<AdminUserRow[]>([]);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const openDeleteConfirm = (
message: string,
onConfirm: () => Promise<void> | void,
title = '',
): void => {
deleteConfirmTitle.value = title;
deleteConfirmMessage.value = message;
deleteConfirmAction = onConfirm;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmTitle.value = '';
deleteConfirmMessage.value = '';
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Failed to load agents', e);
agents.value = [];
}
};
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const schedules = ref<ScheduleTask[]>([]);
const schedulesLoaded = ref(false); void schedulesLoaded;
const selectedScheduleRuns = ref<ScheduleRun[]>([]);
const scheduleLoading = ref(false);
const scheduleRunsLoading = ref(false);
const selectedScheduleId = ref<number | null>(null);
const scheduleRunStatusFilter = ref<'all' | string>('all');
const scheduleRunStartedAfter = ref('');
const scheduleRunStartedBefore = ref('');
const scheduleRunColumnDefs = ref([
{ key: 'run_no', label: '', width: 280, min: 60 },
{ key: 'started_at', label: '', width: 190, min: 60 },
{ key: 'finished_at', label: '', width: 190, min: 60 },
{ key: 'status', label: '', width: 130, min: 50 },
{ key: 'total_count', label: '', width: 70, min: 40 },
{ key: 'success_count', label: '', width: 70, min: 40 },
{ key: 'failed_count', label: '', width: 70, min: 40 },
{ key: 'wecom_notified', label: '', width: 100, min: 80 },
{ key: 'detail', label: '', width: 100, min: 80 },
{ key: 'log', label: '', width: 100, min: 80 },
]);
const syncScheduleRunColumnLabels = () => {
const keyToI18n: Record<string, string> = {
run_no: 'runNo',
started_at: 'startedAt',
finished_at: 'finishedAt',
status: 'status',
total_count: 'totalCount',
success_count: 'successCount',
failed_count: 'failedCount',
wecom_notified: 'wecomNotified',
detail: 'detail',
log: 'log',
};
scheduleRunColumnDefs.value.forEach((col) => {
const i18nKey = keyToI18n[col.key];
if (i18nKey) col.label = t(`admin.schedule.columns.${i18nKey}`);
});
};
watch(locale, syncScheduleRunColumnLabels, { immediate: true });
const resizingScheduleCol = ref<{ index: number; startX: number; startWidth: number } | null>(null);
const onScheduleColResizeMove = (event: MouseEvent) => {
const state = resizingScheduleCol.value;
if (!state) return;
const def = scheduleRunColumnDefs.value[state.index];
if (!def) return;
const delta = event.clientX - state.startX;
def.width = Math.max(def.min, state.startWidth + delta);
};
const stopScheduleColResize = () => {
if (!resizingScheduleCol.value) return;
resizingScheduleCol.value = null;
window.removeEventListener('mousemove', onScheduleColResizeMove);
window.removeEventListener('mouseup', stopScheduleColResize);
};
const startScheduleColResize = (index: number, event: MouseEvent) => {
const def = scheduleRunColumnDefs.value[index];
if (!def) return;
resizingScheduleCol.value = {
index,
startX: event.clientX,
startWidth: def.width,
};
window.addEventListener('mousemove', onScheduleColResizeMove);
window.addEventListener('mouseup', stopScheduleColResize);
};
const scheduleViewMode = ref<'overview' | 'workbench'>('overview');
const showScheduleCreateModal = ref(false);
const scheduleCreateSaving = ref(false);
const scheduleEditingId = ref<number | null>(null);
const scheduleCreateForm = ref({
name: '',
platform_api_path: '',
data_source_type: 'database' as 'database' | 'external_api',
dify_agent_id: null as number | null,
owner_user_id: null as number | null,
wait_seconds: 300,
notify_enabled: true,
notify_user_ids_json: [] as number[],
enabled: true,
});
const scheduleConfigCollapsed = ref(true);
const scheduleCronDesigner = ref({
mode: 'every_minutes' as 'every_minutes' | 'hourly' | 'daily' | 'weekly',
every_minutes: 30,
hourly_minute: 0,
daily_hour: 9,
daily_minute: 0,
weekly_day: 1,
weekly_hour: 9,
weekly_minute: 0,
});
const weeklyDayOptions = computed(() => [
{ value: 1, label: t('admin.schedule.weekday.mon') },
{ value: 2, label: t('admin.schedule.weekday.tue') },
{ value: 3, label: t('admin.schedule.weekday.wed') },
{ value: 4, label: t('admin.schedule.weekday.thu') },
{ value: 5, label: t('admin.schedule.weekday.fri') },
{ value: 6, label: t('admin.schedule.weekday.sat') },
{ value: 0, label: t('admin.schedule.weekday.sun') },
]);
const buildCronExprFromDesigner = () => {
const cfg = scheduleCronDesigner.value;
if (cfg.mode === 'every_minutes') {
const every = Math.max(1, Math.min(59, Number(cfg.every_minutes || 30)));
return `*/${every} * * * *`;
}
if (cfg.mode === 'hourly') {
const minute = Math.max(0, Math.min(59, Number(cfg.hourly_minute || 0)));
return `${minute} * * * *`;
}
if (cfg.mode === 'daily') {
const minute = Math.max(0, Math.min(59, Number(cfg.daily_minute || 0)));
const hour = Math.max(0, Math.min(23, Number(cfg.daily_hour || 0)));
return `${minute} ${hour} * * *`;
}
const minute = Math.max(0, Math.min(59, Number(cfg.weekly_minute || 0)));
const hour = Math.max(0, Math.min(23, Number(cfg.weekly_hour || 0)));
const day = Number(cfg.weekly_day);
return `${minute} ${hour} * * ${Number.isNaN(day) ? 1 : day}`;
};
const scheduleCronPreview = computed(() => buildCronExprFromDesigner());
const scheduleNextRunPreview = computed(() => {
const expr = scheduleCronPreview.value;
if (!expr) return null;
try {
const parts = expr.trim().split(/\s+/);
if (parts.length !== 5) return null;
const now = new Date();
const minuteRaw = parts[0]!;
const hourRaw = parts[1]!;
const dayOfMonth = parts[2]!;
const month = parts[3]!;
const dayOfWeek = parts[4]!;
if (month !== '*') return null;
if (dayOfMonth !== '*' && dayOfWeek !== '*') return null;
const minute = minuteRaw.startsWith('*/') ? undefined : parseInt(minuteRaw, 10);
const hour = hourRaw === '*' ? undefined : parseInt(hourRaw, 10);
if (minuteRaw.startsWith('*/')) {
const every = parseInt(minuteRaw.replace('*/', ''), 10);
const next = new Date(now);
next.setSeconds(0, 0);
const mod = next.getMinutes() % every;
next.setMinutes(next.getMinutes() + (every - mod));
if (next <= now) next.setMinutes(next.getMinutes() + every);
return next;
}
if (minute !== undefined && hour === undefined) {
const next = new Date(now);
next.setMinutes(minute, 0, 0);
if (next <= now) next.setHours(next.getHours() + 1);
return next;
}
if (minute !== undefined && hour !== undefined) {
const next = new Date(now);
next.setHours(hour, minute, 0, 0);
if (next <= now) {
if (dayOfWeek !== '*') {
const dow = parseInt(dayOfWeek, 10);
const currentDow = next.getDay();
let diff = dow - currentDow;
if (diff <= 0) diff += 7;
next.setDate(next.getDate() + diff);
} else {
next.setDate(next.getDate() + 1);
}
} else if (dayOfWeek !== '*') {
const dow = parseInt(dayOfWeek, 10);
const target = new Date(next);
const currentDow = target.getDay();
let diff = dow - currentDow;
if (diff < 0) diff += 7;
if (diff > 0) target.setDate(target.getDate() + diff);
if (target <= now) {
target.setDate(target.getDate() + 7);
}
return target;
}
return next;
}
return null;
} catch {
return null;
}
});
const parseCronExprToDesigner = (expr: string | null | undefined) => {
const text = String(expr || '').trim();
const parts = text.split(/\s+/);
if (parts.length !== 5) {
scheduleCronDesigner.value = {
mode: 'every_minutes',
every_minutes: 30,
hourly_minute: 0,
daily_hour: 9,
daily_minute: 0,
weekly_day: 1,
weekly_hour: 9,
weekly_minute: 0,
};
return;
}
const m = parts[0] ?? '';
const h = parts[1] ?? '';
const dow = parts[4] ?? '';
if (/^\*\/\d+$/.test(m) && h === '*' && dow === '*') {
scheduleCronDesigner.value.mode = 'every_minutes';
scheduleCronDesigner.value.every_minutes = Number(m.replace('*/', '')) || 30;
return;
}
if (/^\d+$/.test(m) && h === '*' && dow === '*') {
scheduleCronDesigner.value.mode = 'hourly';
scheduleCronDesigner.value.hourly_minute = Number(m) || 0;
return;
}
if (/^\d+$/.test(m) && /^\d+$/.test(h) && dow === '*') {
scheduleCronDesigner.value.mode = 'daily';
scheduleCronDesigner.value.daily_hour = Number(h) || 0;
scheduleCronDesigner.value.daily_minute = Number(m) || 0;
return;
}
if (/^\d+$/.test(m) && /^\d+$/.test(h) && /^\d+$/.test(dow)) {
scheduleCronDesigner.value.mode = 'weekly';
scheduleCronDesigner.value.weekly_hour = Number(h) || 0;
scheduleCronDesigner.value.weekly_minute = Number(m) || 0;
scheduleCronDesigner.value.weekly_day = Number(dow);
return;
}
scheduleCronDesigner.value.mode = 'every_minutes';
scheduleCronDesigner.value.every_minutes = 30;
};
const resetScheduleCreateForm = () => {
scheduleEditingId.value = null;
scheduleCreateForm.value = {
name: '',
platform_api_path: '',
data_source_type: 'database',
dify_agent_id: null,
owner_user_id: null,
wait_seconds: 300,
notify_enabled: true,
notify_user_ids_json: [],
enabled: true,
};
scheduleSqlEditForm.value = {
base_fetch_sql: '',
fetch_where_conditions: '',
fetch_order_by: '',
detail_sql: '',
writeback_sql: '',
row_id_key: 'id',
log_prefix: '',
alias_order_str: '',
detail_alias_order_str: '',
header_labels_str: '{}',
ds_db_type: 'sqlserver',
ds_host: '',
ds_port: '',
ds_database: '',
ds_username: '',
ds_password: '',
ds_driver: '',
ds_encrypt: '',
ds_trust_cert: '',
api_url: '',
api_method: 'POST',
api_headers_str: '{}',
api_body_template: '',
dify_system_prompt: '',
};
scheduleTestResult.value = null;
scheduleCronDesigner.value = {
mode: 'every_minutes',
every_minutes: 30,
hourly_minute: 0,
daily_hour: 9,
daily_minute: 0,
weekly_day: 1,
weekly_hour: 9,
weekly_minute: 0,
};
};
const openScheduleCreateModal = async () => {
resetScheduleCreateForm();
scheduleConfigCollapsed.value = true;
await Promise.all([loadAgents(), loadUsers()]);
showScheduleCreateModal.value = true;
};
const openScheduleEditModal = async (task: ScheduleTask) => {
await Promise.all([loadAgents(), loadUsers()]);
scheduleConfigCollapsed.value = true;
scheduleEditingId.value = task.id;
scheduleCreateForm.value = {
name: task.name || '',
platform_api_path: task.platform_api_path || '',
dify_agent_id: task.dify_agent_id || null,
owner_user_id: task.owner_user_id || null,
wait_seconds: task.wait_seconds || 0,
notify_enabled: !!task.notify_enabled,
notify_user_ids_json: task.notify_user_ids_json || [],
enabled: !!task.enabled,
data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
};
try {
const result = await getAdminScheduleTaskConfig(task.id);
const cfg = result.config;
scheduleCreateForm.value.data_source_type = (result.data_source_type || 'database') as 'database' | 'external_api';
if (cfg) {
scheduleSqlEditForm.value = {
base_fetch_sql: cfg.base_fetch_sql || '',
fetch_where_conditions: cfg.fetch_where_conditions || '',
fetch_order_by: cfg.fetch_order_by || '',
detail_sql: cfg.detail_sql || '',
writeback_sql: cfg.writeback_sql || '',
row_id_key: cfg.row_id_key || 'id',
log_prefix: cfg.log_prefix || '',
alias_order_str: (cfg.alias_order || []).join(','),
detail_alias_order_str: (cfg.detail_alias_order || []).join(','),
header_labels_str: cfg.header_labels ? JSON.stringify(cfg.header_labels, null, 2) : '{}',
ds_db_type: cfg.data_source?.db_type || 'sqlserver',
ds_host: cfg.data_source?.host || '',
ds_port: cfg.data_source?.port || '',
ds_database: cfg.data_source?.database || '',
ds_username: cfg.data_source?.username || '',
ds_password: cfg.data_source?.password || '',
ds_driver: cfg.data_source?.driver || '',
ds_encrypt: cfg.data_source?.encrypt || '',
ds_trust_cert: cfg.data_source?.trust_cert || '',
api_url: cfg.external_api?.url || '',
api_method: cfg.external_api?.method || 'POST',
api_headers_str: cfg.external_api?.headers ? JSON.stringify(cfg.external_api.headers, null, 2) : '{}',
api_body_template: cfg.external_api?.body_template || '',
dify_system_prompt: cfg.dify_system_prompt || '',
};
}
} catch {
scheduleSqlEditForm.value = {
base_fetch_sql: '',
fetch_where_conditions: '',
fetch_order_by: '',
detail_sql: '',
writeback_sql: '',
row_id_key: 'id',
log_prefix: '',
alias_order_str: '',
detail_alias_order_str: '',
header_labels_str: '{}',
ds_db_type: 'sqlserver',
ds_host: '',
ds_port: '',
ds_database: '',
ds_username: '',
ds_password: '',
ds_driver: '',
ds_encrypt: '',
ds_trust_cert: '',
api_url: '',
api_method: 'POST',
api_headers_str: '{}',
api_body_template: '',
dify_system_prompt: '',
};
}
scheduleTestResult.value = null;
parseCronExprToDesigner(task.cron_expr);
showScheduleCreateModal.value = true;
};
const selectedSchedule = computed(() =>
schedules.value.find((item) => item.id === selectedScheduleId.value) || null
);
const scheduleRunStatusOptions = computed(() => [
{ value: 'all', label: t('admin.schedule.status.all') },
{ value: 'success', label: t('admin.schedule.status.success') },
{ value: 'partial_failed', label: t('admin.schedule.status.partialFailed') },
{ value: 'failed', label: t('admin.schedule.status.failed') },
{ value: 'running', label: t('admin.schedule.status.running') },
]);
const getScheduleRunStatusBadge = (status: string) => {
const map: Record<string, { cls: string; label: string }> = {
success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
partial_failed: { cls: 'bg-blue-100 text-blue-700', label: t('admin.schedule.status.partialFailed') },
failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
running: { cls: 'bg-amber-100 text-amber-700', label: t('admin.schedule.status.running') },
queued: { cls: 'bg-surface-soft text-secondary', label: t('admin.schedule.status.queued') },
};
return map[status] || { cls: 'bg-surface-soft text-secondary', label: status };
};
const formatDateTime = (iso?: string | null) => {
if (!iso) return '-';
const d = new Date(iso);
if (isNaN(d.getTime())) return iso;
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
const expandedScheduleRunId = ref<number | null>(null);
const expandedScheduleRun = computed(() => {
if (!expandedScheduleRunId.value) return null;
return filteredScheduleRuns.value.find((x) => x.id === expandedScheduleRunId.value) || null;
});
const stepLabelMap: Record<string, string> = {
fetch_srm: t('admin.schedule.step.fetchSrm'),
call_dify: t('admin.schedule.step.callDify'),
writeback_srm: t('admin.schedule.step.writebackSrm'),
call_internal_api: t('admin.schedule.step.callInternalApi'),
pre_dify: t('admin.schedule.step.preDify'),
};
const stepStatusMap: Record<string, { cls: string; label: string }> = {
success: { cls: 'bg-emerald-100 text-emerald-700', label: t('admin.schedule.status.success') },
failed: { cls: 'bg-rose-100 text-rose-700', label: t('admin.schedule.status.failed') },
};
const showTestRunDialog = ref(false);
const testRunSchedule = ref<ScheduleTask | null>(null);
const testRunWhere = ref('');
const testRunOrderBy = ref('');
const testRunBaseFetchSql = ref('');
const testRunLimit = ref(3);
const testRunLoading = ref(false);
const testRunResult = ref<TestScheduleRunResult | null>(null);
const openTestRunDialog = async (s: ScheduleTask) => {
testRunSchedule.value = s;
try {
const result = await getAdminScheduleTaskConfig(s.id);
const cfg = result.config;
testRunWhere.value = cfg?.fetch_where_conditions || '';
testRunOrderBy.value = cfg?.fetch_order_by || '';
testRunBaseFetchSql.value = cfg?.base_fetch_sql || '';
} catch {
testRunWhere.value = '';
testRunOrderBy.value = '';
testRunBaseFetchSql.value = '';
}
testRunLimit.value = 3;
testRunResult.value = null;
testRunLoading.value = false;
showTestRunDialog.value = true;
};
const handleTestRun = async () => {
const s = testRunSchedule.value;
if (!s?.id) return;
testRunLoading.value = true;
testRunResult.value = null;
try {
const result = await testAdminScheduleRun(s.id, {
fetch_where_conditions: testRunWhere.value,
fetch_order_by: testRunOrderBy.value,
limit: testRunLimit.value,
});
testRunResult.value = result;
await loadSchedules();
if (s.id) {
await viewScheduleRuns(s.id);
}
} catch (e: any) {
msg.error(`${t('admin.schedule.msg.testRunFailed')}: ${e?.message || e}`);
} finally {
testRunLoading.value = false;
}
};
const filteredScheduleRuns = computed(() => {
if (scheduleRunStatusFilter.value === 'all') return selectedScheduleRuns.value;
return selectedScheduleRuns.value.filter((item) => item.status === scheduleRunStatusFilter.value);
});
const selectedScheduleRunMetrics = computed(() => {
const runs = selectedScheduleRuns.value;
return runs.reduce(
(acc, item) => {
acc.total += item.total_count || 0;
acc.success += item.success_count || 0;
acc.failed += item.failed_count || 0;
return acc;
},
{ total: 0, success: 0, failed: 0 }
);
});
const selectedScheduleLatestRunAt = computed(
() => selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at || '-'
);
const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length);
const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length);
const loadSchedules = async () => {
scheduleLoading.value = true;
try {
schedules.value = await listAdminSchedules();
if (schedules.value.length === 0) {
selectedScheduleId.value = null;
selectedScheduleRuns.value = [];
scheduleViewMode.value = 'overview';
return;
}
const exists = selectedScheduleId.value && schedules.value.some((item) => item.id === selectedScheduleId.value);
const nextScheduleId = exists && selectedScheduleId.value ? selectedScheduleId.value : schedules.value[0]?.id ?? null;
if (!exists && nextScheduleId) {
selectedScheduleId.value = nextScheduleId;
}
if (scheduleViewMode.value === 'workbench' && nextScheduleId) {
await viewScheduleRuns(nextScheduleId);
}
} finally {
scheduleLoading.value = false;
}
};
const scheduleSqlEditForm = ref({
base_fetch_sql: '',
fetch_where_conditions: '',
fetch_order_by: '',
detail_sql: '',
writeback_sql: '',
row_id_key: 'id',
log_prefix: '',
alias_order_str: '',
detail_alias_order_str: '',
header_labels_str: '{}',
ds_db_type: 'sqlserver',
ds_host: '',
ds_port: '',
ds_database: '',
ds_username: '',
ds_password: '',
ds_driver: '',
ds_encrypt: '',
ds_trust_cert: '',
api_url: '',
api_method: 'POST',
api_headers_str: '{}',
api_body_template: '',
dify_system_prompt: '',
});
const scheduleSqlSaving = ref(false); void scheduleSqlSaving;
const scheduleTestLoading = ref(false);
const scheduleTestResult = ref<{ total: number; showing: number; columns: string[]; rows: any[]; sql: string } | null>(null);
const handleTestScheduleSql = async () => {
const taskId = scheduleEditingId.value;
if (!taskId) return;
scheduleTestLoading.value = true;
scheduleTestResult.value = null;
try {
const result = await testAdminScheduleSql(taskId, {
fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions,
fetch_order_by: scheduleSqlEditForm.value.fetch_order_by,
limit: 10,
});
scheduleTestResult.value = result;
} catch (e: any) {
msg.error(`${t('admin.schedule.msg.testQueryFailed')}: ${e?.message || e}`);
} finally {
scheduleTestLoading.value = false;
}
};
const scheduleNotifyDropdownOpen = ref(false);
watch(() => scheduleCreateForm.value.dify_agent_id, (agentId) => {
if (!agentId) {
scheduleSqlEditForm.value.dify_system_prompt = '';
}
});
const getUserName = (uid: number) => {
const u = users.value.find(x => x.id === uid);
return u ? (u.real_name || u.username) : String(uid);
};
const toggleNotifyUser = (uid: number) => {
const list = scheduleCreateForm.value.notify_user_ids_json;
if (list.includes(uid)) {
scheduleCreateForm.value.notify_user_ids_json = list.filter((id: number) => id !== uid);
} else {
scheduleCreateForm.value.notify_user_ids_json = [...list, uid];
}
};
const removeNotifyUser = (uid: number) => {
scheduleCreateForm.value.notify_user_ids_json = scheduleCreateForm.value.notify_user_ids_json.filter((id: number) => id !== uid);
};
const createSchedule = async () => {
if (!scheduleCreateForm.value.name || !scheduleCreateForm.value.owner_user_id) return;
const dst = scheduleCreateForm.value.data_source_type;
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) {
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;
}
let apiHeaders: Record<string, string> = {};
if (dst === 'external_api') {
try {
apiHeaders = JSON.parse(scheduleSqlEditForm.value.api_headers_str || '{}');
} catch {
msg.error(t('admin.schedule.msg.apiHeadersJsonInvalid'));
return;
}
}
const aliasOrder = scheduleSqlEditForm.value.alias_order_str.split(',').map(s => s.trim()).filter(Boolean);
const detailAliasOrder = scheduleSqlEditForm.value.detail_alias_order_str.split(',').map(s => s.trim()).filter(Boolean);
const configPayload: Record<string, any> = {
base_fetch_sql: scheduleSqlEditForm.value.base_fetch_sql,
fetch_where_conditions: scheduleSqlEditForm.value.fetch_where_conditions,
fetch_order_by: scheduleSqlEditForm.value.fetch_order_by,
detail_sql: scheduleSqlEditForm.value.detail_sql,
writeback_sql: scheduleSqlEditForm.value.writeback_sql,
row_id_key: scheduleSqlEditForm.value.row_id_key || 'id',
log_prefix: scheduleSqlEditForm.value.log_prefix,
alias_order: aliasOrder,
detail_alias_order: detailAliasOrder,
header_labels: headerLabels,
data_source: scheduleSqlEditForm.value.ds_host.trim() ? {
db_type: scheduleSqlEditForm.value.ds_db_type,
host: scheduleSqlEditForm.value.ds_host,
port: scheduleSqlEditForm.value.ds_port,
database: scheduleSqlEditForm.value.ds_database,
username: scheduleSqlEditForm.value.ds_username,
password: scheduleSqlEditForm.value.ds_password,
driver: scheduleSqlEditForm.value.ds_driver,
encrypt: scheduleSqlEditForm.value.ds_encrypt,
trust_cert: scheduleSqlEditForm.value.ds_trust_cert,
} : undefined,
external_api: scheduleSqlEditForm.value.api_url.trim() ? {
url: scheduleSqlEditForm.value.api_url,
method: scheduleSqlEditForm.value.api_method,
headers: apiHeaders,
body_template: scheduleSqlEditForm.value.api_body_template,
} : undefined,
dify_system_prompt: hasAgent ? scheduleSqlEditForm.value.dify_system_prompt : '',
};
scheduleCreateSaving.value = true;
try {
const payload: any = {
name: scheduleCreateForm.value.name,
schedule_type: 'platform_app',
owner_user_id: scheduleCreateForm.value.owner_user_id,
cron_expr: scheduleCronPreview.value,
wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)),
dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined,
notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [],
notify_enabled: scheduleCreateForm.value.notify_enabled,
enabled: scheduleCreateForm.value.enabled,
data_source_type: dst,
config: configPayload,
};
let resultData: any = null;
if (scheduleEditingId.value) {
resultData = await updateAdminSchedule(scheduleEditingId.value, payload);
} else {
resultData = await createAdminSchedule(payload);
}
const createdId = resultData?.id ?? resultData?.schedule?.id ?? null;
const targetId = scheduleEditingId.value || createdId;
showScheduleCreateModal.value = false;
await loadSchedules();
if (targetId) {
await viewScheduleRuns(targetId);
}
} catch (err: any) {
msg.error(err?.message || t('common.errorOccurred'));
} finally {
scheduleCreateSaving.value = false;
}
};
const todayStart = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`;
};
const todayEnd = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T23:59:59`;
};
const resetScheduleRunFilters = () => {
scheduleRunStatusFilter.value = 'all';
scheduleRunStartedAfter.value = todayStart();
scheduleRunStartedBefore.value = todayEnd();
};
const viewScheduleRuns = async (taskId: number) => {
selectedScheduleId.value = taskId;
scheduleRunsLoading.value = true;
if (!scheduleRunStartedAfter.value && !scheduleRunStartedBefore.value) {
resetScheduleRunFilters();
}
try {
const params: { status?: string; started_after?: string; started_before?: string } = {};
if (scheduleRunStatusFilter.value !== 'all') params.status = scheduleRunStatusFilter.value;
if (scheduleRunStartedAfter.value) params.started_after = scheduleRunStartedAfter.value;
if (scheduleRunStartedBefore.value) params.started_before = scheduleRunStartedBefore.value;
selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
} finally {
scheduleRunsLoading.value = false;
}
};
const openScheduleRunSubmenu = async (taskId: number) => {
scheduleViewMode.value = 'workbench';
await viewScheduleRuns(taskId);
};
const backToScheduleOverview = () => {
scheduleViewMode.value = 'overview';
};
const runScheduleNow = async (taskId: number) => {
try {
await runAdminSchedule(taskId);
} catch (err: any) {
msg.error(err?.message || t('admin.schedule.msg.runNowFailed'));
return;
}
await viewScheduleRuns(taskId);
await loadSchedules();
const pollInterval = setInterval(async () => {
await viewScheduleRuns(taskId);
await loadSchedules();
const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
if (target && target.last_status && target.last_status !== 'running') {
clearInterval(pollInterval);
}
}, 5000);
};
const setScheduleEnabled = async (taskId: number, enabled: boolean) => {
try {
await toggleAdminSchedule(taskId, enabled);
await loadSchedules();
} catch (err: any) {
msg.error(err?.message || t('common.errorOccurred'));
}
};
const downloadScheduleExcel = async (runId: number) => {
const res = await fetch(`/api/admin/schedule-runs/${runId}/excel`, { headers: getAuthHeaders() });
if (!res.ok) {
msg.error(t('admin.schedule.msg.downloadExcelFailed'));
return;
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
const disposition = res.headers.get('content-disposition');
a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || 'result.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
const deleteSchedule = (task: ScheduleTask) => {
openDeleteConfirm(
t('admin.schedule.deleteConfirmMessage', { name: task.name }),
async () => {
try {
await deleteAdminSchedule(task.id);
} catch (err: any) {
msg.error(err?.message || t('admin.schedule.msg.deleteFailed'));
return;
}
if (selectedScheduleId.value === task.id) {
selectedScheduleId.value = null;
selectedScheduleRuns.value = [];
}
await loadSchedules();
},
t('admin.schedule.deleteDialogTitle')
);
};
const loadAll = async (): Promise<void> => {
await loadSchedules();
};
return {
agents,
users,
schedules,
selectedScheduleRuns,
scheduleLoading,
scheduleRunsLoading,
selectedScheduleId,
scheduleRunStatusFilter,
scheduleRunStartedAfter,
scheduleRunStartedBefore,
scheduleRunColumnDefs,
scheduleViewMode,
showScheduleCreateModal,
scheduleCreateSaving,
scheduleEditingId,
scheduleCreateForm,
scheduleConfigCollapsed,
scheduleCronDesigner,
weeklyDayOptions,
scheduleCronPreview,
scheduleNextRunPreview,
selectedSchedule,
scheduleRunStatusOptions,
getScheduleRunStatusBadge,
formatDateTime,
expandedScheduleRunId,
expandedScheduleRun,
stepLabelMap,
stepStatusMap,
showTestRunDialog,
testRunSchedule,
testRunWhere,
testRunOrderBy,
testRunBaseFetchSql,
testRunLimit,
testRunLoading,
testRunResult,
filteredScheduleRuns,
selectedScheduleRunMetrics,
selectedScheduleLatestRunAt,
scheduleEnabledCount,
scheduleDisabledCount,
scheduleRunningCount,
scheduleSqlEditForm,
scheduleTestLoading,
scheduleTestResult,
scheduleNotifyDropdownOpen,
showDeleteConfirmDialog,
deleteConfirmTitle,
deleteConfirmMessage,
loadAll,
loadSchedules,
startScheduleColResize,
openScheduleCreateModal,
openScheduleEditModal,
openScheduleRunSubmenu,
backToScheduleOverview,
viewScheduleRuns,
resetScheduleRunFilters,
runScheduleNow,
setScheduleEnabled,
deleteSchedule,
downloadScheduleExcel,
openTestRunDialog,
handleTestRun,
handleTestScheduleSql,
getUserName,
toggleNotifyUser,
removeNotifyUser,
createSchedule,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,244 @@
/**
* features/admin/modules/users/UsersPage.vue
* 用户管理独立页面。路由:/admin/users
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import BatchEditUserModal from './components/BatchEditUserModal.vue';
import BatchPermissionModal from './components/BatchPermissionModal.vue';
import UserFormModal from './components/UserFormModal.vue';
import { useUsersAdmin } from './composables/useUsersAdmin';
const { t } = useI18n();
const {
agents,
departments,
isLoading,
isSaving,
userFilters,
hideRejected,
selectedUserIds,
filteredUsers,
showUserModal,
editingUser,
showBatchEditModal,
batchEditForm,
showBatchPermissionModal,
batchPermissionForm,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateUserModal,
openEditUserModal,
saveUser,
cleanRejectedUsers,
batchDeleteUsers,
toggleUserSelection,
toggleAllUsers,
openBatchEditModal,
openBatchPermissionModal,
submitBatchEdit,
submitBatchPermission,
closeDeleteConfirm,
confirmDelete,
} = useUsersAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.user.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.user.subtitle') }}</p>
</div>
<div class="flex flex-wrap gap-3">
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-red-50 text-red-600 rounded-xl hover:bg-red-100 transition-all border border-red-200 text-sm font-medium"
@click="cleanRejectedUsers"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.cleanRejected') }}</span>
</button>
<button
v-if="selectedUserIds.length > 0"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-xl hover:bg-red-700 transition-all shadow-lg shadow-red-200 active:scale-95 text-sm font-medium"
@click="batchDeleteUsers"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.batchDelete') }} ({{ selectedUserIds.length }})</span>
</button>
<button
v-if="selectedUserIds.length > 0"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-200 active:scale-95 text-sm font-medium"
@click="openBatchEditModal"
>
<Edit class="w-4 h-4" />
<span>{{ t('admin.user.batchEdit') }} ({{ selectedUserIds.length }})</span>
</button>
<button
v-if="selectedUserIds.length > 0"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition-all shadow-lg shadow-purple-200 active:scale-95 text-sm font-medium"
@click="openBatchPermissionModal"
>
<Users class="w-4 h-4" />
<span>{{ t('admin.user.batchPermission') }} ({{ selectedUserIds.length }})</span>
</button>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateUserModal"
>
<Plus class="w-4 h-4" />
<span class="font-medium">{{ t('admin.user.addUser') }}</span>
</button>
</div>
</div>
<div class="admin-table-filters grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5">
<input v-model="userFilters.username" :placeholder="t('admin.user.filterUsername')" class="admin-table-filter-input" />
<input v-model="userFilters.email" :placeholder="t('admin.user.filterEmail')" class="admin-table-filter-input" />
<select v-model="userFilters.department" class="admin-table-filter-input">
<option value="">{{ t('admin.user.allDepts') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
<input v-model="userFilters.role" :placeholder="t('admin.user.filterRole')" class="admin-table-filter-input" />
<div class="flex items-center gap-2">
<input id="hideRejectedUsers" v-model="hideRejected" type="checkbox" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 border-default" />
<label for="hideRejectedUsers" class="text-sm text-secondary select-none">{{ t('admin.user.hideRejected') }}</label>
</div>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 w-12 text-center">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-default"
:checked="selectedUserIds.length === filteredUsers.length && filteredUsers.length > 0"
@change="toggleAllUsers(filteredUsers)"
/>
</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.user') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.role') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.dept') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs">{{ t('admin.user.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="filteredUsers.length === 0">
<td colspan="6" class="px-6 admin-table-empty">{{ t('admin.user.noUsers') }}</td>
</tr>
<tr v-for="user in filteredUsers" :key="user.id" class="group">
<td class="px-6 py-4 text-center">
<input
type="checkbox"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-default"
:checked="selectedUserIds.includes(user.id)"
@change="toggleUserSelection(user.id)"
/>
</td>
<td class="px-6 py-4">
<div class="flex items-center">
<div class="h-9 w-9 rounded-full bg-gradient-to-br from-brand-500 to-indigo-600 text-white flex items-center justify-center text-xs font-bold shadow-sm">
{{ user.username.charAt(0).toUpperCase() }}
</div>
<div class="ml-3">
<div class="text-sm font-medium text-primary">{{ user.username }}</div>
<div class="text-xs text-muted">{{ user.email }}</div>
</div>
</div>
</td>
<td class="px-6 py-4">
<span
class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
:class="user.role === 'admin' ? 'bg-purple-50 text-purple-700 border-purple-100' : 'bg-blue-50 text-blue-700 border-blue-100'"
>
{{ t('admin.role.' + user.role) }}
</span>
</td>
<td class="px-6 py-4 text-sm text-muted">{{ user.department || '-' }}</td>
<td class="px-6 py-4">
<span
class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
:class="{
'bg-green-50 text-green-700 border-green-100': user.status === 'active',
'bg-yellow-50 text-yellow-700 border-yellow-100': user.status === 'pending',
'bg-red-50 text-red-700 border-red-100': user.status === 'disabled' || user.status === 'rejected',
}"
>
{{ t('admin.status.' + user.status) }}
</span>
</td>
<td class="px-6 py-4 text-right">
<button
type="button"
class="text-brand-600 hover:text-brand-900 font-medium text-xs px-3 py-1.5 rounded-lg hover:bg-brand-50 transition-colors"
@click="openEditUserModal(user)"
>
{{ t('admin.edit') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<UserFormModal
:visible="showUserModal"
:form="editingUser"
:agents="agents"
:departments="departments"
:is-saving="isSaving"
@close="showUserModal = false"
@save="saveUser"
/>
<BatchEditUserModal
:visible="showBatchEditModal"
:form="batchEditForm"
:departments="departments"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="showBatchEditModal = false"
@save="submitBatchEdit"
/>
<BatchPermissionModal
:visible="showBatchPermissionModal"
:form="batchPermissionForm"
:agents="agents"
:selected-count="selectedUserIds.length"
:is-saving="isSaving"
@close="showBatchPermissionModal = false"
@save="submitBatchPermission"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
@cancel="closeDeleteConfirm"
/>
</section>
</template>
@@ -0,0 +1,62 @@
/**
* features/admin/modules/users/components/BatchEditUserModal.vue
* 批量编辑用户部门/角色/状态弹窗。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
import type { BatchEditForm } from '@/features/admin/types/user.types';
defineProps<{
visible: boolean;
form: BatchEditForm;
departments: AdminDepartmentRow[];
selectedCount: number;
isSaving: boolean;
}>();
const emit = defineEmits<{ close: []; save: [] }>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-md animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle">
<h3 class="text-lg font-bold text-primary">{{ t('admin.batchEdit.title') }}</h3>
<p class="text-sm text-muted">{{ t('admin.batchEdit.selected', { count: selectedCount }) }}</p>
</div>
<div class="p-8 space-y-4">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.dept') }}</label>
<select v-model="form.department" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.role') }}</label>
<select v-model="form.role" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.batchEdit.fields.status') }}</label>
<select v-model="form.status" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="active">{{ t('admin.status.active') }}</option>
<option value="disabled">{{ t('admin.status.disabled') }}</option>
</select>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-50" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.batchEdit.update') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,70 @@
/**
* features/admin/modules/users/components/BatchPermissionModal.vue
* 批量分配/移除用户 Agent 权限弹窗。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
import type { BatchPermissionForm } from '@/features/admin/types/user.types';
defineProps<{
visible: boolean;
form: BatchPermissionForm;
agents: AdminAgentOption[];
selectedCount: number;
isSaving: boolean;
}>();
const emit = defineEmits<{ close: []; save: [] }>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-lg animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle">
<h3 class="text-lg font-bold text-primary">{{ t('admin.perm.batchModal.title') }}</h3>
<p class="text-sm text-muted">{{ t('admin.perm.batchModal.selected', { count: selectedCount }) }}</p>
</div>
<div class="p-8 space-y-6">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.perm.batchModal.action') }}</label>
<div class="flex gap-4">
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.action" type="radio" value="add" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.add') }}</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.action" type="radio" value="remove" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.remove') }}</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input v-model="form.action" type="radio" value="set" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.set') }}</span>
</label>
</div>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.perm.batchModal.selectAgents') }}</label>
<div class="grid grid-cols-2 gap-3 max-h-60 overflow-y-auto p-1">
<label
v-for="agent in agents"
:key="agent.id"
class="flex items-center gap-2 p-3 border border-default rounded-lg cursor-pointer hover-surface-soft transition-colors"
:class="form.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input v-model="form.agent_ids" type="checkbox" :value="agent.id" class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500" />
<span class="text-sm font-medium text-secondary">{{ agent.name }}</span>
</label>
</div>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-50" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.perm.batchModal.apply') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,109 @@
/**
* features/admin/modules/users/components/UserFormModal.vue
* 创建/编辑用户弹窗。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { AdminAgentOption, AdminDepartmentRow } from '@/features/admin/types/admin.types';
import type { UserFormState } from '@/features/admin/types/user.types';
defineProps<{
visible: boolean;
form: UserFormState;
agents: AdminAgentOption[];
departments: AdminDepartmentRow[];
isSaving: boolean;
}>();
const emit = defineEmits<{
close: [];
save: [];
'update:form': [UserFormState];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in">
<div class="admin-modal-panel max-w-2xl 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.user.editUser') : t('admin.user.createUser') }}</h3>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.realName') }}
</label>
<input v-model="form.real_name" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.employeeId') }}
</label>
<input v-model="form.employee_id" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.phone') }}
</label>
<input v-model="form.phone_number" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5 col-span-1 md:col-span-2">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.allowedAgents') }}</label>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-2">
<label
v-for="agent in agents"
:key="agent.id"
class="flex items-center gap-2 p-3 border border-default rounded-lg cursor-pointer hover-surface-soft transition-colors"
:class="form.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input v-model="form.agent_ids" type="checkbox" :value="agent.id" class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500" />
<span class="text-sm font-medium text-secondary">{{ agent.name }}</span>
</label>
</div>
<p v-if="agents.length === 0" class="text-sm text-muted italic">{{ t('admin.user.fields.noAgents') }}</p>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.username') }}
</label>
<input v-model="form.username" type="text" class="w-full border-default rounded-xl px-4 py-3 text-sm" :disabled="!!form.id" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.email') }}
</label>
<input v-model="form.email" type="email" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.department') }}</label>
<select v-model="form.department" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option value="">{{ t('admin.user.allDepts') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.role') }}</label>
<select v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option value="user">{{ t('admin.role.user') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.password') }}
<span v-if="form.id" class="text-muted font-normal lowercase">{{ t('admin.user.fields.passwordHint') }}</span>
</label>
<input v-model="form.password" type="password" class="w-full border-default rounded-xl px-4 py-3 text-sm" />
</div>
</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') + '...' : t('admin.save') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,360 @@
/**
* features/admin/modules/users/composables/useUsersAdmin.ts
* 用户管理模块业务逻辑:CRUD、筛选、批量操作。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
batchDeleteAdminUsers,
batchUpdateAdminPermissions,
batchUpdateAdminUsers,
cleanupRejectedAdminUsers,
createAdminUser,
listAdminAgents,
listAdminDepartments,
listAdminUsers,
updateAdminUser,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminAgentOption, AdminDepartmentRow, AdminUserRow } from '@/features/admin/types/admin.types';
import {
createEmptyUserFilters,
createEmptyUserForm,
type BatchEditForm,
type BatchPermissionForm,
type UserFilters,
type UserFormState,
} from '@/features/admin/types/user.types';
const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
export function useUsersAdmin() {
const { t } = useI18n();
const msg = useMessage();
const users = ref<AdminUserRow[]>([]);
const agents = ref<AdminAgentOption[]>([]);
const departments = ref<AdminDepartmentRow[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const userFilters = ref<UserFilters>(createEmptyUserFilters());
const hideRejected = ref(true);
const selectedUserIds = ref<number[]>([]);
const showUserModal = ref(false);
const editingUser = ref<UserFormState>(createEmptyUserForm());
const showBatchEditModal = ref(false);
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
const showBatchPermissionModal = ref(false);
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const filteredUsers = computed(() =>
users.value.filter((u) => {
if (hideRejected.value && u.status === 'rejected') return false;
for (const key of Object.keys(userFilters.value) as (keyof UserFilters)[]) {
const filterVal = userFilters.value[key].toLowerCase();
if (!filterVal) continue;
const userVal = u[key]?.toString().toLowerCase() || '';
if (!userVal.includes(filterVal)) return false;
}
return true;
}),
);
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadAgents = async (): Promise<void> => {
try {
agents.value = await listAdminAgents();
} catch (e) {
console.error('Error loading agents:', e);
agents.value = [];
}
};
const loadDepartments = async (): Promise<void> => {
try {
departments.value = await listAdminDepartments();
} catch (e) {
console.error('Error loading departments:', e);
departments.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadUsers(), loadAgents(), loadDepartments()]);
isLoading.value = false;
};
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const openCreateUserModal = (): void => {
editingUser.value = createEmptyUserForm();
showUserModal.value = true;
};
const openEditUserModal = (user: AdminUserRow): void => {
editingUser.value = {
id: user.id,
username: user.username,
email: user.email,
department: user.department || '',
role: user.role,
password: '',
real_name: user.real_name || '',
employee_id: user.employee_id || '',
phone_number: user.phone_number || '',
agent_ids: user.agent_ids || [],
};
showUserModal.value = true;
};
const saveUser = async (): Promise<void> => {
const isCreate = !editingUser.value.id;
if (isCreate) {
if (!(editingUser.value.real_name || '').trim()) {
msg.warning(t('admin.user.msgs.realNameRequired'));
return;
}
if (!(editingUser.value.employee_id || '').trim()) {
msg.warning(t('admin.user.msgs.employeeIdRequired'));
return;
}
if (!(editingUser.value.phone_number || '').trim()) {
msg.warning(t('admin.user.msgs.phoneRequired'));
return;
}
if (!(editingUser.value.username || '').trim()) {
msg.warning(t('admin.user.msgs.usernameRequired'));
return;
}
const email = (editingUser.value.email || '').trim();
if (!email) {
msg.warning(t('admin.user.msgs.emailRequired'));
return;
}
if (!EMAIL_PATTERN.test(email)) {
msg.warning(t('admin.user.msgs.invalidEmail'));
return;
}
if (!(editingUser.value.password || '').trim()) {
msg.warning(t('admin.user.msgs.passwordRequired'));
return;
}
} else {
if (!editingUser.value.username) {
msg.warning(t('admin.user.msgs.usernameRequired'));
return;
}
const email = (editingUser.value.email || '').trim();
if (email && !EMAIL_PATTERN.test(email)) {
msg.warning(t('admin.user.msgs.invalidEmail'));
return;
}
}
isSaving.value = true;
try {
if (editingUser.value.id) {
await updateAdminUser(editingUser.value.id, {
email: editingUser.value.email,
department: editingUser.value.department,
role: editingUser.value.role,
password: editingUser.value.password || undefined,
real_name: editingUser.value.real_name,
employee_id: editingUser.value.employee_id,
phone_number: editingUser.value.phone_number,
agent_ids: editingUser.value.agent_ids,
});
} else {
await createAdminUser({
username: editingUser.value.username,
email: editingUser.value.email,
department: editingUser.value.department,
role: editingUser.value.role,
password: editingUser.value.password,
real_name: editingUser.value.real_name,
employee_id: editingUser.value.employee_id,
phone_number: editingUser.value.phone_number,
agent_ids: editingUser.value.agent_ids,
});
}
await loadUsers();
showUserModal.value = false;
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.failed'));
} finally {
isSaving.value = false;
}
};
const cleanRejectedUsers = async (): Promise<void> => {
openDeleteConfirm(t('admin.user.confirmClean'), async () => {
try {
const data = await cleanupRejectedAdminUsers();
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
await loadUsers();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
const batchDeleteUsers = async (): Promise<void> => {
if (selectedUserIds.value.length === 0) return;
const targetUserIds = [...selectedUserIds.value];
openDeleteConfirm(t('admin.user.confirmBatchDelete', { count: targetUserIds.length }), async () => {
try {
const data = await batchDeleteAdminUsers(targetUserIds);
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
selectedUserIds.value = [];
await loadUsers();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
const toggleUserSelection = (userId: number): void => {
const index = selectedUserIds.value.indexOf(userId);
if (index === -1) selectedUserIds.value.push(userId);
else selectedUserIds.value.splice(index, 1);
};
const toggleAllUsers = (rows: AdminUserRow[]): void => {
if (selectedUserIds.value.length === rows.length) {
selectedUserIds.value = [];
} else {
selectedUserIds.value = rows.map((u) => u.id);
}
};
const openBatchEditModal = (): void => {
if (selectedUserIds.value.length === 0) return;
batchEditForm.value = { department: '', role: '', status: '' };
showBatchEditModal.value = true;
};
const openBatchPermissionModal = (): void => {
if (selectedUserIds.value.length === 0) return;
batchPermissionForm.value = { agent_ids: [], action: 'add' };
showBatchPermissionModal.value = true;
};
const submitBatchEdit = async (): Promise<void> => {
isSaving.value = true;
try {
const data: Record<string, string> = {};
if (batchEditForm.value.department) data.department = batchEditForm.value.department;
if (batchEditForm.value.role) data.role = batchEditForm.value.role;
if (batchEditForm.value.status) data.status = batchEditForm.value.status;
if (Object.keys(data).length === 0) {
msg.warning(t('admin.msg.enterOneField'));
return;
}
await batchUpdateAdminUsers(selectedUserIds.value, data);
await loadUsers();
showBatchEditModal.value = false;
selectedUserIds.value = [];
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.batchUpdateFailed'));
} finally {
isSaving.value = false;
}
};
const submitBatchPermission = async (): Promise<void> => {
if (batchPermissionForm.value.agent_ids.length === 0) {
msg.warning(t('admin.perm.msg.selectAgent'));
return;
}
isSaving.value = true;
try {
await batchUpdateAdminPermissions({
user_ids: selectedUserIds.value,
agent_ids: batchPermissionForm.value.agent_ids,
action: batchPermissionForm.value.action,
});
await loadUsers();
showBatchPermissionModal.value = false;
selectedUserIds.value = [];
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.batchPermissionUpdateFailed'));
} finally {
isSaving.value = false;
}
};
return {
users,
agents,
departments,
isLoading,
isSaving,
userFilters,
hideRejected,
selectedUserIds,
filteredUsers,
showUserModal,
editingUser,
showBatchEditModal,
batchEditForm,
showBatchPermissionModal,
batchPermissionForm,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateUserModal,
openEditUserModal,
saveUser,
cleanRejectedUsers,
batchDeleteUsers,
toggleUserSelection,
toggleAllUsers,
openBatchEditModal,
openBatchPermissionModal,
submitBatchEdit,
submitBatchPermission,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -0,0 +1,456 @@
/**
* features/admin/modules/wecom/WecomPage.vue
* 企业微信管理独立页面。路由:/admin/wecom
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { CircleHelp, Download, Link2, RefreshCw, Unlink2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import { useWecomAdmin } from './composables/useWecomAdmin';
const { t } = useI18n();
const {
isLoading,
isSaving,
wecomBindings,
wecomBindForm,
wecomBindUserQuery,
wecomBindUserDropdownOpen,
wecomBindUserOptions,
wecomBoundOnly,
wecomAuditSourceFilter,
wecomAuditStatusFilter,
filteredWecomLoginAudits,
wecomNotifySettings,
wecomNotifyEventsText,
wecomNotifyMetrics,
wecomSystemSettings,
wecomIntegrationManifest,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
refreshWecomData,
selectWecomBindUser,
scheduleCloseWecomBindUserDropdown,
copyText,
getWecomAuditReasonText,
getWecomAuditMetaText,
generateWecomAddressesFromPublicBase,
generateWecomCallbackToken,
generateWecomEncodingAesKey,
saveWecomSystemSettings,
saveWecomNotifySettings,
bindWecomUser,
unbindWecomUserByAdmin,
exportWecomAudits,
confirmDelete,
} = useWecomAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<section v-else class="section-gap animate-fade-in-up">
<div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
<div>
<h2 class="section-title">{{ t('admin.wecom.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.wecom.subtitle') }}</p>
</div>
<button
@click="refreshWecomData"
class="btn-secondary inline-flex items-center gap-2 px-4 py-2 text-secondary rounded-xl hover-surface-soft transition-all shadow-sm"
>
<RefreshCw class="w-4 h-4" />
{{ t('admin.wecom.refresh') }}
</button>
</div>
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.quickBind') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-4 gap-3">
<div class="relative md:col-span-1">
<input
v-model="wecomBindUserQuery"
type="text"
class="input-field"
:placeholder="t('admin.wecom.fields.userSelect')"
@focus="wecomBindUserDropdownOpen = true"
@input="wecomBindUserDropdownOpen = true"
@blur="scheduleCloseWecomBindUserDropdown"
/>
<div
v-if="wecomBindUserDropdownOpen"
class="admin-dropdown w-72"
>
<button
v-for="u in wecomBindUserOptions"
:key="u.id"
type="button"
class="flex w-full items-center justify-between gap-3 px-3 py-2 text-left hover:bg-blue-50"
@mousedown.prevent="selectWecomBindUser(u.id, u.label)"
>
<span class="text-sm text-primary">{{ u.label }}</span>
<span class="text-xs text-muted">{{ u.employeeId || '' }}</span>
</button>
<div v-if="wecomBindUserOptions.length === 0" class="px-3 py-2 text-sm text-muted">
{{ t('admin.wecom.noData') }}
</div>
</div>
</div>
<input v-model="wecomBindForm.wecom_userid" :placeholder="t('admin.wecom.fields.wecomUserId')" class="input-field md:col-span-2" />
<input v-model="wecomBindForm.wecom_unionid" :placeholder="t('admin.wecom.fields.wecomUnionId')" class="input-field" />
</div>
<div class="flex justify-end">
<button @click="bindWecomUser" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60">
<Link2 class="w-4 h-4" /> {{ t('admin.wecom.bind') }}
</button>
</div>
</div>
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.systemSettings') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input v-model="wecomSystemSettings.enabled" type="checkbox" class="admin-checkbox" />
{{ t('admin.wecom.fields.enabled') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.enabled')" />
</label>
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input v-model="wecomSystemSettings.auto_create_user" type="checkbox" class="admin-checkbox" />
{{ t('admin.wecom.fields.autoCreateUser') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.autoCreateUser')" />
</label>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.corpId') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.corpId')" />
</label>
<input v-model="wecomSystemSettings.corp_id" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.agentId') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.agentId')" />
</label>
<input v-model="wecomSystemSettings.agent_id" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.secret') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.secret')" />
</label>
<input v-model="wecomSystemSettings.secret" type="password" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.redirectUri') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.redirectUri')" />
</label>
<input v-model="wecomSystemSettings.redirect_uri" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.publicBaseUrl') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.publicBaseUrl')" />
</label>
<div class="flex flex-wrap gap-2">
<input
v-model="wecomSystemSettings.public_base_url"
:placeholder="t('admin.wecom.publicBasePlaceholder')"
class="input-field flex-1 min-w-[200px]"
/>
<button type="button" class="btn-secondary px-4 shrink-0" @click="generateWecomAddressesFromPublicBase">
{{ t('admin.wecom.generateAddresses') }}
</button>
</div>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.callbackToken') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.callbackToken')" />
</label>
<div class="flex gap-2">
<input v-model="wecomSystemSettings.callback_token" class="input-field flex-1 min-w-0" />
<button type="button" class="btn-secondary px-3 shrink-0 text-xs" @click="generateWecomCallbackToken">
{{ t('admin.wecom.generateToken') }}
</button>
</div>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.encodingAesKey') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.encodingAesKey')" />
</label>
<div class="flex gap-2">
<input v-model="wecomSystemSettings.encoding_aes_key" class="input-field flex-1 min-w-0 font-mono text-xs" />
<button type="button" class="btn-secondary px-3 shrink-0 text-xs" @click="generateWecomEncodingAesKey">
{{ t('admin.wecom.generateEncodingKey') }}
</button>
</div>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.callbackUrl') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.callbackUrl')" />
</label>
<input v-model="wecomSystemSettings.callback_url" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.homepageUrl') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.homepageUrl')" />
</label>
<input v-model="wecomSystemSettings.homepage_url" class="input-field" />
</div>
<div class="md:col-span-2">
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.trustedDomain') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.trustedDomain')" />
</label>
<input v-model="wecomSystemSettings.trusted_domain" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.matchRules') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.matchRules')" />
</label>
<input v-model="wecomSystemSettings.match_rules" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.matchOperator') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.matchOperator')" />
</label>
<select v-model="wecomSystemSettings.match_operator" class="input-field">
<option value="AND">AND</option>
<option value="OR">OR</option>
</select>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.firstLoginBindMode') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.firstLoginBindMode')" />
</label>
<select v-model="wecomSystemSettings.first_login_bind_mode" class="input-field">
<option value="match_rules">{{ t('admin.wecom.bindModes.match_rules') }}</option>
<option value="input_verify">{{ t('admin.wecom.bindModes.input_verify') }}</option>
</select>
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.firstLoginInputFields') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.firstLoginInputFields')" />
</label>
<input v-model="wecomSystemSettings.first_login_input_fields" class="input-field" />
</div>
<div>
<label class="mb-1.5 inline-flex items-center gap-1 text-xs text-muted">
{{ t('admin.wecom.fields.employeeIdSource') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.employeeIdSource')" />
</label>
<input v-model="wecomSystemSettings.employee_id_source" class="input-field" />
</div>
<label class="inline-flex items-center gap-2 text-sm text-secondary pt-7">
<input v-model="wecomSystemSettings.mobile_normalize" type="checkbox" class="admin-checkbox" />
{{ t('admin.wecom.fields.mobileNormalize') }}
<CircleHelp class="w-3.5 h-3.5 text-muted" :title="t('admin.wecom.tips.mobileNormalize')" />
</label>
</div>
<div class="flex justify-end">
<button @click="saveWecomSystemSettings" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60">
{{ t('admin.save') }}
</button>
</div>
</div>
<div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.notifySettings') }}</h3>
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input v-model="wecomNotifySettings.enabled" type="checkbox" class="admin-checkbox" />
{{ t('admin.wecom.notifyEnabled') }}
</label>
<input v-model="wecomNotifySettings.base_url" :placeholder="t('admin.wecom.notifyBaseUrl')" class="input-field" />
<input v-model="wecomNotifyEventsText" :placeholder="t('admin.wecom.notifyEvents')" class="input-field" />
<div class="flex justify-end">
<button @click="saveWecomNotifySettings" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60">
{{ t('admin.save') }}
</button>
</div>
</div>
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.notifyMetrics') }}</h3>
<div v-if="wecomNotifyMetrics" class="grid grid-cols-2 gap-3 text-sm">
<div class="rounded-lg bg-surface-soft px-3 py-2">
<div class="text-muted">{{ t('admin.wecom.metricTotal') }}</div>
<div class="text-lg font-semibold text-primary">{{ wecomNotifyMetrics.total }}</div>
</div>
<div class="rounded-lg bg-surface-soft px-3 py-2">
<div class="text-muted">{{ t('admin.wecom.metricSuccessRate') }}</div>
<div class="text-lg font-semibold text-emerald-700">{{ wecomNotifyMetrics.send_success_rate }}%</div>
</div>
<div class="rounded-lg bg-surface-soft px-3 py-2">
<div class="text-muted">{{ t('admin.wecom.metricOpenedRate') }}</div>
<div class="text-lg font-semibold text-blue-700">{{ wecomNotifyMetrics.opened_24h_rate }}%</div>
</div>
<div class="rounded-lg bg-surface-soft px-3 py-2">
<div class="text-muted">{{ t('admin.wecom.metricWindowDays') }}</div>
<div class="text-lg font-semibold text-primary">{{ wecomNotifyMetrics.window_days }}</div>
</div>
</div>
</div>
</div>
<div class="card shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.integrationCopyTitle') }}</h3>
<p class="text-xs text-muted">{{ t('admin.wecom.integrationCopyDesc') }}</p>
<p class="text-xs text-amber-800 bg-amber-50 border border-amber-100 rounded-lg px-3 py-2">{{ t('admin.wecom.integrationCopySecretsNote') }}</p>
<div v-if="wecomIntegrationManifest" class="grid grid-cols-1 gap-3">
<div v-for="item in [
{ key: 'public_base_url', label: t('admin.wecom.copyFields.publicBaseUrl') },
{ key: 'callback_url', label: t('admin.wecom.copyFields.callbackUrl') },
{ key: 'callback_token', label: t('admin.wecom.copyFields.callbackToken') },
{ key: 'encoding_aes_key', label: t('admin.wecom.copyFields.encodingAesKey') },
{ key: 'oauth_redirect_uri', label: t('admin.wecom.copyFields.oauthRedirectUri') },
{ key: 'homepage_url', label: t('admin.wecom.copyFields.homepageUrl') },
{ key: 'trusted_domain', label: t('admin.wecom.copyFields.trustedDomain') },
{ key: 'authorize_api', label: t('admin.wecom.copyFields.authorizeApi') },
{ key: 'login_api', label: t('admin.wecom.copyFields.loginApi') },
]" :key="item.key">
<label class="mb-1.5 block text-xs text-muted">{{ item.label }}</label>
<div class="flex gap-2">
<input :value="(wecomIntegrationManifest as any)[item.key] || ''" readonly class="input-field flex-1 bg-surface-soft font-mono text-xs" />
<button class="btn-secondary px-3" @click="copyText(String((wecomIntegrationManifest as any)[item.key] || ''))">{{ t('admin.wecom.copy') }}</button>
</div>
</div>
</div>
</div>
<div class="admin-table-section">
<div class="admin-table-header px-5 py-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.bindingList') }}</h3>
<label class="inline-flex items-center gap-2 text-sm text-secondary">
<input type="checkbox" v-model="wecomBoundOnly" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.wecom.boundOnly') }}
</label>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.user') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.roleStatus') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.wecomUserId') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.headers.unionId') }}</th>
<th class="px-4 py-3 text-xs text-right">{{ t('admin.wecom.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="wecomBindings.length === 0">
<td colspan="5" class="px-4 admin-table-empty">{{ t('admin.wecom.noData') }}</td>
</tr>
<tr v-for="u in wecomBindings" :key="u.id">
<td class="px-4 py-3">
<div class="text-sm font-medium text-primary">{{ u.username }} <span class="text-muted">(#{{ u.id }})</span></div>
<div class="text-xs text-muted">{{ u.real_name || '-' }} · {{ u.email }}</div>
</td>
<td class="px-4 py-3 text-sm text-secondary">{{ t('admin.role.' + u.role) }} / {{ t('admin.status.' + u.status) }}</td>
<td class="px-4 py-3 text-sm text-secondary font-mono">{{ u.wecom_userid || '-' }}</td>
<td class="px-4 py-3 text-sm text-secondary font-mono">{{ u.wecom_unionid || '-' }}</td>
<td class="px-4 py-3 text-right">
<button
v-if="u.wecom_userid"
@click="unbindWecomUserByAdmin(u.id)"
class="inline-flex items-center gap-1 px-3 py-1.5 text-xs text-red-600 bg-red-50 rounded-lg hover:bg-red-100"
>
<Unlink2 class="w-3.5 h-3.5" />
{{ t('admin.wecom.unbind') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="admin-table-section">
<div class="admin-table-header admin-table-header--stacked px-5 py-4">
<h3 class="font-semibold text-primary">{{ t('admin.wecom.auditTitle') }}</h3>
<div class="flex w-full md:w-auto flex-wrap md:flex-nowrap items-center justify-start md:justify-end gap-2">
<select v-model="wecomAuditSourceFilter" class="admin-table-filter-input h-11 min-w-[112px] shrink-0">
<option value="all">{{ t('admin.wecom.filters.allSources') }}</option>
<option value="wecom">{{ t('admin.wecom.sources.wecom') }}</option>
<option value="password">{{ t('admin.wecom.sources.password') }}</option>
</select>
<select v-model="wecomAuditStatusFilter" class="admin-table-filter-input h-11 min-w-[112px] shrink-0">
<option value="all">{{ t('admin.wecom.filters.allStatus') }}</option>
<option value="success">{{ t('admin.wecom.auditStatus.success') }}</option>
<option value="failed">{{ t('admin.wecom.auditStatus.failed') }}</option>
</select>
<button
@click="exportWecomAudits"
class="btn-secondary h-11 shrink-0 text-sm"
>
<Download class="w-4 h-4" />
{{ t('admin.wecom.exportAudit') }}
</button>
</div>
</div>
<div class="admin-table-wrap max-h-[420px]">
<table class="admin-table">
<thead class="sticky top-0 z-10 admin-table-sticky-head">
<tr>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.time') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.source') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.user') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.status') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.reason') }}</th>
<th class="px-4 py-3 text-xs">{{ t('admin.wecom.auditHeaders.ip') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="filteredWecomLoginAudits.length === 0">
<td colspan="6" class="px-4 admin-table-empty">{{ t('admin.wecom.noAuditData') }}</td>
</tr>
<tr v-for="row in filteredWecomLoginAudits" :key="row.id">
<td class="px-4 py-3 text-xs text-muted whitespace-nowrap">{{ row.created_at || '-' }}</td>
<td class="px-4 py-3 text-xs text-secondary">{{ t('admin.wecom.sources.' + row.source) }}</td>
<td class="px-4 py-3 text-xs text-secondary">{{ row.username || '-' }}</td>
<td class="px-4 py-3">
<span class="inline-flex px-2 py-0.5 rounded-full text-[11px] font-medium" :class="row.status === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'">
{{ t('admin.wecom.auditStatus.' + row.status) }}
</span>
</td>
<td class="px-4 py-3 text-xs text-muted max-w-[360px] align-top">
<div class="max-w-[360px] whitespace-normal break-words">
<div class="text-xs text-secondary leading-5">{{ getWecomAuditReasonText(row) }}</div>
<div v-if="getWecomAuditMetaText(row)" class="mt-1 text-[11px] text-muted leading-5" :title="getWecomAuditMetaText(row)">
{{ getWecomAuditMetaText(row) }}
</div>
</div>
</td>
<td class="px-4 py-3 text-xs text-muted font-mono">{{ row.ip || '-' }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
/>
</template>
@@ -0,0 +1,456 @@
/**
* features/admin/modules/wecom/composables/useWecomAdmin.ts
* 企业微信:绑定、系统配置、通知、登录审计。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import * as XLSX from 'xlsx';
import {
bindAdminWecomUser,
getAdminWecomIntegrationManifest,
getAdminWecomNotifyMetrics,
getAdminWecomNotifySettings,
getAdminWecomSystemSettings,
listAdminUsers,
listAdminWecomBindings,
listAdminWecomLoginAudits,
saveAdminWecomNotifySettings,
saveAdminWecomSystemSettings,
unbindAdminWecomUser,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import {
createDefaultWecomSystemSettings,
type WecomBindingRow,
type WecomIntegrationManifest,
type WecomLoginAuditRow,
type WecomNotifyMetrics,
type WecomNotifySettings,
type WecomSystemSettings,
} from '@/features/admin/types/wecom.types';
import { buildWecomAuditMeta, formatWecomAuditReason } from '@/utils/wecom';
export function useWecomAdmin() {
const { t } = useI18n();
const msg = useMessage();
const users = ref<AdminUserRow[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const wecomBindings = ref<WecomBindingRow[]>([]);
const wecomLoginAudits = ref<WecomLoginAuditRow[]>([]);
const wecomBindForm = ref({
user_id: '' as string | number,
wecom_userid: '',
wecom_unionid: '',
});
const wecomBindUserQuery = ref('');
const wecomBindUserDropdownOpen = ref(false);
const wecomBoundOnly = ref(false);
let wecomBindUserCloseTimer: ReturnType<typeof setTimeout> | null = null;
const wecomAuditSourceFilter = ref<'all' | 'wecom' | 'password'>('all');
const wecomAuditStatusFilter = ref<'all' | 'success' | 'failed'>('all');
const filteredWecomLoginAudits = computed(() => wecomLoginAudits.value);
const wecomNotifySettings = ref<WecomNotifySettings>({
enabled: true,
base_url: '',
events: [],
});
const wecomNotifyEventsText = ref('');
const wecomNotifyMetrics = ref<WecomNotifyMetrics | null>(null);
const wecomSystemSettings = ref<WecomSystemSettings>(createDefaultWecomSystemSettings());
const wecomIntegrationManifest = ref<WecomIntegrationManifest | null>(null);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
const wecomBindUserOptions = computed(() => {
const keyword = wecomBindUserQuery.value.trim().toLowerCase();
return users.value
.filter((u) => {
if (!keyword) return true;
return [u.real_name, u.employee_id, String(u.id)]
.filter(Boolean)
.some((val) => String(val).toLowerCase().includes(keyword));
})
.map((u) => ({
id: u.id,
label: `${u.real_name || u.username} ${u.employee_id ? `(${u.employee_id})` : ''}`.trim(),
employeeId: u.employee_id || '',
}));
});
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
const loadUsers = async (): Promise<void> => {
try {
users.value = await listAdminUsers();
} catch (e) {
console.error('Error loading users:', e);
users.value = [];
}
};
const loadWecomBindings = async (): Promise<void> => {
try {
wecomBindings.value = await listAdminWecomBindings(wecomBoundOnly.value);
} catch (e) {
console.error('Error loading WeCom bindings:', e);
}
};
const loadWecomAudits = async (): Promise<void> => {
try {
const params = new URLSearchParams({ limit: '200' });
if (wecomAuditSourceFilter.value !== 'all') {
params.set('source', wecomAuditSourceFilter.value);
}
if (wecomAuditStatusFilter.value !== 'all') {
params.set('status', wecomAuditStatusFilter.value);
}
wecomLoginAudits.value = await listAdminWecomLoginAudits(params.toString());
} catch (e) {
console.error('Error loading WeCom login audits:', e);
}
};
const loadWecomSystemSettings = async (): Promise<void> => {
try {
wecomSystemSettings.value = await getAdminWecomSystemSettings();
} catch (e) {
console.error('Error loading WeCom system settings:', e);
}
};
const loadWecomIntegrationManifest = async (): Promise<void> => {
try {
wecomIntegrationManifest.value = await getAdminWecomIntegrationManifest();
} catch (e) {
console.error('Error loading WeCom integration manifest:', e);
}
};
const loadWecomNotifySettings = async (): Promise<void> => {
try {
wecomNotifySettings.value = await getAdminWecomNotifySettings();
wecomNotifyEventsText.value = (wecomNotifySettings.value.events || []).join(',');
} catch (e) {
console.error('Error loading WeCom notify settings:', e);
}
};
const loadWecomNotifyMetrics = async (): Promise<void> => {
try {
wecomNotifyMetrics.value = await getAdminWecomNotifyMetrics();
} catch (e) {
console.error('Error loading WeCom notify metrics:', e);
}
};
const refreshWecomData = async (): Promise<void> => {
await Promise.all([
loadWecomBindings(),
loadWecomAudits(),
loadWecomSystemSettings(),
loadWecomIntegrationManifest(),
loadWecomNotifySettings(),
loadWecomNotifyMetrics(),
]);
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadUsers(), refreshWecomData()]);
isLoading.value = false;
};
const selectWecomBindUser = (id: number, label: string): void => {
wecomBindForm.value.user_id = id;
wecomBindUserQuery.value = label;
wecomBindUserDropdownOpen.value = false;
};
const scheduleCloseWecomBindUserDropdown = (): void => {
if (wecomBindUserCloseTimer) clearTimeout(wecomBindUserCloseTimer);
wecomBindUserCloseTimer = setTimeout(() => {
wecomBindUserDropdownOpen.value = false;
}, 150);
};
const copyText = async (text: string): Promise<void> => {
if (!text) return;
try {
await navigator.clipboard.writeText(text);
msg.success(t('admin.wecom.msg.copySuccess'));
} catch (e) {
console.error(e);
msg.error(t('admin.wecom.msg.copyFailed'));
}
};
const getWecomAuditReasonText = (row: WecomLoginAuditRow) => formatWecomAuditReason(row, t);
const getWecomAuditMetaText = (row: WecomLoginAuditRow) => buildWecomAuditMeta(row, t).join(' | ');
function normalizeWecomPublicBase(input: string): string | null {
const raw = (input || '').trim();
if (!raw) return null;
let url = raw;
if (!/^https?:\/\//i.test(url)) url = `https://${url}`;
url = url.replace(/\/+$/, '');
try {
const u = new URL(url);
if (!u.hostname) return null;
return `${u.protocol}//${u.host}`;
} catch {
return null;
}
}
function ensureWecomIntegrationManifest(): void {
if (!wecomIntegrationManifest.value) {
wecomIntegrationManifest.value = {
public_base_url: '',
callback_url: '',
callback_token: '',
encoding_aes_key: '',
oauth_redirect_uri: '',
homepage_url: '',
trusted_domain: '',
authorize_api: '',
login_api: '',
};
}
}
function patchWecomIntegrationManifestFromSettings(): void {
ensureWecomIntegrationManifest();
const s = wecomSystemSettings.value;
const base = normalizeWecomPublicBase(s.public_base_url);
const prev = wecomIntegrationManifest.value!;
wecomIntegrationManifest.value = {
...prev,
callback_token: s.callback_token || '',
encoding_aes_key: s.encoding_aes_key || '',
};
if (!base) return;
wecomIntegrationManifest.value = {
...wecomIntegrationManifest.value!,
public_base_url: base,
callback_url: s.callback_url || `${base}/api/user/wecom/callback`,
oauth_redirect_uri: s.redirect_uri || `${base}/workspace`,
homepage_url: s.homepage_url || `${base}/workspace`,
trusted_domain: s.trusted_domain || new URL(base).hostname,
authorize_api: `${base}/api/user/wecom/authorize-url`,
login_api: `${base}/api/user/wecom/login`,
};
}
function generateWecomAddressesFromPublicBase(): void {
const base = normalizeWecomPublicBase(wecomSystemSettings.value.public_base_url);
if (!base) {
msg.warning(t('admin.wecom.msg.publicBaseRequired'));
return;
}
const host = new URL(base).hostname;
wecomSystemSettings.value.callback_url = `${base}/api/user/wecom/callback`;
wecomSystemSettings.value.homepage_url = `${base}/workspace`;
wecomSystemSettings.value.trusted_domain = host;
wecomSystemSettings.value.redirect_uri = `${base}/workspace`;
patchWecomIntegrationManifestFromSettings();
}
function generateWecomCallbackToken(): void {
const bytes = new Uint8Array(24);
crypto.getRandomValues(bytes);
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
wecomSystemSettings.value.callback_token = hex;
patchWecomIntegrationManifestFromSettings();
}
function generateWecomEncodingAesKey(): void {
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
let bin = '';
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
const b64 = btoa(bin);
const key43 = b64.replace(/=+$/, '');
wecomSystemSettings.value.encoding_aes_key = key43;
patchWecomIntegrationManifestFromSettings();
}
const saveWecomSystemSettings = async (): Promise<void> => {
isSaving.value = true;
try {
const payload = {
...wecomSystemSettings.value,
match_operator: (wecomSystemSettings.value.match_operator || 'AND').toUpperCase(),
};
const data = await saveAdminWecomSystemSettings(payload);
wecomSystemSettings.value = data.settings || wecomSystemSettings.value;
await loadWecomIntegrationManifest();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const saveWecomNotifySettings = async (): Promise<void> => {
isSaving.value = true;
try {
wecomNotifySettings.value.events = wecomNotifyEventsText.value
.split(',')
.map((x) => x.trim())
.filter(Boolean);
const data = await saveAdminWecomNotifySettings(wecomNotifySettings.value);
wecomNotifySettings.value = data.settings || wecomNotifySettings.value;
await loadWecomNotifyMetrics();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const bindWecomUser = async (): Promise<void> => {
if (!wecomBindForm.value.user_id || !wecomBindForm.value.wecom_userid.trim()) {
msg.warning(t('admin.wecom.msg.bindInputRequired'));
return;
}
isSaving.value = true;
try {
await bindAdminWecomUser({
user_id: Number(wecomBindForm.value.user_id),
wecom_userid: wecomBindForm.value.wecom_userid.trim(),
wecom_unionid: wecomBindForm.value.wecom_unionid.trim() || undefined,
});
wecomBindUserQuery.value = '';
wecomBindUserDropdownOpen.value = false;
wecomBindForm.value.wecom_userid = '';
wecomBindForm.value.wecom_unionid = '';
await refreshWecomData();
msg.success(t('admin.wecom.msg.bindSuccess'));
} catch (e) {
console.error(e);
const errorMessage = (e as Error).message || t('admin.wecom.msg.bindFailed');
if (String(errorMessage).includes('already bound to user')) {
msg.error(t('admin.wecom.msg.boundConflict', { detail: errorMessage }));
} else {
msg.error(errorMessage);
}
} finally {
isSaving.value = false;
}
};
const unbindWecomUserByAdmin = async (userId: number): Promise<void> => {
openDeleteConfirm(t('admin.wecom.confirmUnbind'), async () => {
isSaving.value = true;
try {
await unbindAdminWecomUser(userId);
await refreshWecomData();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.wecom.msg.unbindFailed'));
} finally {
isSaving.value = false;
}
});
};
const exportWecomAudits = (): void => {
if (filteredWecomLoginAudits.value.length === 0) {
msg.warning(t('admin.wecom.noAuditData'));
return;
}
const rows = filteredWecomLoginAudits.value.map((row) => ({
Time: row.created_at || '',
Source: row.source || '',
Username: row.username || '',
Status: row.status || '',
Reason: getWecomAuditReasonText(row),
Meta: getWecomAuditMetaText(row),
ErrorCode: row.error_code || '',
MatchRules: row.match_rules || '',
MatchOperator: row.match_operator || '',
MatchResult: row.match_result || '',
IP: row.ip || '',
WecomUserId: row.wecom_userid || '',
UserAgent: row.user_agent || '',
}));
const ws = XLSX.utils.json_to_sheet(rows);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'wecom_login_audits');
XLSX.writeFile(wb, `wecom_login_audits_${new Date().toISOString().split('T')[0]}.xlsx`);
};
watch(wecomBoundOnly, () => {
void loadWecomBindings();
});
watch([wecomAuditSourceFilter, wecomAuditStatusFilter], () => {
void loadWecomAudits();
});
return {
isLoading,
isSaving,
wecomBindings,
wecomLoginAudits,
wecomBindForm,
wecomBindUserQuery,
wecomBindUserDropdownOpen,
wecomBindUserOptions,
wecomBoundOnly,
wecomAuditSourceFilter,
wecomAuditStatusFilter,
filteredWecomLoginAudits,
wecomNotifySettings,
wecomNotifyEventsText,
wecomNotifyMetrics,
wecomSystemSettings,
wecomIntegrationManifest,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
refreshWecomData,
selectWecomBindUser,
scheduleCloseWecomBindUserDropdown,
copyText,
getWecomAuditReasonText,
getWecomAuditMetaText,
generateWecomAddressesFromPublicBase,
generateWecomCallbackToken,
generateWecomEncodingAesKey,
saveWecomSystemSettings,
saveWecomNotifySettings,
bindWecomUser,
unbindWecomUserByAdmin,
exportWecomAudits,
confirmDelete,
};
}
@@ -0,0 +1,94 @@
/**
* features/admin/stores/admin-nav.store.ts
* 管理后台导航 UI 状态(侧栏折叠、报表展开、角标)。
*
* 角标数据来自 GET /api/admin/dashboard/badges,在 store 内做 TTL 缓存与 in-flight 去重,
* 避免切换 admin 子路由时重复请求(AdminLayout 挂载一次即可)。
*/
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getAdminDashboardBadges } from '@/api/admin';
import type { AdminModuleId } from '../types/admin.types';
/** 角标缓存有效期(毫秒):此时间内 ensureBadges 直接复用内存中的计数 */
const BADGE_CACHE_TTL_MS = 60_000;
export const useAdminNavStore = defineStore('adminNav', () => {
const sidebarCollapsed = ref(false);
const reportsExpanded = ref(true);
/** 「用户审批」导航角标:pending 注册用户数 */
const pendingApprovalsCount = ref(0);
/** 「权限申请」导航角标:pending 权限申请数 */
const pendingRequestsCount = ref(0);
/** 上次成功拉取 badges 的时间戳;0 表示尚未拉取 */
let badgesFetchedAt = 0;
/** 进行中的 badges 请求 Promise,用于并发调用合并为单次 HTTP */
let badgesInFlight: Promise<void> | null = null;
const toggleSidebar = (): void => {
sidebarCollapsed.value = !sidebarCollapsed.value;
};
const setBadgeCounts = (approvals: number, requests: number): void => {
pendingApprovalsCount.value = approvals;
pendingRequestsCount.value = requests;
};
const badgeForModule = (moduleId: AdminModuleId): number | undefined => {
if (moduleId === 'approvals' && pendingApprovalsCount.value > 0) return pendingApprovalsCount.value;
if (moduleId === 'requests' && pendingRequestsCount.value > 0) return pendingRequestsCount.value;
return undefined;
};
/**
* 拉取侧栏角标。force=false 时命中 TTL 缓存则跳过网络请求;
* 多个组件同时调用时会共享同一 inFlight,避免重复打 /dashboard/badges。
*/
const fetchBadges = async (options?: { force?: boolean }): Promise<void> => {
const force = options?.force ?? false;
const now = Date.now();
// 非强制刷新且缓存未过期:直接返回 store 中已有计数
if (!force && badgesFetchedAt > 0 && now - badgesFetchedAt < BADGE_CACHE_TTL_MS) {
return;
}
// 已有请求在飞:等待同一 Promise,不再发起第二次请求
if (badgesInFlight) {
return badgesInFlight;
}
badgesInFlight = (async () => {
try {
const data = await getAdminDashboardBadges();
setBadgeCounts(data.pending_approvals, data.pending_requests);
badgesFetchedAt = Date.now();
} catch {
setBadgeCounts(0, 0);
} finally {
badgesInFlight = null;
}
})();
return badgesInFlight;
};
/** AdminLayout onMounted:有有效缓存则跳过请求 */
const ensureBadges = (): Promise<void> => fetchBadges({ force: false });
/** 审批/驳回操作后:忽略缓存,立即重新拉取角标 */
const refreshBadges = (): Promise<void> => fetchBadges({ force: true });
return {
sidebarCollapsed,
reportsExpanded,
pendingApprovalsCount,
pendingRequestsCount,
toggleSidebar,
setBadgeCounts,
badgeForModule,
ensureBadges,
refreshBadges,
};
});
@@ -0,0 +1,62 @@
/**
* features/admin/types/admin.types.ts
* 管理后台域公共类型。
*/
export type AdminModuleId =
| 'dashboard'
| 'approvals'
| 'users'
| 'departments'
| 'agents'
| 'knowledge_base'
| 'schedules'
| 'announcements'
| 'questions'
| 'wecom'
| 'permissions'
| 'requests'
| 'reports';
export type AdminReportTableId =
| 'users'
| 'agents'
| 'chat_logs'
| 'permission_requests'
| 'general_feedbacks'
| 'feedbacks';
export interface AdminUserRow {
id: number;
username: string;
email: string;
department?: string;
role: string;
status: string;
real_name?: string;
employee_id?: string;
phone_number?: string;
agent_ids: number[];
}
export interface AdminDepartmentRow {
id: number;
name: string;
code?: string;
company?: string;
description?: string;
}
export interface AdminAgentOption {
id: number;
name: string;
type?: string;
dify_app_id?: string;
}
export interface AdminAnnouncementRow {
id: number;
title: string;
content: string;
created_at: string;
}
@@ -0,0 +1,54 @@
/**
* features/admin/types/agent.types.ts
*
* Agent 管理模块专用类型,供 AgentsPage 与相关 composable / 组件使用。
*/
export interface AgentRow {
id: number;
name: string;
dify_app_id: string;
dify_api_key: string;
is_active: boolean;
description?: string;
type: 'api' | 'iframe';
dify_app_type?: 'chatflow' | 'workflow';
api_base_url?: string;
extra_config?: Record<string, unknown>;
/** 表单编辑时的 iframe 地址辅助字段 */
iframe_url?: string;
}
export interface AgentTestResult {
success: boolean;
request_url: string;
output_info: string;
analysis: string;
http_status?: number;
tested_at?: string;
}
export interface AgentFormState {
id?: number;
name: string;
dify_app_id: string;
dify_api_key: string;
description: string;
type: 'api' | 'iframe';
dify_app_type: 'chatflow' | 'workflow';
api_base_url: string;
iframe_url: string;
is_active: boolean;
}
export const createEmptyAgentForm = (): AgentFormState => ({
name: '',
dify_app_id: '',
dify_api_key: '',
description: '',
type: 'api',
dify_app_type: 'chatflow',
api_base_url: '',
iframe_url: '',
is_active: true,
});
@@ -0,0 +1,14 @@
/**
* features/admin/types/announcement.types.ts
* 公告管理表单类型。
*/
export interface AnnouncementFormState {
title: string;
content: string;
}
export const createEmptyAnnouncementForm = (): AnnouncementFormState => ({
title: '',
content: '',
});
@@ -0,0 +1,31 @@
/**
* features/admin/types/dashboard.types.ts
* 管理后台仪表盘统计类型。
*/
/** GET /api/admin/dashboard/summary — 仪表盘四张卡片 */
export interface AdminDashboardSummary {
agent_count: number;
user_count: number;
total_conversations: number;
avg_score: number;
}
/** GET /api/admin/dashboard/badges — 侧栏「用户审批」「权限申请」角标 */
export interface AdminDashboardBadges {
pending_approvals: number;
pending_requests: number;
}
export interface AdminUsageReport {
total: number;
by_user: { username: string; count: number }[];
by_agent: { agent: string; count: number }[];
by_day: { date: string; count: number }[];
}
export interface AdminFeedbackReportSummary {
total: number;
avg_score: number;
distribution: { score: number; count: number }[];
}
@@ -0,0 +1,19 @@
/**
* features/admin/types/department.types.ts
* 部门管理表单类型。
*/
export interface DepartmentFormState {
id?: number;
name: string;
code?: string;
company?: string;
description?: string;
}
export const createEmptyDepartmentForm = (): DepartmentFormState => ({
name: '',
code: '',
company: '',
description: '',
});
@@ -0,0 +1,16 @@
/**
* features/admin/types/permission.types.ts
* 权限矩阵模块筛选类型。
*/
export interface PermissionFilters {
username: string;
department: string;
role: string;
}
export const createEmptyPermissionFilters = (): PermissionFilters => ({
username: '',
department: '',
role: '',
});
@@ -0,0 +1,28 @@
/**
* features/admin/types/question.types.ts
* 常用问题管理类型。
*/
export interface AdminQuickQuestionRow {
id: number;
title: string;
question: string;
agent_id: number;
agent_name?: string;
sort_order: number;
}
export interface QuestionFormState {
id?: number;
title: string;
question: string;
agent_id?: number;
sort_order: number;
}
export const createEmptyQuestionForm = (): QuestionFormState => ({
title: '',
question: '',
agent_id: undefined,
sort_order: 0,
});
@@ -0,0 +1,31 @@
/**
* features/admin/types/report.types.ts
* 报表模块类型。
*/
export interface UsageReport {
total: number;
by_user: { username: string; count: number }[];
by_agent: { agent: string; count: number }[];
by_day: { date: string; count: number }[];
}
export interface ReportColumnConfig {
key: string;
visible: boolean;
width: number;
}
export interface ChatLogsLayoutPref {
columns: ReportColumnConfig[];
wrapEnabled: boolean;
wrapMaxHeight: number;
sortRules?: SortRule[];
}
export type SortDirection = 'asc' | 'desc';
export interface SortRule {
key: string;
direction: SortDirection;
}
@@ -0,0 +1,14 @@
/**
* features/admin/types/request.types.ts
* 权限申请管理类型。
*/
export interface AdminPermissionRequestRow {
id: number;
user_id: number;
agent_id: number;
reason: string;
status: string;
created_at: string;
reviewed_at?: string | null;
}
@@ -0,0 +1,63 @@
/**
* features/admin/types/user.types.ts
* 用户管理模块表单与筛选类型。
*/
export interface UserFormState {
id: number | null;
username: string;
email: string;
department: string;
role: string;
password: string;
real_name: string;
employee_id: string;
phone_number: string;
agent_ids: number[];
}
export interface UserFilters {
username: string;
email: string;
department: string;
role: string;
status: string;
real_name: string;
employee_id: string;
phone_number: string;
}
export interface BatchEditForm {
department: string;
role: string;
status: string;
}
export interface BatchPermissionForm {
agent_ids: number[];
action: 'add' | 'remove' | 'set';
}
export const createEmptyUserForm = (): UserFormState => ({
id: null,
username: '',
email: '',
department: '',
role: 'user',
password: '',
real_name: '',
employee_id: '',
phone_number: '',
agent_ids: [],
});
export const createEmptyUserFilters = (): UserFilters => ({
username: '',
email: '',
department: '',
role: '',
status: '',
real_name: '',
employee_id: '',
phone_number: '',
});
@@ -0,0 +1,104 @@
/**
* features/admin/types/wecom.types.ts
* 企业微信管理模块类型。
*/
export interface WecomBindingRow {
id: number;
username: string;
real_name?: string;
email: string;
role: string;
status: string;
wecom_userid?: string | null;
wecom_unionid?: string | null;
bound: boolean;
}
export interface WecomLoginAuditRow {
id: number;
user_id?: number | null;
username?: string | null;
source: string;
status: string;
reason?: string | null;
wecom_userid?: string | null;
ip?: string | null;
user_agent?: string | null;
created_at?: string | null;
error_code?: string | null;
match_rules?: string | null;
match_operator?: string | null;
match_result?: string | null;
}
export interface WecomNotifySettings {
enabled: boolean;
base_url: string;
events: string[];
}
export interface WecomNotifyMetrics {
window_days: number;
total: number;
sent: number;
failed: number;
send_success_rate: number;
opened_24h: number;
opened_24h_rate: number;
by_event: Record<string, { sent: number; failed: number }>;
}
export interface WecomSystemSettings {
enabled: boolean;
corp_id: string;
agent_id: string;
secret: string;
redirect_uri: string;
auto_create_user: boolean;
match_rules: string;
match_operator: 'AND' | 'OR';
first_login_bind_mode: 'match_rules' | 'input_verify';
first_login_input_fields: string;
employee_id_source: string;
mobile_normalize: boolean;
callback_token: string;
encoding_aes_key: string;
callback_url: string;
homepage_url: string;
trusted_domain: string;
public_base_url: string;
}
export interface WecomIntegrationManifest {
public_base_url: string;
callback_url: string;
callback_token: string;
encoding_aes_key: string;
oauth_redirect_uri: string;
homepage_url: string;
trusted_domain: string;
authorize_api: string;
login_api: string;
}
export const createDefaultWecomSystemSettings = (): WecomSystemSettings => ({
enabled: true,
corp_id: '',
agent_id: '',
secret: '',
redirect_uri: '',
auto_create_user: true,
match_rules: 'employee_id,mobile',
match_operator: 'AND',
first_login_bind_mode: 'match_rules',
first_login_input_fields: 'employee_id,mobile,email',
employee_id_source: 'userid',
mobile_normalize: true,
callback_token: '',
encoding_aes_key: '',
callback_url: '',
homepage_url: '',
trusted_domain: '',
public_base_url: '',
});
@@ -0,0 +1,52 @@
/**
* features/admin/views/AdminLayout.vue
* 管理后台壳层:顶栏 + AdminNav + 子路由出口。
* 角标仅在 Layout 首次挂载时 ensureBadges(store 内 60s TTL 缓存)。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { ArrowLeft } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import AppHeaderTools from '@/layouts/AppHeaderTools.vue';
import AdminNav from '../components/AdminNav.vue';
import { useAdminNavStore } from '../stores/admin-nav.store';
const { t } = useI18n();
const router = useRouter();
const navStore = useAdminNavStore();
// 进入 /admin 时拉一次角标;切换子路由不重复挂载 Layout,故不会重复请求
onMounted(() => {
void navStore.ensureBadges();
});
</script>
<template>
<div class="page-shell min-h-screen font-sans flex flex-col">
<header class="app-header px-6">
<div class="flex items-center gap-4">
<button type="button" class="btn-icon-ds md:block hidden" @click="navStore.toggleSidebar()">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M9 3v18"/></svg>
</button>
<button type="button" class="btn-icon-ds" @click="router.push('/workspace')">
<ArrowLeft class="w-6 h-6" />
</button>
<div class="flex flex-col">
<h1 class="text-xl md:text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-brand-600 to-indigo-600 tracking-tight">
{{ t('admin.title') }}
</h1>
<span class="text-xs text-muted font-medium tracking-wide">{{ t('admin.subtitle') }}</span>
</div>
</div>
<AppHeaderTools />
</header>
<main class="flex-1 w-full mx-auto px-4 md:px-8 py-6 md:py-8 flex flex-col md:flex-row gap-8 items-start">
<AdminNav />
<section class="flex-1 min-w-0 space-y-8 w-full">
<router-view />
</section>
</main>
</div>
</template>
@@ -0,0 +1,23 @@
import { storeToRefs } from 'pinia';
import { useAuthStore } from '../stores/auth.store';
/**
* 认证 composable:新代码的统一入口。
*/
export function useAuth() {
const store = useAuthStore();
const { user, isLoggedIn, isAdmin, isGuest, token } = storeToRefs(store);
return {
user,
isLoggedIn,
isAdmin,
isGuest,
token,
login: store.login,
logout: store.logout,
refreshAccessToken: store.refreshAccessToken,
getHeaders: store.getHeaders,
syncFromStorage: store.syncFromStorage,
};
}
+2
View File
@@ -0,0 +1,2 @@
export { useAuthStore, bindAuthStoreSync } from './stores/auth.store';
export { useAuth } from './composables/useAuth';
@@ -0,0 +1,85 @@
/**
* features/auth/stores/auth.store.ts
* 认证全局状态;Phase 0 仍委托 utils/auth 读写 storage。
*/
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import {
getStoredAuthUser,
getAuthToken,
getAuthHeaders,
saveAuthUser,
logoutAuth as logoutAuthStorage,
refreshAccessToken as refreshAccessTokenStorage,
} from '@/utils/auth';
export interface AuthUser {
id?: number;
username?: string;
real_name?: string;
employee_id?: string;
role?: string;
token?: string;
access_token?: string;
refresh_token?: string;
expires_in?: number;
token_expires_at?: number;
}
let _syncBound = false;
export const useAuthStore = defineStore('auth', () => {
const user = ref<AuthUser | null>(getStoredAuthUser());
const syncFromStorage = (): void => {
user.value = getStoredAuthUser();
};
const isLoggedIn = computed(() => !!user.value && user.value.role !== 'guest');
const isAdmin = computed(() => user.value?.role === 'admin');
const isGuest = computed(() => user.value?.role === 'guest');
const token = computed(() => getAuthToken());
const login = (nextUser: AuthUser, remember = false): void => {
saveAuthUser(nextUser, remember);
syncFromStorage();
};
const logout = (): void => {
logoutAuthStorage();
user.value = null;
};
const refreshAccessToken = (): Promise<string | null> =>
refreshAccessTokenStorage().then((accessToken) => {
if (accessToken) syncFromStorage();
return accessToken;
});
const getHeaders = (): Record<string, string> => getAuthHeaders();
return {
user,
isLoggedIn,
isAdmin,
isGuest,
token,
syncFromStorage,
login,
logout,
refreshAccessToken,
getHeaders,
};
});
export function bindAuthStoreSync(): void {
if (_syncBound) return;
_syncBound = true;
const store = useAuthStore();
window.addEventListener('hxops:logout', () => {
store.user = null;
});
window.addEventListener('storage', (event: StorageEvent) => {
if (event.key === 'hxops_user') store.syncFromStorage();
});
}
@@ -0,0 +1,20 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
/**
* 聊天域共享状态骨架。Phase 2 迁移 ChatView 时会话列表、当前 agent 等迁入此处。
*/
export const useChatStore = defineStore('chat', () => {
const currentAgentId = ref<number | null>(null);
const sidebarCollapsed = ref(false);
const setCurrentAgentId = (agentId: number | null): void => {
currentAgentId.value = agentId;
};
return {
currentAgentId,
sidebarCollapsed,
setCurrentAgentId,
};
});
+28
View File
@@ -156,6 +156,9 @@ const messages = {
generic: 'Request failed.',
codes: {
AUTH_UNAUTHORIZED: 'Please log in first.',
AUTH_INCORRECT_PASSWORD: 'Incorrect password',
AUTH_USER_NOT_FOUND: 'User not found',
AUTH_ACCOUNT_DISABLED: 'Account is disabled',
AUTH_FORBIDDEN: 'You do not have permission to perform this action.',
RESOURCE_NOT_FOUND: 'The requested resource was not found.',
RESOURCE_CONFLICT: 'Request conflict. Please refresh and try again.',
@@ -578,7 +581,11 @@ const messages = {
confirmClean: 'Are you sure you want to delete all REJECTED users?',
confirmBatchDelete: 'Are you sure you want to delete {count} users?',
msgs: {
realNameRequired: 'Real name is required',
employeeIdRequired: 'Employee ID is required',
phoneRequired: 'Phone number is required',
usernameRequired: 'Username is required',
emailRequired: 'Email is required',
passwordRequired: 'Password is required for new users',
invalidEmail: 'Invalid email format',
created: 'User created successfully',
@@ -1682,6 +1689,9 @@ const messages = {
generic: '请求失败。',
codes: {
AUTH_UNAUTHORIZED: '请先登录。',
AUTH_INCORRECT_PASSWORD: '密码错误',
AUTH_USER_NOT_FOUND: '用户不存在',
AUTH_ACCOUNT_DISABLED: '账号已禁用',
AUTH_FORBIDDEN: '你没有权限执行该操作。',
RESOURCE_NOT_FOUND: '请求的资源不存在。',
RESOURCE_CONFLICT: '请求冲突,请刷新后重试。',
@@ -2105,7 +2115,11 @@ const messages = {
confirmClean: '确定要删除所有“已拒绝”的用户吗?',
confirmBatchDelete: '确定要删除选中的 {count} 个用户吗?',
msgs: {
realNameRequired: '真实姓名必填',
employeeIdRequired: '工号必填',
phoneRequired: '手机号必填',
usernameRequired: '用户名必填',
emailRequired: '邮箱必填',
passwordRequired: '新用户必须设置密码',
invalidEmail: '邮箱格式不正确',
created: '用户创建成功',
@@ -3172,6 +3186,9 @@ const messages = {
generic: '請求失敗。',
codes: {
AUTH_UNAUTHORIZED: '請先登入。',
AUTH_INCORRECT_PASSWORD: '密碼錯誤',
AUTH_USER_NOT_FOUND: '用戶不存在',
AUTH_ACCOUNT_DISABLED: '帳號已禁用',
AUTH_FORBIDDEN: '你沒有權限執行此操作。',
RESOURCE_NOT_FOUND: '請求的資源不存在。',
RESOURCE_CONFLICT: '請求衝突,請刷新後重試。',
@@ -3560,7 +3577,11 @@ const messages = {
confirmClean: '確定要刪除所有“已拒絕”的用戶嗎?',
confirmBatchDelete: '確定要刪除選中的 {count} 個用戶嗎?',
msgs: {
realNameRequired: '真實姓名必填',
employeeIdRequired: '工號必填',
phoneRequired: '手機號必填',
usernameRequired: '用戶名必填',
emailRequired: '郵箱必填',
passwordRequired: '新用戶必須設置密碼',
invalidEmail: '郵箱格式不正確',
created: '用戶創建成功',
@@ -4494,6 +4515,9 @@ const messages = {
generic: 'คำขอล้มเหลว',
codes: {
AUTH_UNAUTHORIZED: 'กรุณาเข้าสู่ระบบก่อน',
AUTH_INCORRECT_PASSWORD: 'รหัสผ่านไม่ถูกต้อง',
AUTH_USER_NOT_FOUND: 'ไม่พบผู้ใช้',
AUTH_ACCOUNT_DISABLED: 'บัญชีถูกปิดใช้งาน',
AUTH_FORBIDDEN: 'คุณไม่มีสิทธิ์ดำเนินการนี้',
RESOURCE_NOT_FOUND: 'ไม่พบทรัพยากรที่ร้องขอ',
RESOURCE_CONFLICT: 'คำขอขัดแย้ง โปรดรีเฟรชแล้วลองใหม่',
@@ -4799,7 +4823,11 @@ const messages = {
confirmClean: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ที่ถูกปฏิเสธทั้งหมด?',
confirmBatchDelete: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ {count} คน?',
msgs: {
realNameRequired: 'กรุณากรอกชื่อจริง',
employeeIdRequired: 'กรุณากรอกรหัสพนักงาน',
phoneRequired: 'กรุณากรอกเบอร์โทรศัพท์',
usernameRequired: 'กรุณากรอกชื่อผู้ใช้',
emailRequired: 'กรุณากรอกอีเมล',
passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่',
invalidEmail: 'รูปแบบอีเมลไม่ถูกต้อง',
created: 'สร้างผู้ใช้สำเร็จ',
+17 -22
View File
@@ -1,29 +1,25 @@
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
import i18n from './i18n'
import { config } from './config'
import { refreshAccessToken, getAuthToken, initAuthSync } from './utils/auth'
import { initAgentTabSync } from './utils/agentTabs'
import { createApp } from 'vue';
import './style.css';
import App from './App.vue';
import router from './app/router';
import i18n from './i18n';
import { config } from './config';
import { pinia } from './app/plugins/pinia';
import { bindAuthStoreSync } from './features/auth/stores/auth.store';
import { refreshAccessToken, getAuthToken, initAuthSync } from './utils/auth';
import { initAgentTabSync } from './utils/agentTabs';
initAuthSync();
initAgentTabSync();
// Set document title from config
document.title = config.appTitle || 'AI工作台';
// Global 401 interceptor for API calls.
const _rawFetch = window.fetch.bind(window);
window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
// Keep original request closure so we can retry with a refreshed token.
const runFetch = (nextInit?: RequestInit) => _rawFetch(input, nextInit);
let reqInit = init;
let res = await runFetch(reqInit);
try {
const url = typeof input === 'string'
? input
: (input instanceof URL ? input.toString() : input.url);
const url = typeof input === 'string' ? input : (input instanceof URL ? input.toString() : input.url);
const isApi = url.includes('/api/');
const isRefreshApi = url.includes('/api/user/casdoor/refresh');
const isLoginApi =
@@ -31,18 +27,15 @@ window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Res
url.includes('/api/user/casdoor/password-login') ||
url.includes('/api/user/casdoor/login');
if (res.status === 401 && isApi && !isRefreshApi) {
// First unauthorized response: try silent refresh once.
const refreshed = await refreshAccessToken();
if (refreshed) {
const mergedHeaders = new Headers((reqInit && reqInit.headers) || {});
mergedHeaders.set('Authorization', `Bearer ${getAuthToken()}`);
reqInit = { ...(reqInit || {}), headers: mergedHeaders };
// Retry original request exactly once with the renewed access token.
res = await runFetch(reqInit);
}
}
if (res.status === 401 && isApi && !isLoginApi) {
// Still unauthorized after retry (or no refresh token): force global logout UX.
window.dispatchEvent(new CustomEvent('hxops:unauthorized', { detail: { url, status: res.status } }));
}
} catch {
@@ -51,10 +44,12 @@ window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Res
return res;
};
createApp(App)
.use(router)
.use(i18n)
.mount('#app')
const app = createApp(App);
app.use(pinia);
bindAuthStoreSync();
app.use(router);
app.use(i18n);
app.mount('#app');
if ('serviceWorker' in navigator) {
window.addEventListener('load', async () => {
+2 -1
View File
@@ -107,4 +107,5 @@ router.afterEach((to) => {
}
});
export default router;
/** @deprecated 请改用 `@/app/router`;保留此文件以兼容现有 import。 */
export { default } from '@/app/router';
+12
View File
@@ -0,0 +1,12 @@
/**
* shared/api/client.ts
* 转发至现有 api/client,后续迁移实现到此文件。
*/
export {
BusinessError,
isEnvelope,
requestJson,
type ApiSuccessEnvelope,
type ApiErrorBody,
type ApiErrorEnvelope,
} from '@/api/client';
+10
View File
@@ -0,0 +1,10 @@
/** 无需登录即可访问的路由 path */
export const PUBLIC_PATHS = ['/', '/workspace', '/casdoor-callback', '/reset-password'] as const;
/** 登录后首页默认跳转的 Agent ID */
export const DEFAULT_CHAT_AGENT_ID = 16;
export type PublicPath = (typeof PUBLIC_PATHS)[number];
export const isPublicPath = (path: string): path is PublicPath =>
(PUBLIC_PATHS as readonly string[]).includes(path);
+1
View File
@@ -0,0 +1 @@
export type { AuthUser } from '@/utils/auth';
File diff suppressed because it is too large. Load diff
+153 -78
View File
@@ -26,7 +26,7 @@ import { useTheme } from '../composables/useTheme';
import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth';
import { copyTextToClipboard } from '../utils/clipboard';
import { setLastChatAgentId } from '../utils/lastChatAgent';
import { openAgentChatTab, registerOpenAgentId } from '../utils/agentTabs';
import { registerOpenAgentId } from '../utils/agentTabs';
import ChatShell from '../layouts/ChatShell.vue';
import { BusinessError } from '../api/client';
import {
@@ -317,18 +317,57 @@ const findFirstByKeys = (payload: any, keyCandidates: string[]): string => {
return '';
};
const findDirectByKeys = (payloads: any[], keyCandidates: string[]): string => {
for (const payload of payloads) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) continue;
for (const key of keyCandidates) {
const value = payload?.[key];
if (value != null && String(value).trim()) {
return String(value).trim();
}
}
}
return '';
};
const getResourceIds = (item: any) => {
const metadata = item?.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata)
? item.metadata
: null;
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
const remoteDocumentId = findFirstByKeys(item, [
const remoteDocumentId = findDirectByKeys([item, metadata], [
'remote_document_id',
'dify_document_id',
'document_id',
'doc_id',
'source_document_id',
]);
'doc_id',
]) || findFirstByKeys(item, [
'remote_document_id',
'dify_document_id',
'source_document_id',
'doc_id',
]) || findDirectByKeys([item, metadata], ['document_id']);
return { datasetId, remoteDocumentId };
};
const canPreviewSourceLink = (link: Partial<SourceFileLink> | null | undefined) => {
if (!link) return false;
return Boolean(link.url || (link.datasetId && link.remoteDocumentId));
};
const buildSourceLinkKey = (name: string, datasetId?: string, remoteDocumentId?: string, url?: string) => {
const normalizedName = String(name || '').trim();
const normalizedDatasetId = String(datasetId || '').trim();
const normalizedRemoteDocumentId = String(remoteDocumentId || '').trim();
const normalizedUrl = String(url || '').split('?')[0];
if (normalizedDatasetId && normalizedRemoteDocumentId) {
return `${normalizedName}|${normalizedDatasetId}|${normalizedRemoteDocumentId}`;
}
if (looksLikeFileName(normalizedName)) {
return normalizedUrl ? `${normalizedName}|${normalizedUrl}` : normalizedName;
}
return `${normalizedName}|${normalizedUrl}`;
};
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
@@ -411,8 +450,8 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
const forceName = item?.source_filename || item?.document_name || item?.title;
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
if (forceName) {
const key = forceName;
if (forceName && (forceUrl || (datasetId && remoteDocumentId))) {
const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl);
mergeSourceLink(key, {
name: forceName,
...(forceUrl ? { url: forceUrl } : {}),
@@ -448,8 +487,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
// 根据配置决定是否显示 MD 文件
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
// Deduplicate by name if it looks like a filename, else by name + base URL
const key = looksLikeFileName(name) ? name : `${name}|${url.split('?')[0]}`;
const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url);
mergeSourceLink(key, {
name,
url,
@@ -458,7 +496,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
});
}
}
const links = Array.from(map.values());
const links = Array.from(map.values()).filter((link) => canPreviewSourceLink(link));
// 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
// return preferred.length > 0 ? preferred : links;
@@ -487,18 +525,19 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
});
};
for (const link of links) {
if (!canPreviewSourceLink(link)) continue;
const linkUrl = link.url || '';
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
if (isNoisySourceName(link.name)) continue;
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
if (isMarkdownFileName(link.name)) {
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
mergeMessageLink(key, link);
continue;
}
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
mergeMessageLink(key, link);
}
};
@@ -567,33 +606,32 @@ const filePreviewVisible = ref(false);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {
if (file.url) {
return {
name: file.name,
url: file.url,
actualExt: file.actualExt,
};
if (file.datasetId && file.remoteDocumentId) {
const data = await resolveChatSourceFile({
agent_id: currentAgentId.value,
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (resolvedUrl) {
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
};
}
}
if (!file.datasetId || !file.remoteDocumentId) {
if (!file.url) {
throw new Error('当前源文件暂未返回可预览链接');
}
const data = await resolveChatSourceFile({
agent_id: agentId,
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (!resolvedUrl) {
throw new Error('未查询到源文件下载地址');
}
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
name: file.name,
url: file.url,
actualExt: file.actualExt,
};
};
@@ -618,7 +656,10 @@ const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
};
const route = useRoute();
const router = useRouter();
const agentId = Number(route.params.agentId);
const currentAgentId = computed(() => {
const id = Number(route.params.agentId);
return Number.isFinite(id) && id > 0 ? id : 0;
});
// Sidebar state for mobile
const isSidebarOpen = ref(false);
@@ -1017,7 +1058,7 @@ const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
isUploadingAttachments.value = true;
try {
for (const item of locals) {
const uploaded = await uploadChatFile(agentId, item.file);
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
if (!uploaded?.id) {
throw new Error('Missing upload id');
}
@@ -1272,7 +1313,7 @@ const fetchLeaveAgents = async (isLoadMore = false) => {
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(agentId, {
const data = await listOaEmployees(currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: leaveAgentPage.value,
page_size: 20,
@@ -1304,7 +1345,7 @@ const loadAllAgents = async () => {
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(agentId, {
const data = await listOaEmployees(currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: 1,
page_size: 100000,
@@ -1606,7 +1647,7 @@ const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
content: msg.content,
payload: msg.payload,
query: userQuery,
agent_id: agentId,
agent_id: currentAgentId.value,
});
if (!conversationId.value && data.conversation_id) {
conversationId.value = data.conversation_id;
@@ -1715,7 +1756,7 @@ const startLocalLeaveFlow = async (content: string) => {
try {
const keyword = payload.form.applicantName || payload.form.employeeId;
if (keyword) {
const data = await listOaEmployees(agentId, { keyword, page: 1, page_size: 1 });
const data = await listOaEmployees(currentAgentId.value, { keyword, page: 1, page_size: 1 });
const match = (data.items || []).find((item: LeaveAgentOption) => item.employeeId === payload.form.employeeId);
if (match) {
payload.form.fillerJobTitle = match.jobtitle || '';
@@ -2029,6 +2070,7 @@ const displayHistory = computed<DisplayHistoryItem[]>(() => {
const server = history.value || [];
const serverIds = new Set(server.map((h) => h.conversation_id));
const pending: DisplayHistoryItem[] = (runs.value || [])
.filter((r) => r.agentId === currentAgentId.value)
.filter((r) => r.runId !== activeRunId.value)
.map((r) => ({
id: 0,
@@ -2049,7 +2091,7 @@ const handleHistorySelect = (item: DisplayHistoryItem) => {
if (item.__runId) {
activateRun(item.__runId);
} else {
const run = runs.value.find((r) => r.conversationId === item.conversation_id);
const run = runs.value.find((r) => r.agentId === currentAgentId.value && r.conversationId === item.conversation_id);
if (run && run.status === 'running') {
activateRun(run.runId);
} else {
@@ -2561,7 +2603,7 @@ const handleSend = async (textOrEvent?: string | Event) => {
if (typeof textOrEvent !== 'string') input.value = '';
attachments.value = [];
await sendMessage(content, agentId, selectedKb.value, files);
await sendMessage(content, currentAgentId.value, selectedKb.value, files);
if (!conversationId.value && history.value.length === 0) {
await loadHistory();
@@ -2778,7 +2820,7 @@ const regenerate = () => {
// 加载历史记录
const loadHistory = async () => {
try {
history.value = await listChatSessions(agentId);
history.value = await listChatSessions(currentAgentId.value);
} catch (e) {
console.error('Failed to load history', e);
}
@@ -2787,7 +2829,7 @@ const loadHistory = async () => {
const clearAllHistory = async () => {
openDeleteConfirmDialog(t('chat.confirmClearHistory'), async () => {
try {
await deleteAllChatSessions(agentId);
await deleteAllChatSessions(currentAgentId.value);
history.value = [];
runs.value = [];
if (conversationId.value || activeRunId.value) {
@@ -2803,7 +2845,7 @@ const deleteHistoryItem = async (id: string, event: Event) => {
event.stopPropagation();
openDeleteConfirmDialog(t('chat.confirmDeleteHistoryItem'), async () => {
try {
await deleteChatSession(id, agentId);
await deleteChatSession(id, currentAgentId.value);
history.value = history.value.filter(h => h.conversation_id !== id);
if (conversationId.value === id) {
startNewChat();
@@ -2820,7 +2862,7 @@ const loadConversation = async (id: string) => {
try {
activeRunId.value = null;
isThinking.value = false;
messages.value = await listChatMessages(id, agentId);
messages.value = await listChatMessages(id, currentAgentId.value);
conversationId.value = id;
} catch (e) {
console.error('Failed to load conversation', e);
@@ -2833,7 +2875,7 @@ const startNewChat = () => {
const loadAgent = async () => {
try {
currentAgent.value = await getUserAgent(agentId);
currentAgent.value = await getUserAgent(currentAgentId.value);
} catch (e) {
if (e instanceof BusinessError && e.status === 403) {
msg.error(t('workspace.permission.denied') || 'Access denied');
@@ -2849,7 +2891,7 @@ const loadUserAgents = async () => {
try {
const agents = await listUserAgents();
userAgents.value = Array.isArray(agents)
? agents.filter((a: any) => a.id !== agentId && (a.dify_app_type || 'chatflow') === 'chatflow')
? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
@@ -2861,10 +2903,9 @@ const loadUserAgents = async () => {
};
const switchToAgent = (agent: { id: number; name: string }) => {
if (agent.id === agentId) return;
if (agent.id === currentAgentId.value) return;
setLastChatAgentId(agent.id);
const url = router.resolve(`/chat/${agent.id}`).href;
openAgentChatTab(url, agent.id);
router.push(`/chat/${agent.id}`);
};
const syncOpenAgentRegistration = () => {
@@ -2877,16 +2918,63 @@ const onPageHide = () => {
};
const goToWorkspace = (view?: string) => {
setLastChatAgentId(Number(route.params.agentId));
setLastChatAgentId(currentAgentId.value);
registerOpenAgentId(null);
const query: Record<string, string> = { no_redirect: '1' };
if (view) query.view = view;
router.push({ path: '/workspace', query });
};
const resetChatStateForAgentChange = () => {
createNewChatView();
history.value = [];
attachments.value = [];
input.value = '';
currentAgent.value = null;
copiedIndex.value = null;
showAttachmentMenu.value = false;
filePreviewVisible.value = false;
previewFile.value = null;
};
let routeSyncToken = 0;
const syncChatStateForRoute = async () => {
const agentId = currentAgentId.value;
if (!agentId) return;
const syncToken = ++routeSyncToken;
resetChatStateForAgentChange();
stopVoiceInput();
setLastChatAgentId(agentId);
syncOpenAgentRegistration();
await syncCurrentUserProfile();
if (syncToken !== routeSyncToken) return;
await loadAgent();
if (syncToken !== routeSyncToken) return;
await loadUserAgents();
if (syncToken !== routeSyncToken) return;
await loadHistory();
if (syncToken !== routeSyncToken) return;
const convId = route.query.conversation_id as string;
if (convId) {
await loadConversation(convId);
if (syncToken !== routeSyncToken) return;
}
if (presetQuestion.value) {
input.value = presetQuestion.value;
await handleSend();
}
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => {
syncOpenAgentRegistration();
window.addEventListener('pagehide', onPageHide);
window.addEventListener('hxops:logout', onAuthLogout);
document.addEventListener('mousedown', handleDocumentPointerDown);
@@ -2894,36 +2982,23 @@ onMounted(async () => {
document.addEventListener('mousedown', handleMobileAgentPopoverClickOutside);
document.addEventListener('touchstart', handleMobileAgentPopoverClickOutside, { passive: true });
window.addEventListener('resize', syncViewportWidth);
await syncCurrentUserProfile();
setLastChatAgentId(Number(route.params.agentId));
await loadAgent();
await loadUserAgents();
await loadHistory();
const convId = route.query.conversation_id as string;
if (convId) {
await loadConversation(convId);
}
if (presetQuestion.value) {
input.value = presetQuestion.value;
handleSend();
} else if (shippingCaseIdFromQuery.value) {
input.value = t('chat.shippingNoticeContinue', { caseId: shippingCaseIdFromQuery.value });
handleSend();
}
await syncChatStateForRoute();
// Use config from config.ts instead of API
showChatRating.value = config.workspace?.showChatRating ?? true;
scheduleScrollChatToBottom();
});
watch(
() => route.params.agentId,
(id) => {
const nextId = Number(id);
if (Number.isFinite(nextId) && nextId > 0) setLastChatAgentId(nextId);
syncOpenAgentRegistration();
() => [route.params.agentId, route.query.conversation_id, route.query.preset],
async ([nextAgentId, nextConversationId, nextPreset], [prevAgentId, prevConversationId, prevPreset]) => {
if (
nextAgentId === prevAgentId
&& nextConversationId === prevConversationId
&& nextPreset === prevPreset
) {
return;
}
await syncChatStateForRoute();
}
);
@@ -3950,7 +4025,7 @@ const showChatRating = ref(false);
<FilePreviewModal
v-model="filePreviewVisible"
:file="previewFile"
:agent-id="agentId"
:agent-id="currentAgentId"
:auth-headers="getAuthHeaders()"
/>
<GeneralFeedbackDialog
+6 -9
View File
@@ -28,7 +28,6 @@ import {
} from '../utils/wecom';
import { getAuthHeaders, getStoredAuthUser, saveAuthUser, logoutAuth } from '../utils/auth';
import { getLastChatAgentId } from '../utils/lastChatAgent';
import { openAgentChatTab } from '../utils/agentTabs';
import {
Settings,
LayoutGrid,
@@ -1122,8 +1121,7 @@ const navigateToChat = (id: number) => {
msg.warning(t('login.loginRequired'));
return;
}
const url = router.resolve(`/chat/${id}`).href;
openAgentChatTab(url, id);
router.push(`/chat/${id}`);
};
const navigateWithQuickQuestion = (agentId: number, question: string) => {
@@ -1132,11 +1130,10 @@ const navigateWithQuickQuestion = (agentId: number, question: string) => {
msg.warning(t('login.loginRequired'));
return;
}
const url = router.resolve({
router.push({
path: `/chat/${agentId}`,
query: { preset: question },
}).href;
openAgentChatTab(url, agentId);
});
};
const handleWecomDeeplinkContext = async () => {
@@ -1165,11 +1162,11 @@ const handleWecomDeeplinkContext = async () => {
if (target === 'chat' && agentIdRaw && isLoggedIn.value) {
const agentId = Number(agentIdRaw);
if (Number.isInteger(agentId) && agents.value.some((a) => a.id === agentId)) {
const url = router.resolve({
await router.push({
path: `/chat/${agentId}`,
query: preset ? { preset } : {},
}).href;
openAgentChatTab(url, agentId);
});
return;
}
}
+4
View File
@@ -3,6 +3,10 @@
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"types": ["vite/client"],
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
/* Linting */
"strict": true,
+9 -1
View File
@@ -1,10 +1,18 @@
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const rootDir = path.dirname(fileURLToPath(import.meta.url))
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(rootDir, 'src'),
},
},
server: {
port: 8881, // 前端开发端口,实际上我们会用 Nginx 反代,但本地开发先改这个方便
allowedHosts: ['hx.benl.cn'],