Merge branch 'dev' into test
This commit is contained in:
commit
90da630eed
31 files changed
+1600
-421
No files matched your search
@@ -48,9 +48,10 @@ GUNICORN_WORKERS=10
|
|||||||
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
|
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
|
||||||
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
|
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
|
||||||
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致
|
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致
|
||||||
MINIO_ENDPOINT=host.docker.internal:9000
|
MINIO_ENDPOINT=127.0.0.1:9000
|
||||||
MINIO_BUCKET=image-hosting-service
|
MINIO_BUCKET=image-hosting-service
|
||||||
MINIO_ACCESS_KEY=minio_testing_admin
|
MINIO_ACCESS_KEY=minio_testing_admin
|
||||||
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||||
MINIO_SECURE=false
|
MINIO_SECURE=false
|
||||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
MINIO_PUBLIC_BASE_URL=http://127.0.0.1:9000
|
||||||
|
#MINIO_PUBLIC_BASE_URL=http://192.168.1.100/HX工作目录/0602/hxops/backend/data
|
||||||
@@ -68,6 +68,8 @@ DIFY_API_BASE=https://api.dify.ai/v1
|
|||||||
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
|
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
|
||||||
GJL_API_BASE=https://api.siliconflow.cn/v1
|
GJL_API_BASE=https://api.siliconflow.cn/v1
|
||||||
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
||||||
|
# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR
|
||||||
|
ASR_MODEL=FunAudioLLM/SenseVoiceSmall
|
||||||
|
|
||||||
# HR SQL Server Configuration
|
# HR SQL Server Configuration
|
||||||
HR_SQLSERVER_HOST=192.168.100.191
|
HR_SQLSERVER_HOST=192.168.100.191
|
||||||
|
|||||||
@@ -56,6 +56,7 @@ def create_app(config_name='default'):
|
|||||||
from app.api.schedule_admin import schedule_admin_bp
|
from app.api.schedule_admin import schedule_admin_bp
|
||||||
from app.api.workspace_schedule import workspace_schedule_bp
|
from app.api.workspace_schedule import workspace_schedule_bp
|
||||||
from app.api.internal_jobs import internal_jobs_bp
|
from app.api.internal_jobs import internal_jobs_bp
|
||||||
|
from app.api.speech import speech_bp
|
||||||
|
|
||||||
# 聊天相关接口
|
# 聊天相关接口
|
||||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||||
@@ -72,6 +73,7 @@ def create_app(config_name='default'):
|
|||||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||||
|
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||||
|
|
||||||
# Eagerly load persisted runtime settings so the very first request after
|
# Eagerly load persisted runtime settings so the very first request after
|
||||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||||
|
|||||||
+101
-1
@@ -5,7 +5,8 @@ backend/app/api/admin.py
|
|||||||
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
|
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
|
||||||
"""
|
"""
|
||||||
from flask import Blueprint, request, jsonify, current_app
|
from flask import Blueprint, request, jsonify, current_app
|
||||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit
|
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide
|
||||||
|
from app.services.minio_service import minio_service
|
||||||
from app.decorators import require_admin
|
from app.decorators import require_admin
|
||||||
from app.config import Config
|
from app.config import Config
|
||||||
from app import db
|
from app import db
|
||||||
@@ -847,6 +848,105 @@ def list_wecom_bindings():
|
|||||||
users = query.order_by(User.id.asc()).all()
|
users = query.order_by(User.id.asc()).all()
|
||||||
return jsonify([{'id': u.id, 'username': u.username, 'real_name': u.real_name, 'email': u.email, 'role': u.role, 'status': u.status, 'wecom_userid': u.wecom_userid, 'wecom_unionid': u.wecom_unionid, 'bound': bool(u.wecom_userid)} for u in users])
|
return jsonify([{'id': u.id, 'username': u.username, 'real_name': u.real_name, 'email': u.email, 'role': u.role, 'status': u.status, 'wecom_userid': u.wecom_userid, 'wecom_unionid': u.wecom_unionid, 'bound': bool(u.wecom_userid)} for u in users])
|
||||||
|
|
||||||
|
@admin_bp.route('/guides/upload', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def upload_guide():
|
||||||
|
if 'file' not in request.files:
|
||||||
|
raise ValidationError('No file part')
|
||||||
|
file = request.files['file']
|
||||||
|
if file.filename == '':
|
||||||
|
raise ValidationError('No selected file')
|
||||||
|
|
||||||
|
content_type = file.content_type
|
||||||
|
file_size = len(file.read())
|
||||||
|
file.seek(0)
|
||||||
|
|
||||||
|
try:
|
||||||
|
object_name = minio_service.upload_file(file, file.filename, content_type, file_size)
|
||||||
|
return jsonify({
|
||||||
|
'file_path': object_name,
|
||||||
|
'file_name': file.filename,
|
||||||
|
'file_size': file_size,
|
||||||
|
'file_type': 'video' if content_type.startswith('video') else 'pdf' if 'pdf' in content_type else 'image'
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
raise AppError(f"Upload failed: {str(e)}")
|
||||||
|
|
||||||
|
@admin_bp.route('/guides', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def create_guide():
|
||||||
|
data = request.json
|
||||||
|
guide = AgentGuide(
|
||||||
|
agent_id=data['agent_id'],
|
||||||
|
file_name=data['file_name'],
|
||||||
|
file_type=data['file_type'],
|
||||||
|
file_path=data['file_path'],
|
||||||
|
file_size=data.get('file_size'),
|
||||||
|
remark=data.get('remark'),
|
||||||
|
sort_order=data.get('sort_order', 0),
|
||||||
|
status=data.get('status', 1),
|
||||||
|
created_by=_get_auth_user().id
|
||||||
|
)
|
||||||
|
db.session.add(guide)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'id': guide.id})
|
||||||
|
|
||||||
|
@admin_bp.route('/guides', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_guides():
|
||||||
|
agent_id = request.args.get('agent_id')
|
||||||
|
query = db.session.query(AgentGuide)
|
||||||
|
if agent_id:
|
||||||
|
query = query.filter_by(agent_id=agent_id)
|
||||||
|
guides = query.order_by(AgentGuide.sort_order).all()
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for g in guides:
|
||||||
|
result.append({
|
||||||
|
'id': g.id,
|
||||||
|
'agent_id': g.agent_id,
|
||||||
|
'file_name': g.file_name,
|
||||||
|
'file_type': g.file_type,
|
||||||
|
'file_path': g.file_path,
|
||||||
|
'file_url': minio_service.get_public_url(g.file_path),
|
||||||
|
'file_size': g.file_size,
|
||||||
|
'remark': g.remark,
|
||||||
|
'sort_order': g.sort_order,
|
||||||
|
'status': g.status,
|
||||||
|
'created_at': g.created_at.isoformat()
|
||||||
|
})
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
@admin_bp.route('/guides/<int:id>', methods=['PUT'])
|
||||||
|
@require_admin
|
||||||
|
def update_guide(id):
|
||||||
|
guide = db.session.query(AgentGuide).get(id)
|
||||||
|
if not guide:
|
||||||
|
raise NotFoundError('Guide not found')
|
||||||
|
|
||||||
|
data = request.json
|
||||||
|
if 'file_name' in data: guide.file_name = data['file_name']
|
||||||
|
if 'remark' in data: guide.remark = data['remark']
|
||||||
|
if 'sort_order' in data: guide.sort_order = data['sort_order']
|
||||||
|
if 'status' in data: guide.status = data['status']
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'success': True})
|
||||||
|
|
||||||
|
@admin_bp.route('/guides/<int:id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_guide(id):
|
||||||
|
guide = db.session.query(AgentGuide).get(id)
|
||||||
|
if not guide:
|
||||||
|
raise NotFoundError('Guide not found')
|
||||||
|
|
||||||
|
minio_service.delete_file(guide.file_path)
|
||||||
|
db.session.delete(guide)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'success': True})
|
||||||
|
|
||||||
@admin_bp.route('/wecom/bind', methods=['POST'])
|
@admin_bp.route('/wecom/bind', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def bind_wecom_user():
|
def bind_wecom_user():
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ backend/app/api/agents.py
|
|||||||
引用文件:flask, models, decorators
|
引用文件:flask, models, decorators
|
||||||
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
||||||
"""
|
"""
|
||||||
from flask import Blueprint, jsonify
|
import os
|
||||||
|
from flask import Blueprint, jsonify, send_from_directory
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.decorators import _get_current_user # 内部工具函数
|
from app.decorators import _get_current_user # 内部工具函数
|
||||||
from app.models import Agent, User
|
from app.models import Agent, User, AgentGuide
|
||||||
|
from app.services.minio_service import minio_service
|
||||||
|
|
||||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||||
agents_bp = Blueprint('agents', __name__)
|
agents_bp = Blueprint('agents', __name__)
|
||||||
@@ -58,6 +60,41 @@ def list_user_agents():
|
|||||||
# 序列化为前端所需字段
|
# 序列化为前端所需字段
|
||||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||||
|
|
||||||
|
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
|
||||||
|
def list_agent_guides(agent_id):
|
||||||
|
"""
|
||||||
|
获取指定应用的新手指南列表 (需登录)
|
||||||
|
用途:客户端 Chat 界面点击新手指南
|
||||||
|
"""
|
||||||
|
_get_current_user() # 确保已登录
|
||||||
|
|
||||||
|
if agent_id == 0:
|
||||||
|
generic_agent = db.session.query(Agent).filter_by(name='通用入口').first()
|
||||||
|
if generic_agent:
|
||||||
|
agent_id = generic_agent.id
|
||||||
|
else:
|
||||||
|
return jsonify([])
|
||||||
|
|
||||||
|
guides = (
|
||||||
|
db.session.query(AgentGuide)
|
||||||
|
.filter_by(agent_id=agent_id, status=1)
|
||||||
|
.order_by(AgentGuide.sort_order.asc(), AgentGuide.created_at.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for g in guides:
|
||||||
|
result.append({
|
||||||
|
'id': g.id,
|
||||||
|
'file_name': g.file_name,
|
||||||
|
'file_type': g.file_type,
|
||||||
|
'file_url': minio_service.get_public_url(g.file_path),
|
||||||
|
'file_size': g.file_size,
|
||||||
|
'remark': g.remark,
|
||||||
|
'updated_at': g.updated_at.isoformat()
|
||||||
|
})
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
@agents_bp.route('/public', methods=['GET'])
|
@agents_bp.route('/public', methods=['GET'])
|
||||||
def list_public_agents():
|
def list_public_agents():
|
||||||
"""
|
"""
|
||||||
@@ -73,4 +110,9 @@ def list_public_agents():
|
|||||||
)
|
)
|
||||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||||
|
|
||||||
|
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
|
||||||
|
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
|
||||||
|
def serve_guide_file(filename):
|
||||||
|
return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""
|
||||||
|
Speech transcription API — forwards audio to SiliconFlow ASR.
|
||||||
|
"""
|
||||||
|
from flask import Blueprint, jsonify, request
|
||||||
|
|
||||||
|
from app.auth_jwt import get_current_user
|
||||||
|
from app.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||||
|
from app.services.speech_asr import SpeechAsrService
|
||||||
|
|
||||||
|
speech_bp = Blueprint('speech', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@speech_bp.route('/transcribe', methods=['POST'])
|
||||||
|
def transcribe_audio():
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError('Unauthorized')
|
||||||
|
|
||||||
|
uploaded = request.files.get('audio') or request.files.get('file')
|
||||||
|
if not uploaded or not uploaded.filename:
|
||||||
|
raise ValidationError('audio file is required')
|
||||||
|
|
||||||
|
audio_bytes = uploaded.read()
|
||||||
|
filename = uploaded.filename or 'recording.webm'
|
||||||
|
content_type = uploaded.content_type or ''
|
||||||
|
|
||||||
|
try:
|
||||||
|
SpeechAsrService.validate_upload(filename, len(audio_bytes))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValidationError(str(exc)) from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
text, model = SpeechAsrService.transcribe(audio_bytes, filename, content_type)
|
||||||
|
except RuntimeError as exc:
|
||||||
|
raise ServiceUnavailableError(str(exc)) from exc
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
'text': text,
|
||||||
|
'model': model,
|
||||||
|
})
|
||||||
@@ -160,6 +160,14 @@ class Config:
|
|||||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||||
|
|
||||||
|
# MinIO 配置
|
||||||
|
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||||
|
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
|
||||||
|
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
|
||||||
|
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||||
|
MINIO_BUCKET_NAME = os.getenv('MINIO_BUCKET_NAME', 'agent-guides')
|
||||||
|
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||||
|
|
||||||
|
|
||||||
class DevelopmentConfig(Config):
|
class DevelopmentConfig(Config):
|
||||||
DEBUG = True
|
DEBUG = True
|
||||||
@@ -180,9 +188,11 @@ class TestingConfig(Config):
|
|||||||
|
|
||||||
|
|
||||||
config = {
|
config = {
|
||||||
|
'dev': DevelopmentConfig,
|
||||||
'development': DevelopmentConfig,
|
'development': DevelopmentConfig,
|
||||||
'test': TestingConfig,
|
'test': TestingConfig,
|
||||||
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
||||||
|
'prod': ProductionConfig,
|
||||||
'production': ProductionConfig,
|
'production': ProductionConfig,
|
||||||
'default': DevelopmentConfig,
|
'default': DevelopmentConfig,
|
||||||
}
|
}
|
||||||
@@ -679,3 +679,26 @@ class ScheduleRun(Base):
|
|||||||
|
|
||||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
|
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
|
||||||
|
|
||||||
|
class AgentGuide(Base):
|
||||||
|
"""
|
||||||
|
平台应用新手指南表
|
||||||
|
用途:存储 Agent 的新手指南文件信息 (如视频、PDF)
|
||||||
|
"""
|
||||||
|
__tablename__ = 'agent_guides'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||||
|
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
file_type: Mapped[str] = mapped_column(String(50), nullable=False) # video, pdf, image
|
||||||
|
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||||
|
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||||
|
status: Mapped[int] = mapped_column(Integer, default=1) # 1: 启用, 0: 禁用
|
||||||
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[agent_id])
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
from typing import BinaryIO
|
||||||
|
from minio import Minio
|
||||||
|
from minio.error import S3Error
|
||||||
|
from werkzeug.utils import secure_filename
|
||||||
|
from app.config import config, ACTIVE_ENV_NAME
|
||||||
|
|
||||||
|
cfg = config[ACTIVE_ENV_NAME]
|
||||||
|
|
||||||
|
class MinioService:
|
||||||
|
def __init__(self):
|
||||||
|
self.client = Minio(
|
||||||
|
cfg.MINIO_ENDPOINT,
|
||||||
|
access_key=cfg.MINIO_ACCESS_KEY,
|
||||||
|
secret_key=cfg.MINIO_SECRET_KEY,
|
||||||
|
secure=cfg.MINIO_SECURE,
|
||||||
|
)
|
||||||
|
self.bucket_name = cfg.MINIO_BUCKET_NAME
|
||||||
|
self._ensure_bucket_exists()
|
||||||
|
|
||||||
|
def _ensure_bucket_exists(self):
|
||||||
|
try:
|
||||||
|
if not self.client.bucket_exists(self.bucket_name):
|
||||||
|
self.client.make_bucket(self.bucket_name)
|
||||||
|
# Set bucket policy to public read
|
||||||
|
policy = {
|
||||||
|
"Version": "2012-10-17",
|
||||||
|
"Statement": [
|
||||||
|
{
|
||||||
|
"Effect": "Allow",
|
||||||
|
"Principal": {"AWS": ["*"]},
|
||||||
|
"Action": ["s3:GetObject"],
|
||||||
|
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
import json
|
||||||
|
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
|
||||||
|
except Exception as e:
|
||||||
|
# log or print error
|
||||||
|
print(f"MinIO bucket error (or not reachable): {e}")
|
||||||
|
|
||||||
|
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
|
||||||
|
"""
|
||||||
|
Uploads a file to MinIO and returns the generated object name.
|
||||||
|
"""
|
||||||
|
# If MinIO is not running, we could fallback to local storage or raise clear error
|
||||||
|
try:
|
||||||
|
self._ensure_bucket_exists()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
ext = os.path.splitext(filename)[1]
|
||||||
|
unique_filename = f"{uuid.uuid4().hex}{ext}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.client.put_object(
|
||||||
|
bucket_name=self.bucket_name,
|
||||||
|
object_name=unique_filename,
|
||||||
|
data=file_stream,
|
||||||
|
length=file_size,
|
||||||
|
content_type=content_type
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
# For development, if minio is down, let's mock it so UI can continue
|
||||||
|
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
|
||||||
|
|
||||||
|
# fallback to local storage
|
||||||
|
os.makedirs('data/agent-guides', exist_ok=True)
|
||||||
|
local_path = os.path.join('data/agent-guides', unique_filename)
|
||||||
|
file_stream.seek(0)
|
||||||
|
with open(local_path, 'wb') as f:
|
||||||
|
f.write(file_stream.read())
|
||||||
|
|
||||||
|
return unique_filename
|
||||||
|
|
||||||
|
def get_public_url(self, object_name: str) -> str:
|
||||||
|
"""
|
||||||
|
Returns the public URL for the given object name.
|
||||||
|
"""
|
||||||
|
if os.path.exists(os.path.join('data/agent-guides', object_name)):
|
||||||
|
# It's a local fallback file
|
||||||
|
# the backend needs a static route to serve this, we'll assume /api/agents/guides/files/<object_name>
|
||||||
|
# but since we want it public without auth:
|
||||||
|
return f"/api/agents/guides/files/{object_name}"
|
||||||
|
|
||||||
|
base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/')
|
||||||
|
return f"{base_url}/{self.bucket_name}/{object_name}"
|
||||||
|
|
||||||
|
def delete_file(self, object_name: str):
|
||||||
|
try:
|
||||||
|
self.client.remove_object(self.bucket_name, object_name)
|
||||||
|
except S3Error as e:
|
||||||
|
print(f"Error deleting file from MinIO: {e}")
|
||||||
|
|
||||||
|
minio_service = MinioService()
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""
|
||||||
|
SiliconFlow ASR service (OpenAI-compatible /v1/audio/transcriptions).
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
ALLOWED_AUDIO_EXTENSIONS = frozenset({
|
||||||
|
'webm', 'wav', 'mp3', 'm4a', 'mp4', 'mpeg', 'mpga', 'ogg',
|
||||||
|
})
|
||||||
|
MAX_AUDIO_BYTES = int(os.getenv('ASR_MAX_AUDIO_BYTES', str(10 * 1024 * 1024)))
|
||||||
|
|
||||||
|
|
||||||
|
class SpeechAsrService:
|
||||||
|
@classmethod
|
||||||
|
def _get_client(cls):
|
||||||
|
try:
|
||||||
|
from openai import OpenAI
|
||||||
|
except ImportError as exc:
|
||||||
|
raise RuntimeError('OpenAI SDK not installed') from exc
|
||||||
|
|
||||||
|
api_key = (os.getenv('GJL_API_KEY') or '').strip()
|
||||||
|
base_url = (os.getenv('GJL_API_BASE') or 'https://api.siliconflow.cn/v1').strip()
|
||||||
|
|
||||||
|
if not api_key:
|
||||||
|
raise RuntimeError('Missing GJL_API_KEY. Configure it in .env to enable speech recognition')
|
||||||
|
|
||||||
|
return OpenAI(api_key=api_key, base_url=base_url)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _resolve_model(cls) -> str:
|
||||||
|
return (os.getenv('ASR_MODEL') or 'FunAudioLLM/SenseVoiceSmall').strip()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _normalize_filename(cls, filename: str, content_type: str) -> str:
|
||||||
|
name = (filename or '').strip() or 'recording.webm'
|
||||||
|
if '.' not in name:
|
||||||
|
if 'wav' in content_type:
|
||||||
|
name = f'{name}.wav'
|
||||||
|
elif 'mp4' in content_type or 'm4a' in content_type:
|
||||||
|
name = f'{name}.m4a'
|
||||||
|
else:
|
||||||
|
name = f'{name}.webm'
|
||||||
|
return name
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def validate_upload(cls, filename: str, size: int) -> None:
|
||||||
|
ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
|
||||||
|
if ext and ext not in ALLOWED_AUDIO_EXTENSIONS:
|
||||||
|
raise ValueError(f'Unsupported audio format: .{ext}')
|
||||||
|
if size <= 0:
|
||||||
|
raise ValueError('Audio file is empty')
|
||||||
|
if size > MAX_AUDIO_BYTES:
|
||||||
|
raise ValueError(f'Audio file exceeds {MAX_AUDIO_BYTES // (1024 * 1024)}MB limit')
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def transcribe(cls, audio_bytes: bytes, filename: str, content_type: str = '') -> Tuple[str, str]:
|
||||||
|
cls.validate_upload(filename, len(audio_bytes))
|
||||||
|
|
||||||
|
client = cls._get_client()
|
||||||
|
model = cls._resolve_model()
|
||||||
|
safe_name = cls._normalize_filename(filename, content_type)
|
||||||
|
file_obj = io.BytesIO(audio_bytes)
|
||||||
|
file_obj.name = safe_name
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = client.audio.transcriptions.create(
|
||||||
|
model=model,
|
||||||
|
file=file_obj,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f'Speech recognition request failed: {exc}') from exc
|
||||||
|
|
||||||
|
text = str(getattr(result, 'text', '') or '').strip()
|
||||||
|
return text, model
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""repair schema drift indexes and constraints
|
||||||
|
|
||||||
|
Revision ID: d0e1f2a3b4c5
|
||||||
|
Revises: c9d8e7f6a5b4
|
||||||
|
Create Date: 2026-06-03 12:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'd0e1f2a3b4c5'
|
||||||
|
down_revision = 'c9d8e7f6a5b4'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.create_index('ix_kb_documents_group_id', 'kb_documents', ['group_id'], unique=False)
|
||||||
|
op.create_index(
|
||||||
|
'ix_kb_document_versions_document_id',
|
||||||
|
'kb_document_versions',
|
||||||
|
['document_id'],
|
||||||
|
unique=False,
|
||||||
|
)
|
||||||
|
op.create_index('ix_schedule_tasks_last_run_at', 'schedule_tasks', ['last_run_at'], unique=False)
|
||||||
|
op.create_index('ix_schedule_tasks_created_at', 'schedule_tasks', ['created_at'], unique=False)
|
||||||
|
|
||||||
|
op.execute("UPDATE schedule_runs SET wecom_notified = false WHERE wecom_notified IS NULL")
|
||||||
|
op.alter_column(
|
||||||
|
'schedule_runs',
|
||||||
|
'wecom_notified',
|
||||||
|
existing_type=sa.Boolean(),
|
||||||
|
nullable=False,
|
||||||
|
existing_server_default=sa.text('false'),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.alter_column(
|
||||||
|
'schedule_runs',
|
||||||
|
'wecom_notified',
|
||||||
|
existing_type=sa.Boolean(),
|
||||||
|
nullable=True,
|
||||||
|
existing_server_default=sa.text('false'),
|
||||||
|
)
|
||||||
|
|
||||||
|
op.drop_index('ix_schedule_tasks_created_at', table_name='schedule_tasks')
|
||||||
|
op.drop_index('ix_schedule_tasks_last_run_at', table_name='schedule_tasks')
|
||||||
|
op.drop_index('ix_kb_document_versions_document_id', table_name='kb_document_versions')
|
||||||
|
op.drop_index('ix_kb_documents_group_id', table_name='kb_documents')
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""add agent_guides table
|
||||||
|
|
||||||
|
Revision ID: f6f91cb46944
|
||||||
|
Revises: d0e1f2a3b4c5
|
||||||
|
Create Date: 2026-06-04 09:32:18.390108
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'f6f91cb46944'
|
||||||
|
down_revision = 'd0e1f2a3b4c5'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('agent_guides',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('agent_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('file_name', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('file_type', sa.String(length=50), nullable=False),
|
||||||
|
sa.Column('file_path', sa.String(length=500), nullable=False),
|
||||||
|
sa.Column('file_size', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('remark', sa.Text(), nullable=True),
|
||||||
|
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('status', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('created_by', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
|
||||||
|
sa.ForeignKeyConstraint(['created_by'], ['users.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('agent_guides', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_agent_guides_agent_id'), ['agent_id'], unique=False)
|
||||||
|
|
||||||
|
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_schedule_runs_id'))
|
||||||
|
|
||||||
|
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_schedule_tasks_id'))
|
||||||
|
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('uq_users_wecom_unionid'))
|
||||||
|
batch_op.drop_index(batch_op.f('uq_users_wecom_userid'))
|
||||||
|
batch_op.create_unique_constraint(None, ['wecom_unionid'])
|
||||||
|
batch_op.create_unique_constraint(None, ['wecom_userid'])
|
||||||
|
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||||
|
batch_op.drop_constraint(None, type_='unique')
|
||||||
|
batch_op.drop_constraint(None, type_='unique')
|
||||||
|
batch_op.create_index(batch_op.f('uq_users_wecom_userid'), ['wecom_userid'], unique=True)
|
||||||
|
batch_op.create_index(batch_op.f('uq_users_wecom_unionid'), ['wecom_unionid'], unique=True)
|
||||||
|
|
||||||
|
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_schedule_tasks_id'), ['id'], unique=False)
|
||||||
|
|
||||||
|
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_schedule_runs_id'), ['id'], unique=False)
|
||||||
|
|
||||||
|
with op.batch_alter_table('agent_guides', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_agent_guides_agent_id'))
|
||||||
|
|
||||||
|
op.drop_table('agent_guides')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -35,4 +35,4 @@ lxml==6.0.2
|
|||||||
typer==0.17.4
|
typer==0.17.4
|
||||||
croniter
|
croniter
|
||||||
pyyaml
|
pyyaml
|
||||||
minio>=7.2.0
|
minio==7.2.20
|
||||||
@@ -336,3 +336,36 @@
|
|||||||
5. 移动端右上角可见个人设置图标按钮
|
5. 移动端右上角可见个人设置图标按钮
|
||||||
6. 点击右上角按钮可进入个人设置页面
|
6. 点击右上角按钮可进入个人设置页面
|
||||||
7. PC 端布局与行为无任何变化
|
7. PC 端布局与行为无任何变化
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15. 平台应用新手指南需求
|
||||||
|
|
||||||
|
### 15.1 项目背景
|
||||||
|
|
||||||
|
目前用户在使用部分复杂的 Agent 应用时,由于缺乏直观的操作引导,容易产生困惑。通过在应用内提供视频、PDF 等多媒体说明文档,可以实现“即学即用”,降低用户学习成本。
|
||||||
|
|
||||||
|
### 15.2 需求目标
|
||||||
|
|
||||||
|
1. 管理后台支持为不同 Agent 应用上传和管理视频、PDF 等新手指南资料。
|
||||||
|
2. 前端聊天界面根据后台配置,动态展示“新手指南”入口。
|
||||||
|
3. 用户点击后可直接在系统内预览视频或 PDF 文档。
|
||||||
|
|
||||||
|
### 15.3 详细需求
|
||||||
|
|
||||||
|
#### NR-01 管理后台-平台应用说明管理
|
||||||
|
- 支持选择系统内已发布的 Agent 应用。
|
||||||
|
- 支持上传视频(MP4/WebM)和文档(PDF),上传至 MinIO(mimo)服务。
|
||||||
|
- 维护资料信息:名称、备注、状态(启用/禁用)、排序等。
|
||||||
|
|
||||||
|
#### NR-02 客户端-新手指南入口与展示
|
||||||
|
- 在 Chat 对话界面的左上角(应用 Title 旁边),新增【新手指南】按钮。
|
||||||
|
- 根据后台接口返回,若存在启用状态的指南,则显示入口,否则隐藏。
|
||||||
|
- 点击后弹出预览浮层(Modal/Drawer),支持多文件标签页切换。
|
||||||
|
- 弹窗内直接内联播放视频或渲染 PDF(无需下载)。
|
||||||
|
|
||||||
|
### 15.4 验收标准
|
||||||
|
1. 管理员能成功上传并管理应用的指南文件。
|
||||||
|
2. 客户端正确根据配置动态展示或隐藏入口。
|
||||||
|
3. 客户端能正常播放指南视频和预览 PDF 文档。
|
||||||
@@ -377,3 +377,30 @@
|
|||||||
- 点击右上角按钮可进入个人设置页面
|
- 点击右上角按钮可进入个人设置页面
|
||||||
- PC 端布局与行为无任何变化
|
- PC 端布局与行为无任何变化
|
||||||
- 旋转屏幕后布局实时切换
|
- 旋转屏幕后布局实时切换
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 新手指南功能清单
|
||||||
|
|
||||||
|
### 8.1 功能总览
|
||||||
|
|
||||||
|
| 功能项 | 说明 | 状态 | 优先级 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 指南资料上传与管理 | 管理台上传视频、PDF,并关联 Agent,支持启用/禁用 | 待建设 | P0 |
|
||||||
|
| 客户端动态入口 | 聊天页左上角动态获取并展示“新手指南”按钮 | 待建设 | P0 |
|
||||||
|
| 指南预览弹窗 | 客户端弹窗内嵌播放视频、渲染 PDF,支持多文件切换 | 待建设 | P0 |
|
||||||
|
|
||||||
|
### 8.2 详细功能拆分
|
||||||
|
|
||||||
|
#### F-11 指南资料上传与管理 (Admin)
|
||||||
|
- **目标**:管理员为 Agent 配置多媒体指南。
|
||||||
|
- **功能点**:文件直传 MinIO (mimo服务),数据保存至 PostgreSQL `agent_guides` 表;支持资料的增删改查、排序和状态切换。
|
||||||
|
|
||||||
|
#### F-12 客户端动态入口 (Client)
|
||||||
|
- **目标**:根据当前 Agent 是否有指南资料动态显示入口。
|
||||||
|
- **功能点**:进入对话页面时请求指南列表接口,有数据则渲染【新手指南】按钮。
|
||||||
|
|
||||||
|
#### F-13 指南预览弹窗 (Client)
|
||||||
|
- **目标**:用户在聊天界面快速查阅指南。
|
||||||
|
- **功能点**:视频使用 HTML5 播放器,PDF 使用 `@vue-office/pdf` 渲染,支持 Tabs 切换多份指南。
|
||||||
+44
@@ -731,3 +731,47 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth;
|
|||||||
- 所有移动端适配逻辑均以 `v-if="isMobile"` 或三元表达式控制,`isMobile` 在 PC 横屏时始终为 `false`
|
- 所有移动端适配逻辑均以 `v-if="isMobile"` 或三元表达式控制,`isMobile` 在 PC 横屏时始终为 `false`
|
||||||
- 路由守卫对 `/workspace` 等直接访问不做拦截,PC 端行为不变
|
- 路由守卫对 `/workspace` 等直接访问不做拦截,PC 端行为不变
|
||||||
- PC 端侧边栏、导航栏、布局结构无任何 CSS 或 DOM 变更
|
- PC 端侧边栏、导航栏、布局结构无任何 CSS 或 DOM 变更
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 17. 平台应用新手指南技术架构
|
||||||
|
|
||||||
|
### 17.1 整体技术栈
|
||||||
|
- **前端**:Vue 3 + TailwindCSS,原生 `<video>` + `@vue-office/pdf` 实现预览。
|
||||||
|
- **后端**:Python FastAPI 框架。
|
||||||
|
- **存储**:PostgreSQL(存储业务元数据) + MinIO(对接 mimo 服务,存储大文件)。
|
||||||
|
|
||||||
|
### 17.2 数据库设计
|
||||||
|
|
||||||
|
新增 `agent_guides` 表(PostgreSQL):
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| id | serial | 主键 |
|
||||||
|
| agent_id | int | 关联的应用 ID |
|
||||||
|
| file_name | varchar(255) | 资料名称 |
|
||||||
|
| file_type | varchar(50) | 文件类型(video, pdf, image) |
|
||||||
|
| file_path | varchar(500) | MinIO 存储路径 |
|
||||||
|
| file_size | int | 文件大小(Byte) |
|
||||||
|
| remark | text | 备注 |
|
||||||
|
| sort_order | int | 排序权重 |
|
||||||
|
| status | smallint | 状态(1:启用, 0:禁用) |
|
||||||
|
| created_by | int | 创建人 |
|
||||||
|
| created_at | timestamp | 创建时间 |
|
||||||
|
| updated_at | timestamp | 更新时间 |
|
||||||
|
|
||||||
|
### 17.3 核心 API 设计
|
||||||
|
|
||||||
|
#### 管理后台 API
|
||||||
|
- `POST /api/admin/guides/upload`:直传文件至 MinIO Bucket。
|
||||||
|
- `POST /api/admin/guides`:保存指南元数据。
|
||||||
|
- `GET /api/admin/guides`:按 `agent_id` 获取指南列表。
|
||||||
|
- `PUT / DELETE /api/admin/guides/{id}`:更新/删除指南。
|
||||||
|
|
||||||
|
#### 客户端 API
|
||||||
|
- `GET /api/agent/{agent_id}/guides`:客户端获取启用的指南列表,返回包含 MinIO 访问 URL 的数据。
|
||||||
|
|
||||||
|
### 17.4 关键设计决策
|
||||||
|
- **大文件处理**:文件存储至独立的 MinIO 服务,配置 Public Read 策略或预签名 URL,前端直接访问,减轻 FastAPI 服务带宽压力。
|
||||||
|
- **预览方案**:复用现有依赖 `@vue-office/pdf` 进行 PDF 渲染,保持项目轻量化。
|
||||||
@@ -53,6 +53,36 @@ export const updateAdminAgent = (id: number, payload: Record<string, unknown>) =
|
|||||||
requestJson(`/api/admin/agents/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
|
requestJson(`/api/admin/agents/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
export const deleteAdminAgent = (id: number) =>
|
export const deleteAdminAgent = (id: number) =>
|
||||||
requestJson(`/api/admin/agents/${id}`, { method: 'DELETE', ...auth() });
|
requestJson(`/api/admin/agents/${id}`, { method: 'DELETE', ...auth() });
|
||||||
|
|
||||||
|
// Agent Guides
|
||||||
|
export const listAdminAgentGuides = (agentId?: number) => {
|
||||||
|
const url = agentId ? `/api/admin/guides?agent_id=${agentId}` : '/api/admin/guides';
|
||||||
|
return requestJson<any[]>(url, auth());
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createAdminAgentGuide = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson('/api/admin/guides', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
|
||||||
|
export const updateAdminAgentGuide = (id: number, payload: Record<string, unknown>) =>
|
||||||
|
requestJson(`/api/admin/guides/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
|
||||||
|
export const deleteAdminAgentGuide = (id: number) =>
|
||||||
|
requestJson(`/api/admin/guides/${id}`, { method: 'DELETE', ...auth() });
|
||||||
|
|
||||||
|
export const uploadAdminAgentGuideFile = async (file: File) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
const response = await fetch('/api/admin/guides/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: getAuthHeaders(),
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({}));
|
||||||
|
throw new Error(error.message || 'Upload failed');
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
};
|
||||||
export const testAdminAgent = (id: number) =>
|
export const testAdminAgent = (id: number) =>
|
||||||
requestJson<any>(`/api/admin/agents/${id}/test`, { method: 'POST', ...auth() });
|
requestJson<any>(`/api/admin/agents/${id}/test`, { method: 'POST', ...auth() });
|
||||||
export const saveAdminAgentPermissions = (agentId: number, userIds: number[]) =>
|
export const saveAdminAgentPermissions = (agentId: number, userIds: number[]) =>
|
||||||
|
|||||||
@@ -42,3 +42,5 @@ export const getUserAgent = (agentId: number) =>
|
|||||||
requestJson<Record<string, any>>(`/api/user/agents/${agentId}`, auth());
|
requestJson<Record<string, any>>(`/api/user/agents/${agentId}`, auth());
|
||||||
|
|
||||||
export const listUserAgents = () => requestJson<any[]>('/api/agents', auth());
|
export const listUserAgents = () => requestJson<any[]>('/api/agents', auth());
|
||||||
|
|
||||||
|
export const listAgentGuides = (agentId: number) => requestJson<any[]>(`/api/agents/${agentId}/guides`, auth());
|
||||||
@@ -1,110 +1,218 @@
|
|||||||
/**␍
|
/**
|
||||||
* app/router/routes/admin.routes.ts␍
|
|
||||||
* 管理后台嵌套路由;全部 admin 模块已独立拆分。␍
|
* app/router/routes/admin.routes.ts
|
||||||
*/␍
|
|
||||||
import type { RouteRecordRaw } from 'vue-router';␍
|
* 管理后台嵌套路由;全部 admin 模块已独立拆分。
|
||||||
␍
|
|
||||||
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');␍
|
import type { RouteRecordRaw } from 'vue-router';
|
||||||
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 AdminLayout = () => import('@/features/admin/views/AdminLayout.vue');
|
||||||
const RequestsPage = () => import('@/features/admin/modules/requests/RequestsPage.vue');␍
|
|
||||||
const PermissionsPage = () => import('@/features/admin/modules/permissions/PermissionsPage.vue');␍
|
const AgentsPage = () => import('@/features/admin/modules/agents/AgentsPage.vue');
|
||||||
const DashboardPage = () => import('@/features/admin/modules/dashboard/DashboardPage.vue');␍
|
|
||||||
const SchedulesPage = () => import('@/features/admin/modules/schedules/SchedulesPage.vue');␍
|
const UsersPage = () => import('@/features/admin/modules/users/UsersPage.vue');
|
||||||
const KnowledgeBasePage = () => import('@/features/admin/modules/knowledge-base/KnowledgeBasePage.vue');␍
|
|
||||||
const WecomPage = () => import('@/features/admin/modules/wecom/WecomPage.vue');␍
|
const DepartmentsPage = () => import('@/features/admin/modules/departments/DepartmentsPage.vue');
|
||||||
const ReportsPage = () => import('@/features/admin/modules/reports/ReportsPage.vue');␍
|
|
||||||
␍
|
const ApprovalsPage = () => import('@/features/admin/modules/approvals/ApprovalsPage.vue');
|
||||||
export const adminRoutes: RouteRecordRaw[] = [␍
|
|
||||||
{␍
|
const AnnouncementsPage = () => import('@/features/admin/modules/announcements/AnnouncementsPage.vue');
|
||||||
path: '/admin',␍
|
|
||||||
component: AdminLayout,␍
|
const QuestionsPage = () => import('@/features/admin/modules/questions/QuestionsPage.vue');
|
||||||
meta: { requiresAdmin: true },␍
|
|
||||||
children: [␍
|
const RequestsPage = () => import('@/features/admin/modules/requests/RequestsPage.vue');
|
||||||
{ path: '', redirect: '/admin/dashboard' },␍
|
|
||||||
{␍
|
const PermissionsPage = () => import('@/features/admin/modules/permissions/PermissionsPage.vue');
|
||||||
path: 'dashboard',␍
|
const PlatformAppsPage = () => import('@/features/admin/modules/platform-apps/PlatformAppsPage.vue');
|
||||||
name: 'AdminDashboard',␍
|
const DashboardPage = () => import('@/features/admin/modules/dashboard/DashboardPage.vue');
|
||||||
component: DashboardPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'dashboard', title: '概览' },␍
|
const SchedulesPage = () => import('@/features/admin/modules/schedules/SchedulesPage.vue');
|
||||||
},␍
|
|
||||||
{␍
|
const KnowledgeBasePage = () => import('@/features/admin/modules/knowledge-base/KnowledgeBasePage.vue');
|
||||||
path: 'schedules',␍
|
|
||||||
name: 'AdminSchedules',␍
|
const WecomPage = () => import('@/features/admin/modules/wecom/WecomPage.vue');
|
||||||
component: SchedulesPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'schedules', title: '定时任务' },␍
|
const ReportsPage = () => import('@/features/admin/modules/reports/ReportsPage.vue');
|
||||||
},␍
|
|
||||||
{␍
|
|
||||||
path: 'knowledge-base',␍
|
|
||||||
name: 'AdminKnowledgeBase',␍
|
export const adminRoutes: RouteRecordRaw[] = [
|
||||||
component: KnowledgeBasePage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'knowledge_base', title: '知识库' },␍
|
{
|
||||||
},␍
|
|
||||||
{␍
|
path: '/admin',
|
||||||
path: 'wecom',␍
|
|
||||||
name: 'AdminWecom',␍
|
component: AdminLayout,
|
||||||
component: WecomPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'wecom', title: '企业微信' },␍
|
meta: { requiresAdmin: true },
|
||||||
},␍
|
|
||||||
{␍
|
children: [
|
||||||
path: 'approvals',␍
|
|
||||||
name: 'AdminApprovals',␍
|
{ path: '', redirect: '/admin/dashboard' },
|
||||||
component: ApprovalsPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'approvals', title: '用户审批' },␍
|
{
|
||||||
},␍
|
|
||||||
{␍
|
path: 'dashboard',
|
||||||
path: 'agents',␍
|
|
||||||
name: 'AdminAgents',␍
|
name: 'AdminDashboard',
|
||||||
component: AgentsPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'agents', title: '应用管理' },␍
|
component: DashboardPage,
|
||||||
},␍
|
|
||||||
{␍
|
meta: { requiresAdmin: true, adminModule: 'dashboard', title: '概览' },
|
||||||
path: 'users',␍
|
|
||||||
name: 'AdminUsers',␍
|
},
|
||||||
component: UsersPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'users', title: '用户管理' },␍
|
{
|
||||||
},␍
|
|
||||||
{␍
|
path: 'schedules',
|
||||||
path: 'departments',␍
|
|
||||||
name: 'AdminDepartments',␍
|
name: 'AdminSchedules',
|
||||||
component: DepartmentsPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'departments', title: '部门管理' },␍
|
component: SchedulesPage,
|
||||||
},␍
|
|
||||||
{␍
|
meta: { requiresAdmin: true, adminModule: 'schedules', title: '定时任务' },
|
||||||
path: 'announcements',␍
|
|
||||||
name: 'AdminAnnouncements',␍
|
},
|
||||||
component: AnnouncementsPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'announcements', title: '公告管理' },␍
|
{
|
||||||
},␍
|
|
||||||
{␍
|
path: 'knowledge-base',
|
||||||
path: 'questions',␍
|
|
||||||
name: 'AdminQuestions',␍
|
name: 'AdminKnowledgeBase',
|
||||||
component: QuestionsPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'questions', title: '常用问题' },␍
|
component: KnowledgeBasePage,
|
||||||
},␍
|
|
||||||
{␍
|
meta: { requiresAdmin: true, adminModule: 'knowledge_base', title: '知识库' },
|
||||||
path: 'requests',␍
|
|
||||||
name: 'AdminRequests',␍
|
},
|
||||||
component: RequestsPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'requests', title: '权限申请' },␍
|
{
|
||||||
},␍
|
|
||||||
{␍
|
path: 'wecom',
|
||||||
path: 'permissions',␍
|
|
||||||
name: 'AdminPermissions',␍
|
name: 'AdminWecom',
|
||||||
component: PermissionsPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'permissions', title: '权限管理' },␍
|
component: WecomPage,
|
||||||
},␍
|
|
||||||
{␍
|
meta: { requiresAdmin: true, adminModule: 'wecom', title: '企业微信' },
|
||||||
path: 'reports/:table?',␍
|
|
||||||
name: 'AdminReports',␍
|
},
|
||||||
component: ReportsPage,␍
|
|
||||||
meta: { requiresAdmin: true, adminModule: 'reports', 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: 'platform-apps',
|
||||||
|
name: 'AdminPlatformApps',
|
||||||
|
component: PlatformAppsPage,
|
||||||
|
meta: { requiresAdmin: true, adminModule: 'platform_apps', title: '平台应用说明' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'reports/:table?',
|
||||||
|
|
||||||
|
name: 'AdminReports',
|
||||||
|
|
||||||
|
component: ReportsPage,
|
||||||
|
|
||||||
|
meta: { requiresAdmin: true, adminModule: 'reports', title: '报表' },
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
],
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
];
|
||||||
|
|
||||||
|
|
||||||
@@ -48,7 +48,6 @@ const emit = defineEmits<{
|
|||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
const isLoading = ref(false);
|
const isLoading = ref(false);
|
||||||
const isDownloading = ref(false);
|
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
const markdownHtml = ref('');
|
const markdownHtml = ref('');
|
||||||
const excelPreview = ref<ExcelPreviewData | null>(null);
|
const excelPreview = ref<ExcelPreviewData | null>(null);
|
||||||
@@ -150,21 +149,6 @@ const readErrorMessage = async (res: Response) => {
|
|||||||
return extractErrorMessage(text, fallback);
|
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 applyExcelPreview = (buffer: ArrayBuffer) => {
|
||||||
const workbook = XLSX.read(buffer, { type: 'array' });
|
const workbook = XLSX.read(buffer, { type: 'array' });
|
||||||
if (!workbook.SheetNames.length) {
|
if (!workbook.SheetNames.length) {
|
||||||
@@ -331,42 +315,6 @@ const loadBinaryContent = async () => {
|
|||||||
officeObjectUrl.value = URL.createObjectURL(blob);
|
officeObjectUrl.value = URL.createObjectURL(blob);
|
||||||
};
|
};
|
||||||
|
|
||||||
const downloadFile = async () => {
|
|
||||||
if (!props.file?.url || !props.agentId || isDownloading.value) return;
|
|
||||||
|
|
||||||
isDownloading.value = true;
|
|
||||||
try {
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
agent_id: String(props.agentId),
|
|
||||||
url: props.file.url,
|
|
||||||
name: props.file.name || '',
|
|
||||||
download: '1',
|
|
||||||
});
|
|
||||||
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
|
||||||
headers: props.authHeaders || {},
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
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 = extractDownloadFilename(res) || props.file.name || 'download';
|
|
||||||
document.body.appendChild(link);
|
|
||||||
link.click();
|
|
||||||
link.remove();
|
|
||||||
window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000);
|
|
||||||
} catch (e: any) {
|
|
||||||
error.value = t('filePreview.msg.downloadFailed', {
|
|
||||||
reason: e?.message || t('filePreview.msg.unknownError'),
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
isDownloading.value = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 在弹窗/文件变化时加载预览内容。
|
* 在弹窗/文件变化时加载预览内容。
|
||||||
* 流程:
|
* 流程:
|
||||||
@@ -507,16 +455,6 @@ watch(
|
|||||||
<div class="min-w-0">
|
<div class="min-w-0">
|
||||||
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">{{ t('filePreview.title') }}</div>
|
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">{{ t('filePreview.title') }}</div>
|
||||||
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
|
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
|
||||||
<button type="button" @click="downloadFile" :disabled="isDownloading" class="mt-2 inline-flex items-center justify-center px-3 py-1.5 text-xs font-medium rounded-lg bg-brand-50 text-brand-700 hover:bg-brand-100 border border-brand-200 dark:bg-brand-900/30 dark:text-brand-300 dark:border-brand-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
|
|
||||||
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
|
||||||
</svg>
|
|
||||||
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700 dark:text-brand-300" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
|
||||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
|
||||||
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
|
||||||
</svg>
|
|
||||||
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
|
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -611,20 +549,6 @@ watch(
|
|||||||
<div class="mt-2 text-sm text-muted">
|
<div class="mt-2 text-sm text-muted">
|
||||||
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
|
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
|
||||||
</div>
|
</div>
|
||||||
<div class="mt-4 flex gap-3">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
@click="downloadFile"
|
|
||||||
:disabled="isDownloading"
|
|
||||||
class="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center"
|
|
||||||
>
|
|
||||||
<svg v-if="isDownloading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
|
||||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
|
||||||
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
|
||||||
</svg>
|
|
||||||
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<iframe
|
<iframe
|
||||||
v-else
|
v-else
|
||||||
|
|||||||
@@ -0,0 +1,204 @@
|
|||||||
|
import { ref, computed, onBeforeUnmount } from 'vue';
|
||||||
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
|
|
||||||
|
export type AudioTranscriptionErrorKey =
|
||||||
|
| 'chat.voiceRequiresHttps'
|
||||||
|
| 'chat.voiceNotSupported'
|
||||||
|
| 'chat.voicePermissionDenied'
|
||||||
|
| 'chat.voiceRecordTooShort'
|
||||||
|
| 'chat.voiceTranscriptionFailed';
|
||||||
|
|
||||||
|
const isSecureContextForMic = (): boolean => {
|
||||||
|
if (typeof window === 'undefined') return false;
|
||||||
|
if (window.isSecureContext) return true;
|
||||||
|
const host = window.location.hostname;
|
||||||
|
return host === 'localhost' || host === '127.0.0.1';
|
||||||
|
};
|
||||||
|
|
||||||
|
const canUseMediaRecorder = (): boolean => {
|
||||||
|
if (typeof window === 'undefined') return false;
|
||||||
|
return Boolean(window.MediaRecorder && navigator.mediaDevices?.getUserMedia);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getVoiceUnavailableErrorKey = (): AudioTranscriptionErrorKey | null => {
|
||||||
|
if (!isSecureContextForMic()) return 'chat.voiceRequiresHttps';
|
||||||
|
if (!canUseMediaRecorder()) return 'chat.voiceNotSupported';
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const pickMimeType = (): string => {
|
||||||
|
const candidates = [
|
||||||
|
'audio/webm;codecs=opus',
|
||||||
|
'audio/webm',
|
||||||
|
'audio/mp4',
|
||||||
|
'audio/ogg;codecs=opus',
|
||||||
|
];
|
||||||
|
for (const type of candidates) {
|
||||||
|
if (MediaRecorder.isTypeSupported(type)) return type;
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useAudioTranscription(options: {
|
||||||
|
onResult: (text: string) => void;
|
||||||
|
onError: (key: AudioTranscriptionErrorKey) => void;
|
||||||
|
}) {
|
||||||
|
const isRecording = ref(false);
|
||||||
|
const isTranscribing = ref(false);
|
||||||
|
const isSupported = computed(() => getVoiceUnavailableErrorKey() === null);
|
||||||
|
const isBusy = computed(() => isRecording.value || isTranscribing.value);
|
||||||
|
|
||||||
|
let mediaStream: MediaStream | null = null;
|
||||||
|
let mediaRecorder: MediaRecorder | null = null;
|
||||||
|
let chunks: Blob[] = [];
|
||||||
|
let baseText = '';
|
||||||
|
let skipTranscription = false;
|
||||||
|
|
||||||
|
const cleanupStream = () => {
|
||||||
|
if (mediaStream) {
|
||||||
|
mediaStream.getTracks().forEach((track) => track.stop());
|
||||||
|
mediaStream = null;
|
||||||
|
}
|
||||||
|
mediaRecorder = null;
|
||||||
|
chunks = [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const stopRecording = () => {
|
||||||
|
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
|
||||||
|
mediaRecorder.stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
isRecording.value = false;
|
||||||
|
cleanupStream();
|
||||||
|
};
|
||||||
|
|
||||||
|
const transcribeBlob = async (blob: Blob, mimeType: string) => {
|
||||||
|
if (blob.size < 800) {
|
||||||
|
options.onError('chat.voiceRecordTooShort');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
isTranscribing.value = true;
|
||||||
|
try {
|
||||||
|
const ext = mimeType.includes('mp4') ? 'm4a' : 'webm';
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('audio', blob, `recording.${ext}`);
|
||||||
|
|
||||||
|
const response = await fetch('/api/speech/transcribe', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { ...getAuthHeaders() },
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) {
|
||||||
|
const errMsg = payload?.error?.message || payload?.message || `Request failed (${response.status})`;
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = String(payload.text || '').trim();
|
||||||
|
if (!text) {
|
||||||
|
options.onError('chat.voiceRecordTooShort');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const prefix = baseText.trim();
|
||||||
|
options.onResult(prefix ? `${prefix} ${text}` : text);
|
||||||
|
} catch {
|
||||||
|
options.onError('chat.voiceTranscriptionFailed');
|
||||||
|
} finally {
|
||||||
|
isTranscribing.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const startRecording = async (existingText = '') => {
|
||||||
|
if (isBusy.value) return;
|
||||||
|
|
||||||
|
const unavailable = getVoiceUnavailableErrorKey();
|
||||||
|
if (unavailable) {
|
||||||
|
options.onError(unavailable);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
baseText = existingText;
|
||||||
|
|
||||||
|
try {
|
||||||
|
mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||||
|
} catch (err) {
|
||||||
|
const denied = err instanceof DOMException && (
|
||||||
|
err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError'
|
||||||
|
);
|
||||||
|
options.onError(denied ? 'chat.voicePermissionDenied' : 'chat.voiceTranscriptionFailed');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
chunks = [];
|
||||||
|
const mimeType = pickMimeType();
|
||||||
|
try {
|
||||||
|
mediaRecorder = mimeType
|
||||||
|
? new MediaRecorder(mediaStream, { mimeType })
|
||||||
|
: new MediaRecorder(mediaStream);
|
||||||
|
} catch {
|
||||||
|
cleanupStream();
|
||||||
|
options.onError('chat.voiceNotSupported');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
mediaRecorder.ondataavailable = (event) => {
|
||||||
|
if (event.data.size > 0) chunks.push(event.data);
|
||||||
|
};
|
||||||
|
|
||||||
|
mediaRecorder.onstop = async () => {
|
||||||
|
isRecording.value = false;
|
||||||
|
const type = mediaRecorder?.mimeType || mimeType || 'audio/webm';
|
||||||
|
const blob = new Blob(chunks, { type });
|
||||||
|
const shouldSkip = skipTranscription;
|
||||||
|
skipTranscription = false;
|
||||||
|
cleanupStream();
|
||||||
|
if (shouldSkip) return;
|
||||||
|
await transcribeBlob(blob, type);
|
||||||
|
};
|
||||||
|
|
||||||
|
mediaRecorder.onerror = () => {
|
||||||
|
isRecording.value = false;
|
||||||
|
cleanupStream();
|
||||||
|
options.onError('chat.voiceTranscriptionFailed');
|
||||||
|
};
|
||||||
|
|
||||||
|
mediaRecorder.start();
|
||||||
|
isRecording.value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggle = (existingText = '') => {
|
||||||
|
if (isTranscribing.value) return;
|
||||||
|
if (isRecording.value) {
|
||||||
|
stopRecording();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void startRecording(existingText);
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancel = () => {
|
||||||
|
skipTranscription = true;
|
||||||
|
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
|
||||||
|
mediaRecorder.stop();
|
||||||
|
} else {
|
||||||
|
cleanupStream();
|
||||||
|
}
|
||||||
|
isRecording.value = false;
|
||||||
|
isTranscribing.value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
onBeforeUnmount(cancel);
|
||||||
|
|
||||||
|
return {
|
||||||
|
isRecording,
|
||||||
|
isTranscribing,
|
||||||
|
isSupported,
|
||||||
|
isBusy,
|
||||||
|
startRecording,
|
||||||
|
stopRecording,
|
||||||
|
toggle,
|
||||||
|
cancel,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,156 +0,0 @@
|
|||||||
import { ref, computed, onBeforeUnmount, type Ref } from 'vue';
|
|
||||||
|
|
||||||
export type SpeechRecognitionErrorKey =
|
|
||||||
| 'chat.voiceNotSupported'
|
|
||||||
| 'chat.voiceRequiresHttps'
|
|
||||||
| 'chat.voicePermissionDenied'
|
|
||||||
| 'chat.voiceNoSpeech'
|
|
||||||
| 'chat.voiceAudioCapture'
|
|
||||||
| 'chat.voiceNetworkError'
|
|
||||||
| 'chat.voiceServiceNotAllowed'
|
|
||||||
| 'chat.voiceRecognitionFailed';
|
|
||||||
|
|
||||||
type SpeechRecognitionCtor = new () => SpeechRecognition;
|
|
||||||
|
|
||||||
const getSpeechRecognitionCtor = (): SpeechRecognitionCtor | null => {
|
|
||||||
if (typeof window === 'undefined') return null;
|
|
||||||
const w = window as Window & {
|
|
||||||
SpeechRecognition?: SpeechRecognitionCtor;
|
|
||||||
webkitSpeechRecognition?: SpeechRecognitionCtor;
|
|
||||||
};
|
|
||||||
return w.SpeechRecognition || w.webkitSpeechRecognition || null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const mapLocaleToSpeechLang = (locale: string): string => {
|
|
||||||
const map: Record<string, string> = {
|
|
||||||
'zh-CN': 'zh-CN',
|
|
||||||
'zh-TW': 'zh-TW',
|
|
||||||
en: 'en-US',
|
|
||||||
th: 'th-TH',
|
|
||||||
};
|
|
||||||
return map[locale] || 'zh-CN';
|
|
||||||
};
|
|
||||||
|
|
||||||
const isSecureContextForSpeech = (): boolean => {
|
|
||||||
if (typeof window === 'undefined') return false;
|
|
||||||
if (window.isSecureContext) return true;
|
|
||||||
const host = window.location.hostname;
|
|
||||||
return host === 'localhost' || host === '127.0.0.1';
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 语音不可用时的提示 key;HTTPS/localhost 且浏览器有 API 时返回 null */
|
|
||||||
export const getVoiceUnavailableErrorKey = (): SpeechRecognitionErrorKey | null => {
|
|
||||||
if (!isSecureContextForSpeech()) return 'chat.voiceRequiresHttps';
|
|
||||||
if (!getSpeechRecognitionCtor()) return 'chat.voiceNotSupported';
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const mapErrorToKey = (error: string): SpeechRecognitionErrorKey => {
|
|
||||||
switch (error) {
|
|
||||||
case 'not-allowed':
|
|
||||||
return 'chat.voicePermissionDenied';
|
|
||||||
case 'service-not-allowed':
|
|
||||||
return 'chat.voiceServiceNotAllowed';
|
|
||||||
case 'no-speech':
|
|
||||||
return 'chat.voiceNoSpeech';
|
|
||||||
case 'audio-capture':
|
|
||||||
return 'chat.voiceAudioCapture';
|
|
||||||
case 'network':
|
|
||||||
return 'chat.voiceNetworkError';
|
|
||||||
default:
|
|
||||||
return 'chat.voiceRecognitionFailed';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export function useSpeechRecognition(options: {
|
|
||||||
lang: Ref<string>;
|
|
||||||
onResult: (text: string) => void;
|
|
||||||
onError: (key: SpeechRecognitionErrorKey) => void;
|
|
||||||
}) {
|
|
||||||
const isListening = ref(false);
|
|
||||||
const isSupported = computed(() => getVoiceUnavailableErrorKey() === null);
|
|
||||||
|
|
||||||
let recognition: SpeechRecognition | null = null;
|
|
||||||
let baseText = '';
|
|
||||||
|
|
||||||
const stop = () => {
|
|
||||||
if (recognition) {
|
|
||||||
try {
|
|
||||||
recognition.abort();
|
|
||||||
} catch {
|
|
||||||
// ignore abort errors
|
|
||||||
}
|
|
||||||
recognition = null;
|
|
||||||
}
|
|
||||||
isListening.value = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
const start = (existingText = '') => {
|
|
||||||
if (isListening.value) return;
|
|
||||||
|
|
||||||
const unavailable = getVoiceUnavailableErrorKey();
|
|
||||||
if (unavailable) {
|
|
||||||
options.onError(unavailable);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const Ctor = getSpeechRecognitionCtor()!;
|
|
||||||
|
|
||||||
stop();
|
|
||||||
baseText = existingText;
|
|
||||||
|
|
||||||
const instance = new Ctor();
|
|
||||||
instance.continuous = true;
|
|
||||||
instance.interimResults = true;
|
|
||||||
instance.lang = mapLocaleToSpeechLang(options.lang.value);
|
|
||||||
|
|
||||||
instance.onstart = () => {
|
|
||||||
isListening.value = true;
|
|
||||||
};
|
|
||||||
|
|
||||||
instance.onresult = (event: SpeechRecognitionEvent) => {
|
|
||||||
let sessionTranscript = '';
|
|
||||||
for (let i = 0; i < event.results.length; i++) {
|
|
||||||
sessionTranscript += event.results[i]?.[0]?.transcript || '';
|
|
||||||
}
|
|
||||||
options.onResult(`${baseText}${sessionTranscript}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
instance.onerror = (event: SpeechRecognitionErrorEvent) => {
|
|
||||||
if (event.error === 'aborted') return;
|
|
||||||
options.onError(mapErrorToKey(event.error));
|
|
||||||
stop();
|
|
||||||
};
|
|
||||||
|
|
||||||
instance.onend = () => {
|
|
||||||
isListening.value = false;
|
|
||||||
recognition = null;
|
|
||||||
};
|
|
||||||
|
|
||||||
recognition = instance;
|
|
||||||
try {
|
|
||||||
recognition.start();
|
|
||||||
} catch {
|
|
||||||
options.onError('chat.voiceRecognitionFailed');
|
|
||||||
stop();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const toggle = (existingText = '') => {
|
|
||||||
if (isListening.value) {
|
|
||||||
stop();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
start(existingText);
|
|
||||||
};
|
|
||||||
|
|
||||||
onBeforeUnmount(stop);
|
|
||||||
|
|
||||||
return {
|
|
||||||
isListening,
|
|
||||||
isSupported,
|
|
||||||
start,
|
|
||||||
stop,
|
|
||||||
toggle,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -59,6 +59,7 @@ export const config = {
|
|||||||
questions: true, // 常用问题
|
questions: true, // 常用问题
|
||||||
wecom: true, // 企业微信
|
wecom: true, // 企业微信
|
||||||
permissions: true, // 应用权限
|
permissions: true, // 应用权限
|
||||||
|
platform_apps: true, // 平台应用说明
|
||||||
requests: true, // 审批权限
|
requests: true, // 审批权限
|
||||||
reports: true, // 数据报表
|
reports: true, // 数据报表
|
||||||
schedules: true, // 定时任务
|
schedules: true, // 定时任务
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { useI18n } from 'vue-i18n';
|
|||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
import {
|
import {
|
||||||
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
|
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
|
||||||
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2,
|
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow
|
||||||
} from 'lucide-vue-next';
|
} from 'lucide-vue-next';
|
||||||
import type { Component } from 'vue';
|
import type { Component } from 'vue';
|
||||||
import { config } from '@/config';
|
import { config } from '@/config';
|
||||||
@@ -33,6 +33,7 @@ const iconMap: Record<AdminModuleId, Component> = {
|
|||||||
questions: MessageCircleQuestion,
|
questions: MessageCircleQuestion,
|
||||||
wecom: Link2,
|
wecom: Link2,
|
||||||
permissions: Users,
|
permissions: Users,
|
||||||
|
platform_apps: AppWindow,
|
||||||
requests: ShieldCheck,
|
requests: ShieldCheck,
|
||||||
reports: BarChart2,
|
reports: BarChart2,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export interface AdminModuleMeta {
|
|||||||
|
|
||||||
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
|
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
|
||||||
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
|
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
|
||||||
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'reports',
|
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'reports',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||||
@@ -30,6 +30,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
|||||||
{ id: 'questions', routeName: 'AdminQuestions', path: 'questions', labelKey: 'admin.nav.questions', configKey: 'questions' },
|
{ 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: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' },
|
||||||
{ id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' },
|
{ id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' },
|
||||||
|
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
|
||||||
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
|
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,328 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted, computed } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Plus, Trash2, Edit2, Play, FileText, Image as ImageIcon } from 'lucide-vue-next';
|
||||||
|
import { listAdminAgents, listAdminAgentGuides, createAdminAgentGuide, updateAdminAgentGuide, deleteAdminAgentGuide, uploadAdminAgentGuideFile } from '@/api/admin';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
const agents = ref<any[]>([]);
|
||||||
|
const selectedAgentId = ref<number | ''>('');
|
||||||
|
const guides = ref<any[]>([]);
|
||||||
|
const isLoading = ref(false);
|
||||||
|
|
||||||
|
const isModalOpen = ref(false);
|
||||||
|
const isEditing = ref(false);
|
||||||
|
const editingId = ref<number | null>(null);
|
||||||
|
|
||||||
|
const form = ref({
|
||||||
|
file_name: '',
|
||||||
|
file_path: '',
|
||||||
|
file_type: 'pdf',
|
||||||
|
file_size: 0,
|
||||||
|
remark: '',
|
||||||
|
sort_order: 0,
|
||||||
|
status: 1
|
||||||
|
});
|
||||||
|
|
||||||
|
const isUploading = ref(false);
|
||||||
|
const uploadError = ref('');
|
||||||
|
|
||||||
|
const fetchAgents = async () => {
|
||||||
|
try {
|
||||||
|
agents.value = await listAdminAgents();
|
||||||
|
if (agents.value.length > 0) {
|
||||||
|
selectedAgentId.value = agents.value[0].id;
|
||||||
|
await fetchGuides();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch agents:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchGuides = async () => {
|
||||||
|
if (!selectedAgentId.value) return;
|
||||||
|
isLoading.value = true;
|
||||||
|
try {
|
||||||
|
guides.value = await listAdminAgentGuides(selectedAgentId.value as number);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch guides:', error);
|
||||||
|
} finally {
|
||||||
|
isLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const currentAgentName = computed(() => {
|
||||||
|
const agent = agents.value.find(a => a.id === selectedAgentId.value);
|
||||||
|
return agent ? agent.name : '-';
|
||||||
|
});
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
fetchAgents();
|
||||||
|
});
|
||||||
|
|
||||||
|
const openCreateModal = () => {
|
||||||
|
isEditing.value = false;
|
||||||
|
editingId.value = null;
|
||||||
|
form.value = {
|
||||||
|
file_name: '',
|
||||||
|
file_path: '',
|
||||||
|
file_type: 'pdf',
|
||||||
|
file_size: 0,
|
||||||
|
remark: '',
|
||||||
|
sort_order: 0,
|
||||||
|
status: 1
|
||||||
|
};
|
||||||
|
uploadError.value = '';
|
||||||
|
isModalOpen.value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const openEditModal = (guide: any) => {
|
||||||
|
isEditing.value = true;
|
||||||
|
editingId.value = guide.id;
|
||||||
|
form.value = {
|
||||||
|
file_name: guide.file_name,
|
||||||
|
file_path: guide.file_path,
|
||||||
|
file_type: guide.file_type,
|
||||||
|
file_size: guide.file_size,
|
||||||
|
remark: guide.remark,
|
||||||
|
sort_order: guide.sort_order,
|
||||||
|
status: guide.status
|
||||||
|
};
|
||||||
|
uploadError.value = '';
|
||||||
|
isModalOpen.value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileUpload = async (event: Event) => {
|
||||||
|
const file = (event.target as HTMLInputElement).files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
isUploading.value = true;
|
||||||
|
uploadError.value = '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await uploadAdminAgentGuideFile(file);
|
||||||
|
form.value.file_path = res.file_path;
|
||||||
|
form.value.file_type = res.file_type;
|
||||||
|
form.value.file_size = res.file_size;
|
||||||
|
if (!form.value.file_name) {
|
||||||
|
form.value.file_name = res.file_name;
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
uploadError.value = err.message || '上传失败';
|
||||||
|
} finally {
|
||||||
|
isUploading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitForm = async () => {
|
||||||
|
if (!selectedAgentId.value || !form.value.file_path || !form.value.file_name) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isEditing.value && editingId.value) {
|
||||||
|
await updateAdminAgentGuide(editingId.value, form.value);
|
||||||
|
} else {
|
||||||
|
await createAdminAgentGuide({
|
||||||
|
...form.value,
|
||||||
|
agent_id: selectedAgentId.value
|
||||||
|
});
|
||||||
|
}
|
||||||
|
isModalOpen.value = false;
|
||||||
|
await fetchGuides();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to save guide:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteGuide = async (id: number) => {
|
||||||
|
if (!confirm('确定要删除该指南吗?删除后不可恢复。')) return;
|
||||||
|
try {
|
||||||
|
await deleteAdminAgentGuide(id);
|
||||||
|
await fetchGuides();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete guide:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleStatus = async (guide: any) => {
|
||||||
|
try {
|
||||||
|
await updateAdminAgentGuide(guide.id, { status: guide.status === 1 ? 0 : 1 });
|
||||||
|
await fetchGuides();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to update status:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatSize = (bytes: number) => {
|
||||||
|
if (!bytes) return '0 B';
|
||||||
|
const k = 1024;
|
||||||
|
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||||
|
};
|
||||||
|
|
||||||
|
const getIcon = (type: string) => {
|
||||||
|
if (type === 'video') return Play;
|
||||||
|
if (type === 'pdf') return FileText;
|
||||||
|
return ImageIcon;
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col h-full gap-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 class="text-2xl font-bold tracking-tight text-default">
|
||||||
|
{{ t('admin.nav.platformApps') }}
|
||||||
|
</h2>
|
||||||
|
<p class="text-sm text-muted mt-1">
|
||||||
|
管理应用的新手指南资料(支持视频、PDF等)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="surface-panel rounded-2xl p-6 shadow-sm border border-subtle flex-1 flex flex-col gap-6">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<label class="font-medium text-sm text-default">选择应用:</label>
|
||||||
|
<select v-model="selectedAgentId" class="input-field w-64" @change="fetchGuides">
|
||||||
|
<option v-for="agent in agents" :key="agent.id" :value="agent.id">
|
||||||
|
{{ agent.name }}
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<button v-if="selectedAgentId" type="button" class="btn-primary" @click="openCreateModal">
|
||||||
|
<Plus class="w-5 h-5 mr-1" />
|
||||||
|
<span>添加指南</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="isLoading" class="flex items-center justify-center py-10">
|
||||||
|
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="!selectedAgentId" class="flex flex-col items-center justify-center py-20 text-muted">
|
||||||
|
请先选择一个应用
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="guides.length === 0" class="flex flex-col items-center justify-center py-20 text-muted">
|
||||||
|
该应用暂无新手指南资料
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="overflow-x-auto rounded-xl border border-subtle">
|
||||||
|
<table class="w-full text-left text-sm whitespace-nowrap">
|
||||||
|
<thead class="bg-muted text-muted uppercase text-xs font-semibold tracking-wider border-b border-subtle">
|
||||||
|
<tr>
|
||||||
|
<th class="px-6 py-4">类型</th>
|
||||||
|
<th class="px-6 py-4">资料名称</th>
|
||||||
|
<th class="px-6 py-4">Agent应用</th>
|
||||||
|
<th class="px-6 py-4">文件大小</th>
|
||||||
|
<th class="px-6 py-4">排序</th>
|
||||||
|
<th class="px-6 py-4">状态</th>
|
||||||
|
<th class="px-6 py-4 text-right">操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="divide-y divide-subtle">
|
||||||
|
<tr v-for="guide in guides" :key="guide.id" class="hover:bg-muted/50 transition-colors">
|
||||||
|
<td class="px-6 py-4">
|
||||||
|
<component :is="getIcon(guide.file_type)" class="w-5 h-5 text-muted" />
|
||||||
|
</td>
|
||||||
|
<td class="px-6 py-4">
|
||||||
|
<div class="font-medium text-default">{{ guide.file_name }}</div>
|
||||||
|
<div class="text-xs text-muted mt-1 truncate max-w-[200px]">{{ guide.remark }}</div>
|
||||||
|
</td>
|
||||||
|
<td class="px-6 py-4">
|
||||||
|
<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-brand-50 text-brand-700 border border-brand-100">
|
||||||
|
{{ currentAgentName }}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td class="px-6 py-4 text-muted">{{ formatSize(guide.file_size) }}</td>
|
||||||
|
<td class="px-6 py-4 text-muted">{{ guide.sort_order }}</td>
|
||||||
|
<td class="px-6 py-4">
|
||||||
|
<button
|
||||||
|
class="px-2 py-1 text-xs font-medium rounded-full transition-colors"
|
||||||
|
:class="guide.status === 1 ? 'bg-green-100 text-green-700 hover:bg-green-200' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
|
||||||
|
@click="toggleStatus(guide)"
|
||||||
|
>
|
||||||
|
{{ guide.status === 1 ? '已启用' : '已禁用' }}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
<td class="px-6 py-4 text-right space-x-2">
|
||||||
|
<button type="button" class="btn-icon-ds" @click="openEditModal(guide)" title="编辑">
|
||||||
|
<Edit2 class="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn-icon-ds text-red-500 hover:bg-red-50" @click="deleteGuide(guide.id)" title="删除">
|
||||||
|
<Trash2 class="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Modal -->
|
||||||
|
<div v-if="isModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
|
||||||
|
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-lg overflow-hidden flex flex-col max-h-[90vh]">
|
||||||
|
<div class="px-6 py-4 border-b border-subtle flex justify-between items-center">
|
||||||
|
<h3 class="text-lg font-bold text-default">{{ isEditing ? '编辑指南' : '添加指南' }}</h3>
|
||||||
|
<button @click="isModalOpen = false" class="text-muted hover:text-default text-xl leading-none">×</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="p-6 overflow-y-auto space-y-4">
|
||||||
|
<div v-if="!isEditing" class="space-y-2">
|
||||||
|
<label class="text-sm font-medium text-default">上传文件</label>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept="video/mp4,video/webm,application/pdf,image/png,image/jpeg"
|
||||||
|
class="w-full text-sm text-muted file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
|
||||||
|
@change="handleFileUpload"
|
||||||
|
/>
|
||||||
|
<div v-if="isUploading" class="text-sm text-blue-600 mt-2 flex items-center gap-2">
|
||||||
|
<div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div> 上传中...
|
||||||
|
</div>
|
||||||
|
<div v-if="uploadError" class="text-sm text-red-500 mt-2">{{ uploadError }}</div>
|
||||||
|
<div v-if="form.file_path && !isUploading" class="text-sm text-green-600 mt-2">已上传文件就绪</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-sm font-medium text-default">资料名称</label>
|
||||||
|
<input v-model="form.file_name" type="text" class="input-field w-full" placeholder="如:人事助手使用手册" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-sm font-medium text-default">备注说明</label>
|
||||||
|
<textarea v-model="form.remark" class="input-field w-full h-20" placeholder="简要说明..."></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-2 gap-4">
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-sm font-medium text-default">排序权重</label>
|
||||||
|
<input v-model.number="form.sort_order" type="number" class="input-field w-full" />
|
||||||
|
<p class="text-xs text-muted">数值越小越靠前</p>
|
||||||
|
</div>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-sm font-medium text-default">状态</label>
|
||||||
|
<select v-model="form.status" class="input-field w-full">
|
||||||
|
<option :value="1">启用</option>
|
||||||
|
<option :value="0">禁用</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="px-6 py-4 border-t border-subtle bg-muted flex justify-end gap-3">
|
||||||
|
<button type="button" class="btn-secondary" @click="isModalOpen = false">取消</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn-primary"
|
||||||
|
@click="submitForm"
|
||||||
|
:disabled="isUploading || !form.file_path || !form.file_name"
|
||||||
|
>
|
||||||
|
保存
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -16,6 +16,7 @@ export type AdminModuleId =
|
|||||||
| 'wecom'
|
| 'wecom'
|
||||||
| 'permissions'
|
| 'permissions'
|
||||||
| 'requests'
|
| 'requests'
|
||||||
|
| 'platform_apps'
|
||||||
| 'reports';
|
| 'reports';
|
||||||
|
|
||||||
export type AdminReportTableId =
|
export type AdminReportTableId =
|
||||||
|
|||||||
+23
-6
@@ -1,4 +1,4 @@
|
|||||||
import { createI18n } from 'vue-i18n';
|
import { createI18n } from 'vue-i18n';
|
||||||
|
|
||||||
const messages = {
|
const messages = {
|
||||||
'en': {
|
'en': {
|
||||||
@@ -1267,6 +1267,9 @@ const messages = {
|
|||||||
voiceNetworkError: 'Voice recognition network error',
|
voiceNetworkError: 'Voice recognition network error',
|
||||||
voiceServiceNotAllowed: 'Voice recognition service is not allowed',
|
voiceServiceNotAllowed: 'Voice recognition service is not allowed',
|
||||||
voiceRecognitionFailed: 'Voice recognition failed. Please try again',
|
voiceRecognitionFailed: 'Voice recognition failed. Please try again',
|
||||||
|
voiceTranscribing: 'Transcribing...',
|
||||||
|
voiceRecordTooShort: 'Recording too short or no speech detected',
|
||||||
|
voiceTranscriptionFailed: 'Speech recognition failed. Please try again',
|
||||||
collapseBrowser: 'Collapse Browser',
|
collapseBrowser: 'Collapse Browser',
|
||||||
openBrowser: 'Open Browser',
|
openBrowser: 'Open Browser',
|
||||||
kb: {
|
kb: {
|
||||||
@@ -1431,7 +1434,8 @@ const messages = {
|
|||||||
currentPassword: 'Current Password',
|
currentPassword: 'Current Password',
|
||||||
newPassword: 'New Password',
|
newPassword: 'New Password',
|
||||||
confirmPassword: 'Confirm Password',
|
confirmPassword: 'Confirm Password',
|
||||||
changePassword: 'Change Password'
|
changePassword: 'Change Password',
|
||||||
|
changePasswordContactAdmin: 'Please contact the administrator to change your password.'
|
||||||
},
|
},
|
||||||
feedback: {
|
feedback: {
|
||||||
title: 'Feedback',
|
title: 'Feedback',
|
||||||
@@ -1689,7 +1693,7 @@ const messages = {
|
|||||||
title: '文件预览',
|
title: '文件预览',
|
||||||
download: '下载文件',
|
download: '下载文件',
|
||||||
downloading: '下载中...',
|
downloading: '下载中...',
|
||||||
tooLarge: '文件较大,暂不支持在线预览,请直接点击上方“下载文件”获取原文件。',
|
tooLarge: '文件较大,暂不支持在线预览。',
|
||||||
previewFailed: '预览失败:',
|
previewFailed: '预览失败:',
|
||||||
msg: {
|
msg: {
|
||||||
downloadFailed: '下载失败: {reason}',
|
downloadFailed: '下载失败: {reason}',
|
||||||
@@ -1963,6 +1967,7 @@ const messages = {
|
|||||||
questions: '常用问题',
|
questions: '常用问题',
|
||||||
wecom: '企业微信',
|
wecom: '企业微信',
|
||||||
permissions: '应用权限',
|
permissions: '应用权限',
|
||||||
|
platformApps: '平台应用说明',
|
||||||
requests: '权限审批',
|
requests: '权限审批',
|
||||||
reports: '数据报表',
|
reports: '数据报表',
|
||||||
schedules: '排程管理'
|
schedules: '排程管理'
|
||||||
@@ -2737,6 +2742,9 @@ const messages = {
|
|||||||
voiceNetworkError: '语音识别网络错误',
|
voiceNetworkError: '语音识别网络错误',
|
||||||
voiceServiceNotAllowed: '不允许使用语音识别服务',
|
voiceServiceNotAllowed: '不允许使用语音识别服务',
|
||||||
voiceRecognitionFailed: '语音识别失败,请重试',
|
voiceRecognitionFailed: '语音识别失败,请重试',
|
||||||
|
voiceTranscribing: '正在识别…',
|
||||||
|
voiceRecordTooShort: '录音太短或未检测到语音',
|
||||||
|
voiceTranscriptionFailed: '语音识别失败,请重试',
|
||||||
collapseBrowser: '收起浏览器',
|
collapseBrowser: '收起浏览器',
|
||||||
openBrowser: '打开浏览器',
|
openBrowser: '打开浏览器',
|
||||||
kb: {
|
kb: {
|
||||||
@@ -2901,7 +2909,8 @@ const messages = {
|
|||||||
currentPassword: '当前密码',
|
currentPassword: '当前密码',
|
||||||
newPassword: '新密码',
|
newPassword: '新密码',
|
||||||
confirmPassword: '确认密码',
|
confirmPassword: '确认密码',
|
||||||
changePassword: '修改密码'
|
changePassword: '修改密码',
|
||||||
|
changePasswordContactAdmin: '请联系管理员修改'
|
||||||
},
|
},
|
||||||
feedback: {
|
feedback: {
|
||||||
title: '意见反馈',
|
title: '意见反馈',
|
||||||
@@ -4066,6 +4075,9 @@ const messages = {
|
|||||||
voiceNetworkError: '語音辨識網路錯誤',
|
voiceNetworkError: '語音辨識網路錯誤',
|
||||||
voiceServiceNotAllowed: '不允許使用語音辨識服務',
|
voiceServiceNotAllowed: '不允許使用語音辨識服務',
|
||||||
voiceRecognitionFailed: '語音辨識失敗,請重試',
|
voiceRecognitionFailed: '語音辨識失敗,請重試',
|
||||||
|
voiceTranscribing: '正在辨識…',
|
||||||
|
voiceRecordTooShort: '錄音太短或未偵測到語音',
|
||||||
|
voiceTranscriptionFailed: '語音辨識失敗,請重試',
|
||||||
collapseBrowser: '收起瀏覽器',
|
collapseBrowser: '收起瀏覽器',
|
||||||
openBrowser: '打開瀏覽器',
|
openBrowser: '打開瀏覽器',
|
||||||
kb: {
|
kb: {
|
||||||
@@ -4230,7 +4242,8 @@ const messages = {
|
|||||||
currentPassword: '當前密碼',
|
currentPassword: '當前密碼',
|
||||||
newPassword: '新密碼',
|
newPassword: '新密碼',
|
||||||
confirmPassword: '確認密碼',
|
confirmPassword: '確認密碼',
|
||||||
changePassword: '修改密碼'
|
changePassword: '修改密碼',
|
||||||
|
changePasswordContactAdmin: '請聯繫管理員修改'
|
||||||
},
|
},
|
||||||
feedback: {
|
feedback: {
|
||||||
title: '意見反饋',
|
title: '意見反饋',
|
||||||
@@ -5312,6 +5325,9 @@ const messages = {
|
|||||||
voiceNetworkError: 'เกิดข้อผิดพลาดเครือข่ายในการรู้จำเสียง',
|
voiceNetworkError: 'เกิดข้อผิดพลาดเครือข่ายในการรู้จำเสียง',
|
||||||
voiceServiceNotAllowed: 'ไม่อนุญาตให้ใช้บริการรู้จำเสียง',
|
voiceServiceNotAllowed: 'ไม่อนุญาตให้ใช้บริการรู้จำเสียง',
|
||||||
voiceRecognitionFailed: 'การรู้จำเสียงล้มเหลว โปรดลองอีกครั้ง',
|
voiceRecognitionFailed: 'การรู้จำเสียงล้มเหลว โปรดลองอีกครั้ง',
|
||||||
|
voiceTranscribing: 'กำลังแปลงเสียง...',
|
||||||
|
voiceRecordTooShort: 'การบันทึกสั้นเกินไปหรือไม่พบเสียงพูด',
|
||||||
|
voiceTranscriptionFailed: 'การรู้จำเสียงล้มเหลว โปรดลองอีกครั้ง',
|
||||||
collapseBrowser: 'ย่อเบราว์เซอร์',
|
collapseBrowser: 'ย่อเบราว์เซอร์',
|
||||||
openBrowser: 'เปิดเบราว์เซอร์',
|
openBrowser: 'เปิดเบราว์เซอร์',
|
||||||
kb: {
|
kb: {
|
||||||
@@ -5476,7 +5492,8 @@ const messages = {
|
|||||||
currentPassword: 'รหัสผ่านปัจจุบัน',
|
currentPassword: 'รหัสผ่านปัจจุบัน',
|
||||||
newPassword: 'รหัสผ่านใหม่',
|
newPassword: 'รหัสผ่านใหม่',
|
||||||
confirmPassword: 'ยืนยันรหัสผ่าน',
|
confirmPassword: 'ยืนยันรหัสผ่าน',
|
||||||
changePassword: 'เปลี่ยนรหัสผ่าน'
|
changePassword: 'เปลี่ยนรหัสผ่าน',
|
||||||
|
changePasswordContactAdmin: 'กรุณาติดต่อผู้ดูแลระบบเพื่อเปลี่ยนรหัสผ่าน'
|
||||||
},
|
},
|
||||||
feedback: {
|
feedback: {
|
||||||
title: 'ข้อเสนอแนะ',
|
title: 'ข้อเสนอแนะ',
|
||||||
|
|||||||
-45
@@ -1,45 +0,0 @@
|
|||||||
interface SpeechRecognitionAlternative {
|
|
||||||
transcript: string;
|
|
||||||
confidence: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SpeechRecognitionResult {
|
|
||||||
readonly isFinal: boolean;
|
|
||||||
readonly length: number;
|
|
||||||
item(index: number): SpeechRecognitionAlternative;
|
|
||||||
[index: number]: SpeechRecognitionAlternative;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SpeechRecognitionResultList {
|
|
||||||
readonly length: number;
|
|
||||||
item(index: number): SpeechRecognitionResult;
|
|
||||||
[index: number]: SpeechRecognitionResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SpeechRecognitionEvent extends Event {
|
|
||||||
readonly resultIndex: number;
|
|
||||||
readonly results: SpeechRecognitionResultList;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SpeechRecognitionErrorEvent extends Event {
|
|
||||||
readonly error: string;
|
|
||||||
readonly message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SpeechRecognition extends EventTarget {
|
|
||||||
continuous: boolean;
|
|
||||||
interimResults: boolean;
|
|
||||||
lang: string;
|
|
||||||
start(): void;
|
|
||||||
stop(): void;
|
|
||||||
abort(): void;
|
|
||||||
onstart: ((this: SpeechRecognition, ev: Event) => void) | null;
|
|
||||||
onend: ((this: SpeechRecognition, ev: Event) => void) | null;
|
|
||||||
onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null;
|
|
||||||
onerror: ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => void) | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Window {
|
|
||||||
SpeechRecognition?: new () => SpeechRecognition;
|
|
||||||
webkitSpeechRecognition?: new () => SpeechRecognition;
|
|
||||||
}
|
|
||||||
+145
-16
@@ -11,7 +11,7 @@
|
|||||||
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
|
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { useChat } from '../composables/useChat';
|
import { useChat } from '../composables/useChat';
|
||||||
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, Briefcase, History, Sun, Moon, CalendarDays, Building, Paperclip, Link2 } from 'lucide-vue-next';
|
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, Briefcase, History, Sun, Moon, CalendarDays, Building, Paperclip, Link2, BookOpen, FileText, Play, Image as ImageIcon } from 'lucide-vue-next';
|
||||||
import LocaleToggleButton from '../components/LocaleToggleButton.vue';
|
import LocaleToggleButton from '../components/LocaleToggleButton.vue';
|
||||||
import { marked } from 'marked';
|
import { marked } from 'marked';
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
@@ -21,7 +21,7 @@ import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
|
|||||||
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
|
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
|
||||||
import { useMessage } from '../composables/useMessage';
|
import { useMessage } from '../composables/useMessage';
|
||||||
import { useIsMobile } from '../composables/useIsMobile';
|
import { useIsMobile } from '../composables/useIsMobile';
|
||||||
import { getVoiceUnavailableErrorKey, useSpeechRecognition } from '../composables/useSpeechRecognition';
|
import { getVoiceUnavailableErrorKey, useAudioTranscription } from '../composables/useAudioTranscription';
|
||||||
import { useTheme } from '../composables/useTheme';
|
import { useTheme } from '../composables/useTheme';
|
||||||
import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth';
|
import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth';
|
||||||
import { copyTextToClipboard } from '../utils/clipboard';
|
import { copyTextToClipboard } from '../utils/clipboard';
|
||||||
@@ -45,6 +45,7 @@ import {
|
|||||||
submitLeaveWorkflow,
|
submitLeaveWorkflow,
|
||||||
getUserAgent,
|
getUserAgent,
|
||||||
listUserAgents,
|
listUserAgents,
|
||||||
|
listAgentGuides,
|
||||||
} from '../api/user';
|
} from '../api/user';
|
||||||
|
|
||||||
const { t, locale } = useI18n();
|
const { t, locale } = useI18n();
|
||||||
@@ -664,11 +665,11 @@ const copiedIndex = ref<number | null>(null);
|
|||||||
const { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage } = useChat();
|
const { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage } = useChat();
|
||||||
const input = ref('');
|
const input = ref('');
|
||||||
const {
|
const {
|
||||||
isListening: isVoiceListening,
|
isRecording: isVoiceRecording,
|
||||||
|
isTranscribing: isVoiceTranscribing,
|
||||||
toggle: toggleVoiceInput,
|
toggle: toggleVoiceInput,
|
||||||
stop: stopVoiceInput,
|
cancel: cancelVoiceInput,
|
||||||
} = useSpeechRecognition({
|
} = useAudioTranscription({
|
||||||
lang: locale,
|
|
||||||
onResult: (text) => {
|
onResult: (text) => {
|
||||||
input.value = text;
|
input.value = text;
|
||||||
},
|
},
|
||||||
@@ -677,8 +678,15 @@ const {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// HTTPS 全站就绪后改为 true,恢复硅基 ASR 录音识别(useAudioTranscription)
|
||||||
|
const VOICE_INPUT_ENABLED = false;
|
||||||
|
|
||||||
const handleVoiceFeatureClick = () => {
|
const handleVoiceFeatureClick = () => {
|
||||||
if (isThinking.value) return;
|
if (!VOICE_INPUT_ENABLED) {
|
||||||
|
msg.info(t('chat.devComingSoon'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (isThinking.value || isVoiceTranscribing.value) return;
|
||||||
const unavailable = getVoiceUnavailableErrorKey();
|
const unavailable = getVoiceUnavailableErrorKey();
|
||||||
if (unavailable) {
|
if (unavailable) {
|
||||||
msg.warning(t(unavailable));
|
msg.warning(t(unavailable));
|
||||||
@@ -688,12 +696,37 @@ const handleVoiceFeatureClick = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
watch(isThinking, (thinking) => {
|
watch(isThinking, (thinking) => {
|
||||||
if (thinking) stopVoiceInput();
|
if (thinking) cancelVoiceInput();
|
||||||
});
|
});
|
||||||
|
|
||||||
const currentAgent = ref<any>(null);
|
const currentAgent = ref<any>(null);
|
||||||
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
|
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
|
||||||
const showGeneralFeedbackDialog = ref(false);
|
const showGeneralFeedbackDialog = ref(false);
|
||||||
|
|
||||||
|
const agentGuides = ref<any[]>([]);
|
||||||
|
const showGuideModal = ref(false);
|
||||||
|
const activeGuideId = ref<number | null>(null);
|
||||||
|
const activeGuide = computed(() => agentGuides.value.find(g => g.id === activeGuideId.value));
|
||||||
|
|
||||||
|
const loadAgentGuides = async () => {
|
||||||
|
try {
|
||||||
|
const res = await listAgentGuides(currentAgentId.value || 0);
|
||||||
|
agentGuides.value = res || [];
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to load agent guides:', error);
|
||||||
|
agentGuides.value = [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const showGuideSidebar = ref(false);
|
||||||
|
|
||||||
|
const openGuideModal = () => {
|
||||||
|
if (agentGuides.value.length > 0) {
|
||||||
|
activeGuideId.value = agentGuides.value[0].id;
|
||||||
|
showGuideModal.value = true;
|
||||||
|
showGuideSidebar.value = false; // 默认收起
|
||||||
|
}
|
||||||
|
};
|
||||||
const showDeleteConfirmDialog = ref(false);
|
const showDeleteConfirmDialog = ref(false);
|
||||||
const deleteConfirmMessage = ref('');
|
const deleteConfirmMessage = ref('');
|
||||||
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
|
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
|
||||||
@@ -2415,6 +2448,7 @@ const startNewChat = () => {
|
|||||||
const loadAgent = async () => {
|
const loadAgent = async () => {
|
||||||
try {
|
try {
|
||||||
currentAgent.value = await getUserAgent(currentAgentId.value);
|
currentAgent.value = await getUserAgent(currentAgentId.value);
|
||||||
|
await loadAgentGuides();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof BusinessError && e.status === 403) {
|
if (e instanceof BusinessError && e.status === 403) {
|
||||||
msg.error(t('workspace.permission.denied') || 'Access denied');
|
msg.error(t('workspace.permission.denied') || 'Access denied');
|
||||||
@@ -2423,6 +2457,7 @@ const loadAgent = async () => {
|
|||||||
}
|
}
|
||||||
console.error('Failed to load agent', e);
|
console.error('Failed to load agent', e);
|
||||||
currentAgent.value = { name: t('workspace.unknownAgent') };
|
currentAgent.value = { name: t('workspace.unknownAgent') };
|
||||||
|
agentGuides.value = [];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -2484,7 +2519,7 @@ const syncChatStateForRoute = async () => {
|
|||||||
|
|
||||||
const syncToken = ++routeSyncToken;
|
const syncToken = ++routeSyncToken;
|
||||||
resetChatStateForAgentChange();
|
resetChatStateForAgentChange();
|
||||||
stopVoiceInput();
|
cancelVoiceInput();
|
||||||
setLastChatAgentId(agentId);
|
setLastChatAgentId(agentId);
|
||||||
syncOpenAgentRegistration();
|
syncOpenAgentRegistration();
|
||||||
|
|
||||||
@@ -2646,7 +2681,17 @@ const showChatRating = ref(false);
|
|||||||
{{ currentAgent?.name === '人事规章' ? 'HR' : 'AI' }}
|
{{ currentAgent?.name === '人事规章' ? 'HR' : 'AI' }}
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col justify-center min-w-0 flex-1 relative group">
|
<div class="flex flex-col justify-center min-w-0 flex-1 relative group">
|
||||||
<span class="font-bold text-primary truncate">{{ currentAgent?.name || 'AI' }}</span>
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="font-bold text-primary truncate">{{ currentAgent?.name || 'AI' }}</span>
|
||||||
|
<button
|
||||||
|
v-if="agentGuides.length > 0"
|
||||||
|
@click="openGuideModal"
|
||||||
|
class="flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold text-brand-700 bg-brand-100 border border-brand-300 rounded-lg hover:bg-brand-200 hover:border-brand-400 transition-all shadow-sm"
|
||||||
|
>
|
||||||
|
<BookOpen class="w-4 h-4" />
|
||||||
|
新手指南
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<span v-if="currentAgent?.name === '人事规章'" class="block text-[11px] text-muted mt-1 truncate cursor-help">
|
<span v-if="currentAgent?.name === '人事规章'" class="block text-[11px] text-muted mt-1 truncate cursor-help">
|
||||||
我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。
|
我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。
|
||||||
</span>
|
</span>
|
||||||
@@ -2776,6 +2821,14 @@ const showChatRating = ref(false);
|
|||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20">AI</div>
|
<div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20">AI</div>
|
||||||
<span class="text-sm font-semibold text-primary">{{ currentAgent?.name || 'AI' }}</span>
|
<span class="text-sm font-semibold text-primary">{{ currentAgent?.name || 'AI' }}</span>
|
||||||
|
<button
|
||||||
|
v-if="agentGuides.length > 0"
|
||||||
|
@click="openGuideModal"
|
||||||
|
class="flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold text-brand-700 bg-brand-100 border border-brand-300 rounded-lg hover:bg-brand-200 hover:border-brand-400 transition-all shadow-sm ml-1"
|
||||||
|
>
|
||||||
|
<BookOpen class="w-4 h-4" />
|
||||||
|
新手指南
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-1">
|
<div class="flex items-center gap-1">
|
||||||
<button @click="toggleMobileAgentPopover" class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft" :title="$t('chat.agents')">
|
<button @click="toggleMobileAgentPopover" class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft" :title="$t('chat.agents')">
|
||||||
@@ -3285,10 +3338,10 @@ const showChatRating = ref(false);
|
|||||||
v-model="input"
|
v-model="input"
|
||||||
@keydown.enter.prevent="handleSend"
|
@keydown.enter.prevent="handleSend"
|
||||||
rows="1"
|
rows="1"
|
||||||
:placeholder="isVoiceListening ? $t('chat.voiceListening') : $t('chat.askAnything')"
|
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')"
|
||||||
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent"
|
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent"
|
||||||
style="min-height: 44px; max-height: 220px;"
|
style="min-height: 44px; max-height: 220px;"
|
||||||
:disabled="isThinking"
|
:disabled="isThinking || isVoiceTranscribing"
|
||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
autocorrect="off"
|
autocorrect="off"
|
||||||
autocapitalize="off"
|
autocapitalize="off"
|
||||||
@@ -3323,12 +3376,13 @@ const showChatRating = ref(false);
|
|||||||
<button
|
<button
|
||||||
@click="handleVoiceFeatureClick"
|
@click="handleVoiceFeatureClick"
|
||||||
type="button"
|
type="button"
|
||||||
:disabled="isThinking"
|
:disabled="isThinking || isVoiceTranscribing"
|
||||||
:title="isVoiceListening ? $t('chat.voiceStop') : $t('chat.voiceFeature')"
|
:title="isVoiceRecording ? $t('chat.voiceStop') : isVoiceTranscribing ? $t('chat.voiceTranscribing') : $t('chat.voiceFeature')"
|
||||||
class="transition-colors disabled:cursor-not-allowed disabled:opacity-50"
|
class="transition-colors disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
:class="isVoiceListening ? 'text-red-500 animate-pulse' : 'text-muted hover:text-brand-600'"
|
:class="isVoiceRecording ? 'text-red-500 animate-pulse' : isVoiceTranscribing ? 'text-brand-500' : 'text-muted hover:text-brand-600'"
|
||||||
>
|
>
|
||||||
<Mic class="h-5 w-5" />
|
<Loader2 v-if="isVoiceTranscribing" class="h-5 w-5 animate-spin" />
|
||||||
|
<Mic v-else class="h-5 w-5" />
|
||||||
</button>
|
</button>
|
||||||
<div v-if="attachmentPolicy.anyEnabled" ref="attachmentMenuRef" class="relative">
|
<div v-if="attachmentPolicy.anyEnabled" ref="attachmentMenuRef" class="relative">
|
||||||
<button
|
<button
|
||||||
@@ -3683,6 +3737,81 @@ const showChatRating = ref(false);
|
|||||||
@cancel="closeDeleteConfirmDialog"
|
@cancel="closeDeleteConfirmDialog"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<Teleport to="body">
|
||||||
|
<!-- 新手指南 Modal -->
|
||||||
|
<div v-if="showGuideModal" class="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
|
||||||
|
<div class="bg-surface rounded-2xl shadow-xl w-full max-w-4xl overflow-hidden flex flex-col h-[85vh]">
|
||||||
|
<div class="px-6 py-4 border-b border-default flex justify-between items-center bg-surface shrink-0">
|
||||||
|
<h3 class="text-lg font-bold text-primary flex items-center gap-2">
|
||||||
|
<BookOpen class="w-5 h-5 text-brand-600" />
|
||||||
|
{{ currentAgent?.name }} - 新手指南
|
||||||
|
</h3>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<button @click="showGuideSidebar = !showGuideSidebar" class="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-brand-600 hover:text-brand-700 hover:bg-brand-50 rounded-lg transition-colors border border-transparent hover:border-brand-100">
|
||||||
|
<component :is="showGuideSidebar ? PanelLeftClose : PanelLeftOpen" class="w-4 h-4" />
|
||||||
|
{{ showGuideSidebar ? '收起目录' : '展开目录' }}
|
||||||
|
</button>
|
||||||
|
<div class="w-px h-5 bg-default"></div>
|
||||||
|
<button @click="showGuideModal = false" class="text-muted hover:text-primary transition-colors p-1 rounded-lg hover:bg-surface-soft">
|
||||||
|
<X class="w-6 h-6" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex-1 overflow-hidden flex min-h-0 relative">
|
||||||
|
<div
|
||||||
|
class="absolute md:relative z-10 h-full w-64 border-r border-default overflow-y-auto bg-surface-soft p-4 space-y-2 shrink-0 transition-transform duration-300 shadow-xl md:shadow-none"
|
||||||
|
:class="showGuideSidebar ? 'translate-x-0' : '-translate-x-full absolute'"
|
||||||
|
v-show="showGuideSidebar"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
v-for="guide in agentGuides"
|
||||||
|
:key="guide.id"
|
||||||
|
@click="activeGuideId = guide.id"
|
||||||
|
class="w-full text-left px-4 py-3 rounded-xl transition-all border"
|
||||||
|
:class="activeGuideId === guide.id ? 'bg-brand-50 border-brand-200 text-brand-700 shadow-sm' : 'bg-surface border-transparent hover:border-default hover:shadow-sm'"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2 mb-1">
|
||||||
|
<component :is="guide.file_type === 'video' ? Play : (guide.file_type === 'pdf' ? FileText : ImageIcon)" class="w-4 h-4 shrink-0" />
|
||||||
|
<span class="font-medium text-sm truncate">{{ guide.file_name }}</span>
|
||||||
|
</div>
|
||||||
|
<p v-if="guide.remark" class="text-xs opacity-70 truncate" :class="activeGuideId === guide.id ? 'text-brand-600' : 'text-muted'">{{ guide.remark }}</p>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex-1 bg-[#ebedf0] dark:bg-gray-900 flex items-center justify-center relative overflow-hidden">
|
||||||
|
<template v-if="activeGuide">
|
||||||
|
<video
|
||||||
|
v-if="activeGuide.file_type === 'video'"
|
||||||
|
:key="'video-' + activeGuide.id"
|
||||||
|
:src="activeGuide.file_url || activeGuide.file_path"
|
||||||
|
controls
|
||||||
|
autoplay
|
||||||
|
class="w-full h-full object-contain bg-black"
|
||||||
|
></video>
|
||||||
|
<iframe
|
||||||
|
v-else-if="activeGuide.file_type === 'pdf'"
|
||||||
|
:key="'pdf-' + activeGuide.id"
|
||||||
|
:src="activeGuide.file_url || activeGuide.file_path"
|
||||||
|
class="w-full h-full border-none bg-white"
|
||||||
|
></iframe>
|
||||||
|
<img
|
||||||
|
v-else
|
||||||
|
:key="'img-' + activeGuide.id"
|
||||||
|
:src="activeGuide.file_url || activeGuide.file_path"
|
||||||
|
class="max-w-full max-h-full object-contain"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<div v-else class="text-muted flex flex-col items-center gap-3">
|
||||||
|
<BookOpen class="w-12 h-12 opacity-20" />
|
||||||
|
<p class="text-sm">请选择左侧指南进行查阅</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
|
||||||
</template>
|
</template>
|
||||||
<style scoped>
|
<style scoped>
|
||||||
:deep(.chat-markdown details) {
|
:deep(.chat-markdown details) {
|
||||||
|
|||||||
@@ -746,6 +746,16 @@ const isProfileLoading = ref(false);
|
|||||||
const isProfileSaving = ref(false);
|
const isProfileSaving = ref(false);
|
||||||
const isProfileEditing = ref(false);
|
const isProfileEditing = ref(false);
|
||||||
const showPasswordModal = ref(false);
|
const showPasswordModal = ref(false);
|
||||||
|
// TODO(casdoor): set true when Casdoor change-password is ready
|
||||||
|
const CHANGE_PASSWORD_ENABLED = false;
|
||||||
|
|
||||||
|
const handleChangePasswordClick = () => {
|
||||||
|
if (!CHANGE_PASSWORD_ENABLED) {
|
||||||
|
msg.warning(t('profile.changePasswordContactAdmin'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showPasswordModal.value = true;
|
||||||
|
};
|
||||||
const profileUser = ref<ProfileForm>({
|
const profileUser = ref<ProfileForm>({
|
||||||
id: 0,
|
id: 0,
|
||||||
username: '',
|
username: '',
|
||||||
@@ -1446,11 +1456,12 @@ onBeforeUnmount(() => {
|
|||||||
<label class="text-xs font-semibold text-primary uppercase ml-1">{{ $t('login.password') }}</label>
|
<label class="text-xs font-semibold text-primary uppercase ml-1">{{ $t('login.password') }}</label>
|
||||||
<input v-model="loginPassword" type="password" class="input-field" :placeholder="$t('login.placeholder.password')" @keyup.enter="handleLogin" />
|
<input v-model="loginPassword" type="password" class="input-field" :placeholder="$t('login.placeholder.password')" @keyup.enter="handleLogin" />
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 30天免登录:仅控制 localStorage vs sessionStorage,与 Casdoor token 实际有效期不一致,且企微/Casdoor 登录不走此选项,暂不展示
|
||||||
<div class="flex items-center gap-2 mt-2">
|
<div class="flex items-center gap-2 mt-2">
|
||||||
<input type="checkbox" id="rememberMe" v-model="rememberMe" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500 w-4 h-4" />
|
<input type="checkbox" id="rememberMe" v-model="rememberMe" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500 w-4 h-4" />
|
||||||
<label for="rememberMe" class="text-sm text-secondary cursor-pointer select-none">{{ $t('login.rememberMe') }}</label>
|
<label for="rememberMe" class="text-sm text-secondary cursor-pointer select-none">{{ $t('login.rememberMe') }}</label>
|
||||||
</div>
|
</div>
|
||||||
|
-->
|
||||||
|
|
||||||
<button type="button" @click="handleLogin" class="btn-primary w-full py-3 text-base shadow-brand-500/40 hover:shadow-brand-500/50 transform hover:-translate-y-0.5 transition-all mt-4">
|
<button type="button" @click="handleLogin" class="btn-primary w-full py-3 text-base shadow-brand-500/40 hover:shadow-brand-500/50 transform hover:-translate-y-0.5 transition-all mt-4">
|
||||||
{{ $t('login.submit') }}
|
{{ $t('login.submit') }}
|
||||||
@@ -1680,13 +1691,13 @@ onBeforeUnmount(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!isMobile" class="flex shrink-0 items-center gap-2 self-start lg:ml-6">
|
<div v-if="!isMobile" class="flex shrink-0 items-center gap-2 self-start lg:ml-6">
|
||||||
<button @click="showPasswordModal = true" class="btn-primary px-6 py-3 text-base">
|
<button @click="handleChangePasswordClick" class="btn-primary px-6 py-3 text-base">
|
||||||
{{ $t('profile.changePassword') }}
|
{{ $t('profile.changePassword') }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="isMobile" class="mt-4 flex items-center justify-center gap-4">
|
<div v-if="isMobile" class="mt-4 flex items-center justify-center gap-4">
|
||||||
<button @click="showPasswordModal = true" class="btn-primary flex-1 py-2.5 text-sm text-center">
|
<button @click="handleChangePasswordClick" class="btn-primary flex-1 py-2.5 text-sm text-center">
|
||||||
{{ $t('profile.changePassword') }}
|
{{ $t('profile.changePassword') }}
|
||||||
</button>
|
</button>
|
||||||
<button @click="handleLogout" class="btn-secondary flex-1 py-2.5 text-sm text-center text-red-600 hover:bg-red-50">
|
<button @click="handleLogout" class="btn-secondary flex-1 py-2.5 text-sm text-center text-red-600 hover:bg-red-50">
|
||||||
@@ -2291,8 +2302,9 @@ onBeforeUnmount(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Change password modal: re-enable via CHANGE_PASSWORD_ENABLED when Casdoor is ready -->
|
||||||
<div
|
<div
|
||||||
v-if="showPasswordModal"
|
v-if="CHANGE_PASSWORD_ENABLED && showPasswordModal"
|
||||||
class="dialog-overlay z-50 items-center"
|
class="dialog-overlay z-50 items-center"
|
||||||
@click.self="showPasswordModal = false"
|
@click.self="showPasswordModal = false"
|
||||||
>
|
>
|
||||||
|
|||||||
Reference in new issue
Block a user