Merge branch 'dev' into hugo-shipping-notice
This commit is contained in:
commit
bc86720744
49 files changed
+2950
-458
No files matched your search
@@ -85,6 +85,12 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
|
||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -118,6 +118,12 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
|
||||
|
||||
Vendored
+3
-2
@@ -1,7 +1,8 @@
|
||||
{
|
||||
// 后端 Python 虚拟环境
|
||||
// 后端 Python 虚拟环境(解释器路径供语言服务/调试使用)
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
|
||||
"python.terminal.activateEnvironment": true,
|
||||
// 关闭 Python 扩展在新建终端时自动 activate,避免与下方 PowerShell (HXOPS) 的 cd 钩子重复激活
|
||||
"python.terminal.activateEnvironment": false,
|
||||
"python.venvPath": "${workspaceFolder}/backend",
|
||||
"python.venvFolders": [".venv"],
|
||||
"github.copilot.chat.commitMessageGeneration.instructions": [
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/api/admin/reports.py
|
||||
|
||||
用途:管理后台报表 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/report_service。
|
||||
逻辑:/reports/* 路由。
|
||||
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -38,6 +38,35 @@ def usage_report():
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/applications', methods=['GET'])
|
||||
@require_admin
|
||||
def applications_report():
|
||||
"""
|
||||
应用运营报表:按应用聚合使用 / 权限 / 评分。
|
||||
Query: range, status, usage, q, sort, order, page, page_size。
|
||||
"""
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
except (TypeError, ValueError):
|
||||
page = 1
|
||||
try:
|
||||
page_size = int(request.args.get('page_size', 20))
|
||||
except (TypeError, ValueError):
|
||||
page_size = 20
|
||||
return jsonify(
|
||||
report_service.build_application_report(
|
||||
range_key=request.args.get('range'),
|
||||
status=request.args.get('status'),
|
||||
usage=request.args.get('usage'),
|
||||
q=request.args.get('q'),
|
||||
sort=request.args.get('sort'),
|
||||
order=request.args.get('order'),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_report():
|
||||
|
||||
+47
-80
@@ -8,6 +8,8 @@ backend/app/api/chat.py
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
@@ -226,26 +228,60 @@ def _update_chat_session(
|
||||
return session
|
||||
|
||||
|
||||
def _normalize_windows_share_path(path_value: str) -> str:
|
||||
normalized = str(path_value or '').strip().strip('"').replace('/', '\\')
|
||||
if normalized.startswith('\\\\'):
|
||||
return '\\\\' + normalized[2:].rstrip('\\')
|
||||
return normalized.rstrip('\\')
|
||||
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
|
||||
"""
|
||||
统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
|
||||
|
||||
Returns:
|
||||
(path_kind, normalized_path)
|
||||
- path_kind: 'windows' | 'posix' | ''
|
||||
- normalized_path: 归一化后的绝对路径文本
|
||||
"""
|
||||
raw_value = str(path_value or '').strip().strip('"')
|
||||
if not raw_value:
|
||||
return ('', '')
|
||||
if raw_value.startswith('\\\\'):
|
||||
normalized = raw_value.replace('/', '\\')
|
||||
normalized = '\\\\' + normalized[2:].rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
|
||||
normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if raw_value.startswith('/'):
|
||||
normalized = posixpath.normpath(raw_value.replace('\\', '/'))
|
||||
return ('posix', normalized.rstrip('/'))
|
||||
return ('', '')
|
||||
|
||||
def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_path)
|
||||
root_kind, normalized_root = _normalize_allowed_share_path(root_path)
|
||||
if not normalized_target or not normalized_root or target_kind != root_kind:
|
||||
return False
|
||||
if target_kind == 'windows':
|
||||
target_lower = normalized_target.lower()
|
||||
root_lower = normalized_root.lower()
|
||||
return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
|
||||
return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
normalized_target = _normalize_windows_share_path(target_url)
|
||||
if not normalized_target.startswith('\\\\'):
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_url)
|
||||
if not normalized_target:
|
||||
return False
|
||||
history_share_root = ''
|
||||
history_local_root = ''
|
||||
if has_request_context():
|
||||
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
|
||||
history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
|
||||
if not history_share_root:
|
||||
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
|
||||
if not history_local_root:
|
||||
history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
|
||||
roots = [
|
||||
_normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT),
|
||||
_normalize_windows_share_path(history_share_root),
|
||||
PLM_PREVIEW_SHARE_ROOT,
|
||||
history_share_root,
|
||||
history_local_root,
|
||||
]
|
||||
return any(root and normalized_target.lower().startswith(root.lower()) for root in roots)
|
||||
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
@@ -300,7 +336,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
if _is_allowed_share_path(file_url):
|
||||
normalized_path = _normalize_windows_share_path(file_url)
|
||||
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
|
||||
try:
|
||||
if not os.path.isfile(normalized_path):
|
||||
return (None, None, ('source file not found', 404))
|
||||
@@ -1166,31 +1202,6 @@ def search_asset_history_files():
|
||||
asset_name = (request.args.get('asset_name') or '').strip()
|
||||
limit = request.args.get('limit', type=int) or 20
|
||||
limit = max(1, min(limit, 50))
|
||||
# #region debug-point C:asset-history-api-entry
|
||||
import json as _debug_json
|
||||
import urllib.request as _debug_urllib_request
|
||||
try:
|
||||
_debug_payload = _debug_json.dumps({
|
||||
'sessionId': 'asset-history-click',
|
||||
'runId': 'pre-fix',
|
||||
'hypothesisId': 'C',
|
||||
'location': 'backend/chat.py:search_asset_history_files',
|
||||
'msg': '[DEBUG] asset history api entry',
|
||||
'data': {
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'limit': limit,
|
||||
},
|
||||
}).encode('utf-8')
|
||||
_debug_urllib_request.urlopen(_debug_urllib_request.Request(
|
||||
'http://127.0.0.1:7777/event',
|
||||
data=_debug_payload,
|
||||
headers={'Content-Type': 'application/json'},
|
||||
method='POST',
|
||||
), timeout=2).read()
|
||||
except Exception:
|
||||
pass
|
||||
# #endregion
|
||||
|
||||
if not asset_id and not asset_name:
|
||||
raise ValidationError('asset_id or asset_name is required')
|
||||
@@ -1198,27 +1209,6 @@ def search_asset_history_files():
|
||||
from app.services.fixed_asset_history import FixedAssetHistoryService
|
||||
|
||||
if not FixedAssetHistoryService.is_enabled():
|
||||
# #region debug-point C:asset-history-api-disabled
|
||||
try:
|
||||
_debug_payload = _debug_json.dumps({
|
||||
'sessionId': 'asset-history-click',
|
||||
'runId': 'pre-fix',
|
||||
'hypothesisId': 'C',
|
||||
'location': 'backend/chat.py:search_asset_history_files',
|
||||
'msg': '[DEBUG] asset history api disabled',
|
||||
'data': {
|
||||
'share_root': str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or ''),
|
||||
},
|
||||
}).encode('utf-8')
|
||||
_debug_urllib_request.urlopen(_debug_urllib_request.Request(
|
||||
'http://127.0.0.1:7777/event',
|
||||
data=_debug_payload,
|
||||
headers={'Content-Type': 'application/json'},
|
||||
method='POST',
|
||||
), timeout=2).read()
|
||||
except Exception:
|
||||
pass
|
||||
# #endregion
|
||||
raise ServiceUnavailableError('asset history share is not configured')
|
||||
|
||||
items = FixedAssetHistoryService.search_history_files(
|
||||
@@ -1226,29 +1216,6 @@ def search_asset_history_files():
|
||||
asset_name=asset_name,
|
||||
limit=limit,
|
||||
)
|
||||
# #region debug-point C:asset-history-api-success
|
||||
try:
|
||||
_debug_payload = _debug_json.dumps({
|
||||
'sessionId': 'asset-history-click',
|
||||
'runId': 'pre-fix',
|
||||
'hypothesisId': 'C',
|
||||
'location': 'backend/chat.py:search_asset_history_files',
|
||||
'msg': '[DEBUG] asset history api success',
|
||||
'data': {
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'item_count': len(items),
|
||||
},
|
||||
}).encode('utf-8')
|
||||
_debug_urllib_request.urlopen(_debug_urllib_request.Request(
|
||||
'http://127.0.0.1:7777/event',
|
||||
data=_debug_payload,
|
||||
headers={'Content-Type': 'application/json'},
|
||||
method='POST',
|
||||
), timeout=2).read()
|
||||
except Exception:
|
||||
pass
|
||||
# #endregion
|
||||
return jsonify({
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
|
||||
@@ -343,6 +343,7 @@ class Config:
|
||||
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
|
||||
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip()
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT = os.getenv('FIXED_ASSET_HISTORY_LOCAL_ROOT', '').strip()
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip()
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '')
|
||||
FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20')
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/admin/database_admin_service.py
|
||||
|
||||
用途:管理后台通用数据表浏览与 chat_logs 批量删除。
|
||||
依赖:models、report_service(chat_logs 报表复用)。
|
||||
逻辑:由 api/admin/database.py 调用。
|
||||
逻辑:由 api/admin/database.py 调用;整型筛选字段对纯数字条件使用等值匹配。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -66,7 +66,12 @@ def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||||
for key, value in query_params.items():
|
||||
if hasattr(model, key) and value:
|
||||
col = getattr(model, key)
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
col_type = getattr(col, 'type', None)
|
||||
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
|
||||
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
|
||||
query = query.filter(col == int(value))
|
||||
else:
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
items = query.limit(100).all()
|
||||
return [_serialize_model_row(item) for item in items]
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/services/admin/report_service.py
|
||||
|
||||
用途:管理后台报表(使用分析、反馈、聊天日志)数据聚合。
|
||||
依赖:models、SQLAlchemy func。
|
||||
用途:管理后台报表(使用分析、应用运营、反馈、聊天日志)数据聚合。
|
||||
依赖:models、SQLAlchemy func、user_agent_permissions。
|
||||
逻辑:由 api/admin/reports.py、database_admin_service 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -11,12 +11,25 @@ import math
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import desc, func
|
||||
from sqlalchemy import asc, desc, func, or_
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
|
||||
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, PermissionRequest, User
|
||||
from app.models.base import user_agent_permissions
|
||||
|
||||
USAGE_BY_USER_TOP_LIMIT = 50
|
||||
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
|
||||
APPLICATION_REPORT_SORT_KEYS = frozenset({
|
||||
'name',
|
||||
'chat_count',
|
||||
'unique_users',
|
||||
'last_active_at',
|
||||
'authorized_users',
|
||||
'pending_requests',
|
||||
'avg_score',
|
||||
'tokens_used',
|
||||
})
|
||||
DEFAULT_APPLICATION_SORT = 'chat_count'
|
||||
|
||||
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
||||
USAGE_RANGE_DAYS = {
|
||||
@@ -52,10 +65,15 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
|
||||
"""
|
||||
聊天使用分析报表(按应用 / 按用户),限定时间范围内的 ChatLog。
|
||||
|
||||
核心逻辑:按 Agent / User 聚合 ChatLog 次数;按用户统计同时返回 username 与 real_name。
|
||||
|
||||
Args:
|
||||
user_page: 按用户统计分页页码。
|
||||
user_page_size: 每页条数(上限 USAGE_BY_USER_TOP_LIMIT)。
|
||||
range_key: 时间范围 key,见 USAGE_RANGE_DAYS。
|
||||
|
||||
Returns:
|
||||
含 total / by_user(username、real_name、count)/ by_agent 及用户分页字段的字典。
|
||||
"""
|
||||
normalized_range, since = resolve_usage_range_start(range_key)
|
||||
base_filter = ChatLog.created_at >= since
|
||||
@@ -69,13 +87,22 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
|
||||
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
||||
.all()
|
||||
)
|
||||
# [STEP 1] 按日期聚合趋势,供管理端判断近几天是否出现使用高峰或低谷。
|
||||
by_day = (
|
||||
db.session.query(func.date(ChatLog.created_at), func.count(ChatLog.id))
|
||||
.filter(base_filter)
|
||||
.group_by(func.date(ChatLog.created_at))
|
||||
.order_by(asc(func.date(ChatLog.created_at)))
|
||||
.all()
|
||||
)
|
||||
user_page = max(1, user_page)
|
||||
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
|
||||
# [STEP 1] 按用户聚合对话量,一并选出真实姓名供管理端展示
|
||||
by_user_top = (
|
||||
db.session.query(User.username, func.count(ChatLog.id))
|
||||
db.session.query(User.username, User.real_name, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.filter(base_filter)
|
||||
.group_by(User.username)
|
||||
.group_by(User.username, User.real_name)
|
||||
.order_by(desc(func.count(ChatLog.id)), User.username)
|
||||
.limit(USAGE_BY_USER_TOP_LIMIT)
|
||||
.all()
|
||||
@@ -88,8 +115,12 @@ def build_usage_report(*, user_page: int, user_page_size: int, range_key: str |
|
||||
return {
|
||||
'total': total,
|
||||
'range': normalized_range,
|
||||
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
|
||||
'by_user': [
|
||||
{'username': u, 'real_name': rn or '', 'count': c}
|
||||
for u, rn, c in by_user_page
|
||||
],
|
||||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||||
'by_day': [{'date': str(day), 'count': c} for day, c in by_day],
|
||||
'user_total': user_total,
|
||||
'user_page': user_page,
|
||||
'user_page_size': user_page_size,
|
||||
@@ -110,6 +141,214 @@ def build_feedback_report() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def build_application_report(
|
||||
*,
|
||||
range_key: str | None = None,
|
||||
status: str | None = None,
|
||||
usage: str | None = None,
|
||||
q: str | None = None,
|
||||
sort: str | None = None,
|
||||
order: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict:
|
||||
"""
|
||||
应用运营报表:以 Agent 为主表,聚合时间范围内的使用 / 权限 / 评分指标。
|
||||
|
||||
核心逻辑:ChatLog 聚合对话与用户;user_agent_permissions 统计授权人数;
|
||||
PermissionRequest 统计待审;Feedback JOIN ChatLog 统计均分。不含 API Key 等配置敏感字段。
|
||||
|
||||
Args:
|
||||
range_key: 时间范围 key(7d/30d/90d/180d/365d),非法值回退近一月。
|
||||
status: all | active | inactive,按 is_active 过滤。
|
||||
usage: all | used | unused,按时间范围内是否有对话过滤。
|
||||
q: 应用名称模糊搜索。
|
||||
sort: 排序字段,见 APPLICATION_REPORT_SORT_KEYS。
|
||||
order: asc | desc,默认 desc。
|
||||
page: 页码(从 1 起)。
|
||||
page_size: 每页条数,上限 APPLICATION_REPORT_PAGE_SIZE_MAX。
|
||||
|
||||
Returns:
|
||||
含 summary / items / 分页字段的字典。
|
||||
"""
|
||||
normalized_range, since = resolve_usage_range_start(range_key)
|
||||
status_key = (status or 'all').strip().lower()
|
||||
if status_key not in {'all', 'active', 'inactive'}:
|
||||
status_key = 'all'
|
||||
usage_key = (usage or 'all').strip().lower()
|
||||
if usage_key not in {'all', 'used', 'unused'}:
|
||||
usage_key = 'all'
|
||||
sort_key = (sort or DEFAULT_APPLICATION_SORT).strip().lower()
|
||||
if sort_key not in APPLICATION_REPORT_SORT_KEYS:
|
||||
sort_key = DEFAULT_APPLICATION_SORT
|
||||
order_key = (order or 'desc').strip().lower()
|
||||
if order_key not in {'asc', 'desc'}:
|
||||
order_key = 'desc'
|
||||
page = max(1, int(page or 1))
|
||||
page_size = max(1, min(int(page_size or 20), APPLICATION_REPORT_PAGE_SIZE_MAX))
|
||||
keyword = (q or '').strip()
|
||||
|
||||
# [STEP 1] 子查询:时间范围内对话 / 授权 / 待审 / 评分
|
||||
chat_stats = (
|
||||
db.session.query(
|
||||
ChatLog.agent_id.label('agent_id'),
|
||||
func.count(ChatLog.id).label('chat_count'),
|
||||
func.count(func.distinct(ChatLog.user_id)).label('unique_users'),
|
||||
func.max(ChatLog.created_at).label('last_active_at'),
|
||||
func.coalesce(func.sum(ChatLog.tokens_used), 0).label('tokens_used'),
|
||||
func.avg(ChatLog.latency).label('avg_latency_ms'),
|
||||
)
|
||||
.filter(ChatLog.created_at >= since)
|
||||
.group_by(ChatLog.agent_id)
|
||||
.subquery()
|
||||
)
|
||||
auth_stats = (
|
||||
db.session.query(
|
||||
user_agent_permissions.c.agent_id.label('agent_id'),
|
||||
func.count(user_agent_permissions.c.user_id).label('authorized_users'),
|
||||
)
|
||||
.group_by(user_agent_permissions.c.agent_id)
|
||||
.subquery()
|
||||
)
|
||||
pending_stats = (
|
||||
db.session.query(
|
||||
PermissionRequest.agent_id.label('agent_id'),
|
||||
func.count(PermissionRequest.id).label('pending_requests'),
|
||||
)
|
||||
.filter(PermissionRequest.status == 'pending')
|
||||
.group_by(PermissionRequest.agent_id)
|
||||
.subquery()
|
||||
)
|
||||
feedback_stats = (
|
||||
db.session.query(
|
||||
ChatLog.agent_id.label('agent_id'),
|
||||
func.avg(Feedback.score).label('avg_score'),
|
||||
func.count(Feedback.id).label('feedback_count'),
|
||||
)
|
||||
.join(Feedback, Feedback.chat_log_id == ChatLog.id)
|
||||
.filter(ChatLog.created_at >= since)
|
||||
.group_by(ChatLog.agent_id)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
chat_count_col = func.coalesce(chat_stats.c.chat_count, 0)
|
||||
unique_users_col = func.coalesce(chat_stats.c.unique_users, 0)
|
||||
authorized_col = func.coalesce(auth_stats.c.authorized_users, 0)
|
||||
pending_col = func.coalesce(pending_stats.c.pending_requests, 0)
|
||||
tokens_col = func.coalesce(chat_stats.c.tokens_used, 0)
|
||||
|
||||
# [STEP 2] Agent 左连接各聚合,应用筛选
|
||||
query = (
|
||||
db.session.query(
|
||||
Agent.id,
|
||||
Agent.name,
|
||||
Agent.is_active,
|
||||
Agent.category,
|
||||
chat_count_col.label('chat_count'),
|
||||
unique_users_col.label('unique_users'),
|
||||
chat_stats.c.last_active_at,
|
||||
authorized_col.label('authorized_users'),
|
||||
pending_col.label('pending_requests'),
|
||||
feedback_stats.c.avg_score,
|
||||
func.coalesce(feedback_stats.c.feedback_count, 0).label('feedback_count'),
|
||||
tokens_col.label('tokens_used'),
|
||||
chat_stats.c.avg_latency_ms,
|
||||
)
|
||||
.outerjoin(chat_stats, chat_stats.c.agent_id == Agent.id)
|
||||
.outerjoin(auth_stats, auth_stats.c.agent_id == Agent.id)
|
||||
.outerjoin(pending_stats, pending_stats.c.agent_id == Agent.id)
|
||||
.outerjoin(feedback_stats, feedback_stats.c.agent_id == Agent.id)
|
||||
)
|
||||
if status_key == 'active':
|
||||
query = query.filter(Agent.is_active.is_(True))
|
||||
elif status_key == 'inactive':
|
||||
query = query.filter(Agent.is_active.is_(False))
|
||||
if usage_key == 'used':
|
||||
query = query.filter(chat_count_col > 0)
|
||||
elif usage_key == 'unused':
|
||||
query = query.filter(or_(chat_stats.c.chat_count.is_(None), chat_stats.c.chat_count == 0))
|
||||
if keyword:
|
||||
query = query.filter(Agent.name.ilike(f'%{keyword}%'))
|
||||
|
||||
# [STEP 3] 一次拉取筛选结果,内存排序分页(应用数量通常较小;兼容 SQLite 测试)
|
||||
filtered_rows = list(query.all())
|
||||
agent_total = len(filtered_rows)
|
||||
active_agents = sum(1 for row in filtered_rows if row.is_active)
|
||||
used_agents = sum(1 for row in filtered_rows if int(row.chat_count or 0) > 0)
|
||||
unused_agents = agent_total - used_agents
|
||||
pending_permission_total = sum(int(row.pending_requests or 0) for row in filtered_rows)
|
||||
|
||||
def _row_sort_key(row: Any) -> tuple:
|
||||
"""
|
||||
构造排序键:(是否空值, 业务值, 名称, id)。
|
||||
空值(无最近活跃 / 无评分)始终排在末尾。
|
||||
"""
|
||||
if sort_key == 'name':
|
||||
return (0, (row.name or '').lower(), row.name or '', row.id)
|
||||
if sort_key in {'chat_count', 'unique_users', 'authorized_users', 'pending_requests', 'tokens_used'}:
|
||||
return (0, int(getattr(row, sort_key) or 0), row.name or '', row.id)
|
||||
raw = getattr(row, sort_key, None)
|
||||
if raw is None:
|
||||
return (1, None, row.name or '', row.id)
|
||||
if sort_key == 'avg_score':
|
||||
return (0, float(raw), row.name or '', row.id)
|
||||
return (0, raw, row.name or '', row.id)
|
||||
|
||||
reverse = order_key == 'desc'
|
||||
non_null = [r for r in filtered_rows if _row_sort_key(r)[0] == 0]
|
||||
nulls = [r for r in filtered_rows if _row_sort_key(r)[0] == 1]
|
||||
non_null.sort(key=_row_sort_key, reverse=reverse)
|
||||
nulls.sort(key=lambda r: (r.name or '', r.id))
|
||||
filtered_rows = non_null + nulls
|
||||
|
||||
pages = max(1, math.ceil(agent_total / page_size)) if agent_total else 1
|
||||
page = min(page, pages)
|
||||
offset = (page - 1) * page_size
|
||||
page_rows = filtered_rows[offset:offset + page_size]
|
||||
|
||||
items = []
|
||||
for row in page_rows:
|
||||
avg_score = float(row.avg_score) if row.avg_score is not None else None
|
||||
avg_latency = float(row.avg_latency_ms) if row.avg_latency_ms is not None else None
|
||||
last_active = row.last_active_at.isoformat() if row.last_active_at else None
|
||||
items.append({
|
||||
'agent_id': row.id,
|
||||
'name': row.name,
|
||||
'is_active': bool(row.is_active),
|
||||
'category': row.category or '',
|
||||
'chat_count': int(row.chat_count or 0),
|
||||
'unique_users': int(row.unique_users or 0),
|
||||
'last_active_at': last_active,
|
||||
'authorized_users': int(row.authorized_users or 0),
|
||||
'pending_requests': int(row.pending_requests or 0),
|
||||
'avg_score': round(avg_score, 2) if avg_score is not None else None,
|
||||
'feedback_count': int(row.feedback_count or 0),
|
||||
'tokens_used': int(row.tokens_used or 0),
|
||||
'avg_latency_ms': round(avg_latency, 1) if avg_latency is not None else None,
|
||||
})
|
||||
|
||||
return {
|
||||
'range': normalized_range,
|
||||
'status': status_key,
|
||||
'usage': usage_key,
|
||||
'q': keyword,
|
||||
'sort': sort_key,
|
||||
'order': order_key,
|
||||
'summary': {
|
||||
'agent_total': agent_total,
|
||||
'active_agents': active_agents,
|
||||
'used_agents': used_agents,
|
||||
'unused_agents': unused_agents,
|
||||
'pending_permission_total': pending_permission_total,
|
||||
},
|
||||
'items': items,
|
||||
'total': agent_total,
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': pages,
|
||||
}
|
||||
|
||||
|
||||
def _apply_general_feedback_filters(query, query_params: dict[str, str]):
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in query_params.items():
|
||||
@@ -208,6 +447,8 @@ def apply_chat_logs_report_filters(query, query_params: dict[str, str]):
|
||||
continue
|
||||
if key == 'agent_name':
|
||||
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'agent_id' and value.isdigit():
|
||||
query = query.filter(ChatLog.agent_id == int(value))
|
||||
elif key == 'username':
|
||||
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'real_name':
|
||||
|
||||
@@ -86,9 +86,23 @@ def list_directory_member_agents(agent_id: int, *, active_only: bool = False) ->
|
||||
return query.all()
|
||||
|
||||
|
||||
def serialize_directory_member(agent: Agent) -> dict[str, Any]:
|
||||
"""Serialize one member Agent for Admin and Dify runtime metadata."""
|
||||
return {
|
||||
def serialize_directory_member(
|
||||
agent: Agent,
|
||||
*,
|
||||
active_only: bool = False,
|
||||
max_depth: int = 0,
|
||||
visited_ids: set[int] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Serialize one member Agent for Admin, user navigation, and Dify metadata.
|
||||
|
||||
Args:
|
||||
active_only: True 时只展开启用中的子应用。
|
||||
max_depth: 允许向下展开的聚合层级,避免用户列表中聚合子应用丢失展开能力。
|
||||
visited_ids: 已访问 Agent ID,用于防止循环配置导致递归。
|
||||
"""
|
||||
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
|
||||
payload = {
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': agent.description,
|
||||
@@ -97,12 +111,41 @@ def serialize_directory_member(agent: Agent) -> dict[str, Any]:
|
||||
'dify_app_id': agent.dify_app_id,
|
||||
'category': agent.category,
|
||||
'sub_category': agent.sub_category,
|
||||
'sort_order': int(getattr(agent, 'sort_order', 0) or 0),
|
||||
'is_aggregate': is_aggregate,
|
||||
}
|
||||
if is_aggregate and max_depth > 0:
|
||||
next_visited = set(visited_ids or set())
|
||||
if agent.id not in next_visited:
|
||||
next_visited.add(agent.id)
|
||||
payload['directory_members'] = serialize_directory_members(
|
||||
agent.id,
|
||||
active_only=active_only,
|
||||
max_depth=max_depth - 1,
|
||||
visited_ids=next_visited,
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def serialize_directory_members(agent_id: int, *, active_only: bool = False) -> list[dict[str, Any]]:
|
||||
def serialize_directory_members(
|
||||
agent_id: int,
|
||||
*,
|
||||
active_only: bool = False,
|
||||
max_depth: int = 0,
|
||||
visited_ids: set[int] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Serialize configured member Agents for a directory Agent."""
|
||||
visited = set(visited_ids or set())
|
||||
if agent_id in visited:
|
||||
return []
|
||||
visited.add(agent_id)
|
||||
return [
|
||||
serialize_directory_member(agent)
|
||||
serialize_directory_member(
|
||||
agent,
|
||||
active_only=active_only,
|
||||
max_depth=max_depth,
|
||||
visited_ids=visited,
|
||||
)
|
||||
for agent in list_directory_member_agents(agent_id, active_only=active_only)
|
||||
if agent.id not in visited
|
||||
]
|
||||
@@ -3,7 +3,9 @@ backend/app/services/fixed_asset_history.py
|
||||
|
||||
用途:为固资管理提供“资产履历”共享盘检索能力,按资产编号/资产名称匹配履历文件。
|
||||
依赖:app.core.config.settings.Config、chat.py 里的预览代理会复用这里返回的共享盘文件路径。
|
||||
逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索共享盘 -> 前端拿到候选履历文件后继续走既有预览弹窗。
|
||||
逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索履历目录 -> 前端拿到候选履历文件后继续走既有预览弹窗;
|
||||
支持 Windows 直接访问 UNC 共享盘,也支持 Linux 通过本地挂载目录访问同一批履历文件;
|
||||
编号命中优先;共享盘按设备名归档时,允许用资产名称匹配文件夹/文件名作为回退。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,6 +19,7 @@ from dataclasses import dataclass
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
from app.core.config.settings import Config
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
|
||||
|
||||
_CONNECT_LOCK = threading.Lock()
|
||||
@@ -75,12 +78,64 @@ class FixedAssetHistoryService:
|
||||
|
||||
@classmethod
|
||||
def is_enabled(cls) -> bool:
|
||||
return bool(cls.get_share_root())
|
||||
return bool(cls.get_local_root() or cls.get_share_root())
|
||||
|
||||
@classmethod
|
||||
def get_share_root(cls) -> str:
|
||||
return cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_ROOT').strip()
|
||||
|
||||
@classmethod
|
||||
def get_local_root(cls) -> str:
|
||||
return cls._get_runtime_setting('FIXED_ASSET_HISTORY_LOCAL_ROOT').strip()
|
||||
|
||||
@classmethod
|
||||
def get_access_root(cls) -> str:
|
||||
"""
|
||||
返回当前环境实际用于检索/预览履历文件的可访问根目录。
|
||||
|
||||
AI 触发时机:
|
||||
- Windows 本地开发环境通常直接访问 UNC 共享盘;
|
||||
- Linux 测试/生产环境通常通过宿主机或容器挂载目录访问共享盘;
|
||||
- 因此优先读取 `FIXED_ASSET_HISTORY_LOCAL_ROOT`,未配置时再回退到原共享盘根目录。
|
||||
"""
|
||||
return cls.get_local_root() or cls.get_share_root()
|
||||
|
||||
@classmethod
|
||||
def _resolve_share_root(cls) -> str:
|
||||
"""
|
||||
解析并校验资产履历共享盘根目录。
|
||||
|
||||
AI 触发时机:当用户点击资产编号查询履历时,必须先确认后端能访问配置的共享盘;
|
||||
若测试/生产环境未挂载成功,不应误报成“未找到履历文件”,而应返回更准确的环境异常提示。
|
||||
"""
|
||||
root = cls.get_access_root()
|
||||
if not root:
|
||||
raise ServiceUnavailableError('asset history share is not configured')
|
||||
if not os.path.exists(root):
|
||||
cls._ensure_share_connected(root)
|
||||
if not os.path.exists(root):
|
||||
raise ServiceUnavailableError('asset history share is unreachable')
|
||||
if not os.path.isdir(root):
|
||||
raise ServiceUnavailableError('asset history share is invalid')
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _build_asset_id_variants(cls, asset_id: str) -> tuple[str, ...]:
|
||||
"""
|
||||
生成资产编号匹配变体。
|
||||
|
||||
AI 触发时机:测试/生产环境的共享盘文件名可能出现“带前缀 A”与“不带前缀”两种写法;
|
||||
这里统一构造多个匹配 key,避免因为命名差一个前缀就查不到履历。
|
||||
"""
|
||||
normalized = cls._normalize_keyword(asset_id)
|
||||
if not normalized:
|
||||
return tuple()
|
||||
variants = [normalized]
|
||||
stripped = re.sub(r'^[a-z]+', '', normalized)
|
||||
if stripped and stripped not in variants:
|
||||
variants.append(stripped)
|
||||
return tuple(variants)
|
||||
|
||||
@classmethod
|
||||
def search_history_files(
|
||||
cls,
|
||||
@@ -97,17 +152,12 @@ class FixedAssetHistoryService:
|
||||
[STEP 3] 再用资产名称命中同名文件夹/文件,补足部分历史文件只按设备名称归档的情况。
|
||||
"""
|
||||
asset_id_value = cls._normalize_keyword(asset_id)
|
||||
asset_id_variants = cls._build_asset_id_variants(asset_id)
|
||||
asset_name_value = cls._normalize_keyword(asset_name)
|
||||
if not asset_id_value and not asset_name_value:
|
||||
if not asset_id_variants and not asset_name_value:
|
||||
return []
|
||||
|
||||
root = cls.get_share_root()
|
||||
if not root:
|
||||
return []
|
||||
if not os.path.exists(root):
|
||||
cls._ensure_share_connected(root)
|
||||
if not os.path.isdir(root):
|
||||
return []
|
||||
root = cls._resolve_share_root()
|
||||
|
||||
max_results = max(
|
||||
1,
|
||||
@@ -115,13 +165,13 @@ class FixedAssetHistoryService:
|
||||
)
|
||||
candidates: dict[str, AssetHistoryCandidate] = {}
|
||||
|
||||
if asset_id_value:
|
||||
if asset_id_variants:
|
||||
for current_root, _dirs, files in os.walk(root):
|
||||
for filename in files:
|
||||
candidate = cls._build_candidate(
|
||||
root=root,
|
||||
file_path=os.path.join(current_root, filename),
|
||||
asset_id=asset_id_value,
|
||||
asset_id_variants=asset_id_variants,
|
||||
asset_name=asset_name_value,
|
||||
match_reason="asset_id",
|
||||
)
|
||||
@@ -135,7 +185,7 @@ class FixedAssetHistoryService:
|
||||
candidate = cls._build_candidate(
|
||||
root=root,
|
||||
file_path=os.path.join(current_root, filename),
|
||||
asset_id=asset_id_value,
|
||||
asset_id_variants=asset_id_variants,
|
||||
asset_name=asset_name_value,
|
||||
match_reason="asset_name_folder",
|
||||
)
|
||||
@@ -143,18 +193,18 @@ class FixedAssetHistoryService:
|
||||
cls._merge_candidate(candidates, candidate)
|
||||
|
||||
if asset_name_value:
|
||||
for entry in os.scandir(root):
|
||||
if not entry.is_file():
|
||||
continue
|
||||
candidate = cls._build_candidate(
|
||||
root=root,
|
||||
file_path=entry.path,
|
||||
asset_id=asset_id_value,
|
||||
asset_name=asset_name_value,
|
||||
match_reason="asset_name_file",
|
||||
)
|
||||
if candidate:
|
||||
cls._merge_candidate(candidates, candidate)
|
||||
# 全树按资产名称匹配文件名(共享盘常见「设备名+履历.xls」,不一定含资产编号)
|
||||
for current_root, _dirs, files in os.walk(root):
|
||||
for filename in files:
|
||||
candidate = cls._build_candidate(
|
||||
root=root,
|
||||
file_path=os.path.join(current_root, filename),
|
||||
asset_id_variants=asset_id_variants,
|
||||
asset_name=asset_name_value,
|
||||
match_reason="asset_name_file",
|
||||
)
|
||||
if candidate:
|
||||
cls._merge_candidate(candidates, candidate)
|
||||
|
||||
ordered = sorted(
|
||||
candidates.values(),
|
||||
@@ -191,10 +241,18 @@ class FixedAssetHistoryService:
|
||||
*,
|
||||
root: str,
|
||||
file_path: str,
|
||||
asset_id: str,
|
||||
asset_id_variants: tuple[str, ...],
|
||||
asset_name: str,
|
||||
match_reason: str,
|
||||
) -> AssetHistoryCandidate | None:
|
||||
"""
|
||||
将单个文件构造成履历候选;按匹配原因施加不同门槛。
|
||||
|
||||
核心逻辑:
|
||||
- asset_id:文件名/相对路径必须包含资产编号(或去字母前缀变体);
|
||||
- asset_name_folder / asset_name_file:共享盘大量按设备名归档,不强制编号出现在文件名;
|
||||
名称文件夹命中后,目录内履历文件均可作为候选。
|
||||
"""
|
||||
if not os.path.isfile(file_path):
|
||||
return None
|
||||
ext = os.path.splitext(file_path)[1].strip().lower()
|
||||
@@ -210,15 +268,23 @@ class FixedAssetHistoryService:
|
||||
if not searchable_text:
|
||||
return None
|
||||
|
||||
if asset_id and asset_id not in searchable_text:
|
||||
return None
|
||||
if asset_name and asset_name not in searchable_text and match_reason != "asset_id":
|
||||
# [STEP] 按匹配原因分流门槛,避免“有资产编号就永远要求文件名含编号”导致设备名归档全部 miss
|
||||
if match_reason == "asset_id":
|
||||
if not asset_id_variants or not any(variant in searchable_text for variant in asset_id_variants):
|
||||
return None
|
||||
elif match_reason == "asset_name_file":
|
||||
if not asset_name or asset_name not in searchable_text:
|
||||
return None
|
||||
elif match_reason == "asset_name_folder":
|
||||
# 文件夹已按资产名称命中;文件本身可不含编号/全名
|
||||
pass
|
||||
else:
|
||||
return None
|
||||
|
||||
score = cls._score_candidate(
|
||||
searchable_text=searchable_text,
|
||||
filename=cls._normalize_keyword(filename),
|
||||
asset_id=asset_id,
|
||||
asset_id_variants=asset_id_variants,
|
||||
asset_name=asset_name,
|
||||
match_reason=match_reason,
|
||||
)
|
||||
@@ -243,21 +309,33 @@ class FixedAssetHistoryService:
|
||||
*,
|
||||
searchable_text: str,
|
||||
filename: str,
|
||||
asset_id: str,
|
||||
asset_id_variants: tuple[str, ...],
|
||||
asset_name: str,
|
||||
match_reason: str,
|
||||
) -> int:
|
||||
"""
|
||||
为履历候选打分;编号命中优先于名称命中。
|
||||
|
||||
核心逻辑:编号精确/模糊命中给高分;名称命中与「履历」关键字加分;
|
||||
纯名称归档场景(无编号)至少要靠名称或文件夹命中拿到正分,否则会被过滤。
|
||||
"""
|
||||
score = 0
|
||||
if asset_id:
|
||||
if asset_id in filename:
|
||||
score += 120
|
||||
elif asset_id in searchable_text:
|
||||
score += 80
|
||||
if asset_id_variants:
|
||||
for index, asset_id in enumerate(asset_id_variants):
|
||||
exact_bonus = 120 if index == 0 else 100
|
||||
fuzzy_bonus = 80 if index == 0 else 60
|
||||
if asset_id in filename:
|
||||
score = max(score, exact_bonus)
|
||||
elif asset_id in searchable_text:
|
||||
score = max(score, fuzzy_bonus)
|
||||
if asset_name:
|
||||
if asset_name in filename:
|
||||
score += 60
|
||||
elif asset_name in searchable_text:
|
||||
score += 40
|
||||
elif match_reason == "asset_name_folder":
|
||||
# 文件夹已按名称命中,目录内文件给基础分,避免 score=0 被丢弃
|
||||
score += 30
|
||||
if "履历" in filename:
|
||||
score += 20
|
||||
if match_reason == "asset_name_folder":
|
||||
@@ -277,7 +355,10 @@ class FixedAssetHistoryService:
|
||||
尝试用配置的账号密码建立共享盘会话。
|
||||
|
||||
账号密码只从环境变量读取,避免把敏感信息写进仓库。
|
||||
Linux 测试/生产环境应优先通过挂载目录访问共享盘,此处仅作为 Windows UNC 共享盘的兜底建连。
|
||||
"""
|
||||
if os.name != 'nt':
|
||||
return
|
||||
username = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_USERNAME').strip()
|
||||
password = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_PASSWORD')
|
||||
if not username or not password:
|
||||
|
||||
@@ -1,8 +1,49 @@
|
||||
"""
|
||||
backend/app/services/oa_sqlserver.py
|
||||
|
||||
用途:封装 OA SQL Server 的员工检索与组织信息查询能力,供请假代理人/申请人选择等场景复用。
|
||||
依赖:pyodbc、OA ecology 数据库视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
|
||||
逻辑:通过只读 SQL 查询返回 OA 用户与组织字段;对于 OA 中夹带的多语言包装串,统一在服务层清洗成可直接展示的中文文本。
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
import pyodbc
|
||||
from flask import current_app
|
||||
|
||||
_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
|
||||
r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
|
||||
)
|
||||
|
||||
class OASQLServerService:
|
||||
@staticmethod
|
||||
def _normalize_oa_text(value) -> str:
|
||||
"""
|
||||
清洗 OA 多语言包装字段。
|
||||
|
||||
AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
|
||||
`~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
|
||||
可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
|
||||
|
||||
Args:
|
||||
value: 来自 OA SQL Server 的原始字段值。
|
||||
|
||||
Returns:
|
||||
优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
|
||||
if not matched:
|
||||
return text
|
||||
simplified, english, traditional = (
|
||||
segment.strip().strip("`").strip()
|
||||
for segment in matched.groups()
|
||||
)
|
||||
return simplified or english or traditional or text
|
||||
|
||||
@staticmethod
|
||||
def _pick_driver():
|
||||
drivers = pyodbc.drivers()
|
||||
@@ -96,13 +137,13 @@ class OASQLServerService:
|
||||
items.append({
|
||||
"uid": str(row.id) if row.id is not None else "",
|
||||
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
||||
"name": str(row.lastname) if row.lastname is not None else "",
|
||||
"jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
|
||||
"name": cls._normalize_oa_text(row.lastname),
|
||||
"jobtitle": cls._normalize_oa_text(row.jobtitle),
|
||||
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
||||
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
||||
"departmentName": str(row.departmentname).strip() if row.departmentname else "",
|
||||
"subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
|
||||
"jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
|
||||
"departmentName": cls._normalize_oa_text(row.departmentname),
|
||||
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
|
||||
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
|
||||
})
|
||||
|
||||
return {
|
||||
@@ -145,13 +186,13 @@ class OASQLServerService:
|
||||
return {
|
||||
"uid": str(row.id) if row.id is not None else "",
|
||||
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
||||
"name": str(row.lastname) if row.lastname is not None else "",
|
||||
"jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
|
||||
"name": cls._normalize_oa_text(row.lastname),
|
||||
"jobtitle": cls._normalize_oa_text(row.jobtitle),
|
||||
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
||||
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
||||
"departmentName": str(row.departmentname).strip() if row.departmentname else "",
|
||||
"subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
|
||||
"jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
|
||||
"departmentName": cls._normalize_oa_text(row.departmentname),
|
||||
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
|
||||
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
@@ -171,7 +212,7 @@ class OASQLServerService:
|
||||
[department_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return str(row.departmentname).strip() if row and row.departmentname else ""
|
||||
return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
@@ -190,7 +231,7 @@ class OASQLServerService:
|
||||
[subcompany_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return str(row.subcompanyname).strip() if row and row.subcompanyname else ""
|
||||
return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
@@ -209,7 +250,7 @@ class OASQLServerService:
|
||||
[jobtitle_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return str(row.jobtitlename).strip() if row and row.jobtitlename else ""
|
||||
return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/services/admin/test_report_service.py
|
||||
|
||||
用途:report_service 报表聚合单元测试。
|
||||
用途:report_service 报表聚合单元测试(使用分析、应用运营、反馈)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, User
|
||||
@@ -11,7 +11,13 @@ from app.services.admin import report_service
|
||||
def test_build_usage_report(app):
|
||||
with app.app_context():
|
||||
agent = Agent(name='report-agent', type='api', dify_app_id='app-r', dify_api_key='key-r')
|
||||
user = User(username='report-user', email='report@example.com', role='user')
|
||||
# 断言:by_user 需带回 real_name,便于管理端展示真实姓名
|
||||
user = User(
|
||||
username='report-user',
|
||||
email='report@example.com',
|
||||
role='user',
|
||||
real_name='报表用户',
|
||||
)
|
||||
db.session.add_all([agent, user])
|
||||
db.session.flush()
|
||||
db.session.add(ChatLog(user_id=user.id, agent_id=agent.id, query='hi', answer='ok', tokens_used=1))
|
||||
@@ -21,7 +27,9 @@ def test_build_usage_report(app):
|
||||
assert data['total'] == 1
|
||||
assert data['range'] == '30d'
|
||||
assert data['by_user'][0]['username'] == 'report-user'
|
||||
assert data['by_user'][0]['real_name'] == '报表用户'
|
||||
assert data['by_agent'][0]['agent'] == 'report-agent'
|
||||
assert data['by_day'][0]['count'] == 1
|
||||
|
||||
|
||||
def test_build_usage_report_excludes_outside_range(app):
|
||||
@@ -51,11 +59,66 @@ def test_build_usage_report_excludes_outside_range(app):
|
||||
|
||||
def test_build_feedback_report(app):
|
||||
with app.app_context():
|
||||
db.session.add(Feedback(score=5))
|
||||
db.session.add(Feedback(score=3))
|
||||
agent = Agent(name='fb-agent', type='api', dify_app_id='app-fb', dify_api_key='key-fb')
|
||||
user = User(username='fb-user', email='fb@example.com', role='user')
|
||||
db.session.add_all([agent, user])
|
||||
db.session.flush()
|
||||
log1 = ChatLog(user_id=user.id, agent_id=agent.id, query='a', answer='b', tokens_used=1)
|
||||
log2 = ChatLog(user_id=user.id, agent_id=agent.id, query='c', answer='d', tokens_used=1)
|
||||
db.session.add_all([log1, log2])
|
||||
db.session.flush()
|
||||
db.session.add(Feedback(chat_log_id=log1.id, score=5))
|
||||
db.session.add(Feedback(chat_log_id=log2.id, score=3))
|
||||
db.session.commit()
|
||||
|
||||
data = report_service.build_feedback_report()
|
||||
assert data['total'] == 2
|
||||
assert data['avg_score'] == 4.0
|
||||
assert len(data['distribution']) == 2
|
||||
|
||||
|
||||
def test_build_application_report(app):
|
||||
"""应用运营报表应聚合对话 / 授权 / 待审 / 评分,且不含配置敏感字段。"""
|
||||
from app.models import PermissionRequest
|
||||
from app.models.base import user_agent_permissions
|
||||
|
||||
with app.app_context():
|
||||
hot = Agent(name='hot-app', type='api', dify_app_id='app-hot', dify_api_key='secret-key', is_active=True)
|
||||
cold = Agent(name='cold-app', type='api', dify_app_id='app-cold', dify_api_key='secret-key-2', is_active=True)
|
||||
user = User(username='app-ops-user', email='app-ops@example.com', role='user', real_name='运营用户')
|
||||
db.session.add_all([hot, cold, user])
|
||||
db.session.flush()
|
||||
log = ChatLog(user_id=user.id, agent_id=hot.id, query='hi', answer='ok', tokens_used=10, latency=1200)
|
||||
db.session.add(log)
|
||||
db.session.flush()
|
||||
db.session.add(Feedback(chat_log_id=log.id, score=4))
|
||||
db.session.execute(
|
||||
user_agent_permissions.insert().values(user_id=user.id, agent_id=hot.id)
|
||||
)
|
||||
db.session.add(
|
||||
PermissionRequest(user_id=user.id, agent_id=cold.id, reason='need', status='pending')
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
data = report_service.build_application_report(range_key='30d', sort='chat_count', order='desc')
|
||||
assert data['range'] == '30d'
|
||||
assert data['summary']['agent_total'] >= 2
|
||||
assert data['summary']['used_agents'] >= 1
|
||||
assert data['summary']['unused_agents'] >= 1
|
||||
assert data['summary']['pending_permission_total'] >= 1
|
||||
|
||||
by_name = {item['name']: item for item in data['items']}
|
||||
assert 'hot-app' in by_name
|
||||
assert by_name['hot-app']['chat_count'] == 1
|
||||
assert by_name['hot-app']['unique_users'] == 1
|
||||
assert by_name['hot-app']['authorized_users'] == 1
|
||||
assert by_name['hot-app']['avg_score'] == 4.0
|
||||
assert by_name['cold-app']['chat_count'] == 0
|
||||
assert by_name['cold-app']['pending_requests'] == 1
|
||||
# 断言:导出字段不含 API Key
|
||||
assert 'dify_api_key' not in by_name['hot-app']
|
||||
assert 'api_base_url' not in by_name['hot-app']
|
||||
|
||||
unused = report_service.build_application_report(range_key='30d', usage='unused')
|
||||
assert all(item['chat_count'] == 0 for item in unused['items'])
|
||||
assert any(item['name'] == 'cold-app' for item in unused['items'])
|
||||
+7
-1
@@ -49,7 +49,9 @@ services:
|
||||
- EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice}
|
||||
# LibreOffice 单次格式转换超时(秒)
|
||||
- EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-600}
|
||||
|
||||
# 固资履历:必须注入 LOCAL_ROOT,避免只加载 .env.shared 时回退到 Linux 不可达的 UNC
|
||||
- FIXED_ASSET_HISTORY_LOCAL_ROOT=${FIXED_ASSET_HISTORY_LOCAL_ROOT:-}
|
||||
- FIXED_ASSET_HISTORY_SHARE_ROOT=${FIXED_ASSET_HISTORY_SHARE_ROOT:-}
|
||||
# 允许容器访问宿主机服务 (如数据库)
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
@@ -59,6 +61,10 @@ services:
|
||||
volumes:
|
||||
- ./oracle_client:/app/oracle_client:ro
|
||||
- hxops_runtime_data:/app/data
|
||||
# 固资履历:宿主机先 CIFS 挂载(scripts/mount_fixed_asset_history.sh),再 bind 进容器只读。
|
||||
# test/prod 的 FIXED_ASSET_HISTORY_LOCAL_ROOT 分别指向对应路径;未使用的一侧为空目录无影响。
|
||||
- /mnt/hxops-fixed-asset-history-test:/mnt/hxops-fixed-asset-history-test:ro
|
||||
- /mnt/hxops-fixed-asset-history-prod:/mnt/hxops-fixed-asset-history-prod:ro
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
| --- | --- | --- |
|
||||
| [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) |
|
||||
| [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) |
|
||||
| [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) |
|
||||
| [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) · [履历挂载命令](fixed-assets/history-share-mount.md) |
|
||||
|
||||
**平台级**设计(跨域)见 [platform/](../platform/README.md)。
|
||||
|
||||
|
||||
@@ -3,5 +3,6 @@
|
||||
| 文档 | 读者 | 路径 |
|
||||
| --- | --- | --- |
|
||||
| **技术方案** | 研发 | [technical.md](technical.md) |
|
||||
| **履历共享盘挂载命令**(test/prod) | 运维 | [history-share-mount.md](history-share-mount.md) |
|
||||
|
||||
**代码**:`backend/app/services/text2sql.py`(查询)、固资快照同步任务 · **状态**:见 [funclist.md](../../funclist.md)(固资管理)
|
||||
@@ -0,0 +1,197 @@
|
||||
# 固资履历共享盘挂载(Linux 运维命令)
|
||||
|
||||
> 适用:Linux 宿主机 + Docker Compose 部署的 hxops-backend。
|
||||
> 已在 test 环境验证:`smbclient` 可达后,用「CIFS 挂共享根 + bind 履历子目录」方式成功。
|
||||
> **不要使用** `subdir=履历`(部分内核会报 `mount error(22): Invalid argument`)。
|
||||
|
||||
## 1. 背景
|
||||
|
||||
| 项 | 值 |
|
||||
| --- | --- |
|
||||
| Windows 源路径 | `\\192.168.100.130\设备履历记录\履历` |
|
||||
| 业务变量 | `FIXED_ASSET_HISTORY_LOCAL_ROOT`(优先于 UNC) |
|
||||
| test 本地根 | `/mnt/hxops-fixed-asset-history-test` |
|
||||
| prod 本地根 | `/mnt/hxops-fixed-asset-history-prod` |
|
||||
| 共享根挂载点 | test: `/mnt/hxops-fixed-asset-history-test-share`<br>prod: `/mnt/hxops-fixed-asset-history-prod-share` |
|
||||
|
||||
挂载顺序:
|
||||
|
||||
1. CIFS 挂载共享根 `设备履历记录` → `*-share`
|
||||
2. `mount --bind` 把其中的 `履历` 挂到 `FIXED_ASSET_HISTORY_LOCAL_ROOT`
|
||||
3. 重建 `hxops-backend`,使容器内能看到该目录
|
||||
|
||||
---
|
||||
|
||||
## 2. 公共准备(test / prod 各做一次即可)
|
||||
|
||||
```bash
|
||||
# 安装工具
|
||||
sudo apt update
|
||||
sudo apt install -y cifs-utils smbclient
|
||||
|
||||
# 凭据文件(密码与 .env.shared / .env.<env> 中 FIXED_ASSET_HISTORY_SHARE_* 一致)
|
||||
sudo mkdir -p /etc/smbcredentials
|
||||
sudo tee /etc/smbcredentials/hxops-fixed-asset-history >/dev/null <<'EOF'
|
||||
username=SBLL00001
|
||||
password=这里填真实密码
|
||||
domain=WORKGROUP
|
||||
EOF
|
||||
sudo chmod 600 /etc/smbcredentials/hxops-fixed-asset-history
|
||||
|
||||
# 连通性探测(应能列出目录)
|
||||
smbclient //192.168.100.130/设备履历记录 -A /etc/smbcredentials/hxops-fixed-asset-history -c "ls"
|
||||
```
|
||||
|
||||
`uid/gid` 默认按 `1001`;不一致时先执行 `id`,替换下面命令中的数值。
|
||||
|
||||
若 `vers=3.0` 报 `Invalid argument`,将命令中的 `vers=3.0` 改为 `vers=2.1` 再试。
|
||||
|
||||
---
|
||||
|
||||
## 3. Test 环境命令(已验证)
|
||||
|
||||
在 hxops 仓库所在宿主机执行:
|
||||
|
||||
```bash
|
||||
# 1) 挂共享根
|
||||
sudo mkdir -p /mnt/hxops-fixed-asset-history-test-share
|
||||
sudo mount -t cifs //192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-test-share \
|
||||
-o credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro
|
||||
|
||||
# 2) 确认有「履历」
|
||||
ls /mnt/hxops-fixed-asset-history-test-share
|
||||
|
||||
# 3) bind 履历 -> LOCAL_ROOT
|
||||
sudo mkdir -p /mnt/hxops-fixed-asset-history-test
|
||||
sudo mount --bind /mnt/hxops-fixed-asset-history-test-share/履历 /mnt/hxops-fixed-asset-history-test
|
||||
|
||||
# 4) 确认履历文件可见
|
||||
ls /mnt/hxops-fixed-asset-history-test | head
|
||||
|
||||
# 5) 重建后端并检查容器内路径(必须带 COMPOSE_ENV_BASENAME,否则读不到 LOCAL_ROOT)
|
||||
cd /path/to/hxops # 换成实际部署目录,例如 ~/ai/platform/hxops
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
export COMPOSE_ENV_BASENAME=.env.test
|
||||
docker compose --env-file .env.test up -d hxops-backend
|
||||
docker exec hxops-backend printenv | grep FIXED_ASSET_HISTORY
|
||||
docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-test
|
||||
```
|
||||
|
||||
### Test 开机自动挂载(可选,写入 /etc/fstab)
|
||||
|
||||
```bash
|
||||
echo '//192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-test-share cifs credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro,nofail,_netdev 0 0' | sudo tee -a /etc/fstab
|
||||
|
||||
echo '/mnt/hxops-fixed-asset-history-test-share/履历 /mnt/hxops-fixed-asset-history-test none bind,nofail 0 0' | sudo tee -a /etc/fstab
|
||||
|
||||
# 验证 fstab(勿在已挂载时盲目 umount 生产业务目录)
|
||||
sudo mount -a
|
||||
findmnt /mnt/hxops-fixed-asset-history-test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Prod 环境命令
|
||||
|
||||
与 test 相同,仅路径与 compose env 不同:
|
||||
|
||||
```bash
|
||||
# 1) 挂共享根
|
||||
sudo mkdir -p /mnt/hxops-fixed-asset-history-prod-share
|
||||
sudo mount -t cifs //192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-prod-share \
|
||||
-o credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro
|
||||
|
||||
# 2) 确认有「履历」
|
||||
ls /mnt/hxops-fixed-asset-history-prod-share
|
||||
|
||||
# 3) bind 履历 -> LOCAL_ROOT
|
||||
sudo mkdir -p /mnt/hxops-fixed-asset-history-prod
|
||||
sudo mount --bind /mnt/hxops-fixed-asset-history-prod-share/履历 /mnt/hxops-fixed-asset-history-prod
|
||||
|
||||
# 4) 确认履历文件可见
|
||||
ls /mnt/hxops-fixed-asset-history-prod | head
|
||||
|
||||
# 5) 重建后端并检查容器内路径(必须带 COMPOSE_ENV_BASENAME,否则读不到 LOCAL_ROOT)
|
||||
cd /path/to/hxops
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
export COMPOSE_ENV_BASENAME=.env.prod
|
||||
docker compose --env-file .env.prod up -d hxops-backend
|
||||
docker exec hxops-backend printenv | grep FIXED_ASSET_HISTORY
|
||||
docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-prod
|
||||
```
|
||||
|
||||
### Prod 开机自动挂载(可选,写入 /etc/fstab)
|
||||
|
||||
```bash
|
||||
echo '//192.168.100.130/设备履历记录 /mnt/hxops-fixed-asset-history-prod-share cifs credentials=/etc/smbcredentials/hxops-fixed-asset-history,vers=3.0,iocharset=utf8,uid=1001,gid=1001,file_mode=0755,dir_mode=0755,ro,nofail,_netdev 0 0' | sudo tee -a /etc/fstab
|
||||
|
||||
echo '/mnt/hxops-fixed-asset-history-prod-share/履历 /mnt/hxops-fixed-asset-history-prod none bind,nofail 0 0' | sudo tee -a /etc/fstab
|
||||
|
||||
sudo mount -a
|
||||
findmnt /mnt/hxops-fixed-asset-history-prod
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 卸载(需要时)
|
||||
|
||||
先卸 bind,再卸共享根:
|
||||
|
||||
```bash
|
||||
# test
|
||||
sudo umount /mnt/hxops-fixed-asset-history-test
|
||||
sudo umount /mnt/hxops-fixed-asset-history-test-share
|
||||
|
||||
# prod
|
||||
sudo umount /mnt/hxops-fixed-asset-history-prod
|
||||
sudo umount /mnt/hxops-fixed-asset-history-prod-share
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 排障
|
||||
|
||||
| 现象 | 处理 |
|
||||
| --- | --- |
|
||||
| `asset history share is unreachable` | 宿主机 `LOCAL_ROOT` 未挂载,或容器未 recreate / compose 未 bind 该路径 |
|
||||
| `mount error(22): Invalid argument` | 勿用 `subdir=`;或改 `vers=2.1` / `vers=2.0` |
|
||||
| `smbclient` 失败 | 查网络、账号密码、Windows 共享权限 |
|
||||
| 宿主机有文件、容器内没有 | `docker compose --env-file .env.<env> up -d hxops-backend` 重建后再 `docker exec ... ls` |
|
||||
| 容器 `ls` 正常但仍 503 `unreachable` | 应用未读到 `FIXED_ASSET_HISTORY_LOCAL_ROOT`,回退到 UNC。执行 `docker exec hxops-backend printenv \| grep FIXED_ASSET`;重建时必须带上 env:见下方「重建后端」 |
|
||||
| 目录存在但为空 | 可能 Docker 先创建了空目录;先 `umount`/清错挂,再按本文重新 mount |
|
||||
|
||||
### 重建后端(重要)
|
||||
|
||||
compose 默认 `env_file` 指向 `.env.dev`(无 LOCAL_ROOT)。手动重建时请显式指定:
|
||||
|
||||
```bash
|
||||
cd /path/to/hxops
|
||||
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
|
||||
export COMPOSE_ENV_BASENAME=.env.test # prod 改成 .env.prod
|
||||
docker compose --env-file .env.test up -d hxops-backend
|
||||
|
||||
# 确认容器内已注入 LOCAL_ROOT(不应为空,且不是 UNC)
|
||||
docker exec hxops-backend printenv | grep FIXED_ASSET_HISTORY
|
||||
```
|
||||
|
||||
期望类似:
|
||||
|
||||
```text
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
```
|
||||
|
||||
|
||||
相关配置:
|
||||
|
||||
- `.env.test` / `.env.prod`:`FIXED_ASSET_HISTORY_LOCAL_ROOT`
|
||||
- `docker-compose.yml`:已把 test/prod 两个 `LOCAL_ROOT` 只读挂进 `hxops-backend`
|
||||
- 可选脚本:`scripts/mount_fixed_asset_history.sh`(封装同上逻辑)
|
||||
|
||||
---
|
||||
|
||||
## 7. 验收
|
||||
|
||||
1. 宿主机:`ls $LOCAL_ROOT` 能看到履历文件
|
||||
2. 容器:`docker exec hxops-backend ls $LOCAL_ROOT` 同样可见
|
||||
3. 前端:聊天页点击资产编号,不再出现 503 / `asset history share is unreachable`
|
||||
@@ -257,6 +257,29 @@ backend/data/fixed_assets/
|
||||
|
||||
这样可避免同步失败导致固资查询整体不可用。
|
||||
|
||||
### 7.4 资产履历共享盘访问约定
|
||||
|
||||
固资聊天结果中的“资产编号”点击后,会走 `backend/app/services/fixed_asset_history.py` 检索履历文件,并经 `api/chat.py` 的预览代理读取二进制内容。为兼容不同部署环境,履历目录访问遵循以下约定:
|
||||
|
||||
- **Windows 本地开发环境**:可直接使用 `FIXED_ASSET_HISTORY_SHARE_ROOT=\\\\server\\share\\...` 访问 UNC 共享盘。
|
||||
- **Linux 测试/生产环境**:应先由宿主机把 SMB 共享盘挂载到本地目录,再配置 `FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/...`;运行时优先使用 `LOCAL_ROOT`,不依赖 `net use`。
|
||||
- **预览安全限制**:`/api/chat/preview-file-raw` 只允许读取 `PLM_PREVIEW_SHARE_ROOT`、`FIXED_ASSET_HISTORY_SHARE_ROOT`、`FIXED_ASSET_HISTORY_LOCAL_ROOT` 这三类受信根目录下的文件路径,避免任意本地文件被前端透传读取。
|
||||
|
||||
#### 7.4.1 Linux 宿主机挂载
|
||||
|
||||
**权威运维命令(含 test / prod 完整步骤)**:见 [history-share-mount.md](history-share-mount.md)。
|
||||
|
||||
要点:先 CIFS 挂共享根 `设备履历记录`,再 `mount --bind` 子目录 `履历` 到 `FIXED_ASSET_HISTORY_LOCAL_ROOT`;**不要**使用 `subdir=`(易触发 `mount error(22)`)。
|
||||
|
||||
可选封装脚本:`scripts/mount_fixed_asset_history.sh`。
|
||||
|
||||
`docker-compose.yml` 已将 test/prod 的 `LOCAL_ROOT` 只读 bind 进 `hxops-backend`;宿主机挂载成功后需:
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env.<env> up -d hxops-backend
|
||||
docker exec hxops-backend ls -la /mnt/hxops-fixed-asset-history-<env>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 定时任务设计
|
||||
|
||||
+17
-4
@@ -121,7 +121,7 @@
|
||||
| 固资本地快照查询 | 已实现 | `固资管理` Agent 优先查询 SQLite 最新快照,减少实时 ERP 压力 |
|
||||
| 固资导出文件 | 已实现 | 同步成功后生成 `FixedAssets_latest.xlsx`,供人工核查与留档 |
|
||||
| 固资快照技术方案 | 已文档化 | 见 [docs/features/fixed-assets/technical.md](features/fixed-assets/technical.md) |
|
||||
| 固资履历查看 | 已实现 | 聊天结果中的 `资产编号` 支持点击后检索共享盘履历文件,并复用现有预览弹窗查看 |
|
||||
| 固资履历查看 | 已实现 | 聊天结果中的 `资产编号` 支持点击后检索共享盘履历文件,并复用现有预览弹窗查看;Windows 本地可直接访问 UNC 共享盘,Linux 测试/生产通过 `scripts/mount_fixed_asset_history.sh` 挂载后由 `FIXED_ASSET_HISTORY_LOCAL_ROOT` 读取(compose 已 bind 进 backend) |
|
||||
|
||||
### F-01 本人假期查询
|
||||
|
||||
@@ -459,14 +459,24 @@
|
||||
|
||||
---
|
||||
|
||||
## 7. 移动端适配功能清单
|
||||
## 7. 管理端功能清单
|
||||
|
||||
### 7.1 功能总览
|
||||
| 功能项 | 说明 | 状态 | 优先级 |
|
||||
| --- | --- | --- | --- |
|
||||
| 管理端使用分析 | 管理控制台「数据报表」首项由原始用户表替换为「使用分析」,展示对话总量、活跃用户/应用、按日趋势、应用/用户排行、低使用应用与异常高峰提醒,并保留聊天明细追溯与导出 | 已实现 | P1 |
|
||||
| 管理端应用运营报表 | 「数据报表 > 应用」由 agents 配置表替换为应用运营看板:按应用聚合对话/用户/最近活跃/授权/待审/均分,支持时间范围与状态筛选、Excel 导出,并可下钻聊天日志与权限申请 | 已实现 | P1 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 移动端适配功能清单
|
||||
|
||||
### 8.1 功能总览
|
||||
|
||||
| 功能项 | 说明 | 状态 | 优先级 |
|
||||
| --- | --- | --- | --- |
|
||||
| 移动端自动识别 | 屏幕高度>宽度时判定为手机端,实时响应方向变化 | 已完成 | P0 |
|
||||
| 手机端登录流程 | 未登录仍进入登录页,登录表单移动端可用 | 已完成 | P0 |
|
||||
| 登录页记住我 | 登录页支持“记住我(记住登录状态 + 记住账号密码)”方案;勾选后优先保持 30 天登录态,用户回到登录页时自动回填账号和密码,可直接点击登录进入系统;取消勾选后自动清除本地回填信息 | 已实现 | P1 |
|
||||
| 登录后默认进 Chat | 已登录访问根路径自动跳转 `/chat/16` | 已完成 | P0 |
|
||||
| 受保护页面认证守卫 | 未登录访问受保护页面重定向到登录页 | 已完成 | P0 |
|
||||
| PC 侧边栏移动端隐藏 | ChatView/WorkspaceView 侧边栏在手机端不渲染 | 已完成 | P0 |
|
||||
@@ -474,10 +484,13 @@
|
||||
| 右上角个人设置按钮 | UserCircle 图标按钮,点击进入 /profile | 已完成 | P0 |
|
||||
| ProfileView 移动端返回 | 返回按钮手机端回 Chat,PC 端回 Workspace | 已完成 | P1 |
|
||||
|
||||
### 7.2 验收清单
|
||||
### 8.2 验收清单
|
||||
|
||||
- 手机竖屏访问时自动进入适配布局
|
||||
- 未登录时正确显示登录页
|
||||
- 勾选“记住我”后,登录态有效时可直接进入系统;用户回到登录页时可自动回填账号和密码
|
||||
- 取消“记住我”后,下次进入登录页不再自动回填账号和密码
|
||||
- 登录页本地 remember 数据可被清理,不影响正常密码登录与企微登录
|
||||
- 登录后默认跳转到 Chat 页面
|
||||
- 移动端不显示 PC 端左侧导航/侧边栏
|
||||
- 移动端右上角可见个人设置图标按钮
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
版本:V26.7.1
|
||||
更新周期:2026-06-23 ~ 2026-07-14
|
||||
|
||||
————————————————————
|
||||
【面向用户】
|
||||
————————————————————
|
||||
|
||||
本次更新亮点:
|
||||
|
||||
1. 员工培训 Agent:新增新人入职与员工培训闭环,可在对话中进入培训/考试工作区,支持学习、答题、交卷结算;管理员与 HR 可查看培训相关统计。
|
||||
|
||||
2. 设备维保助手 Agent:新增设备维保智能助手,可识别维保相关意图,协助查询设备与维保信息。
|
||||
|
||||
3. 固资管理 Agent:支持资产履历直达预览与下载,Excel 预览体验优化,连续查询更稳定。
|
||||
|
||||
4. 货代发货 Agent:支持重新上传发货通知、批量自动处理与任务重试;新增库存快照与导出能力,批次任务跟踪更清晰。
|
||||
|
||||
5. 其它优化:开启语音输入;意见反馈可同步通知企业微信;文件检核进度展示更直观;知识库上传与 PDF(含图文 OCR)同步更可靠;页面加载与后台管理体验持续优化。
|
||||
|
||||
————————————————————
|
||||
【面向开发者】
|
||||
————————————————————
|
||||
|
||||
本次更新亮点:
|
||||
|
||||
1. 员工培训:完成培训闭环与管理配置;培训工作区考试流转(交卷后再结算);角色化常见问题;透传账号角色到 Dify;HR 统计问答兜底与布局交互修复;试题 PDF 导入判断题解析修复
|
||||
|
||||
2. 设备维保:新增维保助手相关能力、意图识别、上下文设备解析及 Tool Key 配置
|
||||
|
||||
3. 固资管理:对接 Dify 查询;支持资产履历预览与下载权限;修复连续问答、宽泛查询空字段与首轮会话中断等问题;快照同步增加账套字段与自动清理
|
||||
|
||||
4. 货代发货:批量自动处理与任务重试;重新上传发货通知;库存快照管理与 RPA 批量导出;发货消息与轻量工作台逻辑优化;排程增加库存源描述与站点 ID、平台任务参数契约与动态选项
|
||||
|
||||
5. 文件检核:进度卡片展示合格/不合格/人工判定笔数;持久化 chat_tool_runs;统一 agent_runtime_context 注入;增强可靠性元信息与错误分类
|
||||
|
||||
6. 知识库:手册/设计类 PDF 保留图片并 OCR 写入 Markdown 再同步;上传提示与页面样式优化;清洗超时与 job 队列重构;旧 KB 任务入队兼容
|
||||
|
||||
7. 聊天与交互:开启语音输入;源文件解析不阻塞 SSE;修复生产源文件名兜底问题;智能体支持分级显示与聚合应用配置;意见反馈通知企业微信群
|
||||
|
||||
8. 管理后台:Admin 列表排序过滤;聊天日志与应用权限优化;知识库配置布局调整
|
||||
|
||||
9. 工程与基建:后端 core/基础设施迁移与 models 拆分;admin/schedule 重构;push 前校验 migration multiple head;文件检核与货代相关单测补充
|
||||
+25
@@ -767,6 +767,31 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth;
|
||||
- 路由守卫对 `/workspace` 等直接访问不做拦截,PC 端行为不变
|
||||
- PC 端侧边栏、导航栏、布局结构无任何 CSS 或 DOM 变更
|
||||
|
||||
### 16.6 登录页“记住我”方案补充
|
||||
|
||||
- **产品口径**:按当前业务确认,登录页采用“记住我(记住登录状态 + 记住账号密码)”方案;用户勾选后,回到登录页时应自动回填账号和密码,允许直接点击【登录】进入系统。
|
||||
- **现有基础**:前端认证工具 `shared/utils/auth.ts` 已支持:
|
||||
- 勾选时将登录态持久化到 `localStorage`
|
||||
- 未勾选时仅保存在 `sessionStorage`
|
||||
- `hxops_user` 本地持久化有效期 30 天
|
||||
- 登录页现已补齐“记住我”勾选框、remembered username/password 回填与浏览器密码自动填充兼容属性
|
||||
- **推荐交互**:
|
||||
- 勾选“记住我”并登录成功后:持久化登录态,并额外记住用户名和密码
|
||||
- 下次进入登录页时:若登录态仍有效,则直接进入系统;若用户因登出或登录态失效回到登录页,则自动回填账号和密码
|
||||
- 用户取消勾选后:清除 remembered username/password、remember flag 与本地持久登录态
|
||||
- **本地存储建议**:
|
||||
- 认证数据继续沿用现有 `hxops_user`
|
||||
- 登录页偏好建议独立存储,如 `hxops_login_remember`、`hxops_login_profile`
|
||||
- `hxops_login_profile` 保存 `username`、本地可恢复的 `password_ciphertext` 与更新时间,用于登录页自动回填
|
||||
- **浏览器密码兼容**:
|
||||
- 用户名输入框补 `autocomplete="username"`
|
||||
- 密码输入框补 `autocomplete="current-password"`
|
||||
- 浏览器若支持密码管理器,可继续辅助自动填充;当前主能力仍以前端 remember 存储为准
|
||||
- **实现边界**:
|
||||
- 本方案不新增后端接口,仍复用现有密码登录与 refresh token 机制
|
||||
- remembered password 仅用于登录页自动回填,不参与后端持久化
|
||||
- 用户取消勾选后,必须同步清理本地 remembered password,避免后续误填
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -7,7 +7,14 @@ import { requestJson } from '@/shared/api/client';
|
||||
import type { AdminUserRow } from '../types/admin.types';
|
||||
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
|
||||
import type { PaginatedResult } from '@/shared/types/pagination.types';
|
||||
import type { UsageReport, UsageRangeKey } from '../types/report.types';
|
||||
import type {
|
||||
ApplicationReport,
|
||||
ApplicationSortKey,
|
||||
ApplicationStatusFilter,
|
||||
ApplicationUsageFilter,
|
||||
UsageReport,
|
||||
UsageRangeKey,
|
||||
} from '../types/report.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
@@ -275,6 +282,39 @@ export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
|
||||
auth(),
|
||||
);
|
||||
};
|
||||
|
||||
export interface AdminApplicationReportParams {
|
||||
range?: UsageRangeKey;
|
||||
status?: ApplicationStatusFilter;
|
||||
usage?: ApplicationUsageFilter;
|
||||
q?: string;
|
||||
sort?: ApplicationSortKey;
|
||||
order?: 'asc' | 'desc';
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取应用运营报表(按应用聚合使用 / 权限 / 评分)。
|
||||
* @param params - 时间范围、状态、使用筛选、搜索与排序分页
|
||||
*/
|
||||
export const getAdminApplicationReport = (params: AdminApplicationReportParams = {}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.range) qs.set('range', params.range);
|
||||
if (params.status && params.status !== 'all') qs.set('status', params.status);
|
||||
if (params.usage && params.usage !== 'all') qs.set('usage', params.usage);
|
||||
if (params.q?.trim()) qs.set('q', params.q.trim());
|
||||
if (params.sort) qs.set('sort', params.sort);
|
||||
if (params.order) qs.set('order', params.order);
|
||||
if (params.page != null) qs.set('page', String(params.page));
|
||||
if (params.page_size != null) qs.set('page_size', String(params.page_size));
|
||||
const query = qs.toString();
|
||||
return requestJson<ApplicationReport>(
|
||||
`/api/admin/reports/applications${query ? `?${query}` : ''}`,
|
||||
auth(),
|
||||
);
|
||||
};
|
||||
|
||||
export const getAdminFeedbackReport = () => requestJson<any>('/api/admin/reports/feedback', auth());
|
||||
export const getAdminReportTable = (url: string) => requestJson<any[]>(url, auth());
|
||||
export const getAdminReportTableCount = (url: string) => requestJson<{ total: number }>(url, auth());
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* features/admin/components/AdminNav.vue
|
||||
* 管理后台左侧导航,使用子路由跳转。
|
||||
* 依赖:admin-nav.store、modules 常量、vue-router。
|
||||
* 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开以便看到激活项。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { computed, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
@@ -76,6 +78,25 @@ const navigateModule = (routeName: string): void => {
|
||||
const navigateReport = (table: string): void => {
|
||||
router.push({ name: 'AdminReports', params: { table } });
|
||||
};
|
||||
|
||||
/**
|
||||
* 进入报表/企微模块时自动展开子菜单,避免当前页在折叠状态下不可见。
|
||||
*/
|
||||
watch(
|
||||
isReportsActive,
|
||||
(active) => {
|
||||
if (active) navStore.reportsExpanded = true;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
isWecomActive,
|
||||
(active) => {
|
||||
if (active) navStore.wecomExpanded = true;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -35,9 +35,9 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
];
|
||||
|
||||
export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [
|
||||
'users',
|
||||
'agents',
|
||||
'usage_analysis',
|
||||
'chat_logs',
|
||||
'agents',
|
||||
'permission_requests',
|
||||
'general_feedbacks',
|
||||
'feedbacks',
|
||||
|
||||
@@ -232,8 +232,12 @@ onMounted(() => {
|
||||
<td class="px-4 py-4 align-middle">
|
||||
<div class="agent-list-cell">
|
||||
<p class="truncate text-sm font-semibold text-primary" :title="agent.name">{{ agent.name }}</p>
|
||||
<p class="truncate text-xs text-muted" :title="agent.description || ''">
|
||||
{{ agent.description || '—' }}
|
||||
<p
|
||||
v-if="agent.description"
|
||||
class="truncate text-xs text-muted"
|
||||
:title="agent.description"
|
||||
>
|
||||
{{ agent.description }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
@@ -1,32 +1,80 @@
|
||||
/**
|
||||
* features/admin/modules/reports/ReportsPage.vue
|
||||
* 用途:管理后台报表独立页面(多表浏览、列筛选、聊天日志批量操作)。
|
||||
* 依赖:useReportsAdmin、DeleteConfirmDialog。
|
||||
* 逻辑:路由 /admin/reports/:table?;列宽由 composable 默认值与本地偏好控制。
|
||||
* 用途:管理后台报表独立页面(使用分析、应用运营、多表浏览与聊天日志批量操作)。
|
||||
* 依赖:useReportsAdmin、DeleteConfirmDialog、PaginationBar、lucide 图标。
|
||||
* 逻辑:路由 /admin/reports/:table?;分页统一复用 shared/PaginationBar。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BarChart2, Download, Settings2 } from 'lucide-vue-next';
|
||||
import { Activity, AlertTriangle, BarChart2, CircleHelp, Download, LineChart, Settings2, Trophy } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import type { ApplicationSortKey } from '@/features/admin/types/report.types';
|
||||
import { useReportsAdmin } from './composables/useReportsAdmin';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 格式化使用分析「按用户统计」展示名:优先真实姓名,并附带用户名便于对照工号。
|
||||
* 核心逻辑:有 real_name 时显示「姓名(username)」,否则仅显示 username。
|
||||
* @param user - 报表 by_user 项
|
||||
* @returns 列表左侧展示文案
|
||||
*/
|
||||
function formatUsageUserLabel(user: { username: string; real_name?: string }): string {
|
||||
const realName = (user.real_name || '').trim();
|
||||
if (realName) {
|
||||
return `${realName}(${user.username})`;
|
||||
}
|
||||
return user.username;
|
||||
}
|
||||
|
||||
const {
|
||||
usageReport,
|
||||
usageRange,
|
||||
usageRangeOptions,
|
||||
usageUserTotal,
|
||||
usageUserTopLimit,
|
||||
usageActiveAgentCount,
|
||||
usageTrendMax,
|
||||
usageLowAgentItems,
|
||||
usageSpikeDayItems,
|
||||
usageTopUserItems,
|
||||
usageTopAgentItems,
|
||||
usageUserPage,
|
||||
usageUserPageSize,
|
||||
usageUserPageSizeOptions,
|
||||
usageUserTotal,
|
||||
usageUserTotalPages,
|
||||
usageUserTopLimit,
|
||||
usageUserPageButtons,
|
||||
goToUsageUserPage,
|
||||
prevUsageUserPage,
|
||||
nextUsageUserPage,
|
||||
usageAgentPage,
|
||||
usageAgentPageSize,
|
||||
usageAgentPageSizeOptions,
|
||||
usageAgentTotal,
|
||||
usageAgentTotalPages,
|
||||
goToUsageAgentPage,
|
||||
usageLowAgentMaxChats,
|
||||
usageLowAgentListLimit,
|
||||
usageSpikeDayMinChats,
|
||||
usageSpikeDayAvgMultiplier,
|
||||
usageSpikeDayListLimit,
|
||||
applicationRange,
|
||||
applicationStatus,
|
||||
applicationUsage,
|
||||
applicationQuery,
|
||||
applicationPage,
|
||||
applicationPageSize,
|
||||
applicationPageSizeOptions,
|
||||
applicationSummary,
|
||||
applicationItems,
|
||||
applicationTotal,
|
||||
applicationTotalPages,
|
||||
goToApplicationPage,
|
||||
onApplicationSortClick,
|
||||
getApplicationSortMark,
|
||||
handleApplicationSearchChange,
|
||||
openApplicationChatLogs,
|
||||
openApplicationPermissionRequests,
|
||||
isLoading,
|
||||
currentTable,
|
||||
tableData,
|
||||
@@ -44,6 +92,8 @@ const {
|
||||
reportPageSizeOptions,
|
||||
chatLogsColumns,
|
||||
chatLogsSortRules,
|
||||
isUsageAnalysisTable,
|
||||
isApplicationOpsTable,
|
||||
isChatLogsTable,
|
||||
showReportTable,
|
||||
visibleReportKeys,
|
||||
@@ -53,7 +103,6 @@ const {
|
||||
reportTotalPages,
|
||||
reportRangeStart,
|
||||
reportRangeEnd,
|
||||
reportPageButtons,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
@@ -80,14 +129,93 @@ const {
|
||||
toggleAllReportRows,
|
||||
batchDeleteChatLogs,
|
||||
goToReportPage,
|
||||
prevReportPage,
|
||||
nextReportPage,
|
||||
confirmDelete,
|
||||
} = useReportsAdmin();
|
||||
|
||||
/** 应用运营可点击排序的列 */
|
||||
const applicationSortableKeys: ApplicationSortKey[] = [
|
||||
'name',
|
||||
'chat_count',
|
||||
'unique_users',
|
||||
'last_active_at',
|
||||
'authorized_users',
|
||||
'pending_requests',
|
||||
'avg_score',
|
||||
];
|
||||
|
||||
/**
|
||||
* 点击摘要卡快速切换「有使用 / 零使用」筛选。
|
||||
* @param usage - used | unused | all
|
||||
*/
|
||||
function setApplicationUsageFilter(usage: 'all' | 'used' | 'unused'): void {
|
||||
applicationUsage.value = usage;
|
||||
}
|
||||
|
||||
/** 低使用应用 / 异常高峰规则提示(点击 ? 以 tooltip 形式展示) */
|
||||
const showLowAgentHint = ref(false);
|
||||
const showSpikeDayHint = ref(false);
|
||||
|
||||
/**
|
||||
* 切换低使用应用选取规则 tooltip 显隐;打开时关闭另一侧提示。
|
||||
*/
|
||||
function toggleLowAgentHint(): void {
|
||||
showSpikeDayHint.value = false;
|
||||
showLowAgentHint.value = !showLowAgentHint.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换异常高峰日期选取规则 tooltip 显隐;打开时关闭另一侧提示。
|
||||
*/
|
||||
function toggleSpikeDayHint(): void {
|
||||
showLowAgentHint.value = false;
|
||||
showSpikeDayHint.value = !showSpikeDayHint.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 点击页面其他区域时关闭运营提醒规则 tooltip。
|
||||
*/
|
||||
function onDocumentClickCloseInsightHints(): void {
|
||||
showLowAgentHint.value = false;
|
||||
showSpikeDayHint.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算使用趋势柱状条高度(像素)。
|
||||
* 核心逻辑:按当前范围最大日对话量归一化;不用百分比——flex 子项无明确高度时 % 会塌成 0,导致「有日期无柱子」。
|
||||
* @param count - 单日对话量
|
||||
* @returns CSS height(px)
|
||||
*/
|
||||
function getUsageTrendBarHeight(count: number): string {
|
||||
/** 图表区 h-44(176px) 减去日期标签与间距后的可绘高度 */
|
||||
const plotMaxPx = 140;
|
||||
const minPx = 8;
|
||||
const max = Math.max(1, usageTrendMax.value);
|
||||
const px = Math.max(minPx, Math.round((count / max) * plotMaxPx));
|
||||
return `${px}px`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化趋势日期标签,供紧凑柱状图展示。
|
||||
* 核心逻辑:保留月日,避免长日期挤压图表横向空间。
|
||||
* @param date - 后端返回的 yyyy-mm-dd 日期
|
||||
* @returns 月/日短标签
|
||||
*/
|
||||
function formatUsageDayLabel(date: string): string {
|
||||
const parts = String(date).split('-');
|
||||
if (parts.length >= 3) {
|
||||
return `${Number(parts[1])}/${Number(parts[2])}`;
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', onDocumentClickCloseInsightHints);
|
||||
void loadAll();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('click', onDocumentClickCloseInsightHints);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -116,13 +244,17 @@ onMounted(() => {
|
||||
<span v-if="isChatLogsTable" class="admin-report-badge admin-report-badge--info font-semibold">
|
||||
{{ t('admin.report.totalRows', { total: chatLogsTotal }) }}
|
||||
</span>
|
||||
<span class="admin-report-badge admin-report-badge--indigo font-semibold">
|
||||
<span v-if="isApplicationOpsTable" class="admin-report-badge admin-report-badge--info font-semibold">
|
||||
{{ t('admin.report.totalRows', { total: applicationTotal }) }}
|
||||
</span>
|
||||
<span v-if="!isApplicationOpsTable" class="admin-report-badge admin-report-badge--indigo font-semibold">
|
||||
{{ t('admin.report.showingRange', { start: reportRangeStart, end: reportRangeEnd, total: reportTotalRows }) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2 md:gap-3">
|
||||
<div v-if="!isUsageAnalysisTable" class="flex flex-wrap items-center gap-2 md:gap-3">
|
||||
<button
|
||||
v-if="!isApplicationOpsTable"
|
||||
@click="showChatLogsColumnPanel = !showChatLogsColumnPanel"
|
||||
class="btn-secondary text-sm font-semibold"
|
||||
:title="t('admin.report.columnSettings')"
|
||||
@@ -166,8 +298,346 @@ onMounted(() => {
|
||||
</div>
|
||||
|
||||
<div class="p-5 md:p-8 space-y-5">
|
||||
<div v-if="isUsageAnalysisTable && usageReport" class="space-y-5">
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h3 class="section-title text-lg">{{ t('admin.report.usage') }}</h3>
|
||||
<p class="mt-1 text-sm text-secondary">{{ t('admin.report.usageIntro') }}</p>
|
||||
</div>
|
||||
<label class="flex items-center gap-2 text-sm text-secondary">
|
||||
<span class="whitespace-nowrap">{{ t('admin.report.usageRangeLabel') }}</span>
|
||||
<select v-model="usageRange" class="admin-table-filter-input min-w-[8rem]">
|
||||
<option v-for="key in usageRangeOptions" :key="key" :value="key">
|
||||
{{ t(`admin.report.usageRanges.${key}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
<div class="rounded-xl border border-default bg-surface p-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm text-muted">{{ t('admin.report.usageTotalSessions') }}</span>
|
||||
<Activity class="h-4 w-4 text-brand-600" />
|
||||
</div>
|
||||
<div class="mt-3 text-2xl font-bold text-primary">{{ usageReport.total }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl border border-default bg-surface p-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm text-muted">{{ t('admin.report.usageActiveUsers') }}</span>
|
||||
<Trophy class="h-4 w-4 text-emerald-600" />
|
||||
</div>
|
||||
<div class="mt-3 text-2xl font-bold text-primary">{{ usageUserTotal }}</div>
|
||||
<div class="mt-1 text-xs text-muted">{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl border border-default bg-surface p-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm text-muted">{{ t('admin.report.usageActiveAgents') }}</span>
|
||||
<BarChart2 class="h-4 w-4 text-sky-600" />
|
||||
</div>
|
||||
<div class="mt-3 text-2xl font-bold text-primary">{{ usageActiveAgentCount }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 gap-5 xl:grid-cols-3">
|
||||
<div class="rounded-xl border border-default bg-surface p-5 xl:col-span-2">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.usageTrend') }}</h4>
|
||||
<LineChart class="h-4 w-4 text-brand-600" />
|
||||
</div>
|
||||
<div v-if="usageReport.by_day?.length" class="flex h-44 items-end gap-2 border-b border-subtle pb-3">
|
||||
<div
|
||||
v-for="day in usageReport.by_day"
|
||||
:key="day.date"
|
||||
class="flex min-w-7 flex-1 flex-col items-center justify-end gap-1.5 self-stretch"
|
||||
:title="`${day.date}: ${day.count}`"
|
||||
>
|
||||
<div
|
||||
class="mt-auto w-full max-w-8 rounded-t bg-brand-500/80"
|
||||
:style="{ height: getUsageTrendBarHeight(day.count) }"
|
||||
/>
|
||||
<span class="text-[10px] leading-none text-muted">{{ formatUsageDayLabel(day.date) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="py-14 text-center text-sm text-muted">{{ t('admin.report.usageTrendEmpty') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-xl border border-default bg-surface p-5">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.usageInsights') }}</h4>
|
||||
<AlertTriangle class="h-4 w-4 text-amber-600" />
|
||||
</div>
|
||||
<div class="space-y-3">
|
||||
<div class="rounded-lg bg-surface-soft p-3">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-xs font-semibold text-secondary">{{ t('admin.report.usageLowAgents') }}</span>
|
||||
<div class="relative inline-flex">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex rounded p-0.5 text-muted transition-colors hover:text-brand-600"
|
||||
:aria-expanded="showLowAgentHint"
|
||||
:aria-label="t('admin.report.usageLowAgentsHintAria')"
|
||||
@click.stop="toggleLowAgentHint"
|
||||
>
|
||||
<CircleHelp class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<div
|
||||
v-if="showLowAgentHint"
|
||||
role="tooltip"
|
||||
class="absolute left-1/2 top-full z-20 mt-1.5 w-56 -translate-x-1/2 rounded-lg border border-default bg-surface px-3 py-2 text-xs leading-relaxed text-secondary shadow-elevated"
|
||||
@click.stop
|
||||
>
|
||||
{{ t('admin.report.usageLowAgentsHint', { max: usageLowAgentMaxChats, limit: usageLowAgentListLimit }) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="usageLowAgentItems.length" class="mt-2 space-y-2">
|
||||
<div v-for="item in usageLowAgentItems" :key="item.agent" class="flex items-center justify-between gap-3 text-sm">
|
||||
<span class="truncate text-secondary" :title="item.agent">{{ item.agent }}</span>
|
||||
<span class="admin-report-badge">{{ item.count }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="mt-2 text-xs text-muted">{{ t('admin.report.usageLowAgentsEmpty') }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft p-3">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-xs font-semibold text-secondary">{{ t('admin.report.usageSpikeDays') }}</span>
|
||||
<div class="relative inline-flex">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex rounded p-0.5 text-muted transition-colors hover:text-brand-600"
|
||||
:aria-expanded="showSpikeDayHint"
|
||||
:aria-label="t('admin.report.usageSpikeDaysHintAria')"
|
||||
@click.stop="toggleSpikeDayHint"
|
||||
>
|
||||
<CircleHelp class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<div
|
||||
v-if="showSpikeDayHint"
|
||||
role="tooltip"
|
||||
class="absolute left-1/2 top-full z-20 mt-1.5 w-60 -translate-x-1/2 rounded-lg border border-default bg-surface px-3 py-2 text-xs leading-relaxed text-secondary shadow-elevated"
|
||||
@click.stop
|
||||
>
|
||||
{{ t('admin.report.usageSpikeDaysHint', {
|
||||
min: usageSpikeDayMinChats,
|
||||
multiplier: usageSpikeDayAvgMultiplier,
|
||||
limit: usageSpikeDayListLimit,
|
||||
}) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="usageSpikeDayItems.length" class="mt-2 space-y-2">
|
||||
<div v-for="item in usageSpikeDayItems" :key="item.date" class="flex items-center justify-between gap-3 text-sm">
|
||||
<span class="text-secondary">{{ item.date }}</span>
|
||||
<span class="admin-report-badge admin-report-badge--info">{{ item.count }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="mt-2 text-xs text-muted">{{ t('admin.report.usageSpikeDaysEmpty') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
|
||||
<div class="rounded-xl border border-default bg-surface p-5 flex flex-col">
|
||||
<div class="mb-4">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.byAgent') }}</h4>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.report.usageByAgentHint') }}</p>
|
||||
</div>
|
||||
<div class="space-y-3 flex-1 min-h-0 max-h-80 overflow-y-auto">
|
||||
<div v-for="a in usageTopAgentItems" :key="a.agent" class="flex items-center justify-between p-3 bg-surface-soft rounded-lg">
|
||||
<span class="font-medium text-secondary truncate" :title="a.agent">{{ a.agent }}</span>
|
||||
<span class="admin-report-badge admin-report-badge--info font-bold shrink-0">{{ a.count }}</span>
|
||||
</div>
|
||||
<div v-if="usageTopAgentItems.length === 0" class="text-center text-muted text-sm py-6">
|
||||
{{ t('admin.report.usageByAgentEmpty') }}
|
||||
</div>
|
||||
</div>
|
||||
<PaginationBar
|
||||
class="mt-4"
|
||||
:page="usageAgentPage"
|
||||
v-model:page-size="usageAgentPageSize"
|
||||
:total="usageAgentTotal"
|
||||
:pages="usageAgentTotalPages"
|
||||
:page-size-options="[...usageAgentPageSizeOptions]"
|
||||
@update:page="goToUsageAgentPage"
|
||||
/>
|
||||
</div>
|
||||
<div class="rounded-xl border border-default bg-surface p-5 flex flex-col">
|
||||
<div class="mb-4">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.byUser') }}</h4>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}</p>
|
||||
</div>
|
||||
<div class="space-y-3 flex-1 min-h-0 max-h-80 overflow-y-auto">
|
||||
<div v-for="u in usageTopUserItems" :key="u.username" class="flex items-center justify-between gap-3 p-3 bg-surface-soft rounded-lg">
|
||||
<span class="font-medium text-secondary truncate" :title="formatUsageUserLabel(u)">{{ formatUsageUserLabel(u) }}</span>
|
||||
<span class="admin-report-badge admin-report-badge--info font-bold shrink-0">{{ u.count }}</span>
|
||||
</div>
|
||||
<div v-if="usageTopUserItems.length === 0" class="text-center text-muted text-sm py-6">
|
||||
{{ t('admin.report.usageByUserEmpty') }}
|
||||
</div>
|
||||
</div>
|
||||
<PaginationBar
|
||||
class="mt-4"
|
||||
:page="usageUserPage"
|
||||
v-model:page-size="usageUserPageSize"
|
||||
:total="usageUserTotal"
|
||||
:pages="usageUserTotalPages"
|
||||
:page-size-options="[...usageUserPageSizeOptions]"
|
||||
@update:page="goToUsageUserPage"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="isApplicationOpsTable" class="space-y-5">
|
||||
<div class="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
|
||||
<div>
|
||||
<h3 class="section-title text-lg">{{ t('admin.report.appOps.title') }}</h3>
|
||||
<p class="mt-1 text-sm text-secondary">{{ t('admin.report.appOps.intro') }}</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<label class="flex items-center gap-2 text-sm text-secondary">
|
||||
<span class="whitespace-nowrap">{{ t('admin.report.usageRangeLabel') }}</span>
|
||||
<select v-model="applicationRange" class="admin-table-filter-input min-w-[8rem]">
|
||||
<option v-for="key in usageRangeOptions" :key="`app-range-${key}`" :value="key">
|
||||
{{ t(`admin.report.usageRanges.${key}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm text-secondary">
|
||||
<span class="whitespace-nowrap">{{ t('admin.report.appOps.statusLabel') }}</span>
|
||||
<select v-model="applicationStatus" class="admin-table-filter-input min-w-[7rem]">
|
||||
<option value="all">{{ t('admin.report.appOps.statusAll') }}</option>
|
||||
<option value="active">{{ t('admin.report.appOps.statusActive') }}</option>
|
||||
<option value="inactive">{{ t('admin.report.appOps.statusInactive') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm text-secondary">
|
||||
<span class="whitespace-nowrap">{{ t('admin.report.appOps.usageLabel') }}</span>
|
||||
<select v-model="applicationUsage" class="admin-table-filter-input min-w-[7rem]">
|
||||
<option value="all">{{ t('admin.report.appOps.usageAll') }}</option>
|
||||
<option value="used">{{ t('admin.report.appOps.usageUsed') }}</option>
|
||||
<option value="unused">{{ t('admin.report.appOps.usageUnused') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<input
|
||||
v-model="applicationQuery"
|
||||
type="search"
|
||||
class="admin-table-filter-input min-w-[10rem]"
|
||||
:placeholder="t('admin.report.appOps.searchPlaceholder')"
|
||||
@input="handleApplicationSearchChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="applicationSummary" class="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
<button type="button" class="rounded-xl border border-default bg-surface p-4 text-left" @click="setApplicationUsageFilter('all')">
|
||||
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryActive') }}</div>
|
||||
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.active_agents }}</div>
|
||||
<div class="mt-1 text-xs text-muted">{{ t('admin.report.appOps.summaryTotal', { total: applicationSummary.agent_total }) }}</div>
|
||||
</button>
|
||||
<button type="button" class="rounded-xl border border-default bg-surface p-4 text-left" @click="setApplicationUsageFilter('used')">
|
||||
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryUsed') }}</div>
|
||||
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.used_agents }}</div>
|
||||
</button>
|
||||
<button type="button" class="rounded-xl border border-default bg-surface p-4 text-left" @click="setApplicationUsageFilter('unused')">
|
||||
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryUnused') }}</div>
|
||||
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.unused_agents }}</div>
|
||||
</button>
|
||||
<div class="rounded-xl border border-default bg-surface p-4">
|
||||
<div class="text-sm text-muted">{{ t('admin.report.appOps.summaryPending') }}</div>
|
||||
<div class="mt-2 text-2xl font-bold text-primary">{{ applicationSummary.pending_permission_total }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-report-table-wrap">
|
||||
<table class="admin-report-table admin-report-table--app-ops w-full table-fixed border-collapse">
|
||||
<colgroup>
|
||||
<col class="w-[14%]" />
|
||||
<col class="w-[7%]" />
|
||||
<col class="w-[7%]" />
|
||||
<col class="w-[16%]" />
|
||||
<col class="w-[7%]" />
|
||||
<col class="w-[7%]" />
|
||||
<col class="w-[8%]" />
|
||||
<col class="w-[8%]" />
|
||||
<col class="w-[8%]" />
|
||||
<col class="w-[18%]" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
v-for="key in applicationSortableKeys"
|
||||
:key="`app-h-${key}`"
|
||||
class="px-3 py-3 text-left align-middle"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="admin-report-app-ops-sort-btn"
|
||||
@click="onApplicationSortClick(key)"
|
||||
>
|
||||
<span class="truncate">{{ t(`admin.report.appOps.columns.${key}`) }}</span>
|
||||
<span class="admin-report-app-ops-sort-mark" aria-hidden="true">{{ getApplicationSortMark(key) || '' }}</span>
|
||||
</button>
|
||||
</th>
|
||||
<th class="px-3 py-3 text-left align-middle">{{ t('admin.report.appOps.columns.category') }}</th>
|
||||
<th class="px-3 py-3 text-left align-middle">{{ t('admin.report.appOps.columns.is_active') }}</th>
|
||||
<th class="px-3 py-3 text-left align-middle">{{ t('admin.report.appOps.columns.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="applicationItems.length === 0">
|
||||
<td colspan="10" class="text-center text-muted py-12">
|
||||
{{ t('admin.report.appOps.empty') }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="row in applicationItems" :key="row.agent_id">
|
||||
<td class="px-3 py-3 text-left align-middle font-medium text-secondary truncate" :title="row.name">{{ row.name }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.chat_count }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.unique_users }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono text-xs whitespace-nowrap">
|
||||
{{ row.last_active_at ? formatLocalDateTime(row.last_active_at) : '-' }}
|
||||
</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.authorized_users }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums">{{ row.pending_requests }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle font-mono tabular-nums whitespace-nowrap">
|
||||
{{ row.avg_score == null ? '-' : row.avg_score }}
|
||||
<span v-if="row.feedback_count" class="text-xs text-muted">({{ row.feedback_count }})</span>
|
||||
</td>
|
||||
<td class="px-3 py-3 text-left align-middle text-secondary truncate">{{ row.category || '-' }}</td>
|
||||
<td class="px-3 py-3 text-left align-middle">
|
||||
<span class="admin-report-badge" :class="row.is_active ? 'admin-report-badge--info' : ''">
|
||||
{{ row.is_active ? t('admin.report.appOps.statusActive') : t('admin.report.appOps.statusInactive') }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-3 py-3 text-left align-middle">
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<button type="button" class="btn-secondary text-xs px-2 py-1" @click="openApplicationChatLogs(row)">
|
||||
{{ t('admin.report.appOps.actionLogs') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary text-xs px-2 py-1" @click="openApplicationPermissionRequests(row)">
|
||||
{{ t('admin.report.appOps.actionRequests') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<PaginationBar
|
||||
:page="applicationPage"
|
||||
v-model:page-size="applicationPageSize"
|
||||
:total="applicationTotal"
|
||||
:pages="applicationTotalPages"
|
||||
:page-size-options="[...applicationPageSizeOptions]"
|
||||
@update:page="goToApplicationPage"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showChatLogsColumnPanel"
|
||||
v-if="showChatLogsColumnPanel && !isApplicationOpsTable"
|
||||
class="admin-report-panel"
|
||||
>
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
@@ -245,7 +715,7 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!showReportTable" class="text-center text-muted py-20 bg-surface-soft rounded-2xl border border-dashed border-default">
|
||||
<div v-if="!showReportTable && !isUsageAnalysisTable && !isApplicationOpsTable" class="text-center text-muted py-20 bg-surface-soft rounded-2xl border border-dashed border-default">
|
||||
<p>{{ t('admin.report.noData', { table: getReportTableLabel(currentTable) }) }}</p>
|
||||
</div>
|
||||
|
||||
@@ -327,147 +797,15 @@ onMounted(() => {
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div v-if="showReportTable" class="flex flex-col gap-3 rounded-2xl border border-default bg-surface px-4 py-3 md:flex-row md:items-center md:justify-between">
|
||||
<div class="text-sm text-secondary">
|
||||
{{ t('admin.report.paginationSummary', { total: reportTotalRows, page: reportCurrentPage, pages: reportTotalPages }) }}
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<label class="flex items-center gap-2 text-xs text-secondary">
|
||||
<span>{{ t('admin.report.perPage') }}</span>
|
||||
<span class="relative inline-flex items-center">
|
||||
<select
|
||||
v-model.number="reportPageSize"
|
||||
class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5"
|
||||
>
|
||||
<option v-for="size in reportPageSizeOptions" :key="`page-size-${size}`" :value="size">{{ size }}</option>
|
||||
</select>
|
||||
<svg class="pointer-events-none absolute right-2 h-3.5 w-3.5 text-muted" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</span>
|
||||
<span>{{ t('admin.report.itemsUnit') }}</span>
|
||||
</label>
|
||||
<button
|
||||
@click="prevReportPage"
|
||||
:disabled="reportCurrentPage <= 1"
|
||||
class="admin-report-page-btn"
|
||||
>
|
||||
{{ t('admin.report.prevPage') }}
|
||||
</button>
|
||||
<button
|
||||
v-for="btn in reportPageButtons"
|
||||
:key="`report-page-btn-${btn}`"
|
||||
:disabled="btn === -1"
|
||||
@click="btn !== -1 && goToReportPage(btn)"
|
||||
class="admin-report-page-btn"
|
||||
:class="btn === -1
|
||||
? 'border-transparent text-muted cursor-default opacity-100'
|
||||
: btn === reportCurrentPage
|
||||
? 'admin-report-page-btn--active'
|
||||
: ''"
|
||||
>
|
||||
{{ btn === -1 ? '...' : btn }}
|
||||
</button>
|
||||
<button
|
||||
@click="nextReportPage"
|
||||
:disabled="reportCurrentPage >= reportTotalPages"
|
||||
class="admin-report-page-btn"
|
||||
>
|
||||
{{ t('admin.report.nextPage') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Statistics Charts -->
|
||||
<div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-default pt-10">
|
||||
<div class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h3 class="section-title text-lg">{{ t('admin.report.usage') }}</h3>
|
||||
<label class="flex items-center gap-2 text-sm text-secondary">
|
||||
<span class="whitespace-nowrap">{{ t('admin.report.usageRangeLabel') }}</span>
|
||||
<select v-model="usageRange" class="admin-table-filter-input min-w-[8rem]">
|
||||
<option v-for="key in usageRangeOptions" :key="key" :value="key">
|
||||
{{ t(`admin.report.usageRanges.${key}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div class="card p-6">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byAgent') }}</h4>
|
||||
<div class="space-y-3">
|
||||
<div v-for="a in usageReport.by_agent" :key="a.agent" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
|
||||
<span class="font-medium text-secondary">{{ a.agent }}</span>
|
||||
<span class="admin-report-badge admin-report-badge--info font-bold">{{ a.count }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card p-6 flex flex-col">
|
||||
<div class="mb-4">
|
||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider">{{ t('admin.report.byUser') }}</h4>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.report.usageByUserTopHint', { limit: usageUserTopLimit }) }}</p>
|
||||
</div>
|
||||
<div class="space-y-3 flex-1">
|
||||
<div v-for="u in usageReport.by_user" :key="u.username" class="flex items-center justify-between p-3 bg-surface-soft rounded-xl">
|
||||
<span class="font-medium text-secondary">{{ u.username }}</span>
|
||||
<span class="admin-report-badge admin-report-badge--info font-bold">{{ u.count }}</span>
|
||||
</div>
|
||||
<div v-if="usageReport.by_user.length === 0" class="text-center text-muted text-sm py-6">
|
||||
{{ t('admin.report.usageByUserEmpty') }}
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="usageUserTotal > 0" class="mt-4 flex flex-col gap-3 border-t border-default pt-4">
|
||||
<div class="text-xs text-secondary">
|
||||
{{ t('admin.report.paginationSummary', { total: usageUserTotal, page: usageUserPage, pages: usageUserTotalPages }) }}
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<label class="flex items-center gap-2 text-xs text-secondary">
|
||||
<span>{{ t('admin.report.perPage') }}</span>
|
||||
<span class="relative inline-flex items-center">
|
||||
<select
|
||||
v-model.number="usageUserPageSize"
|
||||
class="admin-table-filter-input appearance-none pl-2 pr-7 py-1 text-xs leading-5"
|
||||
>
|
||||
<option v-for="size in usageUserPageSizeOptions" :key="`usage-user-size-${size}`" :value="size">{{ size }}</option>
|
||||
</select>
|
||||
<svg class="pointer-events-none absolute right-2 h-3.5 w-3.5 text-muted" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</span>
|
||||
<span>{{ t('admin.report.itemsUnit') }}</span>
|
||||
</label>
|
||||
<button
|
||||
@click="prevUsageUserPage"
|
||||
:disabled="usageUserPage <= 1"
|
||||
class="admin-report-page-btn"
|
||||
>
|
||||
{{ t('admin.report.prevPage') }}
|
||||
</button>
|
||||
<button
|
||||
v-for="btn in usageUserPageButtons"
|
||||
:key="`usage-user-page-btn-${btn}`"
|
||||
:disabled="btn === -1"
|
||||
@click="btn !== -1 && goToUsageUserPage(btn)"
|
||||
class="admin-report-page-btn"
|
||||
:class="btn === -1
|
||||
? 'border-transparent text-muted cursor-default opacity-100'
|
||||
: btn === usageUserPage
|
||||
? 'admin-report-page-btn--active'
|
||||
: ''"
|
||||
>
|
||||
{{ btn === -1 ? '...' : btn }}
|
||||
</button>
|
||||
<button
|
||||
@click="nextUsageUserPage"
|
||||
:disabled="usageUserPage >= usageUserTotalPages"
|
||||
class="admin-report-page-btn"
|
||||
>
|
||||
{{ t('admin.report.nextPage') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<PaginationBar
|
||||
v-if="showReportTable"
|
||||
v-model:page="reportCurrentPage"
|
||||
v-model:page-size="reportPageSize"
|
||||
:total="reportTotalRows"
|
||||
:pages="reportTotalPages"
|
||||
:page-size-options="[...reportPageSizeOptions]"
|
||||
@update:page="goToReportPage"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
/**
|
||||
* features/admin/modules/reports/composables/useReportsAdmin.ts
|
||||
* 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除与带时间范围的用量图表)。
|
||||
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime。
|
||||
* 逻辑:ReportsPage 调用本 composable;使用分析默认近一月,可切换 7d/30d/90d/180d/365d。
|
||||
* 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除、使用分析与应用运营看板)。
|
||||
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime、vue-router。
|
||||
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,均复用 PaginationBar。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute } from 'vue-router';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import * as XLSX from 'xlsx';
|
||||
import {
|
||||
batchDeleteAdminChatLogs,
|
||||
getAdminApplicationReport,
|
||||
getAdminReportTable,
|
||||
getAdminReportTableCount,
|
||||
getAdminUsageReport,
|
||||
@@ -20,6 +21,11 @@ import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import { ADMIN_REPORT_TABLES } from '@/features/admin/constants/modules';
|
||||
import type {
|
||||
ApplicationReport,
|
||||
ApplicationReportItem,
|
||||
ApplicationSortKey,
|
||||
ApplicationStatusFilter,
|
||||
ApplicationUsageFilter,
|
||||
ChatLogsLayoutPref,
|
||||
ReportColumnConfig,
|
||||
SortRule,
|
||||
@@ -72,6 +78,7 @@ export function useReportsAdmin() {
|
||||
const { t, locale } = useI18n();
|
||||
const msg = useMessage();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const usageReport = ref<UsageReport | null>(null);
|
||||
const usageUserPage = ref(1);
|
||||
@@ -81,6 +88,24 @@ export function useReportsAdmin() {
|
||||
const usageRange = ref<UsageRangeKey>('30d');
|
||||
const usageRangeOptions: UsageRangeKey[] = ['7d', '30d', '90d', '180d', '365d'];
|
||||
|
||||
/** 按应用统计:前端分页(后端已返回范围内全部应用) */
|
||||
const usageAgentPage = ref(1);
|
||||
const usageAgentPageSize = ref(10);
|
||||
const usageAgentPageSizeOptions = [5, 10, 20, 50];
|
||||
|
||||
/** 应用运营看板状态(替换原 agents 配置表浏览) */
|
||||
const applicationReport = ref<ApplicationReport | null>(null);
|
||||
const applicationRange = ref<UsageRangeKey>('30d');
|
||||
const applicationStatus = ref<ApplicationStatusFilter>('all');
|
||||
const applicationUsage = ref<ApplicationUsageFilter>('all');
|
||||
const applicationQuery = ref('');
|
||||
const applicationSort = ref<ApplicationSortKey>('chat_count');
|
||||
const applicationOrder = ref<'asc' | 'desc'>('desc');
|
||||
const applicationPage = ref(1);
|
||||
const applicationPageSize = ref(20);
|
||||
const applicationPageSizeOptions = [10, 20, 50, 100];
|
||||
let applicationSearchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const loadUsageReport = async (): Promise<void> => {
|
||||
try {
|
||||
usageReport.value = await getAdminUsageReport({
|
||||
@@ -97,9 +122,179 @@ export function useReportsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 加载应用运营报表。
|
||||
* 核心逻辑:调用 /reports/applications,按当前筛选与排序拉取分页数据。
|
||||
*/
|
||||
const loadApplicationReport = async (): Promise<void> => {
|
||||
try {
|
||||
applicationReport.value = await getAdminApplicationReport({
|
||||
range: applicationRange.value,
|
||||
status: applicationStatus.value,
|
||||
usage: applicationUsage.value,
|
||||
q: applicationQuery.value,
|
||||
sort: applicationSort.value,
|
||||
order: applicationOrder.value,
|
||||
page: applicationPage.value,
|
||||
page_size: applicationPageSize.value,
|
||||
});
|
||||
const pages = applicationReport.value?.pages ?? 1;
|
||||
if (applicationPage.value > pages) {
|
||||
applicationPage.value = pages;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error loading application report:', e);
|
||||
applicationReport.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const applicationSummary = computed(() => applicationReport.value?.summary ?? null);
|
||||
const applicationItems = computed(() => applicationReport.value?.items ?? []);
|
||||
const applicationTotal = computed(() => applicationReport.value?.total ?? 0);
|
||||
const applicationTotalPages = computed(() => Math.max(1, applicationReport.value?.pages ?? 1));
|
||||
const applicationPageButtons = computed(() =>
|
||||
buildOffsetPageButtons(applicationPage.value, applicationTotalPages.value),
|
||||
);
|
||||
|
||||
const goToApplicationPage = (page: number): void => {
|
||||
applicationPage.value = Math.min(Math.max(1, page), applicationTotalPages.value);
|
||||
void loadApplicationReport();
|
||||
};
|
||||
const prevApplicationPage = () => goToApplicationPage(applicationPage.value - 1);
|
||||
const nextApplicationPage = () => goToApplicationPage(applicationPage.value + 1);
|
||||
|
||||
/**
|
||||
* 切换应用运营表头排序;同列再次点击翻转升降序。
|
||||
* @param key - 可排序字段
|
||||
*/
|
||||
const onApplicationSortClick = (key: ApplicationSortKey): void => {
|
||||
if (applicationSort.value === key) {
|
||||
applicationOrder.value = applicationOrder.value === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
applicationSort.value = key;
|
||||
applicationOrder.value = key === 'name' ? 'asc' : 'desc';
|
||||
}
|
||||
applicationPage.value = 1;
|
||||
void loadApplicationReport();
|
||||
};
|
||||
|
||||
const getApplicationSortMark = (key: ApplicationSortKey): string => {
|
||||
if (applicationSort.value !== key) return '';
|
||||
return applicationOrder.value === 'asc' ? '^' : 'v';
|
||||
};
|
||||
|
||||
/**
|
||||
* 应用名称搜索防抖,避免输入过程中频繁打接口。
|
||||
*/
|
||||
const handleApplicationSearchChange = (): void => {
|
||||
if (applicationSearchTimer) clearTimeout(applicationSearchTimer);
|
||||
applicationSearchTimer = setTimeout(() => {
|
||||
applicationPage.value = 1;
|
||||
void loadApplicationReport();
|
||||
}, 400);
|
||||
};
|
||||
|
||||
/**
|
||||
* 下钻到聊天日志,按 agent_id 精确过滤。
|
||||
* @param row - 应用运营行
|
||||
*/
|
||||
const openApplicationChatLogs = (row: ApplicationReportItem): void => {
|
||||
void router.push({
|
||||
name: 'AdminReports',
|
||||
params: { table: 'chat_logs' },
|
||||
query: { agent_id: String(row.agent_id), agent_name: row.name },
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 下钻到权限申请列表,按 agent_id 精确过滤。
|
||||
* @param row - 应用运营行
|
||||
*/
|
||||
const openApplicationPermissionRequests = (row: ApplicationReportItem): void => {
|
||||
void router.push({
|
||||
name: 'AdminReports',
|
||||
params: { table: 'permission_requests' },
|
||||
query: { agent_id: String(row.agent_id) },
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 导出应用运营报表 Excel(仅运营字段)。
|
||||
*/
|
||||
const exportApplicationReport = (): void => {
|
||||
const items = applicationItems.value;
|
||||
if (items.length === 0) return;
|
||||
const rows = items.map((row) => ({
|
||||
[t('admin.report.appOps.columns.name')]: row.name,
|
||||
[t('admin.report.appOps.columns.is_active')]: row.is_active
|
||||
? t('admin.report.appOps.statusActive')
|
||||
: t('admin.report.appOps.statusInactive'),
|
||||
[t('admin.report.appOps.columns.category')]: row.category || '-',
|
||||
[t('admin.report.appOps.columns.chat_count')]: row.chat_count,
|
||||
[t('admin.report.appOps.columns.unique_users')]: row.unique_users,
|
||||
[t('admin.report.appOps.columns.last_active_at')]: row.last_active_at
|
||||
? formatLocalDateTime(row.last_active_at)
|
||||
: '-',
|
||||
[t('admin.report.appOps.columns.authorized_users')]: row.authorized_users,
|
||||
[t('admin.report.appOps.columns.pending_requests')]: row.pending_requests,
|
||||
[t('admin.report.appOps.columns.avg_score')]: row.avg_score ?? '-',
|
||||
[t('admin.report.appOps.columns.feedback_count')]: row.feedback_count,
|
||||
[t('admin.report.appOps.columns.tokens_used')]: row.tokens_used,
|
||||
}));
|
||||
const ws = XLSX.utils.json_to_sheet(rows);
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'applications');
|
||||
XLSX.writeFile(wb, `applications_ops_${new Date().toISOString().split('T')[0]}.xlsx`);
|
||||
};
|
||||
|
||||
const usageUserTotalPages = computed(() => Math.max(1, usageReport.value?.user_pages ?? 1));
|
||||
const usageUserTotal = computed(() => usageReport.value?.user_total ?? 0);
|
||||
const usageUserTopLimit = computed(() => usageReport.value?.user_top_limit ?? 50);
|
||||
const usageActiveAgentCount = computed(() => usageReport.value?.by_agent.length ?? 0);
|
||||
const usageTrendMax = computed(() => Math.max(1, ...(usageReport.value?.by_day || []).map((item) => item.count)));
|
||||
/** 低使用应用:范围内对话次数 ≤ 该阈值 */
|
||||
const USAGE_LOW_AGENT_MAX_CHATS = 2;
|
||||
/** 低使用应用提醒最多展示条数 */
|
||||
const USAGE_LOW_AGENT_LIST_LIMIT = 5;
|
||||
/** 异常高峰:单日对话量下限(与日均倍数取较大者) */
|
||||
const USAGE_SPIKE_DAY_MIN_CHATS = 5;
|
||||
/** 异常高峰:相对日均的倍数阈值 */
|
||||
const USAGE_SPIKE_DAY_AVG_MULTIPLIER = 2;
|
||||
/** 异常高峰日期最多展示条数 */
|
||||
const USAGE_SPIKE_DAY_LIST_LIMIT = 3;
|
||||
const usageLowAgentItems = computed(() =>
|
||||
[...(usageReport.value?.by_agent || [])]
|
||||
.filter((item) => item.count <= USAGE_LOW_AGENT_MAX_CHATS)
|
||||
.sort((a, b) => a.count - b.count || a.agent.localeCompare(b.agent))
|
||||
.slice(0, USAGE_LOW_AGENT_LIST_LIMIT),
|
||||
);
|
||||
const usageSpikeDayItems = computed(() => {
|
||||
const days = usageReport.value?.by_day || [];
|
||||
if (days.length === 0) return [];
|
||||
const average = days.reduce((sum, item) => sum + item.count, 0) / days.length;
|
||||
// 高峰阈值:不低于下限,且不低于日均 × 倍数
|
||||
const threshold = Math.max(USAGE_SPIKE_DAY_MIN_CHATS, average * USAGE_SPIKE_DAY_AVG_MULTIPLIER);
|
||||
return days
|
||||
.filter((item) => item.count >= threshold)
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, USAGE_SPIKE_DAY_LIST_LIMIT);
|
||||
});
|
||||
const usageTopUserItems = computed(() => usageReport.value?.by_user ?? []);
|
||||
const usageAgentTotal = computed(() => usageReport.value?.by_agent.length ?? 0);
|
||||
const usageAgentTotalPages = computed(() => {
|
||||
const size = Math.max(1, Number(usageAgentPageSize.value) || 10);
|
||||
return Math.max(1, Math.ceil(usageAgentTotal.value / size));
|
||||
});
|
||||
/**
|
||||
* 按应用统计当前页数据(对话量降序全集上的偏移分页)。
|
||||
*/
|
||||
const usageTopAgentItems = computed(() => {
|
||||
const list = usageReport.value?.by_agent ?? [];
|
||||
const size = Math.max(1, Number(usageAgentPageSize.value) || 10);
|
||||
const page = Math.min(Math.max(1, usageAgentPage.value), usageAgentTotalPages.value);
|
||||
const start = (page - 1) * size;
|
||||
return list.slice(start, start + size);
|
||||
});
|
||||
const usageUserPageButtons = computed(() =>
|
||||
buildOffsetPageButtons(usageUserPage.value, usageUserTotalPages.value),
|
||||
);
|
||||
@@ -111,6 +306,14 @@ export function useReportsAdmin() {
|
||||
const prevUsageUserPage = () => goToUsageUserPage(usageUserPage.value - 1);
|
||||
const nextUsageUserPage = () => goToUsageUserPage(usageUserPage.value + 1);
|
||||
|
||||
/**
|
||||
* 跳转按应用统计分页(纯前端切片,无需重新请求)。
|
||||
* @param page - 目标页码
|
||||
*/
|
||||
const goToUsageAgentPage = (page: number): void => {
|
||||
usageAgentPage.value = Math.min(Math.max(1, page), usageAgentTotalPages.value);
|
||||
};
|
||||
|
||||
const loadReports = async (): Promise<void> => {
|
||||
await loadUsageReport();
|
||||
};
|
||||
@@ -145,7 +348,7 @@ export function useReportsAdmin() {
|
||||
if (typeof table === 'string' && (ADMIN_REPORT_TABLES as readonly string[]).includes(table)) {
|
||||
return table as AdminReportTableId;
|
||||
}
|
||||
return 'users';
|
||||
return 'usage_analysis';
|
||||
};
|
||||
|
||||
const currentTable = ref<AdminReportTableId>(resolveTableFromRoute());
|
||||
@@ -180,26 +383,55 @@ const resizingColumnKey = ref<string | null>(null);
|
||||
let resizeStartX = 0;
|
||||
let resizeStartWidth = 0;
|
||||
|
||||
/** 使用分析 / 应用运营是菜单层虚拟页,明细表仍复用对应数据源。 */
|
||||
const dataSourceTable = computed<Exclude<AdminReportTableId, 'usage_analysis'>>(() => {
|
||||
if (currentTable.value === 'usage_analysis') return 'chat_logs';
|
||||
return currentTable.value as Exclude<AdminReportTableId, 'usage_analysis'>;
|
||||
});
|
||||
|
||||
/**
|
||||
* 从路由 query 灌入列筛选(用于应用运营下钻到聊天日志 / 权限申请)。
|
||||
*/
|
||||
const applyRouteQueryFilters = (): void => {
|
||||
const next: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(route.query)) {
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
next[key] = value.trim();
|
||||
}
|
||||
}
|
||||
columnFilters.value = next;
|
||||
};
|
||||
|
||||
const loadTableData = async () => {
|
||||
// 应用运营页不走通用配置表
|
||||
if (currentTable.value === 'agents') {
|
||||
tableData.value = [];
|
||||
selectedReportRowIds.value = [];
|
||||
chatLogsColumns.value = [];
|
||||
await loadApplicationReport();
|
||||
return;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(columnFilters.value)) {
|
||||
if (value) params.append(key, value);
|
||||
}
|
||||
|
||||
const url = currentTable.value === 'general_feedbacks'
|
||||
const table = dataSourceTable.value;
|
||||
const url = table === 'general_feedbacks'
|
||||
? `/api/admin/reports/general-feedbacks?${params.toString()}`
|
||||
: `/api/admin/database/${currentTable.value}?${params.toString()}`;
|
||||
: `/api/admin/database/${table}?${params.toString()}`;
|
||||
|
||||
try {
|
||||
tableData.value = await getAdminReportTable(url);
|
||||
if (tableData.value.length > 0) {
|
||||
const rowKeys = Object.keys(tableData.value[0] || {});
|
||||
const columnKeys = currentTable.value === 'chat_logs'
|
||||
const columnKeys = dataSourceTable.value === 'chat_logs'
|
||||
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
|
||||
: rowKeys;
|
||||
initChatLogsColumns(columnKeys);
|
||||
}
|
||||
if (currentTable.value === 'chat_logs') {
|
||||
if (dataSourceTable.value === 'chat_logs') {
|
||||
const validIds = new Set(
|
||||
tableData.value
|
||||
.map((row: any) => Number(row?.id))
|
||||
@@ -229,7 +461,7 @@ const saveChatLogsColumns = () => {
|
||||
const initChatLogsColumns = (keys: string[]) => {
|
||||
chatLogsWrapEnabled.value = false;
|
||||
chatLogsWrapMaxHeight.value = 120;
|
||||
const hideByDefault = currentTable.value === 'chat_logs' && keys.includes('id');
|
||||
const hideByDefault = dataSourceTable.value === 'chat_logs' && keys.includes('id');
|
||||
const defaults: ReportColumnConfig[] = keys.map((k) => ({
|
||||
key: k,
|
||||
visible: hideByDefault ? k !== 'id' : true,
|
||||
@@ -246,7 +478,7 @@ const initChatLogsColumns = (keys: string[]) => {
|
||||
const missing = keys.filter((k) => !order.includes(k));
|
||||
merged = [...order, ...missing].map((k) => ({
|
||||
key: k,
|
||||
visible: savedMap.get(k)?.visible ?? (currentTable.value === 'chat_logs' && k === 'id' ? false : true),
|
||||
visible: savedMap.get(k)?.visible ?? (dataSourceTable.value === 'chat_logs' && k === 'id' ? false : true),
|
||||
width: savedMap.get(k)?.width ?? defaultChatLogsColumnWidth(k),
|
||||
}));
|
||||
if (!Array.isArray(parsed)) {
|
||||
@@ -272,7 +504,7 @@ const resetChatLogsColumns = () => {
|
||||
chatLogsSortRules.value = [];
|
||||
reportHeaderSort.value = null;
|
||||
const rowKeys = Object.keys(tableData.value[0] || {});
|
||||
const columnKeys = currentTable.value === 'chat_logs'
|
||||
const columnKeys = dataSourceTable.value === 'chat_logs'
|
||||
? CHAT_LOGS_TABLE_KEYS.filter((k) => rowKeys.includes(k))
|
||||
: rowKeys;
|
||||
initChatLogsColumns(columnKeys);
|
||||
@@ -353,6 +585,10 @@ const loadTableCount = async (table: string) => {
|
||||
};
|
||||
|
||||
const exportToExcel = () => {
|
||||
if (currentTable.value === 'agents') {
|
||||
exportApplicationReport();
|
||||
return;
|
||||
}
|
||||
if (tableData.value.length === 0) return;
|
||||
const keys = visibleReportKeys.value;
|
||||
const rows = tableData.value.map((row) => {
|
||||
@@ -377,10 +613,14 @@ const handleFilterChange = () => {
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const isChatLogsTable = computed(() => currentTable.value === 'chat_logs');
|
||||
/** 列已初始化后(含筛选无结果)仍展示表头与筛选框,避免用户无法修改条件 */
|
||||
const isUsageAnalysisTable = computed(() => currentTable.value === 'usage_analysis');
|
||||
const isApplicationOpsTable = computed(() => currentTable.value === 'agents');
|
||||
const isChatLogsTable = computed(() => dataSourceTable.value === 'chat_logs');
|
||||
/** 列已初始化后(含筛选无结果)仍展示表头与筛选框;应用运营页用专用看板,不展示通用表 */
|
||||
const showReportTable = computed(
|
||||
() => tableData.value.length > 0 || chatLogsColumns.value.length > 0,
|
||||
() =>
|
||||
!isApplicationOpsTable.value
|
||||
&& (tableData.value.length > 0 || chatLogsColumns.value.length > 0),
|
||||
);
|
||||
const visibleReportKeys = computed(() => {
|
||||
let keys: string[];
|
||||
@@ -406,7 +646,7 @@ const visibleReportKeys = computed(() => {
|
||||
return feedbackFixedOrder.filter((k) => available.has(k));
|
||||
}
|
||||
|
||||
if (currentTable.value === 'chat_logs') {
|
||||
if (dataSourceTable.value === 'chat_logs') {
|
||||
const available = new Set(keys);
|
||||
return CHAT_LOGS_REPORT_KEYS.filter((k) => available.has(k));
|
||||
}
|
||||
@@ -819,7 +1059,7 @@ const batchDeleteChatLogs = async () => {
|
||||
};
|
||||
|
||||
watch(currentTable, async () => {
|
||||
columnFilters.value = {}; // Reset filters on table change
|
||||
applyRouteQueryFilters();
|
||||
chatLogsColumns.value = [];
|
||||
selectedReportRowIds.value = [];
|
||||
showChatLogsColumnPanel.value = false;
|
||||
@@ -827,7 +1067,7 @@ watch(currentTable, async () => {
|
||||
reportCurrentPage.value = 1;
|
||||
await loadTableData();
|
||||
reportHeaderSort.value = null;
|
||||
if (currentTable.value === 'chat_logs') {
|
||||
if (dataSourceTable.value === 'chat_logs' && !isApplicationOpsTable.value) {
|
||||
chatLogsTotal.value = await loadTableCount('chat_logs');
|
||||
}
|
||||
});
|
||||
@@ -862,9 +1102,27 @@ watch(usageUserPageSize, () => {
|
||||
|
||||
watch(usageRange, () => {
|
||||
usageUserPage.value = 1;
|
||||
usageAgentPage.value = 1;
|
||||
void loadUsageReport();
|
||||
});
|
||||
|
||||
watch(usageAgentPageSize, () => {
|
||||
usageAgentPage.value = 1;
|
||||
});
|
||||
|
||||
watch(usageAgentTotalPages, (pages) => {
|
||||
if (usageAgentPage.value > pages) {
|
||||
usageAgentPage.value = pages;
|
||||
}
|
||||
});
|
||||
|
||||
watch([applicationRange, applicationStatus, applicationUsage, applicationPageSize], () => {
|
||||
applicationPage.value = 1;
|
||||
if (isApplicationOpsTable.value) {
|
||||
void loadApplicationReport();
|
||||
}
|
||||
});
|
||||
|
||||
watch([reportPageSize, sortedTableData], () => {
|
||||
if (reportCurrentPage.value > reportTotalPages.value) {
|
||||
reportCurrentPage.value = reportTotalPages.value;
|
||||
@@ -877,14 +1135,14 @@ watch([reportPageSize, sortedTableData], () => {
|
||||
const loadAll = async (): Promise<void> => {
|
||||
isLoading.value = true;
|
||||
await loadReports();
|
||||
columnFilters.value = {};
|
||||
applyRouteQueryFilters();
|
||||
selectedReportRowIds.value = [];
|
||||
showChatLogsColumnPanel.value = false;
|
||||
showChatLogsSelection.value = false;
|
||||
reportCurrentPage.value = 1;
|
||||
reportHeaderSort.value = null;
|
||||
await loadTableData();
|
||||
if (currentTable.value === 'chat_logs') {
|
||||
if (dataSourceTable.value === 'chat_logs' && !isApplicationOpsTable.value) {
|
||||
chatLogsTotal.value = await loadTableCount('chat_logs');
|
||||
} else {
|
||||
showChatLogsSelection.value = false;
|
||||
@@ -902,10 +1160,50 @@ watch([reportPageSize, sortedTableData], () => {
|
||||
usageUserTotal,
|
||||
usageUserTotalPages,
|
||||
usageUserTopLimit,
|
||||
usageActiveAgentCount,
|
||||
usageTrendMax,
|
||||
usageLowAgentMaxChats: USAGE_LOW_AGENT_MAX_CHATS,
|
||||
usageLowAgentListLimit: USAGE_LOW_AGENT_LIST_LIMIT,
|
||||
usageSpikeDayMinChats: USAGE_SPIKE_DAY_MIN_CHATS,
|
||||
usageSpikeDayAvgMultiplier: USAGE_SPIKE_DAY_AVG_MULTIPLIER,
|
||||
usageSpikeDayListLimit: USAGE_SPIKE_DAY_LIST_LIMIT,
|
||||
usageLowAgentItems,
|
||||
usageSpikeDayItems,
|
||||
usageTopUserItems,
|
||||
usageTopAgentItems,
|
||||
usageAgentPage,
|
||||
usageAgentPageSize,
|
||||
usageAgentPageSizeOptions,
|
||||
usageAgentTotal,
|
||||
usageAgentTotalPages,
|
||||
goToUsageAgentPage,
|
||||
usageUserPageButtons,
|
||||
goToUsageUserPage,
|
||||
prevUsageUserPage,
|
||||
nextUsageUserPage,
|
||||
applicationReport,
|
||||
applicationRange,
|
||||
applicationStatus,
|
||||
applicationUsage,
|
||||
applicationQuery,
|
||||
applicationSort,
|
||||
applicationOrder,
|
||||
applicationPage,
|
||||
applicationPageSize,
|
||||
applicationPageSizeOptions,
|
||||
applicationSummary,
|
||||
applicationItems,
|
||||
applicationTotal,
|
||||
applicationTotalPages,
|
||||
applicationPageButtons,
|
||||
goToApplicationPage,
|
||||
prevApplicationPage,
|
||||
nextApplicationPage,
|
||||
onApplicationSortClick,
|
||||
getApplicationSortMark,
|
||||
handleApplicationSearchChange,
|
||||
openApplicationChatLogs,
|
||||
openApplicationPermissionRequests,
|
||||
isLoading,
|
||||
currentTable,
|
||||
tableData,
|
||||
@@ -925,6 +1223,8 @@ watch([reportPageSize, sortedTableData], () => {
|
||||
chatLogsSortRules,
|
||||
reportHeaderSort,
|
||||
draggingColumnKey,
|
||||
isUsageAnalysisTable,
|
||||
isApplicationOpsTable,
|
||||
isChatLogsTable,
|
||||
showReportTable,
|
||||
visibleReportKeys,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* features/admin/stores/admin-nav.store.ts
|
||||
* 管理后台导航 UI 状态(侧栏折叠、报表展开、角标)。
|
||||
* 管理后台导航 UI 状态(侧栏折叠、报表/企微子菜单展开、角标)。
|
||||
*
|
||||
* 角标数据来自 GET /api/admin/dashboard/badges,在 store 内做 TTL 缓存与 in-flight 去重,
|
||||
* 避免切换 admin 子路由时重复请求(AdminLayout 挂载一次即可)。
|
||||
* 报表与企业微信子菜单默认折叠,进入对应模块时由 AdminNav 展开。
|
||||
*/
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
@@ -15,8 +16,10 @@ const BADGE_CACHE_TTL_MS = 60_000;
|
||||
|
||||
export const useAdminNavStore = defineStore('adminNav', () => {
|
||||
const sidebarCollapsed = ref(false);
|
||||
const reportsExpanded = ref(true);
|
||||
const wecomExpanded = ref(true);
|
||||
/** 数据报表子菜单:默认折叠 */
|
||||
const reportsExpanded = ref(false);
|
||||
/** 企业微信子菜单:默认折叠 */
|
||||
const wecomExpanded = ref(false);
|
||||
/** 「用户审批」导航角标:pending 注册用户数 */
|
||||
const pendingApprovalsCount = ref(0);
|
||||
/** 「权限申请」导航角标:pending 权限申请数 */
|
||||
|
||||
@@ -20,6 +20,7 @@ export type AdminModuleId =
|
||||
| 'reports';
|
||||
|
||||
export type AdminReportTableId =
|
||||
| 'usage_analysis'
|
||||
| 'users'
|
||||
| 'agents'
|
||||
| 'chat_logs'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/types/report.types.ts
|
||||
* 用途:报表模块类型(使用分析、列配置、排序规则)。
|
||||
* 用途:报表模块类型(使用分析、应用运营、列配置、排序规则)。
|
||||
* 依赖:无。
|
||||
* 逻辑:useReportsAdmin / admin.api 共用。
|
||||
*/
|
||||
@@ -12,8 +12,9 @@ export interface UsageReport {
|
||||
total: number;
|
||||
/** 当前统计时间范围 */
|
||||
range?: UsageRangeKey;
|
||||
by_user: { username: string; count: number }[];
|
||||
by_user: { username: string; real_name?: string; count: number }[];
|
||||
by_agent: { agent: string; count: number }[];
|
||||
/** 当前范围内按自然日聚合的对话趋势,用于使用分析柱状图。 */
|
||||
by_day?: { date: string; count: number }[];
|
||||
user_total: number;
|
||||
user_page: number;
|
||||
@@ -22,6 +23,62 @@ export interface UsageReport {
|
||||
user_top_limit: number;
|
||||
}
|
||||
|
||||
/** 应用运营报表:启用状态筛选 */
|
||||
export type ApplicationStatusFilter = 'all' | 'active' | 'inactive';
|
||||
|
||||
/** 应用运营报表:是否有使用筛选 */
|
||||
export type ApplicationUsageFilter = 'all' | 'used' | 'unused';
|
||||
|
||||
/** 应用运营报表可排序字段 */
|
||||
export type ApplicationSortKey =
|
||||
| 'name'
|
||||
| 'chat_count'
|
||||
| 'unique_users'
|
||||
| 'last_active_at'
|
||||
| 'authorized_users'
|
||||
| 'pending_requests'
|
||||
| 'avg_score'
|
||||
| 'tokens_used';
|
||||
|
||||
export interface ApplicationReportItem {
|
||||
agent_id: number;
|
||||
name: string;
|
||||
is_active: boolean;
|
||||
category: string;
|
||||
chat_count: number;
|
||||
unique_users: number;
|
||||
last_active_at: string | null;
|
||||
authorized_users: number;
|
||||
pending_requests: number;
|
||||
avg_score: number | null;
|
||||
feedback_count: number;
|
||||
tokens_used: number;
|
||||
avg_latency_ms: number | null;
|
||||
}
|
||||
|
||||
export interface ApplicationReportSummary {
|
||||
agent_total: number;
|
||||
active_agents: number;
|
||||
used_agents: number;
|
||||
unused_agents: number;
|
||||
pending_permission_total: number;
|
||||
}
|
||||
|
||||
export interface ApplicationReport {
|
||||
range: UsageRangeKey;
|
||||
status: ApplicationStatusFilter;
|
||||
usage: ApplicationUsageFilter;
|
||||
q: string;
|
||||
sort: ApplicationSortKey;
|
||||
order: 'asc' | 'desc';
|
||||
summary: ApplicationReportSummary;
|
||||
items: ApplicationReportItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
pages: number;
|
||||
}
|
||||
|
||||
export interface ReportColumnConfig {
|
||||
key: string;
|
||||
visible: boolean;
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/auth/components/LoginPage.vue
|
||||
* 登录页主内容:营销文案、公告列表与用户名/密码/企微登录表单。
|
||||
*
|
||||
* 用途:渲染登录页主内容,包括营销文案、公告列表、用户名/密码表单以及“记住我”入口。
|
||||
* 依赖:LOGIN_KEY provide、AnnouncementCardCarousel、共享登录背景与按钮样式。
|
||||
* 逻辑:登录表单仍以密码登录和企微登录为主;“记住我”按当前业务口径负责账号密码回填与登录态持久化。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { Bot, Megaphone } from 'lucide-vue-next';
|
||||
@@ -68,11 +71,42 @@ const lk = inject(LOGIN_KEY)! as any;
|
||||
<div class="space-y-5">
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs font-semibold text-primary uppercase ml-1">{{ $t('login.username') }}</label>
|
||||
<input v-model="lk.loginUsername" type="text" class="input-field" :placeholder="$t('login.placeholder.username')" @keyup.enter="lk.handleLogin" />
|
||||
<input
|
||||
v-model="lk.loginUsername"
|
||||
type="text"
|
||||
name="username"
|
||||
autocomplete="username"
|
||||
class="input-field"
|
||||
:placeholder="$t('login.placeholder.username')"
|
||||
@keyup.enter="lk.handleLogin"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs font-semibold text-primary uppercase ml-1">{{ $t('login.password') }}</label>
|
||||
<input v-model="lk.loginPassword" type="password" class="input-field" :placeholder="$t('login.placeholder.password')" @keyup.enter="lk.handleLogin" />
|
||||
<input
|
||||
v-model="lk.loginPassword"
|
||||
type="password"
|
||||
name="current-password"
|
||||
autocomplete="current-password"
|
||||
class="input-field"
|
||||
:placeholder="$t('login.placeholder.password')"
|
||||
@keyup.enter="lk.handleLogin"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between gap-4 text-sm">
|
||||
<label class="inline-flex items-center gap-2 text-secondary cursor-pointer select-none">
|
||||
<input
|
||||
v-model="lk.rememberMe"
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500"
|
||||
@change="lk.handleRememberMeChange"
|
||||
/>
|
||||
<span>{{ $t('login.rememberMe') }}</span>
|
||||
</label>
|
||||
<button type="button" @click="lk.openForgotPasswordModal" class="text-sm text-secondary hover:text-brand-700 transition-colors">
|
||||
{{ $t('login.forgotPassword') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button type="button" @click="lk.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">
|
||||
@@ -89,11 +123,7 @@ const lk = inject(LOGIN_KEY)! as any;
|
||||
{{ lk.isWecomLoggingIn ? $t('login.wecomConnecting') : $t('login.wecomLogin') }}
|
||||
</button>
|
||||
|
||||
<div class="flex justify-between items-center pt-4 mt-2 border-t border-subtle/50">
|
||||
<button type="button" @click="lk.openForgotPasswordModal" class="text-sm text-secondary hover:text-brand-700 transition-colors">
|
||||
{{ $t('login.forgotPassword') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="pt-4 mt-2 border-t border-subtle/50"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/auth/composables/useLogin.ts
|
||||
* 登录页编排层:组合认证、公告展示与 OAuth 回调,provide 给 LoginView 子组件。
|
||||
*/
|
||||
@@ -62,6 +62,7 @@ export function useLogin() {
|
||||
return;
|
||||
}
|
||||
|
||||
loginAuth.hydrateRememberedLoginState();
|
||||
await landing.fetchPublicAgents();
|
||||
landing.isLoading.value = false;
|
||||
});
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
/**
|
||||
/**
|
||||
* features/auth/composables/useLoginAuth.ts
|
||||
* 登录表单、企微/Casdoor OAuth 回调、注册与找回密码逻辑。
|
||||
*
|
||||
* 用途:封装登录表单、记住我偏好、企微/Casdoor OAuth 回调、注册与找回密码逻辑。
|
||||
* 依赖:shared/utils/auth、requestJson、WeCom/Casdoor 工具函数。
|
||||
* 逻辑:密码登录成功后根据“记住我”同步本地登录态与 remembered username/password;
|
||||
* OAuth 登录仅负责认证,不自动写入 remember 偏好,避免用户未明确选择时持久化登录页账号。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { config } from '@/config';
|
||||
@@ -10,7 +14,14 @@ import {
|
||||
normalizeWecomMatchRules,
|
||||
type WecomMatchField,
|
||||
} from '@/shared/utils/wecom';
|
||||
import { saveAuthUser } from '@/shared/utils/auth';
|
||||
import {
|
||||
clearRememberedLoginProfile,
|
||||
getRememberedLoginPreference,
|
||||
getRememberedLoginProfile,
|
||||
saveAuthUser,
|
||||
saveRememberedLoginPreference,
|
||||
saveRememberedLoginProfile,
|
||||
} from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
|
||||
import type { WecomBindPromptState, WecomLoginDialogContent } from '@/features/workspace/types/workspace.types';
|
||||
@@ -55,10 +66,47 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
window.history.replaceState({}, '', nextUrl);
|
||||
};
|
||||
|
||||
/**
|
||||
* 初始化登录页 remember 状态。
|
||||
* AI 触发时机:登录页首次渲染且用户尚未登录时使用;若用户上次勾选“记住我”,则回填 remembered username/password。
|
||||
*/
|
||||
const hydrateRememberedLoginState = () => {
|
||||
rememberMe.value = getRememberedLoginPreference();
|
||||
if (!rememberMe.value) return;
|
||||
const profile = getRememberedLoginProfile();
|
||||
if (profile?.username) {
|
||||
loginUsername.value = profile.username;
|
||||
loginPassword.value = profile.password;
|
||||
}
|
||||
};
|
||||
|
||||
const persistLoginUser = (user: Record<string, unknown>) => {
|
||||
saveAuthUser({ ...(user || {}) }, rememberMe.value);
|
||||
};
|
||||
|
||||
/**
|
||||
* 持久化登录页 remember 偏好。
|
||||
* AI 触发时机:仅当密码登录成功后执行;勾选时保存 remembered username/password,未勾选时清理本地自动回填数据。
|
||||
*/
|
||||
const persistRememberedLoginState = () => {
|
||||
if (!rememberMe.value) {
|
||||
clearRememberedLoginProfile();
|
||||
return;
|
||||
}
|
||||
saveRememberedLoginPreference(true);
|
||||
saveRememberedLoginProfile(loginUsername.value.trim(), loginPassword.value);
|
||||
};
|
||||
|
||||
/**
|
||||
* 处理“记住我”勾选变化。
|
||||
* AI 触发时机:用户在登录页手动取消勾选时,必须立即清理 remembered username/password,确保下次进入不再自动回填。
|
||||
*/
|
||||
const handleRememberMeChange = () => {
|
||||
if (!rememberMe.value) {
|
||||
clearRememberedLoginProfile();
|
||||
}
|
||||
};
|
||||
|
||||
const openForgotPasswordModal = () => {
|
||||
forgotPasswordForm.value = {
|
||||
employee_id: '',
|
||||
@@ -135,6 +183,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
});
|
||||
|
||||
persistLoginUser(user);
|
||||
persistRememberedLoginState();
|
||||
await completePasswordLogin();
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
@@ -398,6 +447,8 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
loginUsername,
|
||||
loginPassword,
|
||||
rememberMe,
|
||||
hydrateRememberedLoginState,
|
||||
handleRememberMeChange,
|
||||
showRegisterModal,
|
||||
showForgotPasswordModal,
|
||||
openForgotPasswordModal,
|
||||
|
||||
@@ -28,6 +28,12 @@ function normalizeAssetHistoryErrorMessage(message: string): string {
|
||||
if (lowerCaseMessage.includes('asset history share is not configured')) {
|
||||
return '当前系统暂未配置资产履历文件目录,暂时无法查看履历,请联系管理员处理。';
|
||||
}
|
||||
if (lowerCaseMessage.includes('asset history share is unreachable')) {
|
||||
return '当前环境暂时无法访问资产履历共享盘,请联系管理员检查测试环境共享盘挂载或访问权限。';
|
||||
}
|
||||
if (lowerCaseMessage.includes('asset history share is invalid')) {
|
||||
return '当前环境的资产履历目录配置无效,请联系管理员检查共享盘目录配置。';
|
||||
}
|
||||
return normalizedMessage || '检索资产履历失败';
|
||||
}
|
||||
|
||||
|
||||
@@ -386,26 +386,6 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
const target = event.target as HTMLElement | null;
|
||||
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
|
||||
const rawHref = anchor?.getAttribute('href') || '';
|
||||
// #region debug-point A:asset-history-anchor-click
|
||||
if (rawHref.startsWith('#asset-history?')) {
|
||||
fetch('http://127.0.0.1:7777/event', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
sessionId: 'asset-history-click',
|
||||
runId: 'pre-fix',
|
||||
hypothesisId: 'A',
|
||||
location: 'frontend/useChatPageMarkdown.ts',
|
||||
msg: '[DEBUG] asset history anchor clicked',
|
||||
data: {
|
||||
href: rawHref,
|
||||
tagName: target?.tagName || '',
|
||||
anchorText: String(anchor?.textContent || '').trim(),
|
||||
},
|
||||
ts: Date.now(),
|
||||
}),
|
||||
}).catch(() => {});
|
||||
}
|
||||
// #endregion
|
||||
if (rawHref.startsWith('#asset-history?')) {
|
||||
event.preventDefault();
|
||||
const params = new URLSearchParams(rawHref.slice('#asset-history?'.length));
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
/**
|
||||
* features/kb/utils/kb-display.utils.ts
|
||||
* 文档标题、时间、文件大小与状态徽标等纯展示工具。
|
||||
* 用途:文档标题、时间、文件大小与状态徽标等纯展示工具。
|
||||
* 依赖:kb.api 类型、kb-i18n.types、shared/utils/dateTime(UTC 时间戳本地化)。
|
||||
* 逻辑:KbWorkspace / KbAdminPanel 等调用;时间统一走 formatLocalDateTime,避免无时区后缀被当成本地时间导致差 8 小时。
|
||||
*/
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
import type { KbDocumentItem } from '../api/kb.api';
|
||||
import type { KbTranslateFn } from './kb-i18n.types';
|
||||
|
||||
/**
|
||||
* 格式化知识库时间戳为本地时区 `YYYY-MM-DD HH:mm:ss`。
|
||||
* 核心逻辑:委托 formatLocalDateTime;后端 isoformat() 常无 Z,按 UTC 解析后再转浏览器本地时区。
|
||||
* @param value - API 返回的时间字符串
|
||||
* @returns 本地展示文案;空值返回 `--`
|
||||
*/
|
||||
export const formatDateTime = (value?: string | null) => {
|
||||
if (!value) return '--';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
const formatted = formatLocalDateTime(value);
|
||||
return formatted === '-' ? '--' : formatted;
|
||||
};
|
||||
|
||||
export const formatFileSize = (value?: number | null) => {
|
||||
|
||||
@@ -761,7 +761,7 @@
|
||||
},
|
||||
"report": {
|
||||
"title": "Data Reports: {table}",
|
||||
"subtitle": "Raw data view and statistics",
|
||||
"subtitle": "Operational analytics and detail tracing",
|
||||
"export": "Export Excel",
|
||||
"columnSettings": "Column Settings",
|
||||
"showSelection": "Show Selection",
|
||||
@@ -878,8 +878,9 @@
|
||||
"general_feedbacks": "Feedback",
|
||||
"feedbacks": "Answer Rating",
|
||||
"departments": "Departments",
|
||||
"agents": "Agents",
|
||||
"permission_requests": "Permission Requests"
|
||||
"agents": "App Ops",
|
||||
"permission_requests": "Permission Requests",
|
||||
"usage_analysis": "Usage Analytics"
|
||||
},
|
||||
"feedbackValues": {
|
||||
"types": {
|
||||
@@ -898,6 +899,59 @@
|
||||
"chat": "Chat",
|
||||
"unknown": "Unknown"
|
||||
}
|
||||
},
|
||||
"usageIntro": "Review AI app trends, active users, low-usage apps, and unusual spikes.",
|
||||
"usageTotalSessions": "Total chats",
|
||||
"usageActiveUsers": "Active users",
|
||||
"usageActiveAgents": "Active apps",
|
||||
"usageTrend": "Recent trend",
|
||||
"usageTrendEmpty": "No trend data yet",
|
||||
"usageInsights": "Operational alerts",
|
||||
"usageLowAgents": "Low-usage apps",
|
||||
"usageLowAgentsHint": "Apps with ≤ {max} chats in the selected range, sorted ascending, showing up to {limit}.",
|
||||
"usageLowAgentsHintAria": "Show low-usage app selection rule",
|
||||
"usageLowAgentsEmpty": "No low-usage apps in this range",
|
||||
"usageSpikeDays": "Spike days",
|
||||
"usageSpikeDaysHint": "A day is a spike when chats ≥ max({min}, daily average × {multiplier}); sorted descending, showing up to {limit} days.",
|
||||
"usageSpikeDaysHintAria": "Show spike day selection rule",
|
||||
"usageSpikeDaysEmpty": "No clear spikes in this range",
|
||||
"usageByAgentEmpty": "No app chat activity yet",
|
||||
"usageByAgentHint": "All apps with chats in range, with pagination",
|
||||
"usageActiveUserHint": "Top 50 users by chat volume, with pagination",
|
||||
"appOps": {
|
||||
"title": "App Operations",
|
||||
"intro": "Per-app usage, authorization, pending requests, and ratings — with drill-down to chat logs and permission requests.",
|
||||
"statusLabel": "Status",
|
||||
"statusAll": "All",
|
||||
"statusActive": "Active",
|
||||
"statusInactive": "Inactive",
|
||||
"usageLabel": "Usage",
|
||||
"usageAll": "All",
|
||||
"usageUsed": "Used",
|
||||
"usageUnused": "Unused",
|
||||
"searchPlaceholder": "Search app name…",
|
||||
"summaryActive": "Active apps",
|
||||
"summaryTotal": "{total} total",
|
||||
"summaryUsed": "Used",
|
||||
"summaryUnused": "Unused",
|
||||
"summaryPending": "Pending permissions",
|
||||
"empty": "No application ops data. Try adjusting filters.",
|
||||
"actionLogs": "Logs",
|
||||
"actionRequests": "Requests",
|
||||
"columns": {
|
||||
"name": "App",
|
||||
"is_active": "Status",
|
||||
"category": "Category",
|
||||
"chat_count": "Chats",
|
||||
"unique_users": "Users",
|
||||
"last_active_at": "Last active",
|
||||
"authorized_users": "Authorized",
|
||||
"pending_requests": "Pending",
|
||||
"avg_score": "Avg score",
|
||||
"feedback_count": "Ratings",
|
||||
"tokens_used": "Tokens",
|
||||
"actions": "Actions"
|
||||
}
|
||||
}
|
||||
},
|
||||
"batchEdit": {
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
"accountDisabled": "Account is disabled",
|
||||
"dbConnectionFailed": "Database connection failed. Please check if the database service is running.",
|
||||
"internalError": "Internal server error. Please try again later.",
|
||||
"rememberMe": "Remember me for 30 days",
|
||||
"rememberMe": "Remember me",
|
||||
"forgotPasswordDesc": "Enter your employee ID and username; a reset link will be sent to your WeCom",
|
||||
"findPassword": "Find Password",
|
||||
"employeeIdRequired": "Please enter employee ID",
|
||||
|
||||
@@ -766,7 +766,7 @@
|
||||
},
|
||||
"report": {
|
||||
"title": "รายงานข้อมูล: {table}",
|
||||
"subtitle": "มุมมองข้อมูลดิบและสถิติ",
|
||||
"subtitle": "การวิเคราะห์การใช้งานและรายละเอียดย้อนหลัง",
|
||||
"export": "ส่งออก Excel",
|
||||
"columnSettings": "ตั้งค่าคอลัมน์",
|
||||
"showSelection": "แสดงการเลือก",
|
||||
@@ -797,7 +797,7 @@
|
||||
"exitFullscreen": "ออกจากเต็มหน้าจอ",
|
||||
"noData": "ไม่มีข้อมูลสำหรับ {table}",
|
||||
"noFilterResults": "ไม่พบข้อมูลที่ตรงกับเงื่อนไข โปรดปรับตัวกรอง",
|
||||
"usage": "การวิเคราะห์การใช้งาน",
|
||||
"usage": "วิเคราะห์การใช้งาน",
|
||||
"usageRangeLabel": "ช่วงเวลา",
|
||||
"usageRanges": {
|
||||
"7d": "7 วันล่าสุด",
|
||||
@@ -880,8 +880,62 @@
|
||||
"general_feedbacks": "ข้อเสนอแนะทั่วไป",
|
||||
"feedbacks": "การประเมินคำตอบ",
|
||||
"departments": "แผนก",
|
||||
"agents": "ตัวแทน",
|
||||
"permission_requests": "คำขอสิทธิ์"
|
||||
"agents": "แอปปฏิบัติการ",
|
||||
"permission_requests": "คำขอสิทธิ์",
|
||||
"usage_analysis": "วิเคราะห์การใช้งาน"
|
||||
},
|
||||
"usageIntro": "ดูแนวโน้มการเรียกใช้แอป AI ผู้ใช้ที่ใช้งาน แอปที่ใช้น้อย และช่วงพีคผิดปกติ",
|
||||
"usageTotalSessions": "จำนวนแชทรวม",
|
||||
"usageActiveUsers": "ผู้ใช้ที่ใช้งาน",
|
||||
"usageActiveAgents": "แอปที่ใช้งาน",
|
||||
"usageTrend": "แนวโน้มล่าสุด",
|
||||
"usageTrendEmpty": "ยังไม่มีข้อมูลแนวโน้ม",
|
||||
"usageInsights": "การแจ้งเตือนการดำเนินงาน",
|
||||
"usageLowAgents": "แอปที่ใช้น้อย",
|
||||
"usageLowAgentsHint": "แอปที่มีแชท ≤ {max} ครั้งในช่วงที่เลือก เรียงจากน้อยไปมาก แสดงสูงสุด {limit} รายการ",
|
||||
"usageLowAgentsHintAria": "ดูเกณฑ์การคัดเลือกแอปที่ใช้น้อย",
|
||||
"usageLowAgentsEmpty": "ไม่มีแอปที่ใช้น้อยในช่วงนี้",
|
||||
"usageSpikeDays": "วันที่มีการใช้งานพุ่งสูง",
|
||||
"usageSpikeDaysHint": "ถือว่าเป็นพีคเมื่อแชทต่อวัน ≥ max({min}, ค่าเฉลี่ยรายวัน × {multiplier}) เรียงจากมากไปน้อย แสดงสูงสุด {limit} วัน",
|
||||
"usageSpikeDaysHintAria": "ดูเกณฑ์การคัดเลือกวันพีค",
|
||||
"usageSpikeDaysEmpty": "ไม่พบช่วงพีคที่ชัดเจนในช่วงนี้",
|
||||
"usageByAgentEmpty": "ยังไม่มีประวัติแชทของแอป",
|
||||
"usageByAgentHint": "แสดงแอปทั้งหมดที่มีแชทในช่วงนี้ พร้อมแบ่งหน้า",
|
||||
"usageActiveUserHint": "ผู้ใช้ 50 อันดับแรกตามปริมาณแชท พร้อมแบ่งหน้า",
|
||||
"appOps": {
|
||||
"title": "แอปปฏิบัติการ",
|
||||
"intro": "ดูปริมาณการใช้ สิทธิ์ คำขอที่รอ และคะแนนรายแอป พร้อมเจาะลงบันทึกแชทและคำขอสิทธิ์",
|
||||
"statusLabel": "สถานะ",
|
||||
"statusAll": "ทั้งหมด",
|
||||
"statusActive": "เปิดใช้",
|
||||
"statusInactive": "ปิดใช้",
|
||||
"usageLabel": "การใช้งาน",
|
||||
"usageAll": "ทั้งหมด",
|
||||
"usageUsed": "มีการใช้",
|
||||
"usageUnused": "ไม่มีการใช้",
|
||||
"searchPlaceholder": "ค้นหาชื่อแอป…",
|
||||
"summaryActive": "แอปที่เปิดใช้",
|
||||
"summaryTotal": "ทั้งหมด {total}",
|
||||
"summaryUsed": "มีการใช้",
|
||||
"summaryUnused": "ไม่มีการใช้",
|
||||
"summaryPending": "สิทธิ์รอดำเนินการ",
|
||||
"empty": "ไม่มีข้อมูลแอปปฏิบัติการ ลองปรับตัวกรอง",
|
||||
"actionLogs": "บันทึก",
|
||||
"actionRequests": "คำขอ",
|
||||
"columns": {
|
||||
"name": "แอป",
|
||||
"is_active": "สถานะ",
|
||||
"category": "หมวด",
|
||||
"chat_count": "แชท",
|
||||
"unique_users": "ผู้ใช้",
|
||||
"last_active_at": "ใช้งานล่าสุด",
|
||||
"authorized_users": "ได้รับสิทธิ์",
|
||||
"pending_requests": "รอดำเนินการ",
|
||||
"avg_score": "คะแนนเฉลี่ย",
|
||||
"feedback_count": "จำนวนคะแนน",
|
||||
"tokens_used": "Token",
|
||||
"actions": "การทำงาน"
|
||||
}
|
||||
}
|
||||
},
|
||||
"batchEdit": {
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"loginRequired": "กรุณาเข้าสู่ระบบก่อนเริ่มการสนทนา",
|
||||
"requestFailed": "คำขอเข้าสู่ระบบล้มเหลว",
|
||||
"forgotPassword": "ลืมรหัสผ่าน?",
|
||||
"rememberMe": "จดจำการเข้าสู่ระบบ 30 วัน",
|
||||
"rememberMe": "จดจำฉัน",
|
||||
"announcements": "ประกาศ",
|
||||
"forgotPasswordDesc": "กรอกรหัสพนักงานและชื่อผู้ใช้ ลิงก์รีเซ็ตจะถูกส่งไปยัง WeCom ของคุณ",
|
||||
"findPassword": "ค้นหารหัสผ่าน",
|
||||
|
||||
@@ -762,7 +762,7 @@
|
||||
},
|
||||
"report": {
|
||||
"title": "数据报表: {table}",
|
||||
"subtitle": "原始数据与统计视图",
|
||||
"subtitle": "运营分析与明细追溯",
|
||||
"export": "导出 Excel",
|
||||
"columnSettings": "列设置",
|
||||
"showSelection": "显示选择",
|
||||
@@ -876,8 +876,62 @@
|
||||
"general_feedbacks": "意见反馈",
|
||||
"feedbacks": "回答评价",
|
||||
"departments": "部门",
|
||||
"agents": "应用",
|
||||
"permission_requests": "权限申请"
|
||||
"agents": "应用运营",
|
||||
"permission_requests": "权限申请",
|
||||
"usage_analysis": "使用分析"
|
||||
},
|
||||
"usageIntro": "查看 AI 应用调用趋势、活跃用户、低使用应用与异常高峰。",
|
||||
"usageTotalSessions": "对话总量",
|
||||
"usageActiveUsers": "活跃用户",
|
||||
"usageActiveAgents": "活跃应用",
|
||||
"usageTrend": "近段趋势",
|
||||
"usageTrendEmpty": "暂无趋势数据",
|
||||
"usageInsights": "运营提醒",
|
||||
"usageLowAgents": "低使用应用",
|
||||
"usageLowAgentsHint": "统计范围内对话次数 ≤ {max} 的应用,按对话量升序最多展示 {limit} 个。",
|
||||
"usageLowAgentsHintAria": "查看低使用应用选取规则",
|
||||
"usageLowAgentsEmpty": "当前范围内暂无低使用应用",
|
||||
"usageSpikeDays": "异常高峰日期",
|
||||
"usageSpikeDaysHint": "单日对话量 ≥ max({min}, 日均 × {multiplier}) 视为高峰,按对话量降序最多展示 {limit} 天。",
|
||||
"usageSpikeDaysHintAria": "查看异常高峰日期选取规则",
|
||||
"usageSpikeDaysEmpty": "当前范围内未发现明显高峰",
|
||||
"usageByAgentEmpty": "暂无应用对话记录",
|
||||
"usageByAgentHint": "展示范围内全部有对话的应用,支持翻页",
|
||||
"usageActiveUserHint": "对话量前 50 名用户,支持翻页",
|
||||
"appOps": {
|
||||
"title": "应用运营",
|
||||
"intro": "按应用查看使用量、授权、待审与评分,支持下钻聊天日志与权限申请。",
|
||||
"statusLabel": "状态",
|
||||
"statusAll": "全部",
|
||||
"statusActive": "启用",
|
||||
"statusInactive": "停用",
|
||||
"usageLabel": "使用",
|
||||
"usageAll": "全部",
|
||||
"usageUsed": "有使用",
|
||||
"usageUnused": "零使用",
|
||||
"searchPlaceholder": "搜索应用名称…",
|
||||
"summaryActive": "启用应用",
|
||||
"summaryTotal": "共 {total} 个",
|
||||
"summaryUsed": "有使用",
|
||||
"summaryUnused": "零使用",
|
||||
"summaryPending": "待审权限",
|
||||
"empty": "暂无应用运营数据,请调整筛选条件",
|
||||
"actionLogs": "日志",
|
||||
"actionRequests": "申请",
|
||||
"columns": {
|
||||
"name": "应用",
|
||||
"is_active": "状态",
|
||||
"category": "分类",
|
||||
"chat_count": "对话",
|
||||
"unique_users": "用户",
|
||||
"last_active_at": "最近活跃",
|
||||
"authorized_users": "授权",
|
||||
"pending_requests": "待审",
|
||||
"avg_score": "均分",
|
||||
"feedback_count": "评价数",
|
||||
"tokens_used": "Token",
|
||||
"actions": "操作"
|
||||
}
|
||||
}
|
||||
},
|
||||
"batchEdit": {
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
"accountDisabled": "账号已禁用",
|
||||
"dbConnectionFailed": "数据库连接失败,请检查数据库服务是否运行。",
|
||||
"internalError": "服务器内部错误,请稍后重试。",
|
||||
"rememberMe": "30天内免登录",
|
||||
"rememberMe": "记住我",
|
||||
"forgotPasswordDesc": "输入工号和用户名,重置链接将发送到您的企业微信",
|
||||
"findPassword": "找回密码",
|
||||
"employeeIdRequired": "请输入工号",
|
||||
|
||||
@@ -765,8 +765,8 @@
|
||||
"reject": "拒絕"
|
||||
},
|
||||
"report": {
|
||||
"title": "數據報表: {table}",
|
||||
"subtitle": "原始數據與統計視圖",
|
||||
"title": "資料報表: {table}",
|
||||
"subtitle": "營運分析與明細追溯",
|
||||
"export": "導出 Excel",
|
||||
"columnSettings": "列設置",
|
||||
"showSelection": "顯示選擇",
|
||||
@@ -880,8 +880,62 @@
|
||||
"general_feedbacks": "意見反饋",
|
||||
"feedbacks": "回答評價",
|
||||
"departments": "部門",
|
||||
"agents": "應用",
|
||||
"permission_requests": "權限申請"
|
||||
"agents": "應用運營",
|
||||
"permission_requests": "權限申請",
|
||||
"usage_analysis": "使用分析"
|
||||
},
|
||||
"usageIntro": "查看 AI 應用呼叫趨勢、活躍使用者、低使用應用與異常高峰。",
|
||||
"usageTotalSessions": "對話總量",
|
||||
"usageActiveUsers": "活躍使用者",
|
||||
"usageActiveAgents": "活躍應用",
|
||||
"usageTrend": "近段趨勢",
|
||||
"usageTrendEmpty": "暫無趨勢資料",
|
||||
"usageInsights": "營運提醒",
|
||||
"usageLowAgents": "低使用應用",
|
||||
"usageLowAgentsHint": "統計範圍內對話次數 ≤ {max} 的應用,按對話量升序最多展示 {limit} 個。",
|
||||
"usageLowAgentsHintAria": "查看低使用應用選取規則",
|
||||
"usageLowAgentsEmpty": "目前範圍內暫無低使用應用",
|
||||
"usageSpikeDays": "異常高峰日期",
|
||||
"usageSpikeDaysHint": "單日對話量 ≥ max({min}, 日均 × {multiplier}) 視為高峰,按對話量降序最多展示 {limit} 天。",
|
||||
"usageSpikeDaysHintAria": "查看異常高峰日期選取規則",
|
||||
"usageSpikeDaysEmpty": "目前範圍內未發現明顯高峰",
|
||||
"usageByAgentEmpty": "暫無應用對話記錄",
|
||||
"usageByAgentHint": "展示範圍內全部有對話的應用,支援翻頁",
|
||||
"usageActiveUserHint": "對話量前 50 名使用者,支援翻頁",
|
||||
"appOps": {
|
||||
"title": "應用運營",
|
||||
"intro": "按應用查看使用量、授權、待審與評分,支援下鑽聊天日誌與權限申請。",
|
||||
"statusLabel": "狀態",
|
||||
"statusAll": "全部",
|
||||
"statusActive": "啟用",
|
||||
"statusInactive": "停用",
|
||||
"usageLabel": "使用",
|
||||
"usageAll": "全部",
|
||||
"usageUsed": "有使用",
|
||||
"usageUnused": "零使用",
|
||||
"searchPlaceholder": "搜尋應用名稱…",
|
||||
"summaryActive": "啟用應用",
|
||||
"summaryTotal": "共 {total} 個",
|
||||
"summaryUsed": "有使用",
|
||||
"summaryUnused": "零使用",
|
||||
"summaryPending": "待審權限",
|
||||
"empty": "暫無應用運營資料,請調整篩選條件",
|
||||
"actionLogs": "日誌",
|
||||
"actionRequests": "申請",
|
||||
"columns": {
|
||||
"name": "應用",
|
||||
"is_active": "狀態",
|
||||
"category": "分類",
|
||||
"chat_count": "對話",
|
||||
"unique_users": "使用者",
|
||||
"last_active_at": "最近活躍",
|
||||
"authorized_users": "授權",
|
||||
"pending_requests": "待審",
|
||||
"avg_score": "均分",
|
||||
"feedback_count": "評價數",
|
||||
"tokens_used": "Token",
|
||||
"actions": "操作"
|
||||
}
|
||||
}
|
||||
},
|
||||
"batchEdit": {
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"loginRequired": "請先登錄後再進入對話",
|
||||
"requestFailed": "登錄請求失敗",
|
||||
"forgotPassword": "忘記密碼?",
|
||||
"rememberMe": "30天內免登入",
|
||||
"rememberMe": "記住我",
|
||||
"announcements": "公告",
|
||||
"forgotPasswordDesc": "輸入工號與用戶名,重設連結將發送到您的企業微信",
|
||||
"findPassword": "找回密碼",
|
||||
|
||||
@@ -24,7 +24,7 @@ const props = withDefaults(defineProps<{
|
||||
activeAgentId: null,
|
||||
compact: false,
|
||||
showSearch: true,
|
||||
defaultExpanded: true,
|
||||
defaultExpanded: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -64,7 +64,7 @@ const matchesQuery = (agent: AgentWithCategory, query: string) => {
|
||||
const filteredAgents = computed(() => {
|
||||
const q = searchQuery.value.trim();
|
||||
return props.agents.filter((agent) => {
|
||||
if (directoryMemberIds.value.has(agent.id)) return false;
|
||||
if (directoryMemberIds.value.has(agent.id) && !isAggregateAgent(agent)) return false;
|
||||
return matchesQuery(agent, q);
|
||||
});
|
||||
});
|
||||
@@ -134,18 +134,29 @@ const onSelect = (agent: AgentWithCategory) => {
|
||||
|
||||
/**
|
||||
* 统一 Agent 行的激活/默认样式类。
|
||||
* 核心逻辑:选中态用浅蓝底 + 品牌色文字,比实心 brand-600 更轻,与侧栏历史选中风格一致。
|
||||
* @param active - 是否为当前选中项
|
||||
* @param dense - 是否为目录成员等更紧凑的行
|
||||
*/
|
||||
const agentRowClass = (active: boolean, dense = false) => {
|
||||
const base = dense
|
||||
? 'group relative flex w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[11px] font-medium transition-all duration-150'
|
||||
: 'group relative flex w-full min-w-0 items-center gap-2 rounded-xl px-2.5 py-2 text-left text-xs font-medium transition-all duration-150';
|
||||
? 'group relative flex w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[11px] font-medium transition-colors duration-150'
|
||||
: 'group relative flex w-full min-w-0 items-center gap-2 rounded-xl px-2.5 py-2 text-left text-xs font-medium transition-colors duration-150';
|
||||
if (active) {
|
||||
return `${base} cursor-default bg-brand-50 text-brand-700 shadow-sm ring-1 ring-brand-100/80 dark:bg-brand-900/25 dark:text-brand-300 dark:ring-brand-800/40`;
|
||||
return `${base} cursor-default bg-brand-50 text-brand-700`;
|
||||
}
|
||||
return `${base} text-secondary hover:bg-surface hover:text-primary hover:shadow-sm`;
|
||||
return `${base} text-secondary hover:bg-surface hover:text-primary`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 聚合应用作为一级入口时选中态需要更强,避免与浅色未选中卡片混在一起。
|
||||
* 核心逻辑:浅蓝底 + 浅品牌描边表达选中,不用实心深蓝。
|
||||
*/
|
||||
const aggregateCardClass = (active: boolean) => (
|
||||
active
|
||||
? 'border-brand-200 bg-brand-50 text-brand-700'
|
||||
: 'border-subtle bg-surface'
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -170,12 +181,16 @@ const agentRowClass = (active: boolean, dense = false) => {
|
||||
<div
|
||||
v-for="agent in aggregateAgents"
|
||||
:key="agent.id"
|
||||
class="overflow-hidden rounded-2xl border border-subtle bg-surface shadow-sm"
|
||||
class="overflow-hidden rounded-2xl border transition-all duration-150"
|
||||
:class="aggregateCardClass(isActiveAgent(agent))"
|
||||
>
|
||||
<div class="flex min-w-0 items-stretch">
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-7 shrink-0 items-center justify-center text-muted transition-colors hover:bg-surface-soft hover:text-brand-600"
|
||||
class="flex w-7 shrink-0 items-center justify-center transition-colors"
|
||||
:class="isActiveAgent(agent)
|
||||
? 'text-brand-600 hover:bg-brand-100/60'
|
||||
: 'text-muted hover:bg-surface-soft hover:text-brand-600'"
|
||||
:title="isDirectoryCollapsed(agent.id) ? t('chat.expandAgents') : t('chat.collapseAgents')"
|
||||
@click.stop="toggleDirectory(agent.id)"
|
||||
>
|
||||
@@ -189,7 +204,7 @@ const agentRowClass = (active: boolean, dense = false) => {
|
||||
type="button"
|
||||
class="flex min-w-0 flex-1 items-center gap-1.5 py-1.5 pr-2.5 text-left transition-colors"
|
||||
:class="isActiveAgent(agent)
|
||||
? 'cursor-default bg-brand-50/80'
|
||||
? 'cursor-default bg-brand-50 text-brand-700'
|
||||
: 'hover:bg-surface-soft/80'"
|
||||
:aria-current="isActiveAgent(agent) ? 'page' : undefined"
|
||||
@click="onSelect(agent)"
|
||||
@@ -197,57 +212,55 @@ const agentRowClass = (active: boolean, dense = false) => {
|
||||
<span
|
||||
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md"
|
||||
:class="isActiveAgent(agent)
|
||||
? 'bg-brand-100 text-brand-600 dark:bg-brand-900/40 dark:text-brand-300'
|
||||
? 'bg-brand-100 text-brand-600'
|
||||
: 'bg-surface-strong text-brand-500'"
|
||||
>
|
||||
<FolderTree class="h-3 w-3" />
|
||||
</span>
|
||||
<span
|
||||
class="min-w-0 truncate text-xs font-semibold tracking-tight"
|
||||
:class="isActiveAgent(agent) ? 'text-brand-700 dark:text-brand-300' : 'text-primary'"
|
||||
:class="isActiveAgent(agent) ? 'text-brand-700' : 'text-primary'"
|
||||
>
|
||||
{{ agent.name }}
|
||||
</span>
|
||||
<span
|
||||
v-if="visibleDirectoryMembers(agent).length"
|
||||
class="ml-auto shrink-0 rounded px-1 py-px text-[10px] font-medium tabular-nums text-muted"
|
||||
class="ml-auto shrink-0 rounded px-1 py-px text-[10px] font-medium tabular-nums"
|
||||
:class="isActiveAgent(agent) ? 'text-brand-500' : 'text-muted'"
|
||||
>
|
||||
{{ visibleDirectoryMembers(agent).length }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-show="!isDirectoryCollapsed(agent.id)"
|
||||
class="border-t border-subtle bg-surface-soft/40 px-2 py-2"
|
||||
>
|
||||
<div v-show="!isDirectoryCollapsed(agent.id)" class="border-t border-subtle bg-surface-soft/40 px-2 py-2">
|
||||
<div class="grid grid-cols-2 gap-1">
|
||||
<button
|
||||
<template
|
||||
v-for="member in visibleDirectoryMembers(agent)"
|
||||
:key="`${agent.id}-${member.id}`"
|
||||
type="button"
|
||||
:class="agentRowClass(isActiveAgent(member), true)"
|
||||
:title="member.name"
|
||||
:aria-current="isActiveAgent(member) ? 'page' : undefined"
|
||||
@click="onSelect(member)"
|
||||
>
|
||||
<span
|
||||
v-if="isActiveAgent(member)"
|
||||
class="absolute inset-y-1 left-0 w-0.5 rounded-full bg-brand-500"
|
||||
/>
|
||||
<div
|
||||
v-if="member.icon_url"
|
||||
class="h-5 w-5 shrink-0 rounded-md bg-contain bg-center bg-no-repeat ring-1 ring-black/5"
|
||||
:style="{ backgroundImage: `url(${member.icon_url})` }"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-brand-50 text-[10px] font-bold text-brand-600 ring-1 ring-brand-100/60 dark:bg-brand-900/30 dark:text-brand-300 dark:ring-brand-800/40"
|
||||
<button
|
||||
type="button"
|
||||
:class="agentRowClass(isActiveAgent(member), true)"
|
||||
:title="member.name"
|
||||
:aria-current="isActiveAgent(member) ? 'page' : undefined"
|
||||
@click="onSelect(member)"
|
||||
>
|
||||
{{ member.name.charAt(0) }}
|
||||
</div>
|
||||
<span class="min-w-0 truncate leading-tight">{{ member.name }}</span>
|
||||
</button>
|
||||
<span v-if="isActiveAgent(member)" class="absolute inset-y-1 left-0 w-0.5 rounded-full bg-brand-500" />
|
||||
<div
|
||||
v-if="member.icon_url"
|
||||
class="h-5 w-5 shrink-0 rounded-md bg-contain bg-center bg-no-repeat ring-1 ring-black/5"
|
||||
:style="{ backgroundImage: `url(${member.icon_url})` }"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-brand-50 text-[10px] font-bold text-brand-600 ring-1 ring-brand-100/60 dark:bg-brand-900/30 dark:text-brand-300 dark:ring-brand-800/40"
|
||||
>
|
||||
{{ member.name.charAt(0) }}
|
||||
</div>
|
||||
<span class="min-w-0 truncate leading-tight">{{ member.name }}</span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -467,6 +467,24 @@
|
||||
@apply text-left transition-colors text-secondary hover:text-brand-600;
|
||||
}
|
||||
|
||||
/* 应用运营表:取消 uppercase/tracking;表头与单元格统一左对齐,排序箭头不挤占文案起点 */
|
||||
.admin-report-table--app-ops thead {
|
||||
@apply normal-case tracking-normal;
|
||||
}
|
||||
|
||||
.admin-report-table--app-ops thead th,
|
||||
.admin-report-table--app-ops tbody td {
|
||||
@apply align-middle text-left;
|
||||
}
|
||||
|
||||
.admin-report-app-ops-sort-btn {
|
||||
@apply inline-flex max-w-full items-center justify-start gap-0.5 text-left text-xs font-semibold text-secondary transition-colors hover:text-brand-600;
|
||||
}
|
||||
|
||||
.admin-report-app-ops-sort-mark {
|
||||
@apply inline-block w-2.5 shrink-0 text-left text-[10px] leading-none text-brand-500;
|
||||
}
|
||||
|
||||
.admin-report-page-btn {
|
||||
@apply rounded-lg border border-default px-2.5 py-1.5 text-xs text-secondary transition-colors;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface AgentDirectoryMemberRef extends AgentCategoryFields {
|
||||
description?: string | null;
|
||||
agent_code?: string | null;
|
||||
dify_app_id?: string | null;
|
||||
is_aggregate?: boolean;
|
||||
directory_members?: AgentDirectoryMemberRef[];
|
||||
}
|
||||
|
||||
export interface AgentCategorySubGroup<T extends AgentWithCategory = AgentWithCategory> {
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* shared/utils/auth.test.ts
|
||||
*
|
||||
* 用途:覆盖认证本地存储的关键约束,避免“记住我”回归时把过期登录态或 remembered username/password 逻辑改坏。
|
||||
* 依赖:vitest、shared/utils/auth。
|
||||
* 逻辑:重点验证 remember payload 过期清理、remembered username/password 的存取,以及不勾选时不会生成本地持久登录态。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
clearRememberedLoginProfile,
|
||||
getRememberedLoginPreference,
|
||||
getRememberedLoginProfile,
|
||||
getStoredAuthUser,
|
||||
saveAuthUser,
|
||||
saveRememberedLoginPreference,
|
||||
saveRememberedLoginProfile,
|
||||
} from './auth';
|
||||
|
||||
class MemoryStorage implements Storage {
|
||||
private store = new Map<string, string>();
|
||||
|
||||
get length(): number {
|
||||
return this.store.size;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
getItem(key: string): string | null {
|
||||
return this.store.has(key) ? this.store.get(key) ?? null : null;
|
||||
}
|
||||
|
||||
key(index: number): string | null {
|
||||
return Array.from(this.store.keys())[index] ?? null;
|
||||
}
|
||||
|
||||
removeItem(key: string): void {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
setItem(key: string, value: string): void {
|
||||
this.store.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: new MemoryStorage(),
|
||||
writable: true,
|
||||
});
|
||||
|
||||
Object.defineProperty(globalThis, 'sessionStorage', {
|
||||
value: new MemoryStorage(),
|
||||
writable: true,
|
||||
});
|
||||
|
||||
describe('shared/utils/auth remember me helpers', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
it('stores remembered username and password for auto-fill', () => {
|
||||
saveRememberedLoginPreference(true);
|
||||
saveRememberedLoginProfile('26040006', 'Hxit@54321');
|
||||
|
||||
expect(getRememberedLoginPreference()).toBe(true);
|
||||
expect(getRememberedLoginProfile()).toMatchObject({
|
||||
username: '26040006',
|
||||
password: 'Hxit@54321',
|
||||
});
|
||||
expect(localStorage.getItem('hxops_login_profile')).not.toContain('Hxit@54321');
|
||||
});
|
||||
|
||||
it('clears expired remember login payload automatically', () => {
|
||||
localStorage.setItem('hxops_user', JSON.stringify({
|
||||
user: {
|
||||
username: 'remembered_user',
|
||||
role: 'admin',
|
||||
access_token: 'expired-token',
|
||||
},
|
||||
expiry: Date.now() - 1000,
|
||||
}));
|
||||
|
||||
expect(getStoredAuthUser()).toBeNull();
|
||||
expect(localStorage.getItem('hxops_user')).toBeNull();
|
||||
});
|
||||
|
||||
it('stores non-remembered login state in session storage only', () => {
|
||||
saveAuthUser({
|
||||
username: 'session_only_user',
|
||||
role: 'user',
|
||||
access_token: 'session-token',
|
||||
}, false);
|
||||
|
||||
expect(getStoredAuthUser()).toMatchObject({
|
||||
username: 'session_only_user',
|
||||
role: 'user',
|
||||
});
|
||||
expect(sessionStorage.getItem('hxops_user')).toContain('session_only_user');
|
||||
expect(localStorage.getItem('hxops_user')).toBeNull();
|
||||
});
|
||||
|
||||
it('removes remembered login preference when user cancels remember me', () => {
|
||||
saveRememberedLoginPreference(true);
|
||||
saveRememberedLoginProfile('26040006', 'Hxit@54321');
|
||||
|
||||
clearRememberedLoginProfile();
|
||||
|
||||
expect(getRememberedLoginPreference()).toBe(false);
|
||||
expect(getRememberedLoginProfile()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* shared/utils/auth.ts
|
||||
* 认证 token / 用户读写、logout、跨标签同步。
|
||||
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步等认证相关本地存储能力。
|
||||
* 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。
|
||||
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理,既支持 30 天免登录,也支持按业务确认方案回填账号密码。
|
||||
*/
|
||||
export interface AuthUser {
|
||||
id?: number;
|
||||
@@ -19,18 +21,87 @@ export interface AuthUser {
|
||||
token_expires_at?: number;
|
||||
}
|
||||
|
||||
interface StoredAuthPayload {
|
||||
user?: AuthUser;
|
||||
expiry?: number;
|
||||
}
|
||||
|
||||
export interface RememberedLoginProfile {
|
||||
username: string;
|
||||
password: string;
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
interface StoredRememberedLoginProfile {
|
||||
username?: string;
|
||||
password_ciphertext?: string;
|
||||
updated_at?: number;
|
||||
}
|
||||
|
||||
const AUTH_USER_KEY = 'hxops_user';
|
||||
const LOGIN_REMEMBER_KEY = 'hxops_login_remember';
|
||||
const LOGIN_PROFILE_KEY = 'hxops_login_profile';
|
||||
|
||||
/**
|
||||
* 对登录页 remember password 做轻量编码,避免在本地存储中直接裸露原始密码文本。
|
||||
* AI 触发时机:当业务明确要求自动回填密码时使用;这里只做本地编码,不改变“浏览器端可恢复”的事实。
|
||||
*/
|
||||
const encodeRememberedSecret = (value: string): string => {
|
||||
const text = String(value || '');
|
||||
if (!text) return '';
|
||||
const bytes = new TextEncoder().encode(text);
|
||||
let binary = '';
|
||||
for (const byte of bytes) {
|
||||
binary += String.fromCharCode(byte);
|
||||
}
|
||||
return globalThis.btoa(binary);
|
||||
};
|
||||
|
||||
/**
|
||||
* 解码本地 remember password。
|
||||
* AI 触发时机:登录页初始化需要回填密码时使用;解码失败时返回空串并清理坏数据。
|
||||
*/
|
||||
const decodeRememberedSecret = (value: string): string => {
|
||||
const text = String(value || '');
|
||||
if (!text) return '';
|
||||
const binary = globalThis.atob(text);
|
||||
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
||||
return new TextDecoder().decode(bytes);
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析认证存储载荷,并在 remember payload 过期时自动清理。
|
||||
* AI 触发时机:当登录页或请求拦截器需要读取当前登录态时,必须先经过这里判断 30 天免登录是否仍有效,
|
||||
* 避免 localStorage 中残留的旧 token 被误认为是有效登录态。
|
||||
*/
|
||||
const readStoredAuthPayload = (storage: Storage, key: string): StoredAuthPayload | null => {
|
||||
const stored = storage.getItem(key);
|
||||
if (!stored) return null;
|
||||
try {
|
||||
const data = JSON.parse(stored) as StoredAuthPayload | AuthUser;
|
||||
const payload = (data && typeof data === 'object' && ('user' in data || 'expiry' in data))
|
||||
? data as StoredAuthPayload
|
||||
: { user: data as AuthUser };
|
||||
if (payload.expiry && payload.expiry <= Date.now()) {
|
||||
storage.removeItem(key);
|
||||
return null;
|
||||
}
|
||||
return payload;
|
||||
} catch {
|
||||
storage.removeItem(key);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const getStoredAuthUser = (): AuthUser | null => {
|
||||
const candidates = [
|
||||
sessionStorage.getItem('hxops_user'),
|
||||
localStorage.getItem('hxops_user'),
|
||||
const candidates: Array<[Storage, string]> = [
|
||||
[sessionStorage, AUTH_USER_KEY],
|
||||
[localStorage, AUTH_USER_KEY],
|
||||
];
|
||||
for (const stored of candidates) {
|
||||
if (!stored) continue;
|
||||
try {
|
||||
const data = JSON.parse(stored);
|
||||
return (data.user || data) as AuthUser;
|
||||
} catch {
|
||||
continue;
|
||||
for (const [storage, key] of candidates) {
|
||||
const payload = readStoredAuthPayload(storage, key);
|
||||
if (payload?.user) {
|
||||
return payload.user;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -58,11 +129,11 @@ export const saveAuthUser = (user: AuthUser, remember = false): void => {
|
||||
? { user: next, expiry: Date.now() + 30 * 24 * 60 * 60 * 1000 }
|
||||
: { user: next };
|
||||
if (remember) {
|
||||
localStorage.setItem('hxops_user', JSON.stringify(payload));
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(payload));
|
||||
sessionStorage.removeItem(AUTH_USER_KEY);
|
||||
} else {
|
||||
sessionStorage.setItem('hxops_user', JSON.stringify(payload));
|
||||
localStorage.removeItem('hxops_user');
|
||||
sessionStorage.setItem(AUTH_USER_KEY, JSON.stringify(payload));
|
||||
localStorage.removeItem(AUTH_USER_KEY);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -73,12 +144,100 @@ let _authBroadcast: BroadcastChannel | null = null;
|
||||
let _authSyncInitialized = false;
|
||||
|
||||
const clearAuthStorage = (): void => {
|
||||
localStorage.removeItem('hxops_user');
|
||||
sessionStorage.removeItem('hxops_user');
|
||||
localStorage.removeItem(AUTH_USER_KEY);
|
||||
sessionStorage.removeItem(AUTH_USER_KEY);
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
sessionStorage.removeItem('hxops_casdoor_state');
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取登录页“记住我”偏好。
|
||||
* AI 触发时机:进入登录页时,需要先判断用户是否曾选择记住我,再决定是否回填 remembered username/password。
|
||||
*/
|
||||
export const getRememberedLoginPreference = (): boolean => {
|
||||
try {
|
||||
const stored = localStorage.getItem(LOGIN_REMEMBER_KEY);
|
||||
if (!stored) return false;
|
||||
const data = JSON.parse(stored) as { remember?: boolean };
|
||||
return Boolean(data?.remember);
|
||||
} catch {
|
||||
localStorage.removeItem(LOGIN_REMEMBER_KEY);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存登录页“记住我”偏好。
|
||||
* AI 触发时机:用户勾选或取消“记住我”时,应只调整登录偏好,不要误写密码或覆盖业务 token。
|
||||
*/
|
||||
export const saveRememberedLoginPreference = (remember: boolean): void => {
|
||||
if (!remember) {
|
||||
localStorage.removeItem(LOGIN_REMEMBER_KEY);
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(LOGIN_REMEMBER_KEY, JSON.stringify({ remember: true }));
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取 remembered username/password。
|
||||
* AI 触发时机:登录页初始化且 remember=true 时,用于回填上次成功登录的账号和密码,减少重复输入。
|
||||
*/
|
||||
export const getRememberedLoginProfile = (): RememberedLoginProfile | null => {
|
||||
try {
|
||||
const stored = localStorage.getItem(LOGIN_PROFILE_KEY);
|
||||
if (!stored) return null;
|
||||
const data = JSON.parse(stored) as StoredRememberedLoginProfile;
|
||||
const username = String(data?.username || '').trim();
|
||||
const password = decodeRememberedSecret(String(data?.password_ciphertext || ''));
|
||||
if (!username) {
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
return null;
|
||||
}
|
||||
if (!password) {
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
username,
|
||||
password,
|
||||
updated_at: Number(data?.updated_at || Date.now()),
|
||||
};
|
||||
} catch {
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存 remembered username/password。
|
||||
* AI 触发时机:仅当密码登录成功且用户明确勾选“记住我”后保存,用于下次回到登录页时直接回填并允许用户直接点登录。
|
||||
*/
|
||||
export const saveRememberedLoginProfile = (username: string, password: string): void => {
|
||||
const normalizedUsername = String(username || '').trim();
|
||||
const normalizedPassword = String(password || '');
|
||||
if (!normalizedUsername || !normalizedPassword) {
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(
|
||||
LOGIN_PROFILE_KEY,
|
||||
JSON.stringify({
|
||||
username: normalizedUsername,
|
||||
password_ciphertext: encodeRememberedSecret(normalizedPassword),
|
||||
updated_at: Date.now(),
|
||||
} satisfies StoredRememberedLoginProfile),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 清理登录页 remember 偏好和 remembered username/password。
|
||||
* AI 触发时机:用户取消“记住我”时,必须同步清理自动回填账号密码所需的数据,避免下次进入登录页仍残留旧凭据。
|
||||
*/
|
||||
export const clearRememberedLoginProfile = (): void => {
|
||||
localStorage.removeItem(LOGIN_REMEMBER_KEY);
|
||||
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
||||
};
|
||||
|
||||
const broadcastLogout = (): void => {
|
||||
try {
|
||||
localStorage.setItem(AUTH_LOGOUT_KEY, String(Date.now()));
|
||||
@@ -123,7 +282,7 @@ export const initAuthSync = (): void => {
|
||||
_authSyncInitialized = true;
|
||||
|
||||
window.addEventListener('storage', (event: StorageEvent) => {
|
||||
if (event.key === 'hxops_user' && event.newValue === null && event.oldValue != null) {
|
||||
if (event.key === AUTH_USER_KEY && event.newValue === null && event.oldValue != null) {
|
||||
handleRemoteLogout();
|
||||
return;
|
||||
}
|
||||
@@ -166,7 +325,7 @@ export const refreshAccessToken = async (): Promise<string | null> => {
|
||||
const data = await res.json();
|
||||
if (!data?.access_token) return null;
|
||||
// Preserve existing profile fields while replacing rotated token material.
|
||||
saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem('hxops_user')));
|
||||
saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem(AUTH_USER_KEY)));
|
||||
return String(data.access_token);
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# scripts/mount_fixed_asset_history.sh
|
||||
# 用途:在 Linux 宿主机将 Windows 固资履历 SMB 共享挂载到本地目录,供 hxops-backend 容器只读访问。
|
||||
# 依赖:cifs-utils、smbclient(可选连通性探测)、sudo;仓库内 .env.shared / .env.<env> 或已有凭据文件。
|
||||
# 逻辑:按 test/prod 选择挂载点 → 从 env 读账号密码写入 /etc/smbcredentials → mount.cifs → 可选写入 fstab。
|
||||
# 用法(在仓库根目录,最简):
|
||||
# sudo ./scripts/mount_fixed_asset_history.sh test --fstab
|
||||
# sudo ./scripts/mount_fixed_asset_history.sh prod --fstab
|
||||
# sudo ./scripts/mount_fixed_asset_history.sh test --status
|
||||
# sudo ./scripts/mount_fixed_asset_history.sh prod --umount
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
|
||||
ENV_NAME="${1:-}"
|
||||
ACTION="mount"
|
||||
if [[ "${2:-}" == "--fstab" ]]; then
|
||||
ACTION="mount_fstab"
|
||||
elif [[ "${2:-}" == "--umount" ]]; then
|
||||
ACTION="umount"
|
||||
elif [[ "${2:-}" == "--status" ]]; then
|
||||
ACTION="status"
|
||||
elif [[ -n "${2:-}" ]]; then
|
||||
echo "Unknown option: ${2}"
|
||||
echo "Usage: $0 <test|prod> [--fstab|--umount|--status]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "${ENV_NAME}" != "test" && "${ENV_NAME}" != "prod" ]]; then
|
||||
echo "Usage: $0 <test|prod> [--fstab|--umount|--status]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "Please run as root (sudo)."
|
||||
echo "Example: sudo $0 ${ENV_NAME:-test} --fstab"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
#
|
||||
# 从仓库 env 文件读取 KEY=VALUE(仅导出 FIXED_ASSET_HISTORY_*,避免 source 整份 .env)。
|
||||
# 核心逻辑:先读 .env.shared,再读 .env.<env> 覆盖;密码等特殊字符用 printf -v 赋值。
|
||||
#
|
||||
load_env_key() {
|
||||
local key="$1"
|
||||
local file="$2"
|
||||
local override="${3:-0}"
|
||||
local line value
|
||||
[[ -f "${file}" ]] || return 0
|
||||
line="$(grep -E "^${key}=" "${file}" | tail -n 1 || true)"
|
||||
[[ -n "${line}" ]] || return 0
|
||||
value="${line#*=}"
|
||||
value="${value%$'\r'}"
|
||||
if [[ "${value}" == \"*\" && "${value}" == *\" ]]; then
|
||||
value="${value:1:${#value}-2}"
|
||||
elif [[ "${value}" == \'*\' && "${value}" == *\' ]]; then
|
||||
value="${value:1:${#value}-2}"
|
||||
fi
|
||||
if [[ "${override}" == "1" || -z "${!key:-}" ]]; then
|
||||
printf -v "${key}" '%s' "${value}"
|
||||
export "${key}"
|
||||
fi
|
||||
}
|
||||
|
||||
load_fixed_asset_history_env() {
|
||||
local shared_env="${ROOT_DIR}/.env.shared"
|
||||
local env_file="${ROOT_DIR}/.env.${ENV_NAME}"
|
||||
local keys=(
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT
|
||||
FIXED_ASSET_HISTORY_SMB_SERVER
|
||||
FIXED_ASSET_HISTORY_SMB_SHARE
|
||||
FIXED_ASSET_HISTORY_SMB_SUBDIR
|
||||
FIXED_ASSET_HISTORY_SMB_DOMAIN
|
||||
FIXED_ASSET_HISTORY_MOUNT_UID
|
||||
FIXED_ASSET_HISTORY_MOUNT_GID
|
||||
FIXED_ASSET_HISTORY_CIFS_VERS
|
||||
)
|
||||
local key
|
||||
for key in "${keys[@]}"; do
|
||||
load_env_key "${key}" "${shared_env}" 0
|
||||
load_env_key "${key}" "${env_file}" 1
|
||||
done
|
||||
echo "[env] loaded FIXED_ASSET_HISTORY_* from .env.shared + .env.${ENV_NAME}"
|
||||
}
|
||||
|
||||
load_fixed_asset_history_env
|
||||
|
||||
# Windows UNC: \\192.168.100.130\设备履历记录\履历
|
||||
# 说明:部分内核不支持 mount.cifs 的 subdir= 选项(会报 Invalid argument / 22),
|
||||
# 因此改为:先挂共享根目录,再把「履历」子目录 bind 到 LOCAL_ROOT。
|
||||
SMB_SERVER="${FIXED_ASSET_HISTORY_SMB_SERVER:-192.168.100.130}"
|
||||
SMB_SHARE="${FIXED_ASSET_HISTORY_SMB_SHARE:-设备履历记录}"
|
||||
SMB_SUBDIR="${FIXED_ASSET_HISTORY_SMB_SUBDIR:-履历}"
|
||||
SMB_DOMAIN="${FIXED_ASSET_HISTORY_SMB_DOMAIN:-WORKGROUP}"
|
||||
CREDENTIALS_FILE="${FIXED_ASSET_HISTORY_CREDENTIALS_FILE:-/etc/smbcredentials/hxops-fixed-asset-history}"
|
||||
MOUNT_UID="${FIXED_ASSET_HISTORY_MOUNT_UID:-1001}"
|
||||
MOUNT_GID="${FIXED_ASSET_HISTORY_MOUNT_GID:-1001}"
|
||||
CIFS_VERS="${FIXED_ASSET_HISTORY_CIFS_VERS:-3.0}"
|
||||
|
||||
if [[ -n "${FIXED_ASSET_HISTORY_LOCAL_ROOT:-}" ]]; then
|
||||
MOUNT_POINT="${FIXED_ASSET_HISTORY_LOCAL_ROOT}"
|
||||
elif [[ "${ENV_NAME}" == "test" ]]; then
|
||||
MOUNT_POINT="/mnt/hxops-fixed-asset-history-test"
|
||||
else
|
||||
MOUNT_POINT="/mnt/hxops-fixed-asset-history-prod"
|
||||
fi
|
||||
|
||||
SHARE_MOUNT_POINT="${FIXED_ASSET_HISTORY_SHARE_MOUNT_POINT:-${MOUNT_POINT}-share}"
|
||||
|
||||
# [STEP 1] 组装 CIFS 远端路径与挂载选项(不含 subdir,兼容旧内核)
|
||||
REMOTE="//${SMB_SERVER}/${SMB_SHARE}"
|
||||
CIFS_OPTS_BASE="credentials=${CREDENTIALS_FILE},iocharset=utf8,uid=${MOUNT_UID},gid=${MOUNT_GID},file_mode=0755,dir_mode=0755,ro"
|
||||
MOUNT_OPTS="${CIFS_OPTS_BASE},vers=${CIFS_VERS}"
|
||||
FSTAB_CIFS_LINE="${REMOTE} ${SHARE_MOUNT_POINT} cifs ${MOUNT_OPTS},nofail,_netdev 0 0"
|
||||
FSTAB_BIND_LINE="${SHARE_MOUNT_POINT}/${SMB_SUBDIR} ${MOUNT_POINT} none bind,nofail 0 0"
|
||||
|
||||
ensure_packages() {
|
||||
if ! command -v mount.cifs >/dev/null 2>&1; then
|
||||
echo "[pkg] installing cifs-utils..."
|
||||
apt-get update -y
|
||||
apt-get install -y cifs-utils
|
||||
fi
|
||||
if ! command -v smbclient >/dev/null 2>&1; then
|
||||
echo "[pkg] installing smbclient (optional probe)..."
|
||||
apt-get install -y smbclient || true
|
||||
fi
|
||||
}
|
||||
|
||||
#
|
||||
# 确保凭据文件存在;优先复用已有文件,否则从环境变量写入。
|
||||
# 核心逻辑:绝不把密码写进仓库脚本;仅写入 chmod 600 的宿主机凭据文件。
|
||||
#
|
||||
ensure_credentials() {
|
||||
mkdir -p "$(dirname "${CREDENTIALS_FILE}")"
|
||||
if [[ -f "${CREDENTIALS_FILE}" ]]; then
|
||||
chmod 600 "${CREDENTIALS_FILE}"
|
||||
echo "[cred] using existing ${CREDENTIALS_FILE}"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local username="${FIXED_ASSET_HISTORY_SHARE_USERNAME:-}"
|
||||
local password="${FIXED_ASSET_HISTORY_SHARE_PASSWORD:-}"
|
||||
if [[ -z "${username}" || -z "${password}" ]]; then
|
||||
echo "[cred] missing ${CREDENTIALS_FILE}"
|
||||
echo "Create it manually:"
|
||||
echo " sudo mkdir -p /etc/smbcredentials"
|
||||
echo " sudo tee ${CREDENTIALS_FILE} >/dev/null <<'EOF'"
|
||||
echo "username=YOUR_USER"
|
||||
echo "password=YOUR_PASSWORD"
|
||||
echo "domain=${SMB_DOMAIN}"
|
||||
echo "EOF"
|
||||
echo " sudo chmod 600 ${CREDENTIALS_FILE}"
|
||||
echo "Or export FIXED_ASSET_HISTORY_SHARE_USERNAME / FIXED_ASSET_HISTORY_SHARE_PASSWORD then re-run."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
umask 077
|
||||
cat >"${CREDENTIALS_FILE}" <<EOF
|
||||
username=${username}
|
||||
password=${password}
|
||||
domain=${SMB_DOMAIN}
|
||||
EOF
|
||||
chmod 600 "${CREDENTIALS_FILE}"
|
||||
echo "[cred] wrote ${CREDENTIALS_FILE} (mode 600)"
|
||||
}
|
||||
|
||||
show_status() {
|
||||
echo "[status] env=${ENV_NAME}"
|
||||
echo "[status] remote=${REMOTE}"
|
||||
echo "[status] share_mount=${SHARE_MOUNT_POINT}"
|
||||
echo "[status] subdir=${SMB_SUBDIR}"
|
||||
echo "[status] local_root=${MOUNT_POINT}"
|
||||
if mountpoint -q "${SHARE_MOUNT_POINT}" 2>/dev/null; then
|
||||
echo "[status] share_mounted=yes"
|
||||
findmnt -n -o SOURCE,TARGET,FSTYPE,OPTIONS "${SHARE_MOUNT_POINT}" || true
|
||||
else
|
||||
echo "[status] share_mounted=no"
|
||||
fi
|
||||
if mountpoint -q "${MOUNT_POINT}" 2>/dev/null; then
|
||||
echo "[status] local_root_mounted=yes"
|
||||
findmnt -n -o SOURCE,TARGET,FSTYPE,OPTIONS "${MOUNT_POINT}" || true
|
||||
echo "[status] sample entries:"
|
||||
ls -la "${MOUNT_POINT}" | head -n 20
|
||||
else
|
||||
echo "[status] local_root_mounted=no"
|
||||
if [[ -d "${MOUNT_POINT}" ]]; then
|
||||
echo "[status] local_root directory exists but is not mounted"
|
||||
else
|
||||
echo "[status] local_root directory missing"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
do_umount() {
|
||||
if mountpoint -q "${MOUNT_POINT}" 2>/dev/null; then
|
||||
umount "${MOUNT_POINT}"
|
||||
echo "[umount] ${MOUNT_POINT}"
|
||||
else
|
||||
echo "[umount] ${MOUNT_POINT} is not mounted"
|
||||
fi
|
||||
if mountpoint -q "${SHARE_MOUNT_POINT}" 2>/dev/null; then
|
||||
umount "${SHARE_MOUNT_POINT}"
|
||||
echo "[umount] ${SHARE_MOUNT_POINT}"
|
||||
else
|
||||
echo "[umount] ${SHARE_MOUNT_POINT} is not mounted"
|
||||
fi
|
||||
}
|
||||
|
||||
#
|
||||
# 尝试多种 SMB 版本挂载共享根目录(避免单一 vers 导致 Invalid argument)。
|
||||
#
|
||||
mount_cifs_share_root() {
|
||||
local vers candidate_opts
|
||||
local versions=("${CIFS_VERS}" "3.0" "2.1" "2.0" "1.0")
|
||||
local tried=()
|
||||
local vers_item
|
||||
|
||||
for vers_item in "${versions[@]}"; do
|
||||
local skip=0
|
||||
local t
|
||||
for t in "${tried[@]:-}"; do
|
||||
if [[ "${t}" == "${vers_item}" ]]; then
|
||||
skip=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
[[ "${skip}" -eq 1 ]] && continue
|
||||
tried+=("${vers_item}")
|
||||
|
||||
candidate_opts="${CIFS_OPTS_BASE},vers=${vers_item}"
|
||||
echo "[mount] try cifs vers=${vers_item}: ${REMOTE} -> ${SHARE_MOUNT_POINT}"
|
||||
if mount -t cifs "${REMOTE}" "${SHARE_MOUNT_POINT}" -o "${candidate_opts}"; then
|
||||
MOUNT_OPTS="${candidate_opts}"
|
||||
FSTAB_CIFS_LINE="${REMOTE} ${SHARE_MOUNT_POINT} cifs ${MOUNT_OPTS},nofail,_netdev 0 0"
|
||||
echo "[mount] cifs ok with vers=${vers_item}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
echo "[mount] all cifs version attempts failed; check: dmesg | tail -n 30"
|
||||
return 1
|
||||
}
|
||||
|
||||
#
|
||||
# 执行挂载:共享根目录 CIFS + 「履历」子目录 bind 到 LOCAL_ROOT。
|
||||
#
|
||||
do_mount() {
|
||||
ensure_packages
|
||||
ensure_credentials
|
||||
mkdir -p "${SHARE_MOUNT_POINT}" "${MOUNT_POINT}"
|
||||
|
||||
if mountpoint -q "${MOUNT_POINT}" 2>/dev/null && mountpoint -q "${SHARE_MOUNT_POINT}" 2>/dev/null; then
|
||||
echo "[mount] already mounted"
|
||||
show_status
|
||||
return 0
|
||||
fi
|
||||
|
||||
# [STEP 2] 可选:用 smbclient 探测共享是否可达(失败不阻断,仅提示)
|
||||
if command -v smbclient >/dev/null 2>&1; then
|
||||
local user
|
||||
user="$(awk -F= '/^username=/{print $2; exit}' "${CREDENTIALS_FILE}")"
|
||||
echo "[probe] smbclient //${SMB_SERVER}/${SMB_SHARE} -U ${user} ..."
|
||||
if ! smbclient "//${SMB_SERVER}/${SMB_SHARE}" -A "${CREDENTIALS_FILE}" -c "ls" >/tmp/hxops-asset-history-smb-probe.log 2>&1; then
|
||||
echo "[probe] warning: smbclient probe failed; see /tmp/hxops-asset-history-smb-probe.log"
|
||||
echo "[probe] continue to mount.cifs anyway"
|
||||
else
|
||||
echo "[probe] smbclient ok"
|
||||
fi
|
||||
fi
|
||||
|
||||
# [STEP 3] 挂载共享根(不使用 subdir=,避免 error 22)
|
||||
if ! mountpoint -q "${SHARE_MOUNT_POINT}" 2>/dev/null; then
|
||||
mount_cifs_share_root
|
||||
else
|
||||
echo "[mount] share root already mounted: ${SHARE_MOUNT_POINT}"
|
||||
fi
|
||||
|
||||
local subdir_path="${SHARE_MOUNT_POINT}/${SMB_SUBDIR}"
|
||||
if [[ ! -d "${subdir_path}" ]]; then
|
||||
echo "[mount] subdir not found: ${subdir_path}"
|
||||
echo "[mount] share root contents:"
|
||||
ls -la "${SHARE_MOUNT_POINT}" | head -n 30
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# [STEP 4] 把「履历」bind 到 FIXED_ASSET_HISTORY_LOCAL_ROOT
|
||||
if ! mountpoint -q "${MOUNT_POINT}" 2>/dev/null; then
|
||||
echo "[mount] bind ${subdir_path} -> ${MOUNT_POINT}"
|
||||
mount --bind "${subdir_path}" "${MOUNT_POINT}"
|
||||
else
|
||||
echo "[mount] local_root already mounted: ${MOUNT_POINT}"
|
||||
fi
|
||||
|
||||
show_status
|
||||
}
|
||||
|
||||
#
|
||||
# 将 fstab 行幂等追加(CIFS 共享根 + bind 子目录),保证开机自动挂载。
|
||||
#
|
||||
ensure_fstab() {
|
||||
touch /etc/fstab
|
||||
if ! grep -Fqs "${SHARE_MOUNT_POINT}" /etc/fstab; then
|
||||
echo "${FSTAB_CIFS_LINE}" >>/etc/fstab
|
||||
echo "[fstab] appended cifs:"
|
||||
echo " ${FSTAB_CIFS_LINE}"
|
||||
else
|
||||
echo "[fstab] cifs entry for ${SHARE_MOUNT_POINT} already exists"
|
||||
fi
|
||||
if ! grep -Fqs "${MOUNT_POINT}" /etc/fstab; then
|
||||
echo "${FSTAB_BIND_LINE}" >>/etc/fstab
|
||||
echo "[fstab] appended bind:"
|
||||
echo " ${FSTAB_BIND_LINE}"
|
||||
else
|
||||
echo "[fstab] bind entry for ${MOUNT_POINT} already exists; review /etc/fstab if options changed"
|
||||
fi
|
||||
echo "[fstab] verify with: sudo mount -a && findmnt ${MOUNT_POINT}"
|
||||
}
|
||||
|
||||
case "${ACTION}" in
|
||||
status)
|
||||
show_status
|
||||
;;
|
||||
umount)
|
||||
do_umount
|
||||
;;
|
||||
mount)
|
||||
do_mount
|
||||
;;
|
||||
mount_fstab)
|
||||
do_mount
|
||||
ensure_fstab
|
||||
;;
|
||||
esac
|
||||
|
||||
echo
|
||||
echo "Next: recreate backend so the bind mount is visible inside the container:"
|
||||
echo " docker compose --env-file .env.${ENV_NAME} up -d hxops-backend"
|
||||
echo " docker exec hxops-backend ls -la ${MOUNT_POINT}"
|
||||
Reference in new issue
Block a user