fix(admin): admin管理页面优化,增加排序过滤等
This commit is contained in:
1 parent
0939aeb0d8
commit
fc843905d1
31 files changed
+1090
-671
No files matched your search
@@ -19,7 +19,7 @@ def _query_params() -> dict[str, str]:
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""聊天使用分析报表。"""
|
||||
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
@@ -28,7 +28,14 @@ def usage_report():
|
||||
user_page_size = int(request.args.get('user_page_size', 10))
|
||||
except (TypeError, ValueError):
|
||||
user_page_size = 10
|
||||
return jsonify(report_service.build_usage_report(user_page=user_page, user_page_size=user_page_size))
|
||||
range_key = request.args.get('range')
|
||||
return jsonify(
|
||||
report_service.build_usage_report(
|
||||
user_page=user_page,
|
||||
user_page_size=user_page_size,
|
||||
range_key=range_key,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
|
||||
@@ -8,7 +8,7 @@ backend/app/services/admin/report_service.py
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import desc, func
|
||||
@@ -18,13 +18,53 @@ from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
|
||||
|
||||
USAGE_BY_USER_TOP_LIMIT = 50
|
||||
|
||||
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
||||
USAGE_RANGE_DAYS = {
|
||||
'7d': 7,
|
||||
'30d': 30,
|
||||
'90d': 90,
|
||||
'180d': 180,
|
||||
'365d': 365,
|
||||
}
|
||||
DEFAULT_USAGE_RANGE = '30d'
|
||||
|
||||
def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
|
||||
"""聊天使用分析报表。"""
|
||||
total = db.session.query(ChatLog).count()
|
||||
|
||||
def resolve_usage_range_start(range_key: str | None) -> tuple[str, datetime]:
|
||||
"""
|
||||
解析使用分析时间范围,返回规范化 key 与起始 UTC 时间。
|
||||
|
||||
Args:
|
||||
range_key: 前端传入的 range(7d/30d/90d/180d/365d),非法值回退近一月。
|
||||
|
||||
Returns:
|
||||
(normalized_key, since_utc)
|
||||
"""
|
||||
key = (range_key or DEFAULT_USAGE_RANGE).strip().lower()
|
||||
days = USAGE_RANGE_DAYS.get(key)
|
||||
if days is None:
|
||||
key = DEFAULT_USAGE_RANGE
|
||||
days = USAGE_RANGE_DAYS[key]
|
||||
since = datetime.utcnow() - timedelta(days=days)
|
||||
return key, since
|
||||
|
||||
|
||||
def build_usage_report(*, user_page: int, user_page_size: int, range_key: str | None = None) -> dict:
|
||||
"""
|
||||
聊天使用分析报表(按应用 / 按用户),限定时间范围内的 ChatLog。
|
||||
|
||||
Args:
|
||||
user_page: 按用户统计分页页码。
|
||||
user_page_size: 每页条数(上限 USAGE_BY_USER_TOP_LIMIT)。
|
||||
range_key: 时间范围 key,见 USAGE_RANGE_DAYS。
|
||||
"""
|
||||
normalized_range, since = resolve_usage_range_start(range_key)
|
||||
base_filter = ChatLog.created_at >= since
|
||||
|
||||
total = db.session.query(ChatLog).filter(base_filter).count()
|
||||
by_agent = (
|
||||
db.session.query(Agent.name, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.filter(base_filter)
|
||||
.group_by(Agent.name)
|
||||
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
||||
.all()
|
||||
@@ -34,6 +74,7 @@ def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
|
||||
by_user_top = (
|
||||
db.session.query(User.username, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.filter(base_filter)
|
||||
.group_by(User.username)
|
||||
.order_by(desc(func.count(ChatLog.id)), User.username)
|
||||
.limit(USAGE_BY_USER_TOP_LIMIT)
|
||||
@@ -46,6 +87,7 @@ def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
|
||||
by_user_page = by_user_top[offset:offset + user_page_size]
|
||||
return {
|
||||
'total': total,
|
||||
'range': normalized_range,
|
||||
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
|
||||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||||
'user_total': user_total,
|
||||
|
||||
@@ -104,10 +104,39 @@ def apply_users_filters(query, query_params: dict[str, str]):
|
||||
return query
|
||||
|
||||
|
||||
# 用户列表允许的排序列(与前端「用户 / 部门」表头对应)
|
||||
USER_SORT_COLUMNS = {
|
||||
'username': User.username,
|
||||
'department': User.department,
|
||||
}
|
||||
|
||||
|
||||
def resolve_users_order_by(query_params: dict[str, str]):
|
||||
"""
|
||||
解析 sort_by / sort_dir,返回 order_by 列元组。
|
||||
|
||||
核心逻辑:仅允许 username、department;非法值回退按 id 升序;同值用 id 稳定次序。
|
||||
|
||||
Args:
|
||||
query_params: 请求查询参数(含 sort_by、sort_dir)。
|
||||
|
||||
Returns:
|
||||
可直接传入 Query.order_by(*...) 的列表达式元组。
|
||||
"""
|
||||
sort_by = (query_params.get('sort_by') or '').strip().lower()
|
||||
sort_dir = (query_params.get('sort_dir') or 'asc').strip().lower()
|
||||
column = USER_SORT_COLUMNS.get(sort_by)
|
||||
if column is None:
|
||||
return (User.id.asc(),)
|
||||
primary = column.desc() if sort_dir == 'desc' else column.asc()
|
||||
return (primary, User.id.asc())
|
||||
|
||||
|
||||
def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
query = apply_users_filters(db.session.query(User), query_params)
|
||||
order_by = resolve_users_order_by(query_params)
|
||||
if 'page' not in query_params:
|
||||
users = query.options(joinedload(User.agents)).order_by(User.id.asc()).all()
|
||||
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
||||
return [serialize_admin_user(u) for u in users]
|
||||
|
||||
try:
|
||||
@@ -128,7 +157,7 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
|
||||
users = (
|
||||
query.options(joinedload(User.agents))
|
||||
.order_by(User.id.asc())
|
||||
.order_by(*order_by)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
|
||||
@@ -17,12 +17,38 @@ def test_build_usage_report(app):
|
||||
db.session.add(ChatLog(user_id=user.id, agent_id=agent.id, query='hi', answer='ok', tokens_used=1))
|
||||
db.session.commit()
|
||||
|
||||
data = report_service.build_usage_report(user_page=1, user_page_size=10)
|
||||
data = report_service.build_usage_report(user_page=1, user_page_size=10, range_key='30d')
|
||||
assert data['total'] == 1
|
||||
assert data['range'] == '30d'
|
||||
assert data['by_user'][0]['username'] == 'report-user'
|
||||
assert data['by_agent'][0]['agent'] == 'report-agent'
|
||||
|
||||
|
||||
def test_build_usage_report_excludes_outside_range(app):
|
||||
"""超出所选时间范围的聊天日志不计入统计。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
with app.app_context():
|
||||
agent = Agent(name='range-agent', type='api', dify_app_id='app-range', dify_api_key='key-range')
|
||||
user = User(username='range-user', email='range@example.com', role='user')
|
||||
db.session.add_all([agent, user])
|
||||
db.session.flush()
|
||||
old = ChatLog(user_id=user.id, agent_id=agent.id, query='old', answer='ok', tokens_used=1)
|
||||
recent = ChatLog(user_id=user.id, agent_id=agent.id, query='new', answer='ok', tokens_used=1)
|
||||
db.session.add_all([old, recent])
|
||||
db.session.commit()
|
||||
old.created_at = datetime.utcnow() - timedelta(days=40)
|
||||
db.session.commit()
|
||||
|
||||
data = report_service.build_usage_report(user_page=1, user_page_size=10, range_key='7d')
|
||||
assert data['range'] == '7d'
|
||||
assert data['total'] == 1
|
||||
assert data['by_user'][0]['count'] == 1
|
||||
|
||||
invalid = report_service.resolve_usage_range_start('bad')
|
||||
assert invalid[0] == '30d'
|
||||
|
||||
|
||||
def test_build_feedback_report(app):
|
||||
with app.app_context():
|
||||
db.session.add(Feedback(score=5))
|
||||
|
||||
@@ -21,3 +21,34 @@ def test_approve_and_reject_user(app):
|
||||
user_service.reject_user(user.id)
|
||||
db.session.refresh(user)
|
||||
assert user.status == 'rejected'
|
||||
|
||||
|
||||
def test_list_users_sort_by_username_and_department(app):
|
||||
"""分页列表支持按用户名 / 部门排序,非法 sort_by 回退按 id。"""
|
||||
with app.app_context():
|
||||
db.session.add_all(
|
||||
[
|
||||
User(username='z-user', email='z@example.com', department='品保部', role='user', status='active'),
|
||||
User(username='a-user', email='a@example.com', department='资讯', role='user', status='active'),
|
||||
User(username='m-user', email='m@example.com', department='资讯', role='user', status='active'),
|
||||
]
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
by_name = user_service.list_users(
|
||||
{'page': '1', 'page_size': '20', 'sort_by': 'username', 'sort_dir': 'asc'}
|
||||
)
|
||||
assert [u['username'] for u in by_name['items'] if u['username'].endswith('-user')] == [
|
||||
'a-user',
|
||||
'm-user',
|
||||
'z-user',
|
||||
]
|
||||
|
||||
by_dept_desc = user_service.list_users(
|
||||
{'page': '1', 'page_size': '20', 'sort_by': 'department', 'sort_dir': 'desc'}
|
||||
)
|
||||
depts = [u['department'] for u in by_dept_desc['items'] if u['username'].endswith('-user')]
|
||||
assert depts == sorted(depts, reverse=True)
|
||||
|
||||
fallback = user_service.resolve_users_order_by({'sort_by': 'role', 'sort_dir': 'asc'})
|
||||
assert len(fallback) == 1
|
||||
@@ -7,7 +7,7 @@ import { requestJson } from '@/shared/api/client';
|
||||
import type { AdminUserRow } from '../types/admin.types';
|
||||
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
|
||||
import type { PaginatedResult } from '@/shared/types/pagination.types';
|
||||
import type { UsageReport } from '../types/report.types';
|
||||
import type { UsageReport, UsageRangeKey } from '../types/report.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
@@ -27,11 +27,15 @@ export interface ListAdminUsersPageParams {
|
||||
employee_id?: string;
|
||||
phone_number?: string;
|
||||
hideRejected?: boolean;
|
||||
/** 排序列:username | department */
|
||||
sortBy?: 'username' | 'department';
|
||||
/** 排序方向 */
|
||||
sortDir?: 'asc' | 'desc';
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页拉取用户列表(服务端筛选 + 分页,供用户管理页使用)。
|
||||
* @param params - 页码、每页条数与各字段模糊筛选
|
||||
* 分页拉取用户列表(服务端筛选 + 分页 + 排序,供用户管理页使用)。
|
||||
* @param params - 页码、每页条数、字段模糊筛选与 sortBy/sortDir
|
||||
*/
|
||||
export const listAdminUsersPage = (params: ListAdminUsersPageParams) => {
|
||||
const qs = new URLSearchParams();
|
||||
@@ -53,6 +57,8 @@ export const listAdminUsersPage = (params: ListAdminUsersPageParams) => {
|
||||
if (value) qs.set(queryKey, value);
|
||||
}
|
||||
if (params.hideRejected) qs.set('hide_rejected', 'true');
|
||||
if (params.sortBy) qs.set('sort_by', params.sortBy);
|
||||
if (params.sortDir) qs.set('sort_dir', params.sortDir);
|
||||
return requestJson<PaginatedResult<AdminUserRow>>(`/api/admin/users?${qs.toString()}`, auth());
|
||||
};
|
||||
export const createAdminUser = (payload: Record<string, unknown>) =>
|
||||
@@ -254,12 +260,15 @@ export const getAdminDashboardBadges = () =>
|
||||
export interface AdminUsageReportParams {
|
||||
user_page?: number;
|
||||
user_page_size?: number;
|
||||
/** 时间范围:7d | 30d | 90d | 180d | 365d */
|
||||
range?: UsageRangeKey;
|
||||
}
|
||||
|
||||
export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.user_page != null) qs.set('user_page', String(params.user_page));
|
||||
if (params.user_page_size != null) qs.set('user_page_size', String(params.user_page_size));
|
||||
if (params.range) qs.set('range', params.range);
|
||||
const query = qs.toString();
|
||||
return requestJson<UsageReport>(
|
||||
`/api/admin/reports/usage${query ? `?${query}` : ''}`,
|
||||
|
||||
@@ -1,25 +1,36 @@
|
||||
/**
|
||||
* features/admin/modules/departments/DepartmentsPage.vue
|
||||
* 部门管理独立页面。路由:/admin/departments
|
||||
* 用途:部门管理独立页面——全宽表格列表 + 列排序 + 创建/编辑居中弹窗。
|
||||
* 依赖:useDepartmentsAdmin、SortableTableHeader、DepartmentFormModal、DeleteConfirmDialog。
|
||||
* 逻辑:路由 /admin/departments;表头排序复用 shared SortableTableHeader + useTableSort。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Edit, Trash2 } from 'lucide-vue-next';
|
||||
import { Edit, Plus, Search, Trash2 } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
|
||||
import DepartmentFormModal from './components/DepartmentFormModal.vue';
|
||||
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const {
|
||||
departments,
|
||||
editingDept,
|
||||
filteredDepartments,
|
||||
form,
|
||||
searchQuery,
|
||||
sortKey,
|
||||
sortDir,
|
||||
isLoading,
|
||||
isSaving,
|
||||
showFormModal,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
resetForm,
|
||||
editDepartment,
|
||||
toggleSort,
|
||||
openCreateModal,
|
||||
openEditModal,
|
||||
closeFormModal,
|
||||
saveDepartment,
|
||||
deleteDepartment,
|
||||
closeDeleteConfirm,
|
||||
@@ -32,127 +43,137 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="section-gap animate-fade-in-up">
|
||||
<section class="admin-table-section animate-fade-in-up">
|
||||
<div v-if="isLoading" class="flex items-center justify-center py-20">
|
||||
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="admin-table-header admin-table-header--stacked">
|
||||
<div>
|
||||
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
|
||||
@click="openCreateModal"
|
||||
>
|
||||
<Plus class="w-4 h-4" />
|
||||
<span>{{ t('admin.dept.add') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
|
||||
<h3 class="font-bold text-primary mb-4">
|
||||
{{ editingDept.id ? t('admin.dept.edit') : t('admin.dept.add') }}
|
||||
</h3>
|
||||
<div class="form-stack">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field block">{{ t('admin.dept.fields.name') }}</label>
|
||||
<input
|
||||
v-model="editingDept.name"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.dept.fields.namePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.code') }}</label>
|
||||
<input
|
||||
v-model="editingDept.code"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.dept.fields.codePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.company') }}</label>
|
||||
<input
|
||||
v-model="editingDept.company"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.dept.fields.companyPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
|
||||
<textarea
|
||||
v-model="editingDept.description"
|
||||
rows="3"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.dept.fields.descriptionPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2 pt-2">
|
||||
<button
|
||||
v-if="editingDept.id"
|
||||
type="button"
|
||||
class="btn-ghost btn-sm"
|
||||
@click="resetForm"
|
||||
>
|
||||
{{ t('admin.cancel') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary btn-sm" @click="saveDepartment">
|
||||
{{ editingDept.id ? t('admin.update') : t('admin.add') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-table-filters--inline gap-3">
|
||||
<div class="relative flex-1 min-w-[200px] max-w-sm">
|
||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted pointer-events-none" />
|
||||
<input
|
||||
v-model="searchQuery"
|
||||
type="search"
|
||||
class="admin-table-filter-input w-full pl-9"
|
||||
:placeholder="t('admin.dept.searchPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="lg:col-span-2 admin-table-section">
|
||||
<div v-if="departments.length === 0" class="p-8 text-center text-muted">
|
||||
{{ t('admin.dept.noDepts') }}
|
||||
</div>
|
||||
<table v-else class="admin-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
|
||||
{{ t('admin.dept.headers.name') }}
|
||||
</th>
|
||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
|
||||
{{ t('admin.dept.headers.code') }}
|
||||
</th>
|
||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
|
||||
{{ t('admin.dept.headers.company') }}
|
||||
</th>
|
||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase text-right">
|
||||
{{ t('admin.dept.headers.actions') }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-subtle">
|
||||
<tr v-for="d in departments" :key="d.id">
|
||||
<td class="px-6 py-4">
|
||||
<div class="font-medium text-primary text-sm">{{ d.name }}</div>
|
||||
<div class="text-xs text-muted truncate max-w-xs mt-0.5">{{ d.description }}</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted font-mono">{{ d.code || '-' }}</td>
|
||||
<td class="px-6 py-4 text-sm text-muted">{{ d.company || '-' }}</td>
|
||||
<td class="px-6 py-4 text-right flex justify-end gap-2">
|
||||
<div class="admin-table-wrap">
|
||||
<!-- 列宽:名称 / 编码 / 公司 / 操作 -->
|
||||
<table class="admin-table table-fixed">
|
||||
<colgroup>
|
||||
<col class="w-[25%]" />
|
||||
<col class="w-[20%]" />
|
||||
<col class="w-[35%]" />
|
||||
<col class="w-[15%]" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-6 py-4 text-left text-xs">
|
||||
<SortableTableHeader
|
||||
column-key="name"
|
||||
:label="t('admin.dept.headers.name')"
|
||||
:active-key="sortKey"
|
||||
:direction="sortDir"
|
||||
@sort="toggleSort"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-xs">
|
||||
<SortableTableHeader
|
||||
column-key="code"
|
||||
:label="t('admin.dept.headers.code')"
|
||||
:active-key="sortKey"
|
||||
:direction="sortDir"
|
||||
@sort="toggleSort"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-xs">
|
||||
<SortableTableHeader
|
||||
column-key="company"
|
||||
:label="t('admin.dept.headers.company')"
|
||||
:active-key="sortKey"
|
||||
:direction="sortDir"
|
||||
@sort="toggleSort"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-right text-xs">{{ t('admin.dept.headers.actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="filteredDepartments.length === 0">
|
||||
<td colspan="4" class="px-6 admin-table-empty">
|
||||
{{ searchQuery.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts') }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="d in filteredDepartments" :key="d.id" class="group">
|
||||
<td class="px-6 py-4">
|
||||
<div class="font-medium text-primary text-sm truncate" :title="d.name">{{ d.name }}</div>
|
||||
<div
|
||||
v-if="d.description"
|
||||
class="text-xs text-muted truncate mt-0.5"
|
||||
:title="d.description"
|
||||
>
|
||||
{{ d.description }}
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted font-mono whitespace-nowrap truncate" :title="d.code || '-'">
|
||||
{{ d.code || '-' }}
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-muted truncate" :title="d.company || '-'">
|
||||
{{ d.company || '-' }}
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<div class="flex justify-end gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
|
||||
@click="editDepartment(d)"
|
||||
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
|
||||
:title="t('admin.dept.actions.edit')"
|
||||
@click="openEditModal(d)"
|
||||
>
|
||||
<Edit class="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||
:title="t('admin.dept.actions.delete')"
|
||||
@click="deleteDepartment(d.id)"
|
||||
>
|
||||
<Trash2 class="w-4 h-4" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<DepartmentFormModal
|
||||
:visible="showFormModal"
|
||||
:form="form"
|
||||
:is-saving="isSaving"
|
||||
@close="closeFormModal"
|
||||
@save="saveDepartment"
|
||||
/>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="showDeleteConfirmDialog"
|
||||
:message="deleteConfirmMessage"
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* features/admin/modules/departments/components/DepartmentFormModal.vue
|
||||
* 用途:部门创建/编辑居中弹窗。
|
||||
* 依赖:DepartmentFormState、admin 通用 modal 样式。
|
||||
* 逻辑:DepartmentsPage 打开本组件;提交时 emit save,由 useDepartmentsAdmin 调 API。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { DepartmentFormState } from '@/features/admin/types/department.types';
|
||||
|
||||
defineProps<{
|
||||
visible: boolean;
|
||||
form: DepartmentFormState;
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
save: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
||||
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">
|
||||
{{ form.id ? t('admin.dept.edit') : t('admin.dept.add') }}
|
||||
</h3>
|
||||
</div>
|
||||
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.name') }}</label>
|
||||
<input
|
||||
v-model="form.name"
|
||||
type="text"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.dept.fields.namePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.code') }}</label>
|
||||
<input
|
||||
v-model="form.code"
|
||||
type="text"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.dept.fields.codePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.company') }}</label>
|
||||
<input
|
||||
v-model="form.company"
|
||||
type="text"
|
||||
class="input-field text-sm"
|
||||
:placeholder="t('admin.dept.fields.companyPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
|
||||
<textarea
|
||||
v-model="form.description"
|
||||
rows="3"
|
||||
class="input-field text-sm resize-y"
|
||||
:placeholder="t('admin.dept.fields.descriptionPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">
|
||||
{{ t('admin.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary disabled:opacity-70"
|
||||
:disabled="isSaving"
|
||||
@click="emit('save')"
|
||||
>
|
||||
{{
|
||||
isSaving
|
||||
? t('admin.save') + '...'
|
||||
: form.id
|
||||
? t('admin.update')
|
||||
: t('admin.add')
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+106
-24
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
|
||||
* 部门管理:列表、创建、编辑、删除。
|
||||
* 用途:部门管理列表、搜索过滤、列排序、创建/编辑弹窗、删除。
|
||||
* 依赖:admin.api、department.types、useMessage、useTableSort。
|
||||
* 逻辑:DepartmentsPage 调用本 composable;排序状态委托 shared useTableSort。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
createAdminDepartment,
|
||||
@@ -11,24 +13,63 @@ import {
|
||||
updateAdminDepartment,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useTableSort } from '@/shared/composables/useTableSort';
|
||||
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
||||
import {
|
||||
createEmptyDepartmentForm,
|
||||
departmentRowToForm,
|
||||
type DepartmentFormState,
|
||||
} from '@/features/admin/types/department.types';
|
||||
|
||||
/** 部门表可排序列 */
|
||||
export type DeptSortKey = 'name' | 'code' | 'company';
|
||||
|
||||
export function useDepartmentsAdmin() {
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const departments = ref<AdminDepartmentRow[]>([]);
|
||||
const editingDept = ref<DepartmentFormState>(createEmptyDepartmentForm());
|
||||
const form = ref<DepartmentFormState>(createEmptyDepartmentForm());
|
||||
const searchQuery = ref('');
|
||||
const { sortKey, sortDir, toggleSort, sortItems } = useTableSort<DeptSortKey>({
|
||||
initialKey: 'name',
|
||||
initialDir: 'asc',
|
||||
});
|
||||
const isLoading = ref(true);
|
||||
const isSaving = ref(false);
|
||||
const showFormModal = ref(false);
|
||||
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
const deleteConfirmMessage = ref('');
|
||||
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
/**
|
||||
* 先按关键词过滤,再按当前排序列排序。
|
||||
* 核心逻辑:模糊匹配四字段 → useTableSort.sortItems。
|
||||
*/
|
||||
const filteredDepartments = computed(() => {
|
||||
const q = searchQuery.value.trim().toLowerCase();
|
||||
const filtered = q
|
||||
? departments.value.filter((d) => {
|
||||
const haystack = [d.name, d.code, d.company, d.description]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase();
|
||||
return haystack.includes(q);
|
||||
})
|
||||
: departments.value;
|
||||
|
||||
return sortItems(
|
||||
filtered,
|
||||
(row, key) => row[key],
|
||||
(a, b) => a.id - b.id,
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* 拉取部门列表并写入 departments。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const loadDepartments = async (): Promise<void> => {
|
||||
try {
|
||||
departments.value = await listAdminDepartments();
|
||||
@@ -38,23 +79,37 @@ export function useDepartmentsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 页面初始化:加载部门列表并结束 loading。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const loadAll = async (): Promise<void> => {
|
||||
isLoading.value = true;
|
||||
await loadDepartments();
|
||||
isLoading.value = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开删除确认对话框并绑定确认后的删除动作。
|
||||
* @param message - 确认文案
|
||||
* @param action - 用户确认后执行的异步删除逻辑
|
||||
*/
|
||||
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
|
||||
deleteConfirmMessage.value = message;
|
||||
deleteConfirmAction = action;
|
||||
showDeleteConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
/** 关闭删除确认对话框并清空待执行动作。 */
|
||||
const closeDeleteConfirm = (): void => {
|
||||
showDeleteConfirmDialog.value = false;
|
||||
deleteConfirmAction = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 执行删除确认对话框中绑定的删除动作。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const confirmDelete = async (): Promise<void> => {
|
||||
if (!deleteConfirmAction) return;
|
||||
try {
|
||||
@@ -64,44 +119,63 @@ export function useDepartmentsAdmin() {
|
||||
}
|
||||
};
|
||||
|
||||
const resetForm = (): void => {
|
||||
editingDept.value = createEmptyDepartmentForm();
|
||||
/** 打开「添加部门」弹窗并重置表单。 */
|
||||
const openCreateModal = (): void => {
|
||||
form.value = createEmptyDepartmentForm();
|
||||
showFormModal.value = true;
|
||||
};
|
||||
|
||||
const editDepartment = (dept: AdminDepartmentRow): void => {
|
||||
editingDept.value = {
|
||||
id: dept.id,
|
||||
name: dept.name,
|
||||
code: dept.code || '',
|
||||
company: dept.company || '',
|
||||
description: dept.description || '',
|
||||
};
|
||||
/**
|
||||
* 打开「编辑部门」弹窗并回填选中行数据。
|
||||
* @param dept - 待编辑的部门行
|
||||
*/
|
||||
const openEditModal = (dept: AdminDepartmentRow): void => {
|
||||
form.value = departmentRowToForm(dept);
|
||||
showFormModal.value = true;
|
||||
};
|
||||
|
||||
/** 关闭创建/编辑弹窗并重置表单。 */
|
||||
const closeFormModal = (): void => {
|
||||
showFormModal.value = false;
|
||||
form.value = createEmptyDepartmentForm();
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存部门:有 id 则更新,否则新建。
|
||||
* 核心逻辑:校验名称 → 调 create/update API → 刷新列表并关闭弹窗。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const saveDepartment = async (): Promise<void> => {
|
||||
if (!editingDept.value.name?.trim()) {
|
||||
if (!form.value.name?.trim()) {
|
||||
msg.warning(t('admin.dept.msg.nameRequired'));
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
const payload = {
|
||||
name: editingDept.value.name,
|
||||
code: editingDept.value.code,
|
||||
company: editingDept.value.company,
|
||||
description: editingDept.value.description,
|
||||
name: form.value.name.trim(),
|
||||
code: form.value.code?.trim() || '',
|
||||
company: form.value.company?.trim() || '',
|
||||
description: form.value.description?.trim() || '',
|
||||
};
|
||||
if (editingDept.value.id) {
|
||||
await updateAdminDepartment(editingDept.value.id, payload);
|
||||
if (form.value.id) {
|
||||
await updateAdminDepartment(form.value.id, payload);
|
||||
} else {
|
||||
await createAdminDepartment(payload);
|
||||
}
|
||||
closeFormModal();
|
||||
await loadDepartments();
|
||||
resetForm();
|
||||
} catch (e) {
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除指定部门,删除前弹出确认框。
|
||||
* @param id - 部门主键
|
||||
*/
|
||||
const deleteDepartment = (id: number): void => {
|
||||
openDeleteConfirm(t('admin.dept.confirmDelete'), async () => {
|
||||
try {
|
||||
@@ -116,13 +190,21 @@ export function useDepartmentsAdmin() {
|
||||
|
||||
return {
|
||||
departments,
|
||||
editingDept,
|
||||
filteredDepartments,
|
||||
form,
|
||||
searchQuery,
|
||||
sortKey,
|
||||
sortDir,
|
||||
isLoading,
|
||||
isSaving,
|
||||
showFormModal,
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
resetForm,
|
||||
editDepartment,
|
||||
toggleSort,
|
||||
openCreateModal,
|
||||
openEditModal,
|
||||
closeFormModal,
|
||||
saveDepartment,
|
||||
deleteDepartment,
|
||||
closeDeleteConfirm,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* features/admin/modules/permissions/PermissionsPage.vue
|
||||
* 用户权限矩阵独立页面。路由:/admin/permissions
|
||||
* 用途:应用权限矩阵独立页面(用户 / 真实姓名 / 部门 + Agent 勾选)。
|
||||
* 依赖:usePermissionsAdmin、BatchPermissionModal、PaginationBar。
|
||||
* 逻辑:路由 /admin/permissions;左侧用户相关列 sticky,右侧为各应用权限列。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
@@ -115,12 +117,17 @@ onMounted(() => {
|
||||
/>
|
||||
</th>
|
||||
<th
|
||||
class="px-6 py-4 text-left text-sm sticky left-12 admin-table-sticky-head z-20 w-64 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
|
||||
class="px-6 py-4 text-left text-sm sticky left-12 admin-table-sticky-head z-20 w-56"
|
||||
>
|
||||
{{ t('admin.perm.headers.user') }}
|
||||
</th>
|
||||
<th
|
||||
class="px-6 py-4 text-left text-sm sticky left-[19rem] admin-table-sticky-head z-20 w-40 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
|
||||
class="px-6 py-4 text-left text-sm sticky left-[17rem] admin-table-sticky-head z-20 w-36"
|
||||
>
|
||||
{{ t('admin.perm.headers.realName') }}
|
||||
</th>
|
||||
<th
|
||||
class="px-6 py-4 text-left text-sm sticky left-[26rem] admin-table-sticky-head z-20 w-40 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
|
||||
>
|
||||
{{ t('admin.perm.headers.dept') }}
|
||||
</th>
|
||||
@@ -148,25 +155,25 @@ onMounted(() => {
|
||||
@change="toggleUserSelection(user.id)"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-6 py-4 sticky left-12 admin-table-sticky-cell z-20 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]">
|
||||
<td class="px-6 py-4 sticky left-12 admin-table-sticky-cell z-20">
|
||||
<div class="flex items-center gap-3">
|
||||
<div
|
||||
class="w-8 h-8 rounded-full bg-gradient-to-br from-brand-100 to-indigo-100 text-brand-600 flex items-center justify-center font-bold text-sm"
|
||||
>
|
||||
{{ user.username.charAt(0).toUpperCase() }}
|
||||
</div>
|
||||
<div class="truncate max-w-[150px]">
|
||||
<div class="font-medium text-primary truncate" :title="user.username">
|
||||
{{ user.username }}
|
||||
</div>
|
||||
<div class="text-xs text-muted truncate" :title="user.email">
|
||||
{{ user.email }}
|
||||
</div>
|
||||
<div class="font-medium text-primary text-sm truncate max-w-[120px]" :title="user.username">
|
||||
{{ user.username }}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 sticky left-[17rem] admin-table-sticky-cell z-20">
|
||||
<div class="text-sm text-primary truncate" :title="user.real_name || '-'">
|
||||
{{ user.real_name || '-' }}
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class="px-6 py-4 sticky left-[19rem] admin-table-sticky-cell z-20 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]"
|
||||
class="px-6 py-4 sticky left-[26rem] admin-table-sticky-cell z-20 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]"
|
||||
>
|
||||
<div class="text-sm text-muted truncate" :title="user.department">
|
||||
{{ user.department || '-' }}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* features/admin/modules/reports/ReportsPage.vue
|
||||
* 管理后台报表独立页面。路由:/admin/reports/:table?
|
||||
* 用途:管理后台报表独立页面(多表浏览、列筛选、聊天日志批量操作)。
|
||||
* 依赖:useReportsAdmin、DeleteConfirmDialog。
|
||||
* 逻辑:路由 /admin/reports/:table?;列宽由 composable 默认值与本地偏好控制。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
@@ -13,6 +15,8 @@ const { t } = useI18n();
|
||||
|
||||
const {
|
||||
usageReport,
|
||||
usageRange,
|
||||
usageRangeOptions,
|
||||
usageUserPage,
|
||||
usageUserPageSize,
|
||||
usageUserPageSizeOptions,
|
||||
@@ -260,7 +264,7 @@ onMounted(() => {
|
||||
<th
|
||||
v-for="key in visibleReportKeys"
|
||||
:key="key"
|
||||
class="px-6 py-4 whitespace-nowrap align-top relative"
|
||||
class="px-3 py-4 whitespace-nowrap align-top relative"
|
||||
:style="getColumnWidthStyle(key)"
|
||||
:draggable="true"
|
||||
@dragstart="onColumnDragStart(String(key))"
|
||||
@@ -310,7 +314,7 @@ onMounted(() => {
|
||||
<td
|
||||
v-for="key in visibleReportKeys"
|
||||
:key="`cell-${idx}-${key}`"
|
||||
class="px-6 py-3 font-mono"
|
||||
class="px-3 py-3 font-mono"
|
||||
:title="String(getReportCellValue(row, String(key)))"
|
||||
:style="getReportCellDisplayStyle(String(key))"
|
||||
>
|
||||
@@ -376,7 +380,17 @@ onMounted(() => {
|
||||
|
||||
<!-- Statistics Charts -->
|
||||
<div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-default pt-10">
|
||||
<h3 class="section-title text-lg mb-6">{{ t('admin.report.usage') }}</h3>
|
||||
<div class="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>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* features/admin/modules/reports/composables/useReportsAdmin.ts
|
||||
* 管理后台报表:多表浏览、筛选、排序、chat_logs 批量删除与用量图表。
|
||||
* 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除与带时间范围的用量图表)。
|
||||
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime。
|
||||
* 逻辑:ReportsPage 调用本 composable;使用分析默认近一月,可切换 7d/30d/90d/180d/365d。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -21,6 +23,7 @@ import type {
|
||||
ChatLogsLayoutPref,
|
||||
ReportColumnConfig,
|
||||
SortRule,
|
||||
UsageRangeKey,
|
||||
UsageReport,
|
||||
} from '@/features/admin/types/report.types';
|
||||
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
|
||||
@@ -38,6 +41,33 @@ const CHAT_LOGS_REPORT_KEYS = [
|
||||
|
||||
const CHAT_LOGS_TABLE_KEYS = ['id', ...CHAT_LOGS_REPORT_KEYS] as const;
|
||||
|
||||
/**
|
||||
* 聊天日志列默认宽度:前三列与 Token 收窄,提问/回答留宽。
|
||||
* @param key - 列字段名
|
||||
* @returns 像素宽度
|
||||
*/
|
||||
const defaultChatLogsColumnWidth = (key: string): number => {
|
||||
switch (key) {
|
||||
case 'id':
|
||||
return 72;
|
||||
case 'agent_name':
|
||||
return 120;
|
||||
case 'username':
|
||||
return 108;
|
||||
case 'real_name':
|
||||
return 108;
|
||||
case 'created_at':
|
||||
return 156;
|
||||
case 'tokens_used':
|
||||
return 96;
|
||||
case 'query':
|
||||
case 'answer':
|
||||
return 240;
|
||||
default:
|
||||
return 160;
|
||||
}
|
||||
};
|
||||
|
||||
export function useReportsAdmin() {
|
||||
const { t, locale } = useI18n();
|
||||
const msg = useMessage();
|
||||
@@ -47,12 +77,16 @@ export function useReportsAdmin() {
|
||||
const usageUserPage = ref(1);
|
||||
const usageUserPageSize = ref(10);
|
||||
const usageUserPageSizeOptions = [5, 10, 20, 50];
|
||||
/** 使用分析时间范围,默认近一月 */
|
||||
const usageRange = ref<UsageRangeKey>('30d');
|
||||
const usageRangeOptions: UsageRangeKey[] = ['7d', '30d', '90d', '180d', '365d'];
|
||||
|
||||
const loadUsageReport = async (): Promise<void> => {
|
||||
try {
|
||||
usageReport.value = await getAdminUsageReport({
|
||||
user_page: usageUserPage.value,
|
||||
user_page_size: usageUserPageSize.value,
|
||||
range: usageRange.value,
|
||||
});
|
||||
const pages = usageReport.value?.user_pages ?? 1;
|
||||
if (usageUserPage.value > pages) {
|
||||
@@ -199,7 +233,7 @@ const initChatLogsColumns = (keys: string[]) => {
|
||||
const defaults: ReportColumnConfig[] = keys.map((k) => ({
|
||||
key: k,
|
||||
visible: hideByDefault ? k !== 'id' : true,
|
||||
width: k === 'id' ? 90 : k === 'tokens_used' ? 120 : 180,
|
||||
width: defaultChatLogsColumnWidth(k),
|
||||
}));
|
||||
|
||||
let merged = defaults;
|
||||
@@ -213,7 +247,7 @@ const initChatLogsColumns = (keys: string[]) => {
|
||||
merged = [...order, ...missing].map((k) => ({
|
||||
key: k,
|
||||
visible: savedMap.get(k)?.visible ?? (currentTable.value === 'chat_logs' && k === 'id' ? false : true),
|
||||
width: savedMap.get(k)?.width ?? (k === 'id' ? 90 : k === 'tokens_used' ? 120 : 180),
|
||||
width: savedMap.get(k)?.width ?? defaultChatLogsColumnWidth(k),
|
||||
}));
|
||||
if (!Array.isArray(parsed)) {
|
||||
chatLogsWrapEnabled.value = !!parsed.wrapEnabled;
|
||||
@@ -826,6 +860,11 @@ watch(usageUserPageSize, () => {
|
||||
void loadUsageReport();
|
||||
});
|
||||
|
||||
watch(usageRange, () => {
|
||||
usageUserPage.value = 1;
|
||||
void loadUsageReport();
|
||||
});
|
||||
|
||||
watch([reportPageSize, sortedTableData], () => {
|
||||
if (reportCurrentPage.value > reportTotalPages.value) {
|
||||
reportCurrentPage.value = reportTotalPages.value;
|
||||
@@ -855,6 +894,8 @@ watch([reportPageSize, sortedTableData], () => {
|
||||
|
||||
return {
|
||||
usageReport,
|
||||
usageRange,
|
||||
usageRangeOptions,
|
||||
usageUserPage,
|
||||
usageUserPageSize,
|
||||
usageUserPageSizeOptions,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/admin/modules/users/UsersPage.vue
|
||||
* 用途:用户管理独立页面(服务端筛选分页、批量操作)。
|
||||
* 依赖:useUsersAdmin、PaginationBar、用户相关 Modal。
|
||||
* 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取。
|
||||
* 用途:用户管理独立页面(服务端筛选分页、用户/部门列排序、批量操作)。
|
||||
* 依赖:useUsersAdmin、SortableTableHeader、PaginationBar、用户相关 Modal。
|
||||
* 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取,表头排序复用 shared 组件。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
@@ -10,6 +10,7 @@ import { useI18n } from 'vue-i18n';
|
||||
import { Edit, Plus, Trash2, Users } from 'lucide-vue-next';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
|
||||
import BatchEditUserModal from './components/BatchEditUserModal.vue';
|
||||
import BatchPermissionModal from './components/BatchPermissionModal.vue';
|
||||
import UserFormModal from './components/UserFormModal.vue';
|
||||
@@ -24,6 +25,8 @@ const {
|
||||
isListLoading,
|
||||
isSaving,
|
||||
userFilters,
|
||||
sortKey,
|
||||
sortDir,
|
||||
// hideRejected,
|
||||
selectedUserIds,
|
||||
users,
|
||||
@@ -42,6 +45,7 @@ const {
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
loadAll,
|
||||
toggleSort,
|
||||
openCreateUserModal,
|
||||
openEditUserModal,
|
||||
saveUser,
|
||||
@@ -156,9 +160,25 @@ onMounted(() => {
|
||||
@change="toggleAllUsers(users)"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.user') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">
|
||||
<SortableTableHeader
|
||||
column-key="username"
|
||||
:label="t('admin.user.headers.user')"
|
||||
:active-key="sortKey"
|
||||
:direction="sortDir"
|
||||
@sort="toggleSort"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.fields.realName') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.dept') }}</th>
|
||||
<th class="px-6 py-4 text-left text-xs">
|
||||
<SortableTableHeader
|
||||
column-key="department"
|
||||
:label="t('admin.user.headers.dept')"
|
||||
:active-key="sortKey"
|
||||
:direction="sortDir"
|
||||
@sort="toggleSort"
|
||||
/>
|
||||
</th>
|
||||
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.role') }}</th>
|
||||
<th class="px-6 py-4 text-right text-xs">{{ t('admin.user.headers.actions') }}</th>
|
||||
</tr>
|
||||
|
||||
@@ -1,864 +1,457 @@
|
||||
/**
|
||||
|
||||
* features/admin/modules/users/composables/useUsersAdmin.ts
|
||||
|
||||
* 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、批量操作)。
|
||||
|
||||
* 依赖:admin.api、useMessage。
|
||||
|
||||
* 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取。
|
||||
|
||||
* 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、用户/部门列排序、批量操作)。
|
||||
* 依赖:admin.api、useMessage、useTableSort。
|
||||
* 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取,排序参数随请求下发。
|
||||
*/
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
import {
|
||||
|
||||
batchDeleteAdminUsers,
|
||||
|
||||
batchUpdateAdminPermissions,
|
||||
|
||||
batchUpdateAdminUsers,
|
||||
|
||||
cleanupRejectedAdminUsers,
|
||||
|
||||
createAdminUser,
|
||||
|
||||
listAdminAgents,
|
||||
|
||||
listAdminDepartments,
|
||||
|
||||
listAdminUsersPage,
|
||||
|
||||
updateAdminUser,
|
||||
|
||||
} from '@/features/admin/api/admin.api';
|
||||
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
import { useTableSort } from '@/shared/composables/useTableSort';
|
||||
import type { AdminAgentOption, AdminDepartmentRow, AdminUserRow } from '@/features/admin/types/admin.types';
|
||||
|
||||
import {
|
||||
|
||||
createEmptyUserFilters,
|
||||
|
||||
createEmptyUserForm,
|
||||
|
||||
type BatchEditForm,
|
||||
|
||||
type BatchPermissionForm,
|
||||
|
||||
type UserFilters,
|
||||
|
||||
type UserFormState,
|
||||
|
||||
} from '@/features/admin/types/user.types';
|
||||
|
||||
|
||||
|
||||
const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
|
||||
|
||||
const USER_PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
|
||||
|
||||
|
||||
/** 用户表可排序列:用户名 / 部门(与后端 sort_by 白名单一致) */
|
||||
export type UserSortKey = 'username' | 'department';
|
||||
|
||||
export function useUsersAdmin() {
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const msg = useMessage();
|
||||
|
||||
|
||||
|
||||
const users = ref<AdminUserRow[]>([]);
|
||||
|
||||
const agents = ref<AdminAgentOption[]>([]);
|
||||
|
||||
const departments = ref<AdminDepartmentRow[]>([]);
|
||||
|
||||
const isLoading = ref(true);
|
||||
|
||||
const isListLoading = ref(false);
|
||||
|
||||
const isSaving = ref(false);
|
||||
|
||||
|
||||
|
||||
const userFilters = ref<UserFilters>(createEmptyUserFilters());
|
||||
|
||||
/** 用户 / 部门列排序,默认按用户名升序 */
|
||||
const { sortKey, sortDir, toggleSort: toggleSortBase } = useTableSort<UserSortKey>({
|
||||
initialKey: 'username',
|
||||
initialDir: 'asc',
|
||||
});
|
||||
const hideRejected = ref(true);
|
||||
|
||||
const selectedUserIds = ref<number[]>([]);
|
||||
|
||||
|
||||
|
||||
const userPage = ref(1);
|
||||
|
||||
const userPageSize = ref(20);
|
||||
|
||||
const usersTotal = ref(0);
|
||||
|
||||
const usersPages = ref(1);
|
||||
|
||||
let userSearchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
|
||||
|
||||
const showUserModal = ref(false);
|
||||
|
||||
const editingUser = ref<UserFormState>(createEmptyUserForm());
|
||||
|
||||
|
||||
|
||||
const showBatchEditModal = ref(false);
|
||||
|
||||
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
|
||||
|
||||
|
||||
|
||||
const showBatchPermissionModal = ref(false);
|
||||
|
||||
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
|
||||
|
||||
|
||||
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
|
||||
const deleteConfirmMessage = ref('');
|
||||
|
||||
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
|
||||
|
||||
/** 当前页是否已全部选中 */
|
||||
|
||||
const allPaginatedUsersSelected = computed(
|
||||
|
||||
() =>
|
||||
|
||||
users.value.length > 0
|
||||
|
||||
&& users.value.every((u) => selectedUserIds.value.includes(u.id)),
|
||||
|
||||
);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 拉取当前页用户(服务端筛选 + 分页)。
|
||||
|
||||
* 核心逻辑:将 userFilters / hideRejected 传给 listAdminUsersPage,写回 items 与分页元数据。
|
||||
|
||||
* 拉取当前页用户(服务端筛选 + 分页 + 排序)。
|
||||
* 核心逻辑:将 userFilters / hideRejected / sortKey / sortDir 传给 listAdminUsersPage。
|
||||
*/
|
||||
|
||||
const loadUsers = async (): Promise<void> => {
|
||||
|
||||
isListLoading.value = true;
|
||||
|
||||
try {
|
||||
|
||||
const data = await listAdminUsersPage({
|
||||
|
||||
page: userPage.value,
|
||||
|
||||
pageSize: userPageSize.value,
|
||||
|
||||
username: userFilters.value.username,
|
||||
|
||||
real_name: userFilters.value.real_name,
|
||||
|
||||
department: userFilters.value.department,
|
||||
|
||||
hideRejected: hideRejected.value,
|
||||
|
||||
sortBy: sortKey.value,
|
||||
sortDir: sortDir.value,
|
||||
});
|
||||
|
||||
users.value = data.items;
|
||||
|
||||
usersTotal.value = data.total;
|
||||
|
||||
userPage.value = data.page;
|
||||
|
||||
usersPages.value = data.pages;
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.error('Error loading users:', e);
|
||||
|
||||
users.value = [];
|
||||
|
||||
usersTotal.value = 0;
|
||||
|
||||
usersPages.value = 1;
|
||||
|
||||
} finally {
|
||||
|
||||
isListLoading.value = false;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 重置页码并刷新列表;若页码已是 1 则直接请求。
|
||||
|
||||
* @param resetPage - 为 true 时将 page 置 1
|
||||
|
||||
*/
|
||||
|
||||
const scheduleLoadUsers = (resetPage = false): void => {
|
||||
|
||||
if (resetPage) {
|
||||
|
||||
if (userPage.value !== 1) {
|
||||
|
||||
userPage.value = 1;
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void loadUsers();
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const loadAgents = async (): Promise<void> => {
|
||||
|
||||
try {
|
||||
|
||||
agents.value = await listAdminAgents();
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.error('Error loading agents:', e);
|
||||
|
||||
agents.value = [];
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const loadDepartments = async (): Promise<void> => {
|
||||
|
||||
try {
|
||||
|
||||
departments.value = await listAdminDepartments();
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.error('Error loading departments:', e);
|
||||
|
||||
departments.value = [];
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const loadAll = async (): Promise<void> => {
|
||||
|
||||
isLoading.value = true;
|
||||
|
||||
await Promise.all([loadUsers(), loadAgents(), loadDepartments()]);
|
||||
|
||||
isLoading.value = false;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
watch(userPage, () => {
|
||||
|
||||
void loadUsers();
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
watch(userPageSize, () => {
|
||||
|
||||
scheduleLoadUsers(true);
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
watch([userFilters, hideRejected], () => {
|
||||
|
||||
if (userSearchTimer) clearTimeout(userSearchTimer);
|
||||
|
||||
userSearchTimer = setTimeout(() => {
|
||||
|
||||
scheduleLoadUsers(true);
|
||||
|
||||
}, 300);
|
||||
|
||||
}, { deep: true });
|
||||
|
||||
|
||||
|
||||
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
|
||||
|
||||
deleteConfirmMessage.value = message;
|
||||
|
||||
deleteConfirmAction = action;
|
||||
|
||||
showDeleteConfirmDialog.value = true;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const closeDeleteConfirm = (): void => {
|
||||
|
||||
showDeleteConfirmDialog.value = false;
|
||||
|
||||
deleteConfirmAction = null;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 执行待确认的删除操作。
|
||||
|
||||
* 核心逻辑:先快照 action 并立即关闭弹窗,再 await 删除与刷新,避免异步完成前弹窗无法关闭。
|
||||
|
||||
*/
|
||||
|
||||
const confirmDelete = async (): Promise<void> => {
|
||||
|
||||
const action = deleteConfirmAction;
|
||||
|
||||
closeDeleteConfirm();
|
||||
|
||||
if (!action) return;
|
||||
|
||||
await action();
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const openCreateUserModal = (): void => {
|
||||
|
||||
editingUser.value = createEmptyUserForm();
|
||||
|
||||
showUserModal.value = true;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const openEditUserModal = (user: AdminUserRow): void => {
|
||||
|
||||
editingUser.value = {
|
||||
|
||||
id: user.id,
|
||||
|
||||
username: user.username,
|
||||
|
||||
email: user.email,
|
||||
|
||||
department: user.department || '',
|
||||
|
||||
role: user.role,
|
||||
|
||||
password: '',
|
||||
|
||||
real_name: user.real_name || '',
|
||||
|
||||
employee_id: user.employee_id || '',
|
||||
|
||||
phone_number: user.phone_number || '',
|
||||
|
||||
feature_permissions: {
|
||||
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
|
||||
},
|
||||
|
||||
agent_ids: user.agent_ids || [],
|
||||
|
||||
};
|
||||
|
||||
showUserModal.value = true;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const saveUser = async (): Promise<void> => {
|
||||
|
||||
const isCreate = !editingUser.value.id;
|
||||
|
||||
|
||||
|
||||
if (isCreate) {
|
||||
|
||||
if (!(editingUser.value.real_name || '').trim()) {
|
||||
|
||||
msg.warning(t('admin.user.msgs.realNameRequired'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (!(editingUser.value.employee_id || '').trim()) {
|
||||
|
||||
msg.warning(t('admin.user.msgs.employeeIdRequired'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (!(editingUser.value.phone_number || '').trim()) {
|
||||
|
||||
msg.warning(t('admin.user.msgs.phoneRequired'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (!(editingUser.value.username || '').trim()) {
|
||||
|
||||
msg.warning(t('admin.user.msgs.usernameRequired'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
const email = (editingUser.value.email || '').trim();
|
||||
|
||||
if (!email) {
|
||||
|
||||
msg.warning(t('admin.user.msgs.emailRequired'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (!EMAIL_PATTERN.test(email)) {
|
||||
|
||||
msg.warning(t('admin.user.msgs.invalidEmail'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (!(editingUser.value.password || '').trim()) {
|
||||
|
||||
msg.warning(t('admin.user.msgs.passwordRequired'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
if (!editingUser.value.username) {
|
||||
|
||||
msg.warning(t('admin.user.msgs.usernameRequired'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
const email = (editingUser.value.email || '').trim();
|
||||
|
||||
if (email && !EMAIL_PATTERN.test(email)) {
|
||||
|
||||
msg.warning(t('admin.user.msgs.invalidEmail'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
isSaving.value = true;
|
||||
|
||||
try {
|
||||
|
||||
if (editingUser.value.id) {
|
||||
|
||||
await updateAdminUser(editingUser.value.id, {
|
||||
|
||||
email: editingUser.value.email,
|
||||
|
||||
department: editingUser.value.department,
|
||||
|
||||
role: editingUser.value.role,
|
||||
|
||||
password: editingUser.value.password || undefined,
|
||||
|
||||
real_name: editingUser.value.real_name,
|
||||
|
||||
employee_id: editingUser.value.employee_id,
|
||||
|
||||
phone_number: editingUser.value.phone_number,
|
||||
|
||||
feature_permissions: editingUser.value.feature_permissions,
|
||||
|
||||
agent_ids: editingUser.value.agent_ids,
|
||||
|
||||
});
|
||||
|
||||
} else {
|
||||
|
||||
await createAdminUser({
|
||||
|
||||
username: editingUser.value.username,
|
||||
|
||||
email: editingUser.value.email,
|
||||
|
||||
department: editingUser.value.department,
|
||||
|
||||
role: editingUser.value.role,
|
||||
|
||||
password: editingUser.value.password,
|
||||
|
||||
real_name: editingUser.value.real_name,
|
||||
|
||||
employee_id: editingUser.value.employee_id,
|
||||
|
||||
phone_number: editingUser.value.phone_number,
|
||||
|
||||
feature_permissions: editingUser.value.feature_permissions,
|
||||
|
||||
agent_ids: editingUser.value.agent_ids,
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
await loadUsers();
|
||||
|
||||
showUserModal.value = false;
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.error(e);
|
||||
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
|
||||
} finally {
|
||||
|
||||
isSaving.value = false;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const cleanRejectedUsers = async (): Promise<void> => {
|
||||
|
||||
openDeleteConfirm(t('admin.user.confirmClean'), async () => {
|
||||
|
||||
try {
|
||||
|
||||
const data = await cleanupRejectedAdminUsers();
|
||||
|
||||
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
|
||||
|
||||
await loadUsers();
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.error(e);
|
||||
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const batchDeleteUsers = async (): Promise<void> => {
|
||||
|
||||
if (selectedUserIds.value.length === 0) return;
|
||||
|
||||
const targetUserIds = [...selectedUserIds.value];
|
||||
|
||||
openDeleteConfirm(t('admin.user.confirmBatchDelete', { count: targetUserIds.length }), async () => {
|
||||
|
||||
try {
|
||||
|
||||
const data = await batchDeleteAdminUsers(targetUserIds);
|
||||
|
||||
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
|
||||
|
||||
selectedUserIds.value = [];
|
||||
|
||||
await loadUsers();
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.error(e);
|
||||
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const toggleUserSelection = (userId: number): void => {
|
||||
|
||||
const index = selectedUserIds.value.indexOf(userId);
|
||||
|
||||
if (index === -1) selectedUserIds.value.push(userId);
|
||||
|
||||
else selectedUserIds.value.splice(index, 1);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换当前页用户的全选状态,保留其他页已选中的用户。
|
||||
* 核心逻辑:若本页已全部选中则仅取消本页 ID;否则合并本页 ID 到 selectedUserIds。
|
||||
* @param rows - 当前页用户行
|
||||
*/
|
||||
const toggleAllUsers = (rows: AdminUserRow[]): void => {
|
||||
const rowIds = rows.map((u) => u.id);
|
||||
const allSelected = rowIds.length > 0 && rowIds.every((id) => selectedUserIds.value.includes(id));
|
||||
if (allSelected) {
|
||||
selectedUserIds.value = selectedUserIds.value.filter((id) => !rowIds.includes(id));
|
||||
} else {
|
||||
selectedUserIds.value = [...new Set([...selectedUserIds.value, ...rowIds])];
|
||||
}
|
||||
};
|
||||
|
||||
const openBatchEditModal = (): void => {
|
||||
if (selectedUserIds.value.length === 0) return;
|
||||
batchEditForm.value = { department: '', role: '', status: '' };
|
||||
showBatchEditModal.value = true;
|
||||
};
|
||||
|
||||
const openBatchPermissionModal = (): void => {
|
||||
if (selectedUserIds.value.length === 0) return;
|
||||
batchPermissionForm.value = { agent_ids: [], action: 'add' };
|
||||
showBatchPermissionModal.value = true;
|
||||
};
|
||||
|
||||
const submitBatchEdit = async (): Promise<void> => {
|
||||
isSaving.value = true;
|
||||
try {
|
||||
const data: Record<string, string> = {};
|
||||
if (batchEditForm.value.department) data.department = batchEditForm.value.department;
|
||||
if (batchEditForm.value.role) data.role = batchEditForm.value.role;
|
||||
if (batchEditForm.value.status) data.status = batchEditForm.value.status;
|
||||
if (Object.keys(data).length === 0) {
|
||||
msg.warning(t('admin.msg.enterOneField'));
|
||||
return;
|
||||
}
|
||||
await batchUpdateAdminUsers(selectedUserIds.value, data);
|
||||
await loadUsers();
|
||||
showBatchEditModal.value = false;
|
||||
selectedUserIds.value = [];
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.batchUpdateFailed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const submitBatchPermission = async (): Promise<void> => {
|
||||
if (batchPermissionForm.value.agent_ids.length === 0) {
|
||||
msg.warning(t('admin.perm.msg.selectAgent'));
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
await batchUpdateAdminPermissions({
|
||||
user_ids: selectedUserIds.value,
|
||||
agent_ids: batchPermissionForm.value.agent_ids,
|
||||
action: batchPermissionForm.value.action,
|
||||
});
|
||||
await loadUsers();
|
||||
showBatchPermissionModal.value = false;
|
||||
selectedUserIds.value = [];
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.batchPermissionUpdateFailed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 切换当前页用户的全选状态,保留其他页已选中的用户。
|
||||
|
||||
* 核心逻辑:若本页已全部选中则仅取消本页 ID;否则合并本页 ID 到 selectedUserIds。
|
||||
|
||||
* @param rows - 当前页用户行
|
||||
|
||||
* 切换用户/部门列排序并重新拉取第一页。
|
||||
* @param key - username | department
|
||||
*/
|
||||
|
||||
const toggleAllUsers = (rows: AdminUserRow[]): void => {
|
||||
|
||||
const rowIds = rows.map((u) => u.id);
|
||||
|
||||
const allSelected = rowIds.length > 0 && rowIds.every((id) => selectedUserIds.value.includes(id));
|
||||
|
||||
if (allSelected) {
|
||||
|
||||
selectedUserIds.value = selectedUserIds.value.filter((id) => !rowIds.includes(id));
|
||||
|
||||
} else {
|
||||
|
||||
selectedUserIds.value = [...new Set([...selectedUserIds.value, ...rowIds])];
|
||||
|
||||
}
|
||||
|
||||
const toggleSort = (key: UserSortKey): void => {
|
||||
toggleSortBase(key);
|
||||
scheduleLoadUsers(true);
|
||||
};
|
||||
|
||||
|
||||
|
||||
const openBatchEditModal = (): void => {
|
||||
|
||||
if (selectedUserIds.value.length === 0) return;
|
||||
|
||||
batchEditForm.value = { department: '', role: '', status: '' };
|
||||
|
||||
showBatchEditModal.value = true;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const openBatchPermissionModal = (): void => {
|
||||
|
||||
if (selectedUserIds.value.length === 0) return;
|
||||
|
||||
batchPermissionForm.value = { agent_ids: [], action: 'add' };
|
||||
|
||||
showBatchPermissionModal.value = true;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const submitBatchEdit = async (): Promise<void> => {
|
||||
|
||||
isSaving.value = true;
|
||||
|
||||
try {
|
||||
|
||||
const data: Record<string, string> = {};
|
||||
|
||||
if (batchEditForm.value.department) data.department = batchEditForm.value.department;
|
||||
|
||||
if (batchEditForm.value.role) data.role = batchEditForm.value.role;
|
||||
|
||||
if (batchEditForm.value.status) data.status = batchEditForm.value.status;
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
|
||||
msg.warning(t('admin.msg.enterOneField'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
await batchUpdateAdminUsers(selectedUserIds.value, data);
|
||||
|
||||
await loadUsers();
|
||||
|
||||
showBatchEditModal.value = false;
|
||||
|
||||
selectedUserIds.value = [];
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.error(e);
|
||||
|
||||
msg.error((e as Error).message || t('admin.msg.batchUpdateFailed'));
|
||||
|
||||
} finally {
|
||||
|
||||
isSaving.value = false;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const submitBatchPermission = async (): Promise<void> => {
|
||||
|
||||
if (batchPermissionForm.value.agent_ids.length === 0) {
|
||||
|
||||
msg.warning(t('admin.perm.msg.selectAgent'));
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
isSaving.value = true;
|
||||
|
||||
try {
|
||||
|
||||
await batchUpdateAdminPermissions({
|
||||
|
||||
user_ids: selectedUserIds.value,
|
||||
|
||||
agent_ids: batchPermissionForm.value.agent_ids,
|
||||
|
||||
action: batchPermissionForm.value.action,
|
||||
|
||||
});
|
||||
|
||||
await loadUsers();
|
||||
|
||||
showBatchPermissionModal.value = false;
|
||||
|
||||
selectedUserIds.value = [];
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.error(e);
|
||||
|
||||
msg.error((e as Error).message || t('admin.msg.batchPermissionUpdateFailed'));
|
||||
|
||||
} finally {
|
||||
|
||||
isSaving.value = false;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
return {
|
||||
|
||||
users,
|
||||
|
||||
agents,
|
||||
|
||||
departments,
|
||||
|
||||
isLoading,
|
||||
|
||||
isListLoading,
|
||||
|
||||
isSaving,
|
||||
|
||||
userFilters,
|
||||
|
||||
sortKey,
|
||||
sortDir,
|
||||
hideRejected,
|
||||
|
||||
selectedUserIds,
|
||||
|
||||
usersTotal,
|
||||
|
||||
userPage,
|
||||
|
||||
userPageSize,
|
||||
|
||||
userPageSizeOptions: USER_PAGE_SIZE_OPTIONS,
|
||||
|
||||
usersPages,
|
||||
|
||||
allPaginatedUsersSelected,
|
||||
|
||||
showUserModal,
|
||||
|
||||
editingUser,
|
||||
|
||||
showBatchEditModal,
|
||||
|
||||
batchEditForm,
|
||||
|
||||
showBatchPermissionModal,
|
||||
|
||||
batchPermissionForm,
|
||||
|
||||
showDeleteConfirmDialog,
|
||||
|
||||
deleteConfirmMessage,
|
||||
|
||||
loadAll,
|
||||
|
||||
toggleSort,
|
||||
openCreateUserModal,
|
||||
|
||||
openEditUserModal,
|
||||
|
||||
saveUser,
|
||||
|
||||
cleanRejectedUsers,
|
||||
|
||||
batchDeleteUsers,
|
||||
|
||||
toggleUserSelection,
|
||||
|
||||
toggleAllUsers,
|
||||
|
||||
openBatchEditModal,
|
||||
|
||||
openBatchPermissionModal,
|
||||
|
||||
submitBatchEdit,
|
||||
|
||||
submitBatchPermission,
|
||||
|
||||
closeDeleteConfirm,
|
||||
|
||||
confirmDelete,
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
/**
|
||||
* features/admin/types/department.types.ts
|
||||
* 部门管理表单类型。
|
||||
* 用途:部门管理表单状态与行数据转换。
|
||||
* 依赖:AdminDepartmentRow(admin.types)。
|
||||
* 逻辑:useDepartmentsAdmin / DepartmentFormModal 共用本类型与工厂方法。
|
||||
*/
|
||||
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
||||
|
||||
export interface DepartmentFormState {
|
||||
id?: number;
|
||||
@@ -11,9 +14,26 @@ export interface DepartmentFormState {
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建空白部门表单(用于「添加部门」弹窗)。
|
||||
* @returns 空表单初始值
|
||||
*/
|
||||
export const createEmptyDepartmentForm = (): DepartmentFormState => ({
|
||||
name: '',
|
||||
code: '',
|
||||
company: '',
|
||||
description: '',
|
||||
});
|
||||
|
||||
/**
|
||||
* 将列表行转为编辑表单状态。
|
||||
* @param dept - 部门列表行
|
||||
* @returns 可绑定到弹窗的表单对象
|
||||
*/
|
||||
export const departmentRowToForm = (dept: AdminDepartmentRow): DepartmentFormState => ({
|
||||
id: dept.id,
|
||||
name: dept.name,
|
||||
code: dept.code || '',
|
||||
company: dept.company || '',
|
||||
description: dept.description || '',
|
||||
});
|
||||
@@ -1,10 +1,17 @@
|
||||
/**
|
||||
* features/admin/types/report.types.ts
|
||||
* 报表模块类型。
|
||||
* 用途:报表模块类型(使用分析、列配置、排序规则)。
|
||||
* 依赖:无。
|
||||
* 逻辑:useReportsAdmin / admin.api 共用。
|
||||
*/
|
||||
|
||||
/** 使用分析时间范围(与后端 USAGE_RANGE_DAYS 一致) */
|
||||
export type UsageRangeKey = '7d' | '30d' | '90d' | '180d' | '365d';
|
||||
|
||||
export interface UsageReport {
|
||||
total: number;
|
||||
/** 当前统计时间范围 */
|
||||
range?: UsageRangeKey;
|
||||
by_user: { username: string; count: number }[];
|
||||
by_agent: { agent: string; count: number }[];
|
||||
by_day?: { date: string; count: number }[];
|
||||
|
||||
@@ -122,12 +122,18 @@
|
||||
"edit": "Edit Department",
|
||||
"add": "Add New Department",
|
||||
"noDepts": "No departments configured.",
|
||||
"noSearchResults": "No matching departments found",
|
||||
"searchPlaceholder": "Search by name, code, or company…",
|
||||
"headers": {
|
||||
"name": "Name",
|
||||
"code": "Code",
|
||||
"company": "Company",
|
||||
"actions": "Actions"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Edit",
|
||||
"delete": "Delete"
|
||||
},
|
||||
"fields": {
|
||||
"name": "Name",
|
||||
"namePlaceholder": "e.g. IT Department",
|
||||
@@ -716,6 +722,7 @@
|
||||
"allRoles": "All Roles",
|
||||
"headers": {
|
||||
"user": "User",
|
||||
"realName": "Real Name",
|
||||
"dept": "Dept"
|
||||
},
|
||||
"batchModal": {
|
||||
@@ -786,6 +793,14 @@
|
||||
"noData": "No data available for {table}",
|
||||
"noFilterResults": "No matching rows. Adjust your filters.",
|
||||
"usage": "Usage Analytics",
|
||||
"usageRangeLabel": "Time range",
|
||||
"usageRanges": {
|
||||
"7d": "Last 7 days",
|
||||
"30d": "Last 30 days",
|
||||
"90d": "Last 3 months",
|
||||
"180d": "Last 6 months",
|
||||
"365d": "Last 12 months"
|
||||
},
|
||||
"byUser": "Requests by User",
|
||||
"byAgent": "Requests by Agent",
|
||||
"usageByUserTopHint": "Top {limit} users by chat volume",
|
||||
|
||||
@@ -26,5 +26,10 @@
|
||||
"itemsUnit": "rows",
|
||||
"prevPage": "Previous",
|
||||
"nextPage": "Next"
|
||||
},
|
||||
"sort": {
|
||||
"unsorted": "Click to sort",
|
||||
"asc": "Ascending, click for descending",
|
||||
"desc": "Descending, click for ascending"
|
||||
}
|
||||
}
|
||||
@@ -122,12 +122,18 @@
|
||||
"edit": "แก้ไขแผนก",
|
||||
"add": "เพิ่มแผนกใหม่",
|
||||
"noDepts": "ยังไม่มีการกำหนดค่าแผนก",
|
||||
"noSearchResults": "ไม่พบแผนกที่ตรงกัน",
|
||||
"searchPlaceholder": "ค้นหาชื่อ รหัส หรือบริษัท…",
|
||||
"headers": {
|
||||
"name": "ชื่อ",
|
||||
"code": "รหัส",
|
||||
"company": "บริษัท",
|
||||
"actions": "การกระทำ"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "แก้ไข",
|
||||
"delete": "ลบ"
|
||||
},
|
||||
"fields": {
|
||||
"name": "ชื่อ",
|
||||
"namePlaceholder": "เช่น แผนกไอที",
|
||||
@@ -721,6 +727,7 @@
|
||||
"allRoles": "ทุกบทบาท",
|
||||
"headers": {
|
||||
"user": "ผู้ใช้",
|
||||
"realName": "ชื่อจริง",
|
||||
"dept": "แผนก"
|
||||
},
|
||||
"batchModal": {
|
||||
@@ -791,6 +798,14 @@
|
||||
"noData": "ไม่มีข้อมูลสำหรับ {table}",
|
||||
"noFilterResults": "ไม่พบข้อมูลที่ตรงกับเงื่อนไข โปรดปรับตัวกรอง",
|
||||
"usage": "การวิเคราะห์การใช้งาน",
|
||||
"usageRangeLabel": "ช่วงเวลา",
|
||||
"usageRanges": {
|
||||
"7d": "7 วันล่าสุด",
|
||||
"30d": "30 วันล่าสุด",
|
||||
"90d": "3 เดือนล่าสุด",
|
||||
"180d": "6 เดือนล่าสุด",
|
||||
"365d": "12 เดือนล่าสุด"
|
||||
},
|
||||
"byUser": "ตามผู้ใช้",
|
||||
"byAgent": "ตามตัวแทน",
|
||||
"usageByUserTopHint": "แสดงผู้ใช้ {limit} อันดับแรกตามปริมาณการสนทนา",
|
||||
|
||||
@@ -26,5 +26,10 @@
|
||||
"itemsUnit": "รายการ",
|
||||
"prevPage": "ก่อนหน้า",
|
||||
"nextPage": "ถัดไป"
|
||||
},
|
||||
"sort": {
|
||||
"unsorted": "คลิกเพื่อเรียงลำดับ",
|
||||
"asc": "เรียงจากน้อยไปมาก คลิกเพื่อสลับ",
|
||||
"desc": "เรียงจากมากไปน้อย คลิกเพื่อสลับ"
|
||||
}
|
||||
}
|
||||
@@ -123,12 +123,18 @@
|
||||
"edit": "编辑部门",
|
||||
"add": "添加部门",
|
||||
"noDepts": "暂无部门配置",
|
||||
"noSearchResults": "未找到匹配的部门",
|
||||
"searchPlaceholder": "搜索名称、编码或公司…",
|
||||
"headers": {
|
||||
"name": "名称",
|
||||
"code": "编码",
|
||||
"company": "公司",
|
||||
"actions": "操作"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "编辑",
|
||||
"delete": "删除"
|
||||
},
|
||||
"fields": {
|
||||
"name": "名称",
|
||||
"namePlaceholder": "例如:信息技术部",
|
||||
@@ -717,6 +723,7 @@
|
||||
"allRoles": "所有角色",
|
||||
"headers": {
|
||||
"user": "用户",
|
||||
"realName": "真实姓名",
|
||||
"dept": "部门"
|
||||
},
|
||||
"batchModal": {
|
||||
@@ -787,6 +794,14 @@
|
||||
"noData": "暂无数据: {table}",
|
||||
"noFilterResults": "没有匹配的数据,请调整筛选条件",
|
||||
"usage": "使用分析",
|
||||
"usageRangeLabel": "统计范围",
|
||||
"usageRanges": {
|
||||
"7d": "近一周",
|
||||
"30d": "近一月",
|
||||
"90d": "近三月",
|
||||
"180d": "近半年",
|
||||
"365d": "近一年"
|
||||
},
|
||||
"byUser": "按用户统计",
|
||||
"byAgent": "按应用统计",
|
||||
"usageByUserTopHint": "仅显示对话量前 {limit} 名用户",
|
||||
|
||||
@@ -26,5 +26,10 @@
|
||||
"itemsUnit": "条",
|
||||
"prevPage": "上一页",
|
||||
"nextPage": "下一页"
|
||||
},
|
||||
"sort": {
|
||||
"unsorted": "点击排序",
|
||||
"asc": "升序,点击切换为降序",
|
||||
"desc": "降序,点击切换为升序"
|
||||
}
|
||||
}
|
||||
@@ -122,12 +122,18 @@
|
||||
"edit": "編輯部門",
|
||||
"add": "添加部門",
|
||||
"noDepts": "暫無部門配置",
|
||||
"noSearchResults": "未找到匹配的部門",
|
||||
"searchPlaceholder": "搜尋名稱、編碼或公司…",
|
||||
"headers": {
|
||||
"name": "名稱",
|
||||
"code": "編碼",
|
||||
"company": "公司",
|
||||
"actions": "操作"
|
||||
},
|
||||
"actions": {
|
||||
"edit": "編輯",
|
||||
"delete": "刪除"
|
||||
},
|
||||
"fields": {
|
||||
"name": "名稱",
|
||||
"namePlaceholder": "例如:資訊技術部",
|
||||
@@ -721,6 +727,7 @@
|
||||
"allRoles": "所有角色",
|
||||
"headers": {
|
||||
"user": "用戶",
|
||||
"realName": "真實姓名",
|
||||
"dept": "部門"
|
||||
},
|
||||
"batchModal": {
|
||||
@@ -791,6 +798,14 @@
|
||||
"noData": "暫無數據: {table}",
|
||||
"noFilterResults": "沒有匹配的數據,請調整篩選條件",
|
||||
"usage": "使用分析",
|
||||
"usageRangeLabel": "統計範圍",
|
||||
"usageRanges": {
|
||||
"7d": "近一週",
|
||||
"30d": "近一月",
|
||||
"90d": "近三月",
|
||||
"180d": "近半年",
|
||||
"365d": "近一年"
|
||||
},
|
||||
"byUser": "按用戶統計",
|
||||
"byAgent": "按應用統計",
|
||||
"usageByUserTopHint": "僅顯示對話量前 {limit} 名用戶",
|
||||
|
||||
@@ -26,5 +26,10 @@
|
||||
"itemsUnit": "條",
|
||||
"prevPage": "上一頁",
|
||||
"nextPage": "下一頁"
|
||||
},
|
||||
"sort": {
|
||||
"unsorted": "點擊排序",
|
||||
"asc": "升序,點擊切換為降序",
|
||||
"desc": "降序,點擊切換為升序"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* shared/components/SortableTableHeader.vue
|
||||
* 用途:可点击的表格排序表头(文案 + 升/降/未排序图标)。
|
||||
* 依赖:lucide 图标、common.sort i18n、table-sort 类型。
|
||||
* 逻辑:管理端表格 th 内使用;点击 emit sort,由 useTableSort.toggleSort 处理。
|
||||
*/
|
||||
<script setup lang="ts" generic="K extends string">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-vue-next';
|
||||
import type { SortDir } from '@/shared/utils/table-sort';
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** 本列表头对应的列键 */
|
||||
columnKey: K;
|
||||
/** 表头展示文案 */
|
||||
label: string;
|
||||
/** 当前激活的排序列 */
|
||||
activeKey?: K;
|
||||
/** 当前排序方向 */
|
||||
direction?: SortDir;
|
||||
/** 对齐方式 */
|
||||
align?: 'left' | 'right';
|
||||
}>(),
|
||||
{
|
||||
direction: 'asc',
|
||||
align: 'left',
|
||||
},
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
sort: [key: K];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const isActive = computed(() => props.activeKey === props.columnKey);
|
||||
|
||||
/**
|
||||
* 无障碍 title:标明未排序 / 升序 / 降序。
|
||||
*/
|
||||
const title = computed(() => {
|
||||
if (!isActive.value) return t('common.sort.unsorted');
|
||||
return props.direction === 'asc' ? t('common.sort.asc') : t('common.sort.desc');
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1.5 hover:text-primary transition-colors"
|
||||
:class="align === 'right' ? 'ml-auto' : ''"
|
||||
:title="title"
|
||||
@click="emit('sort', columnKey)"
|
||||
>
|
||||
<span>{{ label }}</span>
|
||||
<ArrowUp v-if="isActive && direction === 'asc'" class="w-3.5 h-3.5 text-brand-600" />
|
||||
<ArrowDown v-else-if="isActive && direction === 'desc'" class="w-3.5 h-3.5 text-brand-600" />
|
||||
<ArrowUpDown v-else class="w-3.5 h-3.5 opacity-40" />
|
||||
</button>
|
||||
</template>
|
||||
@@ -1,10 +1,8 @@
|
||||
/**
|
||||
* shared/composables/useReportLayoutStorage.ts
|
||||
* 报表页面布局偏好 localStorage 持久化。
|
||||
*/
|
||||
/**
|
||||
* useReportLayoutStorage.ts
|
||||
* 用途:为报表页面提供统一的布局偏好持久化能力(按用户 + 表名隔离)
|
||||
* 用途:报表页面布局偏好 localStorage 持久化(按用户 + 表名隔离)。
|
||||
* 依赖:localStorage / sessionStorage 中的 hxops_user。
|
||||
* 逻辑:ReportsPage / useReportsAdmin 读写列宽、显隐与排序偏好;v3 起聊天日志默认列宽收窄。
|
||||
*/
|
||||
|
||||
const getCurrentAuthUser = () => {
|
||||
@@ -24,10 +22,20 @@ const getCurrentIdentity = () => {
|
||||
return user?.id ? `id_${user.id}` : `u_${user?.username || 'guest'}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成报表布局偏好的 storage key。
|
||||
* @param table - 报表表名(如 chat_logs)
|
||||
*/
|
||||
const getReportLayoutStorageKey = (table: string) => {
|
||||
return `hxops_report_layout_v2_${getCurrentIdentity()}_${table}`;
|
||||
// v3:聊天日志默认列宽收窄(应用名/用户/姓名/Token),旧 v2 偏好不再沿用
|
||||
return `hxops_report_layout_v3_${getCurrentIdentity()}_${table}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取指定报表表的布局偏好。
|
||||
* @param table - 报表表名
|
||||
* @returns 解析后的偏好,失败或不存在时返回 null
|
||||
*/
|
||||
export const loadReportLayoutPref = <T = any>(table: string): T | null => {
|
||||
try {
|
||||
const raw = localStorage.getItem(getReportLayoutStorageKey(table));
|
||||
@@ -38,6 +46,11 @@ export const loadReportLayoutPref = <T = any>(table: string): T | null => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 写入指定报表表的布局偏好。
|
||||
* @param table - 报表表名
|
||||
* @param payload - 可序列化的布局对象
|
||||
*/
|
||||
export const saveReportLayoutPref = (table: string, payload: unknown) => {
|
||||
try {
|
||||
localStorage.setItem(getReportLayoutStorageKey(table), JSON.stringify(payload));
|
||||
@@ -45,4 +58,3 @@ export const saveReportLayoutPref = (table: string, payload: unknown) => {
|
||||
// Ignore storage write failure to avoid blocking core report flow.
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* shared/composables/useTableSort.ts
|
||||
* 用途:表格列排序状态(当前列、方向)与切换/排序辅助。
|
||||
* 依赖:vue ref、table-sort 纯函数。
|
||||
* 逻辑:业务 composable(如 useDepartmentsAdmin)注入本 hook,页面用 SortableTableHeader 展示。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import {
|
||||
nextSortState,
|
||||
sortByKey,
|
||||
type SortComparable,
|
||||
type SortDir,
|
||||
} from '@/shared/utils/table-sort';
|
||||
|
||||
export interface UseTableSortOptions<K extends string> {
|
||||
/** 初始排序列 */
|
||||
initialKey?: K;
|
||||
/** 初始方向,默认 asc */
|
||||
initialDir?: SortDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理表格排序状态,并提供按当前状态排序列表的方法。
|
||||
* @param options.initialKey - 默认排序列
|
||||
* @param options.initialDir - 默认方向
|
||||
*/
|
||||
export function useTableSort<K extends string>(options: UseTableSortOptions<K> = {}) {
|
||||
const sortKey = ref(options.initialKey as K | undefined);
|
||||
const sortDir = ref<SortDir>(options.initialDir ?? 'asc');
|
||||
|
||||
/**
|
||||
* 切换表头排序:同列升/降切换,换列从升序开始。
|
||||
* @param key - 点击的列键
|
||||
*/
|
||||
const toggleSort = (key: K): void => {
|
||||
const next = nextSortState(sortKey.value, sortDir.value, key);
|
||||
sortKey.value = next.sortKey;
|
||||
sortDir.value = next.sortDir;
|
||||
};
|
||||
|
||||
/**
|
||||
* 按当前 sortKey / sortDir 对列表排序。
|
||||
* @param items - 源列表
|
||||
* @param getValue - 从行取比较值
|
||||
* @param tieBreaker - 可选稳定次序
|
||||
* @returns 新排序数组
|
||||
*/
|
||||
const sortItems = <T>(
|
||||
items: readonly T[],
|
||||
getValue: (item: T, key: K) => SortComparable,
|
||||
tieBreaker?: (a: T, b: T) => number,
|
||||
): T[] =>
|
||||
sortByKey(items, {
|
||||
sortKey: sortKey.value,
|
||||
sortDir: sortDir.value,
|
||||
getValue,
|
||||
tieBreaker,
|
||||
});
|
||||
|
||||
return {
|
||||
sortKey,
|
||||
sortDir,
|
||||
toggleSort,
|
||||
sortItems,
|
||||
};
|
||||
}
|
||||
@@ -8,6 +8,8 @@ export * from './composables/useIsMobile';
|
||||
export * from './composables/useGlobalMessageDialog';
|
||||
export * from './composables/useReportLayoutStorage';
|
||||
export * from './composables/useAudioTranscription';
|
||||
export * from './composables/useTableSort';
|
||||
export * from './utils/table-sort';
|
||||
export * from './api/client';
|
||||
export * from './constants/routes';
|
||||
export type * from './types/schedule.types';
|
||||
@@ -395,7 +395,7 @@
|
||||
}
|
||||
|
||||
.admin-report-filter-input {
|
||||
@apply w-full px-2 py-1 text-xs border rounded outline-none font-normal normal-case;
|
||||
@apply w-full max-w-full min-w-0 box-border px-1.5 py-1 text-xs border rounded outline-none font-normal normal-case;
|
||||
border-color: var(--border-default);
|
||||
background-color: var(--bg-surface);
|
||||
color: var(--text-primary);
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* shared/utils/table-sort.test.ts
|
||||
* 用途:保护表格列排序纯函数的比较与切换语义。
|
||||
* 依赖:Vitest、table-sort。
|
||||
* 逻辑:覆盖空值、数字自然序、同列切换方向、换列重置升序。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
compareSortValues,
|
||||
nextSortState,
|
||||
normalizeSortValue,
|
||||
sortByKey,
|
||||
} from './table-sort';
|
||||
|
||||
describe('table-sort utils', () => {
|
||||
it('normalizes blank strings to null', () => {
|
||||
expect(normalizeSortValue(' ')).toBeNull();
|
||||
expect(normalizeSortValue('IT')).toBe('IT');
|
||||
expect(normalizeSortValue(12)).toBe(12);
|
||||
});
|
||||
|
||||
it('compares numeric-looking codes naturally', () => {
|
||||
expect(compareSortValues('2', '10')).toBeLessThan(0);
|
||||
expect(compareSortValues(null, 'a')).toBe(1);
|
||||
});
|
||||
|
||||
it('toggles direction on same key and resets on new key', () => {
|
||||
expect(nextSortState('name', 'asc', 'name')).toEqual({
|
||||
sortKey: 'name',
|
||||
sortDir: 'desc',
|
||||
});
|
||||
expect(nextSortState('name', 'desc', 'code')).toEqual({
|
||||
sortKey: 'code',
|
||||
sortDir: 'asc',
|
||||
});
|
||||
});
|
||||
|
||||
it('sorts rows by key with id tie-breaker', () => {
|
||||
const rows = [
|
||||
{ id: 2, name: 'B' },
|
||||
{ id: 1, name: 'A' },
|
||||
{ id: 3, name: 'A' },
|
||||
];
|
||||
const sorted = sortByKey(rows, {
|
||||
sortKey: 'name',
|
||||
sortDir: 'asc',
|
||||
getValue: (row, key) => row[key],
|
||||
tieBreaker: (a, b) => a.id - b.id,
|
||||
});
|
||||
expect(sorted.map((r) => r.id)).toEqual([1, 3, 2]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* shared/utils/table-sort.ts
|
||||
* 用途:管理端表格列排序的纯函数(比较、切换方向、按列排序)。
|
||||
* 依赖:无。
|
||||
* 逻辑:useTableSort / SortableTableHeader 复用;业务页传入取值函数即可。
|
||||
*/
|
||||
|
||||
export type SortDir = 'asc' | 'desc';
|
||||
|
||||
/** 可参与比较的原始值(空值统一排后) */
|
||||
export type SortComparable = string | number | null | undefined;
|
||||
|
||||
/**
|
||||
* 规范化比较值:字符串 trim,空串/null/undefined 视为空。
|
||||
* @param value - 原始字段值
|
||||
* @returns 规范化后的 string | number,空则为 null
|
||||
*/
|
||||
export function normalizeSortValue(value: SortComparable): string | number | null {
|
||||
if (value == null) return null;
|
||||
if (typeof value === 'number') {
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
const trimmed = String(value).trim();
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个规范化后的排序值。
|
||||
* 核心逻辑:空值排后;数字直接相减;字符串用 localeCompare(numeric)。
|
||||
* @param a - 左值
|
||||
* @param b - 右值
|
||||
* @returns 负/零/正,与 Array.sort 约定一致
|
||||
*/
|
||||
export function compareSortValues(
|
||||
a: string | number | null,
|
||||
b: string | number | null,
|
||||
): number {
|
||||
if (a == null && b == null) return 0;
|
||||
if (a == null) return 1;
|
||||
if (b == null) return -1;
|
||||
if (typeof a === 'number' && typeof b === 'number') return a - b;
|
||||
return String(a).localeCompare(String(b), undefined, {
|
||||
numeric: true,
|
||||
sensitivity: 'base',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换排序状态:同列在升/降序间切换,换列则从升序开始。
|
||||
* @param currentKey - 当前排序列
|
||||
* @param currentDir - 当前方向
|
||||
* @param nextKey - 点击的列
|
||||
* @returns 新的 sortKey / sortDir
|
||||
*/
|
||||
export function nextSortState<K extends string>(
|
||||
currentKey: K | undefined,
|
||||
currentDir: SortDir,
|
||||
nextKey: K,
|
||||
): { sortKey: K; sortDir: SortDir } {
|
||||
if (currentKey === nextKey) {
|
||||
return {
|
||||
sortKey: nextKey,
|
||||
sortDir: currentDir === 'asc' ? 'desc' : 'asc',
|
||||
};
|
||||
}
|
||||
return { sortKey: nextKey, sortDir: 'asc' };
|
||||
}
|
||||
|
||||
export interface SortByKeyOptions<T, K extends string> {
|
||||
/** 当前排序列;未指定时返回浅拷贝原列表 */
|
||||
sortKey?: K;
|
||||
sortDir?: SortDir;
|
||||
/** 从行中取出比较值 */
|
||||
getValue: (item: T, key: K) => SortComparable;
|
||||
/** 主值相等时的稳定次序(如按 id) */
|
||||
tieBreaker?: (a: T, b: T) => number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按指定列对列表排序(不修改原数组)。
|
||||
* @param items - 源列表
|
||||
* @param options - 排序列、方向、取值与 tie-break
|
||||
* @returns 新排序数组
|
||||
*/
|
||||
export function sortByKey<T, K extends string>(
|
||||
items: readonly T[],
|
||||
options: SortByKeyOptions<T, K>,
|
||||
): T[] {
|
||||
const { sortKey, sortDir = 'asc', getValue, tieBreaker } = options;
|
||||
const list = [...items];
|
||||
if (!sortKey) return list;
|
||||
|
||||
const dir = sortDir === 'asc' ? 1 : -1;
|
||||
list.sort((a, b) => {
|
||||
const av = normalizeSortValue(getValue(a, sortKey));
|
||||
const bv = normalizeSortValue(getValue(b, sortKey));
|
||||
const cmp = compareSortValues(av, bv);
|
||||
if (cmp !== 0) return cmp * dir;
|
||||
return tieBreaker ? tieBreaker(a, b) : 0;
|
||||
});
|
||||
return list;
|
||||
}
|
||||
Reference in new issue
Block a user