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'])
|
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def usage_report():
|
def usage_report():
|
||||||
"""聊天使用分析报表。"""
|
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||||
try:
|
try:
|
||||||
user_page = int(request.args.get('user_page', 1))
|
user_page = int(request.args.get('user_page', 1))
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
@@ -28,7 +28,14 @@ def usage_report():
|
|||||||
user_page_size = int(request.args.get('user_page_size', 10))
|
user_page_size = int(request.args.get('user_page_size', 10))
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
user_page_size = 10
|
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'])
|
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ backend/app/services/admin/report_service.py
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import math
|
import math
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from sqlalchemy import desc, func
|
from sqlalchemy import desc, func
|
||||||
@@ -18,13 +18,53 @@ from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
|
|||||||
|
|
||||||
USAGE_BY_USER_TOP_LIMIT = 50
|
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:
|
|
||||||
"""聊天使用分析报表。"""
|
def resolve_usage_range_start(range_key: str | None) -> tuple[str, datetime]:
|
||||||
total = db.session.query(ChatLog).count()
|
"""
|
||||||
|
解析使用分析时间范围,返回规范化 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 = (
|
by_agent = (
|
||||||
db.session.query(Agent.name, func.count(ChatLog.id))
|
db.session.query(Agent.name, func.count(ChatLog.id))
|
||||||
.join(ChatLog)
|
.join(ChatLog)
|
||||||
|
.filter(base_filter)
|
||||||
.group_by(Agent.name)
|
.group_by(Agent.name)
|
||||||
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
||||||
.all()
|
.all()
|
||||||
@@ -34,6 +74,7 @@ def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
|
|||||||
by_user_top = (
|
by_user_top = (
|
||||||
db.session.query(User.username, func.count(ChatLog.id))
|
db.session.query(User.username, func.count(ChatLog.id))
|
||||||
.join(ChatLog)
|
.join(ChatLog)
|
||||||
|
.filter(base_filter)
|
||||||
.group_by(User.username)
|
.group_by(User.username)
|
||||||
.order_by(desc(func.count(ChatLog.id)), User.username)
|
.order_by(desc(func.count(ChatLog.id)), User.username)
|
||||||
.limit(USAGE_BY_USER_TOP_LIMIT)
|
.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]
|
by_user_page = by_user_top[offset:offset + user_page_size]
|
||||||
return {
|
return {
|
||||||
'total': total,
|
'total': total,
|
||||||
|
'range': normalized_range,
|
||||||
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
|
'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],
|
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||||||
'user_total': user_total,
|
'user_total': user_total,
|
||||||
|
|||||||
@@ -104,10 +104,39 @@ def apply_users_filters(query, query_params: dict[str, str]):
|
|||||||
return query
|
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:
|
def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||||
query = apply_users_filters(db.session.query(User), query_params)
|
query = apply_users_filters(db.session.query(User), query_params)
|
||||||
|
order_by = resolve_users_order_by(query_params)
|
||||||
if 'page' not in 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]
|
return [serialize_admin_user(u) for u in users]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -128,7 +157,7 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
|||||||
|
|
||||||
users = (
|
users = (
|
||||||
query.options(joinedload(User.agents))
|
query.options(joinedload(User.agents))
|
||||||
.order_by(User.id.asc())
|
.order_by(*order_by)
|
||||||
.offset((page - 1) * page_size)
|
.offset((page - 1) * page_size)
|
||||||
.limit(page_size)
|
.limit(page_size)
|
||||||
.all()
|
.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.add(ChatLog(user_id=user.id, agent_id=agent.id, query='hi', answer='ok', tokens_used=1))
|
||||||
db.session.commit()
|
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['total'] == 1
|
||||||
|
assert data['range'] == '30d'
|
||||||
assert data['by_user'][0]['username'] == 'report-user'
|
assert data['by_user'][0]['username'] == 'report-user'
|
||||||
assert data['by_agent'][0]['agent'] == 'report-agent'
|
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):
|
def test_build_feedback_report(app):
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
db.session.add(Feedback(score=5))
|
db.session.add(Feedback(score=5))
|
||||||
|
|||||||
@@ -21,3 +21,34 @@ def test_approve_and_reject_user(app):
|
|||||||
user_service.reject_user(user.id)
|
user_service.reject_user(user.id)
|
||||||
db.session.refresh(user)
|
db.session.refresh(user)
|
||||||
assert user.status == 'rejected'
|
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 { AdminUserRow } from '../types/admin.types';
|
||||||
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
|
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
|
||||||
import type { PaginatedResult } from '@/shared/types/pagination.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 auth = () => ({ headers: getAuthHeaders() });
|
||||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||||
@@ -27,11 +27,15 @@ export interface ListAdminUsersPageParams {
|
|||||||
employee_id?: string;
|
employee_id?: string;
|
||||||
phone_number?: string;
|
phone_number?: string;
|
||||||
hideRejected?: boolean;
|
hideRejected?: boolean;
|
||||||
|
/** 排序列:username | department */
|
||||||
|
sortBy?: 'username' | 'department';
|
||||||
|
/** 排序方向 */
|
||||||
|
sortDir?: 'asc' | 'desc';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 分页拉取用户列表(服务端筛选 + 分页,供用户管理页使用)。
|
* 分页拉取用户列表(服务端筛选 + 分页 + 排序,供用户管理页使用)。
|
||||||
* @param params - 页码、每页条数与各字段模糊筛选
|
* @param params - 页码、每页条数、字段模糊筛选与 sortBy/sortDir
|
||||||
*/
|
*/
|
||||||
export const listAdminUsersPage = (params: ListAdminUsersPageParams) => {
|
export const listAdminUsersPage = (params: ListAdminUsersPageParams) => {
|
||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
@@ -53,6 +57,8 @@ export const listAdminUsersPage = (params: ListAdminUsersPageParams) => {
|
|||||||
if (value) qs.set(queryKey, value);
|
if (value) qs.set(queryKey, value);
|
||||||
}
|
}
|
||||||
if (params.hideRejected) qs.set('hide_rejected', 'true');
|
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());
|
return requestJson<PaginatedResult<AdminUserRow>>(`/api/admin/users?${qs.toString()}`, auth());
|
||||||
};
|
};
|
||||||
export const createAdminUser = (payload: Record<string, unknown>) =>
|
export const createAdminUser = (payload: Record<string, unknown>) =>
|
||||||
@@ -254,12 +260,15 @@ export const getAdminDashboardBadges = () =>
|
|||||||
export interface AdminUsageReportParams {
|
export interface AdminUsageReportParams {
|
||||||
user_page?: number;
|
user_page?: number;
|
||||||
user_page_size?: number;
|
user_page_size?: number;
|
||||||
|
/** 时间范围:7d | 30d | 90d | 180d | 365d */
|
||||||
|
range?: UsageRangeKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
|
export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
|
||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
if (params.user_page != null) qs.set('user_page', String(params.user_page));
|
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.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();
|
const query = qs.toString();
|
||||||
return requestJson<UsageReport>(
|
return requestJson<UsageReport>(
|
||||||
`/api/admin/reports/usage${query ? `?${query}` : ''}`,
|
`/api/admin/reports/usage${query ? `?${query}` : ''}`,
|
||||||
|
|||||||
@@ -1,25 +1,36 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/departments/DepartmentsPage.vue
|
* features/admin/modules/departments/DepartmentsPage.vue
|
||||||
* 部门管理独立页面。路由:/admin/departments
|
* 用途:部门管理独立页面——全宽表格列表 + 列排序 + 创建/编辑居中弹窗。
|
||||||
|
* 依赖:useDepartmentsAdmin、SortableTableHeader、DepartmentFormModal、DeleteConfirmDialog。
|
||||||
|
* 逻辑:路由 /admin/departments;表头排序复用 shared SortableTableHeader + useTableSort。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted } from 'vue';
|
import { onMounted } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
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 DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||||
|
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
|
||||||
|
import DepartmentFormModal from './components/DepartmentFormModal.vue';
|
||||||
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
|
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
const {
|
const {
|
||||||
departments,
|
filteredDepartments,
|
||||||
editingDept,
|
form,
|
||||||
|
searchQuery,
|
||||||
|
sortKey,
|
||||||
|
sortDir,
|
||||||
isLoading,
|
isLoading,
|
||||||
|
isSaving,
|
||||||
|
showFormModal,
|
||||||
showDeleteConfirmDialog,
|
showDeleteConfirmDialog,
|
||||||
deleteConfirmMessage,
|
deleteConfirmMessage,
|
||||||
loadAll,
|
loadAll,
|
||||||
resetForm,
|
toggleSort,
|
||||||
editDepartment,
|
openCreateModal,
|
||||||
|
openEditModal,
|
||||||
|
closeFormModal,
|
||||||
saveDepartment,
|
saveDepartment,
|
||||||
deleteDepartment,
|
deleteDepartment,
|
||||||
closeDeleteConfirm,
|
closeDeleteConfirm,
|
||||||
@@ -32,127 +43,137 @@ onMounted(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<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 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 class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<div class="flex items-center justify-between">
|
<div class="admin-table-header admin-table-header--stacked">
|
||||||
<div>
|
<div>
|
||||||
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
|
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
|
||||||
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
|
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
|
||||||
</div>
|
</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>
|
||||||
|
|
||||||
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
<div class="admin-table-filters--inline gap-3">
|
||||||
<div class="lg:col-span-1 card p-6 shadow-sm h-fit">
|
<div class="relative flex-1 min-w-[200px] max-w-sm">
|
||||||
<h3 class="font-bold text-primary mb-4">
|
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted pointer-events-none" />
|
||||||
{{ editingDept.id ? t('admin.dept.edit') : t('admin.dept.add') }}
|
<input
|
||||||
</h3>
|
v-model="searchQuery"
|
||||||
<div class="form-stack">
|
type="search"
|
||||||
<div class="space-y-1.5">
|
class="admin-table-filter-input w-full pl-9"
|
||||||
<label class="label-field block">{{ t('admin.dept.fields.name') }}</label>
|
:placeholder="t('admin.dept.searchPlaceholder')"
|
||||||
<input
|
/>
|
||||||
v-model="editingDept.name"
|
|
||||||
class="input-field text-sm"
|
|
||||||
:placeholder="t('admin.dept.fields.namePlaceholder')"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div class="space-y-1.5">
|
|
||||||
<label class="label-field">{{ t('admin.dept.fields.code') }}</label>
|
|
||||||
<input
|
|
||||||
v-model="editingDept.code"
|
|
||||||
class="input-field text-sm"
|
|
||||||
:placeholder="t('admin.dept.fields.codePlaceholder')"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div class="space-y-1.5">
|
|
||||||
<label class="label-field">{{ t('admin.dept.fields.company') }}</label>
|
|
||||||
<input
|
|
||||||
v-model="editingDept.company"
|
|
||||||
class="input-field text-sm"
|
|
||||||
:placeholder="t('admin.dept.fields.companyPlaceholder')"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div class="space-y-1.5">
|
|
||||||
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
|
|
||||||
<textarea
|
|
||||||
v-model="editingDept.description"
|
|
||||||
rows="3"
|
|
||||||
class="input-field text-sm"
|
|
||||||
:placeholder="t('admin.dept.fields.descriptionPlaceholder')"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="flex justify-end gap-2 pt-2">
|
|
||||||
<button
|
|
||||||
v-if="editingDept.id"
|
|
||||||
type="button"
|
|
||||||
class="btn-ghost btn-sm"
|
|
||||||
@click="resetForm"
|
|
||||||
>
|
|
||||||
{{ t('admin.cancel') }}
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn-primary btn-sm" @click="saveDepartment">
|
|
||||||
{{ editingDept.id ? t('admin.update') : t('admin.add') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="lg:col-span-2 admin-table-section">
|
<div class="admin-table-wrap">
|
||||||
<div v-if="departments.length === 0" class="p-8 text-center text-muted">
|
<!-- 列宽:名称 / 编码 / 公司 / 操作 -->
|
||||||
{{ t('admin.dept.noDepts') }}
|
<table class="admin-table table-fixed">
|
||||||
</div>
|
<colgroup>
|
||||||
<table v-else class="admin-table">
|
<col class="w-[25%]" />
|
||||||
<thead>
|
<col class="w-[20%]" />
|
||||||
<tr>
|
<col class="w-[35%]" />
|
||||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
|
<col class="w-[15%]" />
|
||||||
{{ t('admin.dept.headers.name') }}
|
</colgroup>
|
||||||
</th>
|
<thead>
|
||||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
|
<tr>
|
||||||
{{ t('admin.dept.headers.code') }}
|
<th class="px-6 py-4 text-left text-xs">
|
||||||
</th>
|
<SortableTableHeader
|
||||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase">
|
column-key="name"
|
||||||
{{ t('admin.dept.headers.company') }}
|
:label="t('admin.dept.headers.name')"
|
||||||
</th>
|
:active-key="sortKey"
|
||||||
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase text-right">
|
:direction="sortDir"
|
||||||
{{ t('admin.dept.headers.actions') }}
|
@sort="toggleSort"
|
||||||
</th>
|
/>
|
||||||
</tr>
|
</th>
|
||||||
</thead>
|
<th class="px-6 py-4 text-left text-xs">
|
||||||
<tbody class="divide-y divide-subtle">
|
<SortableTableHeader
|
||||||
<tr v-for="d in departments" :key="d.id">
|
column-key="code"
|
||||||
<td class="px-6 py-4">
|
:label="t('admin.dept.headers.code')"
|
||||||
<div class="font-medium text-primary text-sm">{{ d.name }}</div>
|
:active-key="sortKey"
|
||||||
<div class="text-xs text-muted truncate max-w-xs mt-0.5">{{ d.description }}</div>
|
:direction="sortDir"
|
||||||
</td>
|
@sort="toggleSort"
|
||||||
<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>
|
</th>
|
||||||
<td class="px-6 py-4 text-right flex justify-end gap-2">
|
<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
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
|
class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
|
||||||
@click="editDepartment(d)"
|
:title="t('admin.dept.actions.edit')"
|
||||||
|
@click="openEditModal(d)"
|
||||||
>
|
>
|
||||||
<Edit class="w-4 h-4" />
|
<Edit class="w-4 h-4" />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
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)"
|
@click="deleteDepartment(d.id)"
|
||||||
>
|
>
|
||||||
<Trash2 class="w-4 h-4" />
|
<Trash2 class="w-4 h-4" />
|
||||||
</button>
|
</button>
|
||||||
</td>
|
</div>
|
||||||
</tr>
|
</td>
|
||||||
</tbody>
|
</tr>
|
||||||
</table>
|
</tbody>
|
||||||
</div>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<DepartmentFormModal
|
||||||
|
:visible="showFormModal"
|
||||||
|
:form="form"
|
||||||
|
:is-saving="isSaving"
|
||||||
|
@close="closeFormModal"
|
||||||
|
@save="saveDepartment"
|
||||||
|
/>
|
||||||
|
|
||||||
<DeleteConfirmDialog
|
<DeleteConfirmDialog
|
||||||
v-model="showDeleteConfirmDialog"
|
v-model="showDeleteConfirmDialog"
|
||||||
:message="deleteConfirmMessage"
|
: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
|
* 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 { useI18n } from 'vue-i18n';
|
||||||
import {
|
import {
|
||||||
createAdminDepartment,
|
createAdminDepartment,
|
||||||
@@ -11,24 +13,63 @@ import {
|
|||||||
updateAdminDepartment,
|
updateAdminDepartment,
|
||||||
} from '@/features/admin/api/admin.api';
|
} from '@/features/admin/api/admin.api';
|
||||||
import { useMessage } from '@/shared/composables/useMessage';
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
|
import { useTableSort } from '@/shared/composables/useTableSort';
|
||||||
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
||||||
import {
|
import {
|
||||||
createEmptyDepartmentForm,
|
createEmptyDepartmentForm,
|
||||||
|
departmentRowToForm,
|
||||||
type DepartmentFormState,
|
type DepartmentFormState,
|
||||||
} from '@/features/admin/types/department.types';
|
} from '@/features/admin/types/department.types';
|
||||||
|
|
||||||
|
/** 部门表可排序列 */
|
||||||
|
export type DeptSortKey = 'name' | 'code' | 'company';
|
||||||
|
|
||||||
export function useDepartmentsAdmin() {
|
export function useDepartmentsAdmin() {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const msg = useMessage();
|
const msg = useMessage();
|
||||||
|
|
||||||
const departments = ref<AdminDepartmentRow[]>([]);
|
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 isLoading = ref(true);
|
||||||
|
const isSaving = ref(false);
|
||||||
|
const showFormModal = ref(false);
|
||||||
|
|
||||||
const showDeleteConfirmDialog = ref(false);
|
const showDeleteConfirmDialog = ref(false);
|
||||||
const deleteConfirmMessage = ref('');
|
const deleteConfirmMessage = ref('');
|
||||||
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
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> => {
|
const loadDepartments = async (): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
departments.value = await listAdminDepartments();
|
departments.value = await listAdminDepartments();
|
||||||
@@ -38,23 +79,37 @@ export function useDepartmentsAdmin() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 页面初始化:加载部门列表并结束 loading。
|
||||||
|
* @returns Promise<void>
|
||||||
|
*/
|
||||||
const loadAll = async (): Promise<void> => {
|
const loadAll = async (): Promise<void> => {
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
await loadDepartments();
|
await loadDepartments();
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开删除确认对话框并绑定确认后的删除动作。
|
||||||
|
* @param message - 确认文案
|
||||||
|
* @param action - 用户确认后执行的异步删除逻辑
|
||||||
|
*/
|
||||||
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
|
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
|
||||||
deleteConfirmMessage.value = message;
|
deleteConfirmMessage.value = message;
|
||||||
deleteConfirmAction = action;
|
deleteConfirmAction = action;
|
||||||
showDeleteConfirmDialog.value = true;
|
showDeleteConfirmDialog.value = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 关闭删除确认对话框并清空待执行动作。 */
|
||||||
const closeDeleteConfirm = (): void => {
|
const closeDeleteConfirm = (): void => {
|
||||||
showDeleteConfirmDialog.value = false;
|
showDeleteConfirmDialog.value = false;
|
||||||
deleteConfirmAction = null;
|
deleteConfirmAction = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行删除确认对话框中绑定的删除动作。
|
||||||
|
* @returns Promise<void>
|
||||||
|
*/
|
||||||
const confirmDelete = async (): Promise<void> => {
|
const confirmDelete = async (): Promise<void> => {
|
||||||
if (!deleteConfirmAction) return;
|
if (!deleteConfirmAction) return;
|
||||||
try {
|
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,
|
* @param dept - 待编辑的部门行
|
||||||
name: dept.name,
|
*/
|
||||||
code: dept.code || '',
|
const openEditModal = (dept: AdminDepartmentRow): void => {
|
||||||
company: dept.company || '',
|
form.value = departmentRowToForm(dept);
|
||||||
description: dept.description || '',
|
showFormModal.value = true;
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 关闭创建/编辑弹窗并重置表单。 */
|
||||||
|
const closeFormModal = (): void => {
|
||||||
|
showFormModal.value = false;
|
||||||
|
form.value = createEmptyDepartmentForm();
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存部门:有 id 则更新,否则新建。
|
||||||
|
* 核心逻辑:校验名称 → 调 create/update API → 刷新列表并关闭弹窗。
|
||||||
|
* @returns Promise<void>
|
||||||
|
*/
|
||||||
const saveDepartment = async (): Promise<void> => {
|
const saveDepartment = async (): Promise<void> => {
|
||||||
if (!editingDept.value.name?.trim()) {
|
if (!form.value.name?.trim()) {
|
||||||
msg.warning(t('admin.dept.msg.nameRequired'));
|
msg.warning(t('admin.dept.msg.nameRequired'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
isSaving.value = true;
|
||||||
try {
|
try {
|
||||||
const payload = {
|
const payload = {
|
||||||
name: editingDept.value.name,
|
name: form.value.name.trim(),
|
||||||
code: editingDept.value.code,
|
code: form.value.code?.trim() || '',
|
||||||
company: editingDept.value.company,
|
company: form.value.company?.trim() || '',
|
||||||
description: editingDept.value.description,
|
description: form.value.description?.trim() || '',
|
||||||
};
|
};
|
||||||
if (editingDept.value.id) {
|
if (form.value.id) {
|
||||||
await updateAdminDepartment(editingDept.value.id, payload);
|
await updateAdminDepartment(form.value.id, payload);
|
||||||
} else {
|
} else {
|
||||||
await createAdminDepartment(payload);
|
await createAdminDepartment(payload);
|
||||||
}
|
}
|
||||||
|
closeFormModal();
|
||||||
await loadDepartments();
|
await loadDepartments();
|
||||||
resetForm();
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||||
|
} finally {
|
||||||
|
isSaving.value = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除指定部门,删除前弹出确认框。
|
||||||
|
* @param id - 部门主键
|
||||||
|
*/
|
||||||
const deleteDepartment = (id: number): void => {
|
const deleteDepartment = (id: number): void => {
|
||||||
openDeleteConfirm(t('admin.dept.confirmDelete'), async () => {
|
openDeleteConfirm(t('admin.dept.confirmDelete'), async () => {
|
||||||
try {
|
try {
|
||||||
@@ -116,13 +190,21 @@ export function useDepartmentsAdmin() {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
departments,
|
departments,
|
||||||
editingDept,
|
filteredDepartments,
|
||||||
|
form,
|
||||||
|
searchQuery,
|
||||||
|
sortKey,
|
||||||
|
sortDir,
|
||||||
isLoading,
|
isLoading,
|
||||||
|
isSaving,
|
||||||
|
showFormModal,
|
||||||
showDeleteConfirmDialog,
|
showDeleteConfirmDialog,
|
||||||
deleteConfirmMessage,
|
deleteConfirmMessage,
|
||||||
loadAll,
|
loadAll,
|
||||||
resetForm,
|
toggleSort,
|
||||||
editDepartment,
|
openCreateModal,
|
||||||
|
openEditModal,
|
||||||
|
closeFormModal,
|
||||||
saveDepartment,
|
saveDepartment,
|
||||||
deleteDepartment,
|
deleteDepartment,
|
||||||
closeDeleteConfirm,
|
closeDeleteConfirm,
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/permissions/PermissionsPage.vue
|
* features/admin/modules/permissions/PermissionsPage.vue
|
||||||
* 用户权限矩阵独立页面。路由:/admin/permissions
|
* 用途:应用权限矩阵独立页面(用户 / 真实姓名 / 部门 + Agent 勾选)。
|
||||||
|
* 依赖:usePermissionsAdmin、BatchPermissionModal、PaginationBar。
|
||||||
|
* 逻辑:路由 /admin/permissions;左侧用户相关列 sticky,右侧为各应用权限列。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted } from 'vue';
|
import { onMounted } from 'vue';
|
||||||
@@ -115,12 +117,17 @@ onMounted(() => {
|
|||||||
/>
|
/>
|
||||||
</th>
|
</th>
|
||||||
<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') }}
|
{{ t('admin.perm.headers.user') }}
|
||||||
</th>
|
</th>
|
||||||
<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') }}
|
{{ t('admin.perm.headers.dept') }}
|
||||||
</th>
|
</th>
|
||||||
@@ -148,25 +155,25 @@ onMounted(() => {
|
|||||||
@change="toggleUserSelection(user.id)"
|
@change="toggleUserSelection(user.id)"
|
||||||
/>
|
/>
|
||||||
</td>
|
</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="flex items-center gap-3">
|
||||||
<div
|
<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"
|
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() }}
|
{{ user.username.charAt(0).toUpperCase() }}
|
||||||
</div>
|
</div>
|
||||||
<div class="truncate max-w-[150px]">
|
<div class="font-medium text-primary text-sm truncate max-w-[120px]" :title="user.username">
|
||||||
<div class="font-medium text-primary truncate" :title="user.username">
|
{{ user.username }}
|
||||||
{{ user.username }}
|
|
||||||
</div>
|
|
||||||
<div class="text-xs text-muted truncate" :title="user.email">
|
|
||||||
{{ user.email }}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</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
|
<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">
|
<div class="text-sm text-muted truncate" :title="user.department">
|
||||||
{{ user.department || '-' }}
|
{{ user.department || '-' }}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/reports/ReportsPage.vue
|
* features/admin/modules/reports/ReportsPage.vue
|
||||||
* 管理后台报表独立页面。路由:/admin/reports/:table?
|
* 用途:管理后台报表独立页面(多表浏览、列筛选、聊天日志批量操作)。
|
||||||
|
* 依赖:useReportsAdmin、DeleteConfirmDialog。
|
||||||
|
* 逻辑:路由 /admin/reports/:table?;列宽由 composable 默认值与本地偏好控制。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted } from 'vue';
|
import { onMounted } from 'vue';
|
||||||
@@ -13,6 +15,8 @@ const { t } = useI18n();
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
usageReport,
|
usageReport,
|
||||||
|
usageRange,
|
||||||
|
usageRangeOptions,
|
||||||
usageUserPage,
|
usageUserPage,
|
||||||
usageUserPageSize,
|
usageUserPageSize,
|
||||||
usageUserPageSizeOptions,
|
usageUserPageSizeOptions,
|
||||||
@@ -260,7 +264,7 @@ onMounted(() => {
|
|||||||
<th
|
<th
|
||||||
v-for="key in visibleReportKeys"
|
v-for="key in visibleReportKeys"
|
||||||
:key="key"
|
: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)"
|
:style="getColumnWidthStyle(key)"
|
||||||
:draggable="true"
|
:draggable="true"
|
||||||
@dragstart="onColumnDragStart(String(key))"
|
@dragstart="onColumnDragStart(String(key))"
|
||||||
@@ -310,7 +314,7 @@ onMounted(() => {
|
|||||||
<td
|
<td
|
||||||
v-for="key in visibleReportKeys"
|
v-for="key in visibleReportKeys"
|
||||||
:key="`cell-${idx}-${key}`"
|
:key="`cell-${idx}-${key}`"
|
||||||
class="px-6 py-3 font-mono"
|
class="px-3 py-3 font-mono"
|
||||||
:title="String(getReportCellValue(row, String(key)))"
|
:title="String(getReportCellValue(row, String(key)))"
|
||||||
:style="getReportCellDisplayStyle(String(key))"
|
:style="getReportCellDisplayStyle(String(key))"
|
||||||
>
|
>
|
||||||
@@ -376,7 +380,17 @@ onMounted(() => {
|
|||||||
|
|
||||||
<!-- Statistics Charts -->
|
<!-- Statistics Charts -->
|
||||||
<div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-default pt-10">
|
<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="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
<div class="card p-6">
|
<div class="card p-6">
|
||||||
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byAgent') }}</h4>
|
<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
|
* 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 { computed, ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
@@ -21,6 +23,7 @@ import type {
|
|||||||
ChatLogsLayoutPref,
|
ChatLogsLayoutPref,
|
||||||
ReportColumnConfig,
|
ReportColumnConfig,
|
||||||
SortRule,
|
SortRule,
|
||||||
|
UsageRangeKey,
|
||||||
UsageReport,
|
UsageReport,
|
||||||
} from '@/features/admin/types/report.types';
|
} from '@/features/admin/types/report.types';
|
||||||
import type { AdminReportTableId } from '@/features/admin/types/admin.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;
|
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() {
|
export function useReportsAdmin() {
|
||||||
const { t, locale } = useI18n();
|
const { t, locale } = useI18n();
|
||||||
const msg = useMessage();
|
const msg = useMessage();
|
||||||
@@ -47,12 +77,16 @@ export function useReportsAdmin() {
|
|||||||
const usageUserPage = ref(1);
|
const usageUserPage = ref(1);
|
||||||
const usageUserPageSize = ref(10);
|
const usageUserPageSize = ref(10);
|
||||||
const usageUserPageSizeOptions = [5, 10, 20, 50];
|
const usageUserPageSizeOptions = [5, 10, 20, 50];
|
||||||
|
/** 使用分析时间范围,默认近一月 */
|
||||||
|
const usageRange = ref<UsageRangeKey>('30d');
|
||||||
|
const usageRangeOptions: UsageRangeKey[] = ['7d', '30d', '90d', '180d', '365d'];
|
||||||
|
|
||||||
const loadUsageReport = async (): Promise<void> => {
|
const loadUsageReport = async (): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
usageReport.value = await getAdminUsageReport({
|
usageReport.value = await getAdminUsageReport({
|
||||||
user_page: usageUserPage.value,
|
user_page: usageUserPage.value,
|
||||||
user_page_size: usageUserPageSize.value,
|
user_page_size: usageUserPageSize.value,
|
||||||
|
range: usageRange.value,
|
||||||
});
|
});
|
||||||
const pages = usageReport.value?.user_pages ?? 1;
|
const pages = usageReport.value?.user_pages ?? 1;
|
||||||
if (usageUserPage.value > pages) {
|
if (usageUserPage.value > pages) {
|
||||||
@@ -199,7 +233,7 @@ const initChatLogsColumns = (keys: string[]) => {
|
|||||||
const defaults: ReportColumnConfig[] = keys.map((k) => ({
|
const defaults: ReportColumnConfig[] = keys.map((k) => ({
|
||||||
key: k,
|
key: k,
|
||||||
visible: hideByDefault ? k !== 'id' : true,
|
visible: hideByDefault ? k !== 'id' : true,
|
||||||
width: k === 'id' ? 90 : k === 'tokens_used' ? 120 : 180,
|
width: defaultChatLogsColumnWidth(k),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
let merged = defaults;
|
let merged = defaults;
|
||||||
@@ -213,7 +247,7 @@ const initChatLogsColumns = (keys: string[]) => {
|
|||||||
merged = [...order, ...missing].map((k) => ({
|
merged = [...order, ...missing].map((k) => ({
|
||||||
key: k,
|
key: k,
|
||||||
visible: savedMap.get(k)?.visible ?? (currentTable.value === 'chat_logs' && k === 'id' ? false : true),
|
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)) {
|
if (!Array.isArray(parsed)) {
|
||||||
chatLogsWrapEnabled.value = !!parsed.wrapEnabled;
|
chatLogsWrapEnabled.value = !!parsed.wrapEnabled;
|
||||||
@@ -826,6 +860,11 @@ watch(usageUserPageSize, () => {
|
|||||||
void loadUsageReport();
|
void loadUsageReport();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
watch(usageRange, () => {
|
||||||
|
usageUserPage.value = 1;
|
||||||
|
void loadUsageReport();
|
||||||
|
});
|
||||||
|
|
||||||
watch([reportPageSize, sortedTableData], () => {
|
watch([reportPageSize, sortedTableData], () => {
|
||||||
if (reportCurrentPage.value > reportTotalPages.value) {
|
if (reportCurrentPage.value > reportTotalPages.value) {
|
||||||
reportCurrentPage.value = reportTotalPages.value;
|
reportCurrentPage.value = reportTotalPages.value;
|
||||||
@@ -855,6 +894,8 @@ watch([reportPageSize, sortedTableData], () => {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
usageReport,
|
usageReport,
|
||||||
|
usageRange,
|
||||||
|
usageRangeOptions,
|
||||||
usageUserPage,
|
usageUserPage,
|
||||||
usageUserPageSize,
|
usageUserPageSize,
|
||||||
usageUserPageSizeOptions,
|
usageUserPageSizeOptions,
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/users/UsersPage.vue
|
* features/admin/modules/users/UsersPage.vue
|
||||||
* 用途:用户管理独立页面(服务端筛选分页、批量操作)。
|
* 用途:用户管理独立页面(服务端筛选分页、用户/部门列排序、批量操作)。
|
||||||
* 依赖:useUsersAdmin、PaginationBar、用户相关 Modal。
|
* 依赖:useUsersAdmin、SortableTableHeader、PaginationBar、用户相关 Modal。
|
||||||
* 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取。
|
* 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取,表头排序复用 shared 组件。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted } from 'vue';
|
import { onMounted } from 'vue';
|
||||||
@@ -10,6 +10,7 @@ import { useI18n } from 'vue-i18n';
|
|||||||
import { Edit, Plus, Trash2, Users } from 'lucide-vue-next';
|
import { Edit, Plus, Trash2, Users } from 'lucide-vue-next';
|
||||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||||
|
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
|
||||||
import BatchEditUserModal from './components/BatchEditUserModal.vue';
|
import BatchEditUserModal from './components/BatchEditUserModal.vue';
|
||||||
import BatchPermissionModal from './components/BatchPermissionModal.vue';
|
import BatchPermissionModal from './components/BatchPermissionModal.vue';
|
||||||
import UserFormModal from './components/UserFormModal.vue';
|
import UserFormModal from './components/UserFormModal.vue';
|
||||||
@@ -24,6 +25,8 @@ const {
|
|||||||
isListLoading,
|
isListLoading,
|
||||||
isSaving,
|
isSaving,
|
||||||
userFilters,
|
userFilters,
|
||||||
|
sortKey,
|
||||||
|
sortDir,
|
||||||
// hideRejected,
|
// hideRejected,
|
||||||
selectedUserIds,
|
selectedUserIds,
|
||||||
users,
|
users,
|
||||||
@@ -42,6 +45,7 @@ const {
|
|||||||
showDeleteConfirmDialog,
|
showDeleteConfirmDialog,
|
||||||
deleteConfirmMessage,
|
deleteConfirmMessage,
|
||||||
loadAll,
|
loadAll,
|
||||||
|
toggleSort,
|
||||||
openCreateUserModal,
|
openCreateUserModal,
|
||||||
openEditUserModal,
|
openEditUserModal,
|
||||||
saveUser,
|
saveUser,
|
||||||
@@ -156,9 +160,25 @@ onMounted(() => {
|
|||||||
@change="toggleAllUsers(users)"
|
@change="toggleAllUsers(users)"
|
||||||
/>
|
/>
|
||||||
</th>
|
</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.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-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>
|
<th class="px-6 py-4 text-right text-xs">{{ t('admin.user.headers.actions') }}</th>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -1,864 +1,457 @@
|
|||||||
/**
|
/**
|
||||||
|
|
||||||
* features/admin/modules/users/composables/useUsersAdmin.ts
|
* features/admin/modules/users/composables/useUsersAdmin.ts
|
||||||
|
* 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、用户/部门列排序、批量操作)。
|
||||||
* 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、批量操作)。
|
* 依赖:admin.api、useMessage、useTableSort。
|
||||||
|
* 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取,排序参数随请求下发。
|
||||||
* 依赖:admin.api、useMessage。
|
|
||||||
|
|
||||||
* 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取。
|
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { computed, ref, watch } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
|
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
|
||||||
batchDeleteAdminUsers,
|
batchDeleteAdminUsers,
|
||||||
|
|
||||||
batchUpdateAdminPermissions,
|
batchUpdateAdminPermissions,
|
||||||
|
|
||||||
batchUpdateAdminUsers,
|
batchUpdateAdminUsers,
|
||||||
|
|
||||||
cleanupRejectedAdminUsers,
|
cleanupRejectedAdminUsers,
|
||||||
|
|
||||||
createAdminUser,
|
createAdminUser,
|
||||||
|
|
||||||
listAdminAgents,
|
listAdminAgents,
|
||||||
|
|
||||||
listAdminDepartments,
|
listAdminDepartments,
|
||||||
|
|
||||||
listAdminUsersPage,
|
listAdminUsersPage,
|
||||||
|
|
||||||
updateAdminUser,
|
updateAdminUser,
|
||||||
|
|
||||||
} from '@/features/admin/api/admin.api';
|
} from '@/features/admin/api/admin.api';
|
||||||
|
|
||||||
import { useMessage } from '@/shared/composables/useMessage';
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
|
import { useTableSort } from '@/shared/composables/useTableSort';
|
||||||
import type { AdminAgentOption, AdminDepartmentRow, AdminUserRow } from '@/features/admin/types/admin.types';
|
import type { AdminAgentOption, AdminDepartmentRow, AdminUserRow } from '@/features/admin/types/admin.types';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
|
||||||
createEmptyUserFilters,
|
createEmptyUserFilters,
|
||||||
|
|
||||||
createEmptyUserForm,
|
createEmptyUserForm,
|
||||||
|
|
||||||
type BatchEditForm,
|
type BatchEditForm,
|
||||||
|
|
||||||
type BatchPermissionForm,
|
type BatchPermissionForm,
|
||||||
|
|
||||||
type UserFilters,
|
type UserFilters,
|
||||||
|
|
||||||
type UserFormState,
|
type UserFormState,
|
||||||
|
|
||||||
} from '@/features/admin/types/user.types';
|
} from '@/features/admin/types/user.types';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
|
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;
|
const USER_PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
|
||||||
|
|
||||||
|
/** 用户表可排序列:用户名 / 部门(与后端 sort_by 白名单一致) */
|
||||||
|
export type UserSortKey = 'username' | 'department';
|
||||||
|
|
||||||
export function useUsersAdmin() {
|
export function useUsersAdmin() {
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
const msg = useMessage();
|
const msg = useMessage();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const users = ref<AdminUserRow[]>([]);
|
const users = ref<AdminUserRow[]>([]);
|
||||||
|
|
||||||
const agents = ref<AdminAgentOption[]>([]);
|
const agents = ref<AdminAgentOption[]>([]);
|
||||||
|
|
||||||
const departments = ref<AdminDepartmentRow[]>([]);
|
const departments = ref<AdminDepartmentRow[]>([]);
|
||||||
|
|
||||||
const isLoading = ref(true);
|
const isLoading = ref(true);
|
||||||
|
|
||||||
const isListLoading = ref(false);
|
const isListLoading = ref(false);
|
||||||
|
|
||||||
const isSaving = ref(false);
|
const isSaving = ref(false);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const userFilters = ref<UserFilters>(createEmptyUserFilters());
|
const userFilters = ref<UserFilters>(createEmptyUserFilters());
|
||||||
|
/** 用户 / 部门列排序,默认按用户名升序 */
|
||||||
|
const { sortKey, sortDir, toggleSort: toggleSortBase } = useTableSort<UserSortKey>({
|
||||||
|
initialKey: 'username',
|
||||||
|
initialDir: 'asc',
|
||||||
|
});
|
||||||
const hideRejected = ref(true);
|
const hideRejected = ref(true);
|
||||||
|
|
||||||
const selectedUserIds = ref<number[]>([]);
|
const selectedUserIds = ref<number[]>([]);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const userPage = ref(1);
|
const userPage = ref(1);
|
||||||
|
|
||||||
const userPageSize = ref(20);
|
const userPageSize = ref(20);
|
||||||
|
|
||||||
const usersTotal = ref(0);
|
const usersTotal = ref(0);
|
||||||
|
|
||||||
const usersPages = ref(1);
|
const usersPages = ref(1);
|
||||||
|
|
||||||
let userSearchTimer: ReturnType<typeof setTimeout> | null = null;
|
let userSearchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const showUserModal = ref(false);
|
const showUserModal = ref(false);
|
||||||
|
|
||||||
const editingUser = ref<UserFormState>(createEmptyUserForm());
|
const editingUser = ref<UserFormState>(createEmptyUserForm());
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const showBatchEditModal = ref(false);
|
const showBatchEditModal = ref(false);
|
||||||
|
|
||||||
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
|
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const showBatchPermissionModal = ref(false);
|
const showBatchPermissionModal = ref(false);
|
||||||
|
|
||||||
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
|
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const showDeleteConfirmDialog = ref(false);
|
const showDeleteConfirmDialog = ref(false);
|
||||||
|
|
||||||
const deleteConfirmMessage = ref('');
|
const deleteConfirmMessage = ref('');
|
||||||
|
|
||||||
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/** 当前页是否已全部选中 */
|
/** 当前页是否已全部选中 */
|
||||||
|
|
||||||
const allPaginatedUsersSelected = computed(
|
const allPaginatedUsersSelected = computed(
|
||||||
|
|
||||||
() =>
|
() =>
|
||||||
|
|
||||||
users.value.length > 0
|
users.value.length > 0
|
||||||
|
|
||||||
&& users.value.every((u) => selectedUserIds.value.includes(u.id)),
|
&& users.value.every((u) => selectedUserIds.value.includes(u.id)),
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* 拉取当前页用户(服务端筛选 + 分页 + 排序)。
|
||||||
* 拉取当前页用户(服务端筛选 + 分页)。
|
* 核心逻辑:将 userFilters / hideRejected / sortKey / sortDir 传给 listAdminUsersPage。
|
||||||
|
|
||||||
* 核心逻辑:将 userFilters / hideRejected 传给 listAdminUsersPage,写回 items 与分页元数据。
|
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const loadUsers = async (): Promise<void> => {
|
const loadUsers = async (): Promise<void> => {
|
||||||
|
|
||||||
isListLoading.value = true;
|
isListLoading.value = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
const data = await listAdminUsersPage({
|
const data = await listAdminUsersPage({
|
||||||
|
|
||||||
page: userPage.value,
|
page: userPage.value,
|
||||||
|
|
||||||
pageSize: userPageSize.value,
|
pageSize: userPageSize.value,
|
||||||
|
|
||||||
username: userFilters.value.username,
|
username: userFilters.value.username,
|
||||||
|
|
||||||
real_name: userFilters.value.real_name,
|
real_name: userFilters.value.real_name,
|
||||||
|
|
||||||
department: userFilters.value.department,
|
department: userFilters.value.department,
|
||||||
|
|
||||||
hideRejected: hideRejected.value,
|
hideRejected: hideRejected.value,
|
||||||
|
sortBy: sortKey.value,
|
||||||
|
sortDir: sortDir.value,
|
||||||
});
|
});
|
||||||
|
|
||||||
users.value = data.items;
|
users.value = data.items;
|
||||||
|
|
||||||
usersTotal.value = data.total;
|
usersTotal.value = data.total;
|
||||||
|
|
||||||
userPage.value = data.page;
|
userPage.value = data.page;
|
||||||
|
|
||||||
usersPages.value = data.pages;
|
usersPages.value = data.pages;
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
||||||
console.error('Error loading users:', e);
|
console.error('Error loading users:', e);
|
||||||
|
|
||||||
users.value = [];
|
users.value = [];
|
||||||
|
|
||||||
usersTotal.value = 0;
|
usersTotal.value = 0;
|
||||||
|
|
||||||
usersPages.value = 1;
|
usersPages.value = 1;
|
||||||
|
|
||||||
} finally {
|
} finally {
|
||||||
|
|
||||||
isListLoading.value = false;
|
isListLoading.value = false;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
||||||
* 重置页码并刷新列表;若页码已是 1 则直接请求。
|
* 重置页码并刷新列表;若页码已是 1 则直接请求。
|
||||||
|
|
||||||
* @param resetPage - 为 true 时将 page 置 1
|
* @param resetPage - 为 true 时将 page 置 1
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const scheduleLoadUsers = (resetPage = false): void => {
|
const scheduleLoadUsers = (resetPage = false): void => {
|
||||||
|
|
||||||
if (resetPage) {
|
if (resetPage) {
|
||||||
|
|
||||||
if (userPage.value !== 1) {
|
if (userPage.value !== 1) {
|
||||||
|
|
||||||
userPage.value = 1;
|
userPage.value = 1;
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loadUsers();
|
void loadUsers();
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const loadAgents = async (): Promise<void> => {
|
const loadAgents = async (): Promise<void> => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
agents.value = await listAdminAgents();
|
agents.value = await listAdminAgents();
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
||||||
console.error('Error loading agents:', e);
|
console.error('Error loading agents:', e);
|
||||||
|
|
||||||
agents.value = [];
|
agents.value = [];
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const loadDepartments = async (): Promise<void> => {
|
const loadDepartments = async (): Promise<void> => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
departments.value = await listAdminDepartments();
|
departments.value = await listAdminDepartments();
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
||||||
console.error('Error loading departments:', e);
|
console.error('Error loading departments:', e);
|
||||||
|
|
||||||
departments.value = [];
|
departments.value = [];
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const loadAll = async (): Promise<void> => {
|
const loadAll = async (): Promise<void> => {
|
||||||
|
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
|
|
||||||
await Promise.all([loadUsers(), loadAgents(), loadDepartments()]);
|
await Promise.all([loadUsers(), loadAgents(), loadDepartments()]);
|
||||||
|
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
watch(userPage, () => {
|
watch(userPage, () => {
|
||||||
|
|
||||||
void loadUsers();
|
void loadUsers();
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
watch(userPageSize, () => {
|
watch(userPageSize, () => {
|
||||||
|
|
||||||
scheduleLoadUsers(true);
|
scheduleLoadUsers(true);
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
watch([userFilters, hideRejected], () => {
|
watch([userFilters, hideRejected], () => {
|
||||||
|
|
||||||
if (userSearchTimer) clearTimeout(userSearchTimer);
|
if (userSearchTimer) clearTimeout(userSearchTimer);
|
||||||
|
|
||||||
userSearchTimer = setTimeout(() => {
|
userSearchTimer = setTimeout(() => {
|
||||||
|
|
||||||
scheduleLoadUsers(true);
|
scheduleLoadUsers(true);
|
||||||
|
|
||||||
}, 300);
|
}, 300);
|
||||||
|
|
||||||
}, { deep: true });
|
}, { deep: true });
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
|
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
|
||||||
|
|
||||||
deleteConfirmMessage.value = message;
|
deleteConfirmMessage.value = message;
|
||||||
|
|
||||||
deleteConfirmAction = action;
|
deleteConfirmAction = action;
|
||||||
|
|
||||||
showDeleteConfirmDialog.value = true;
|
showDeleteConfirmDialog.value = true;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const closeDeleteConfirm = (): void => {
|
const closeDeleteConfirm = (): void => {
|
||||||
|
|
||||||
showDeleteConfirmDialog.value = false;
|
showDeleteConfirmDialog.value = false;
|
||||||
|
|
||||||
deleteConfirmAction = null;
|
deleteConfirmAction = null;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
||||||
* 执行待确认的删除操作。
|
* 执行待确认的删除操作。
|
||||||
|
|
||||||
* 核心逻辑:先快照 action 并立即关闭弹窗,再 await 删除与刷新,避免异步完成前弹窗无法关闭。
|
* 核心逻辑:先快照 action 并立即关闭弹窗,再 await 删除与刷新,避免异步完成前弹窗无法关闭。
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const confirmDelete = async (): Promise<void> => {
|
const confirmDelete = async (): Promise<void> => {
|
||||||
|
|
||||||
const action = deleteConfirmAction;
|
const action = deleteConfirmAction;
|
||||||
|
|
||||||
closeDeleteConfirm();
|
closeDeleteConfirm();
|
||||||
|
|
||||||
if (!action) return;
|
if (!action) return;
|
||||||
|
|
||||||
await action();
|
await action();
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const openCreateUserModal = (): void => {
|
const openCreateUserModal = (): void => {
|
||||||
|
|
||||||
editingUser.value = createEmptyUserForm();
|
editingUser.value = createEmptyUserForm();
|
||||||
|
|
||||||
showUserModal.value = true;
|
showUserModal.value = true;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const openEditUserModal = (user: AdminUserRow): void => {
|
const openEditUserModal = (user: AdminUserRow): void => {
|
||||||
|
|
||||||
editingUser.value = {
|
editingUser.value = {
|
||||||
|
|
||||||
id: user.id,
|
id: user.id,
|
||||||
|
|
||||||
username: user.username,
|
username: user.username,
|
||||||
|
|
||||||
email: user.email,
|
email: user.email,
|
||||||
|
|
||||||
department: user.department || '',
|
department: user.department || '',
|
||||||
|
|
||||||
role: user.role,
|
role: user.role,
|
||||||
|
|
||||||
password: '',
|
password: '',
|
||||||
|
|
||||||
real_name: user.real_name || '',
|
real_name: user.real_name || '',
|
||||||
|
|
||||||
employee_id: user.employee_id || '',
|
employee_id: user.employee_id || '',
|
||||||
|
|
||||||
phone_number: user.phone_number || '',
|
phone_number: user.phone_number || '',
|
||||||
|
|
||||||
feature_permissions: {
|
feature_permissions: {
|
||||||
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
|
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
|
||||||
},
|
},
|
||||||
|
|
||||||
agent_ids: user.agent_ids || [],
|
agent_ids: user.agent_ids || [],
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
showUserModal.value = true;
|
showUserModal.value = true;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const saveUser = async (): Promise<void> => {
|
const saveUser = async (): Promise<void> => {
|
||||||
|
|
||||||
const isCreate = !editingUser.value.id;
|
const isCreate = !editingUser.value.id;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if (isCreate) {
|
if (isCreate) {
|
||||||
|
|
||||||
if (!(editingUser.value.real_name || '').trim()) {
|
if (!(editingUser.value.real_name || '').trim()) {
|
||||||
|
|
||||||
msg.warning(t('admin.user.msgs.realNameRequired'));
|
msg.warning(t('admin.user.msgs.realNameRequired'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(editingUser.value.employee_id || '').trim()) {
|
if (!(editingUser.value.employee_id || '').trim()) {
|
||||||
|
|
||||||
msg.warning(t('admin.user.msgs.employeeIdRequired'));
|
msg.warning(t('admin.user.msgs.employeeIdRequired'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(editingUser.value.phone_number || '').trim()) {
|
if (!(editingUser.value.phone_number || '').trim()) {
|
||||||
|
|
||||||
msg.warning(t('admin.user.msgs.phoneRequired'));
|
msg.warning(t('admin.user.msgs.phoneRequired'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(editingUser.value.username || '').trim()) {
|
if (!(editingUser.value.username || '').trim()) {
|
||||||
|
|
||||||
msg.warning(t('admin.user.msgs.usernameRequired'));
|
msg.warning(t('admin.user.msgs.usernameRequired'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const email = (editingUser.value.email || '').trim();
|
const email = (editingUser.value.email || '').trim();
|
||||||
|
|
||||||
if (!email) {
|
if (!email) {
|
||||||
|
|
||||||
msg.warning(t('admin.user.msgs.emailRequired'));
|
msg.warning(t('admin.user.msgs.emailRequired'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!EMAIL_PATTERN.test(email)) {
|
if (!EMAIL_PATTERN.test(email)) {
|
||||||
|
|
||||||
msg.warning(t('admin.user.msgs.invalidEmail'));
|
msg.warning(t('admin.user.msgs.invalidEmail'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(editingUser.value.password || '').trim()) {
|
if (!(editingUser.value.password || '').trim()) {
|
||||||
|
|
||||||
msg.warning(t('admin.user.msgs.passwordRequired'));
|
msg.warning(t('admin.user.msgs.passwordRequired'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
if (!editingUser.value.username) {
|
if (!editingUser.value.username) {
|
||||||
|
|
||||||
msg.warning(t('admin.user.msgs.usernameRequired'));
|
msg.warning(t('admin.user.msgs.usernameRequired'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const email = (editingUser.value.email || '').trim();
|
const email = (editingUser.value.email || '').trim();
|
||||||
|
|
||||||
if (email && !EMAIL_PATTERN.test(email)) {
|
if (email && !EMAIL_PATTERN.test(email)) {
|
||||||
|
|
||||||
msg.warning(t('admin.user.msgs.invalidEmail'));
|
msg.warning(t('admin.user.msgs.invalidEmail'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
isSaving.value = true;
|
isSaving.value = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
if (editingUser.value.id) {
|
if (editingUser.value.id) {
|
||||||
|
|
||||||
await updateAdminUser(editingUser.value.id, {
|
await updateAdminUser(editingUser.value.id, {
|
||||||
|
|
||||||
email: editingUser.value.email,
|
email: editingUser.value.email,
|
||||||
|
|
||||||
department: editingUser.value.department,
|
department: editingUser.value.department,
|
||||||
|
|
||||||
role: editingUser.value.role,
|
role: editingUser.value.role,
|
||||||
|
|
||||||
password: editingUser.value.password || undefined,
|
password: editingUser.value.password || undefined,
|
||||||
|
|
||||||
real_name: editingUser.value.real_name,
|
real_name: editingUser.value.real_name,
|
||||||
|
|
||||||
employee_id: editingUser.value.employee_id,
|
employee_id: editingUser.value.employee_id,
|
||||||
|
|
||||||
phone_number: editingUser.value.phone_number,
|
phone_number: editingUser.value.phone_number,
|
||||||
|
|
||||||
feature_permissions: editingUser.value.feature_permissions,
|
feature_permissions: editingUser.value.feature_permissions,
|
||||||
|
|
||||||
agent_ids: editingUser.value.agent_ids,
|
agent_ids: editingUser.value.agent_ids,
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
await createAdminUser({
|
await createAdminUser({
|
||||||
|
|
||||||
username: editingUser.value.username,
|
username: editingUser.value.username,
|
||||||
|
|
||||||
email: editingUser.value.email,
|
email: editingUser.value.email,
|
||||||
|
|
||||||
department: editingUser.value.department,
|
department: editingUser.value.department,
|
||||||
|
|
||||||
role: editingUser.value.role,
|
role: editingUser.value.role,
|
||||||
|
|
||||||
password: editingUser.value.password,
|
password: editingUser.value.password,
|
||||||
|
|
||||||
real_name: editingUser.value.real_name,
|
real_name: editingUser.value.real_name,
|
||||||
|
|
||||||
employee_id: editingUser.value.employee_id,
|
employee_id: editingUser.value.employee_id,
|
||||||
|
|
||||||
phone_number: editingUser.value.phone_number,
|
phone_number: editingUser.value.phone_number,
|
||||||
|
|
||||||
feature_permissions: editingUser.value.feature_permissions,
|
feature_permissions: editingUser.value.feature_permissions,
|
||||||
|
|
||||||
agent_ids: editingUser.value.agent_ids,
|
agent_ids: editingUser.value.agent_ids,
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await loadUsers();
|
await loadUsers();
|
||||||
|
|
||||||
showUserModal.value = false;
|
showUserModal.value = false;
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
|
||||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||||
|
|
||||||
} finally {
|
} finally {
|
||||||
|
|
||||||
isSaving.value = false;
|
isSaving.value = false;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const cleanRejectedUsers = async (): Promise<void> => {
|
const cleanRejectedUsers = async (): Promise<void> => {
|
||||||
|
|
||||||
openDeleteConfirm(t('admin.user.confirmClean'), async () => {
|
openDeleteConfirm(t('admin.user.confirmClean'), async () => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
const data = await cleanupRejectedAdminUsers();
|
const data = await cleanupRejectedAdminUsers();
|
||||||
|
|
||||||
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
|
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
|
||||||
|
|
||||||
await loadUsers();
|
await loadUsers();
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
|
||||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const batchDeleteUsers = async (): Promise<void> => {
|
const batchDeleteUsers = async (): Promise<void> => {
|
||||||
|
|
||||||
if (selectedUserIds.value.length === 0) return;
|
if (selectedUserIds.value.length === 0) return;
|
||||||
|
|
||||||
const targetUserIds = [...selectedUserIds.value];
|
const targetUserIds = [...selectedUserIds.value];
|
||||||
|
|
||||||
openDeleteConfirm(t('admin.user.confirmBatchDelete', { count: targetUserIds.length }), async () => {
|
openDeleteConfirm(t('admin.user.confirmBatchDelete', { count: targetUserIds.length }), async () => {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
const data = await batchDeleteAdminUsers(targetUserIds);
|
const data = await batchDeleteAdminUsers(targetUserIds);
|
||||||
|
|
||||||
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
|
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
|
||||||
|
|
||||||
selectedUserIds.value = [];
|
selectedUserIds.value = [];
|
||||||
|
|
||||||
await loadUsers();
|
await loadUsers();
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
|
||||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const toggleUserSelection = (userId: number): void => {
|
const toggleUserSelection = (userId: number): void => {
|
||||||
|
|
||||||
const index = selectedUserIds.value.indexOf(userId);
|
const index = selectedUserIds.value.indexOf(userId);
|
||||||
|
|
||||||
if (index === -1) selectedUserIds.value.push(userId);
|
if (index === -1) selectedUserIds.value.push(userId);
|
||||||
|
|
||||||
else selectedUserIds.value.splice(index, 1);
|
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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* 切换用户/部门列排序并重新拉取第一页。
|
||||||
* 切换当前页用户的全选状态,保留其他页已选中的用户。
|
* @param key - username | department
|
||||||
|
|
||||||
* 核心逻辑:若本页已全部选中则仅取消本页 ID;否则合并本页 ID 到 selectedUserIds。
|
|
||||||
|
|
||||||
* @param rows - 当前页用户行
|
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
const toggleSort = (key: UserSortKey): void => {
|
||||||
const toggleAllUsers = (rows: AdminUserRow[]): void => {
|
toggleSortBase(key);
|
||||||
|
scheduleLoadUsers(true);
|
||||||
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;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
||||||
users,
|
users,
|
||||||
|
|
||||||
agents,
|
agents,
|
||||||
|
|
||||||
departments,
|
departments,
|
||||||
|
|
||||||
isLoading,
|
isLoading,
|
||||||
|
|
||||||
isListLoading,
|
isListLoading,
|
||||||
|
|
||||||
isSaving,
|
isSaving,
|
||||||
|
|
||||||
userFilters,
|
userFilters,
|
||||||
|
sortKey,
|
||||||
|
sortDir,
|
||||||
hideRejected,
|
hideRejected,
|
||||||
|
|
||||||
selectedUserIds,
|
selectedUserIds,
|
||||||
|
|
||||||
usersTotal,
|
usersTotal,
|
||||||
|
|
||||||
userPage,
|
userPage,
|
||||||
|
|
||||||
userPageSize,
|
userPageSize,
|
||||||
|
|
||||||
userPageSizeOptions: USER_PAGE_SIZE_OPTIONS,
|
userPageSizeOptions: USER_PAGE_SIZE_OPTIONS,
|
||||||
|
|
||||||
usersPages,
|
usersPages,
|
||||||
|
|
||||||
allPaginatedUsersSelected,
|
allPaginatedUsersSelected,
|
||||||
|
|
||||||
showUserModal,
|
showUserModal,
|
||||||
|
|
||||||
editingUser,
|
editingUser,
|
||||||
|
|
||||||
showBatchEditModal,
|
showBatchEditModal,
|
||||||
|
|
||||||
batchEditForm,
|
batchEditForm,
|
||||||
|
|
||||||
showBatchPermissionModal,
|
showBatchPermissionModal,
|
||||||
|
|
||||||
batchPermissionForm,
|
batchPermissionForm,
|
||||||
|
|
||||||
showDeleteConfirmDialog,
|
showDeleteConfirmDialog,
|
||||||
|
|
||||||
deleteConfirmMessage,
|
deleteConfirmMessage,
|
||||||
|
|
||||||
loadAll,
|
loadAll,
|
||||||
|
toggleSort,
|
||||||
openCreateUserModal,
|
openCreateUserModal,
|
||||||
|
|
||||||
openEditUserModal,
|
openEditUserModal,
|
||||||
|
|
||||||
saveUser,
|
saveUser,
|
||||||
|
|
||||||
cleanRejectedUsers,
|
cleanRejectedUsers,
|
||||||
|
|
||||||
batchDeleteUsers,
|
batchDeleteUsers,
|
||||||
|
|
||||||
toggleUserSelection,
|
toggleUserSelection,
|
||||||
|
|
||||||
toggleAllUsers,
|
toggleAllUsers,
|
||||||
|
|
||||||
openBatchEditModal,
|
openBatchEditModal,
|
||||||
|
|
||||||
openBatchPermissionModal,
|
openBatchPermissionModal,
|
||||||
|
|
||||||
submitBatchEdit,
|
submitBatchEdit,
|
||||||
|
|
||||||
submitBatchPermission,
|
submitBatchPermission,
|
||||||
|
|
||||||
closeDeleteConfirm,
|
closeDeleteConfirm,
|
||||||
|
|
||||||
confirmDelete,
|
confirmDelete,
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/types/department.types.ts
|
* features/admin/types/department.types.ts
|
||||||
* 部门管理表单类型。
|
* 用途:部门管理表单状态与行数据转换。
|
||||||
|
* 依赖:AdminDepartmentRow(admin.types)。
|
||||||
|
* 逻辑:useDepartmentsAdmin / DepartmentFormModal 共用本类型与工厂方法。
|
||||||
*/
|
*/
|
||||||
|
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
||||||
|
|
||||||
export interface DepartmentFormState {
|
export interface DepartmentFormState {
|
||||||
id?: number;
|
id?: number;
|
||||||
@@ -11,9 +14,26 @@ export interface DepartmentFormState {
|
|||||||
description?: string;
|
description?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建空白部门表单(用于「添加部门」弹窗)。
|
||||||
|
* @returns 空表单初始值
|
||||||
|
*/
|
||||||
export const createEmptyDepartmentForm = (): DepartmentFormState => ({
|
export const createEmptyDepartmentForm = (): DepartmentFormState => ({
|
||||||
name: '',
|
name: '',
|
||||||
code: '',
|
code: '',
|
||||||
company: '',
|
company: '',
|
||||||
description: '',
|
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
|
* features/admin/types/report.types.ts
|
||||||
* 报表模块类型。
|
* 用途:报表模块类型(使用分析、列配置、排序规则)。
|
||||||
|
* 依赖:无。
|
||||||
|
* 逻辑:useReportsAdmin / admin.api 共用。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/** 使用分析时间范围(与后端 USAGE_RANGE_DAYS 一致) */
|
||||||
|
export type UsageRangeKey = '7d' | '30d' | '90d' | '180d' | '365d';
|
||||||
|
|
||||||
export interface UsageReport {
|
export interface UsageReport {
|
||||||
total: number;
|
total: number;
|
||||||
|
/** 当前统计时间范围 */
|
||||||
|
range?: UsageRangeKey;
|
||||||
by_user: { username: string; count: number }[];
|
by_user: { username: string; count: number }[];
|
||||||
by_agent: { agent: string; count: number }[];
|
by_agent: { agent: string; count: number }[];
|
||||||
by_day?: { date: string; count: number }[];
|
by_day?: { date: string; count: number }[];
|
||||||
|
|||||||
@@ -122,12 +122,18 @@
|
|||||||
"edit": "Edit Department",
|
"edit": "Edit Department",
|
||||||
"add": "Add New Department",
|
"add": "Add New Department",
|
||||||
"noDepts": "No departments configured.",
|
"noDepts": "No departments configured.",
|
||||||
|
"noSearchResults": "No matching departments found",
|
||||||
|
"searchPlaceholder": "Search by name, code, or company…",
|
||||||
"headers": {
|
"headers": {
|
||||||
"name": "Name",
|
"name": "Name",
|
||||||
"code": "Code",
|
"code": "Code",
|
||||||
"company": "Company",
|
"company": "Company",
|
||||||
"actions": "Actions"
|
"actions": "Actions"
|
||||||
},
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "Edit",
|
||||||
|
"delete": "Delete"
|
||||||
|
},
|
||||||
"fields": {
|
"fields": {
|
||||||
"name": "Name",
|
"name": "Name",
|
||||||
"namePlaceholder": "e.g. IT Department",
|
"namePlaceholder": "e.g. IT Department",
|
||||||
@@ -716,6 +722,7 @@
|
|||||||
"allRoles": "All Roles",
|
"allRoles": "All Roles",
|
||||||
"headers": {
|
"headers": {
|
||||||
"user": "User",
|
"user": "User",
|
||||||
|
"realName": "Real Name",
|
||||||
"dept": "Dept"
|
"dept": "Dept"
|
||||||
},
|
},
|
||||||
"batchModal": {
|
"batchModal": {
|
||||||
@@ -786,6 +793,14 @@
|
|||||||
"noData": "No data available for {table}",
|
"noData": "No data available for {table}",
|
||||||
"noFilterResults": "No matching rows. Adjust your filters.",
|
"noFilterResults": "No matching rows. Adjust your filters.",
|
||||||
"usage": "Usage Analytics",
|
"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",
|
"byUser": "Requests by User",
|
||||||
"byAgent": "Requests by Agent",
|
"byAgent": "Requests by Agent",
|
||||||
"usageByUserTopHint": "Top {limit} users by chat volume",
|
"usageByUserTopHint": "Top {limit} users by chat volume",
|
||||||
|
|||||||
@@ -26,5 +26,10 @@
|
|||||||
"itemsUnit": "rows",
|
"itemsUnit": "rows",
|
||||||
"prevPage": "Previous",
|
"prevPage": "Previous",
|
||||||
"nextPage": "Next"
|
"nextPage": "Next"
|
||||||
|
},
|
||||||
|
"sort": {
|
||||||
|
"unsorted": "Click to sort",
|
||||||
|
"asc": "Ascending, click for descending",
|
||||||
|
"desc": "Descending, click for ascending"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -122,12 +122,18 @@
|
|||||||
"edit": "แก้ไขแผนก",
|
"edit": "แก้ไขแผนก",
|
||||||
"add": "เพิ่มแผนกใหม่",
|
"add": "เพิ่มแผนกใหม่",
|
||||||
"noDepts": "ยังไม่มีการกำหนดค่าแผนก",
|
"noDepts": "ยังไม่มีการกำหนดค่าแผนก",
|
||||||
|
"noSearchResults": "ไม่พบแผนกที่ตรงกัน",
|
||||||
|
"searchPlaceholder": "ค้นหาชื่อ รหัส หรือบริษัท…",
|
||||||
"headers": {
|
"headers": {
|
||||||
"name": "ชื่อ",
|
"name": "ชื่อ",
|
||||||
"code": "รหัส",
|
"code": "รหัส",
|
||||||
"company": "บริษัท",
|
"company": "บริษัท",
|
||||||
"actions": "การกระทำ"
|
"actions": "การกระทำ"
|
||||||
},
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "แก้ไข",
|
||||||
|
"delete": "ลบ"
|
||||||
|
},
|
||||||
"fields": {
|
"fields": {
|
||||||
"name": "ชื่อ",
|
"name": "ชื่อ",
|
||||||
"namePlaceholder": "เช่น แผนกไอที",
|
"namePlaceholder": "เช่น แผนกไอที",
|
||||||
@@ -721,6 +727,7 @@
|
|||||||
"allRoles": "ทุกบทบาท",
|
"allRoles": "ทุกบทบาท",
|
||||||
"headers": {
|
"headers": {
|
||||||
"user": "ผู้ใช้",
|
"user": "ผู้ใช้",
|
||||||
|
"realName": "ชื่อจริง",
|
||||||
"dept": "แผนก"
|
"dept": "แผนก"
|
||||||
},
|
},
|
||||||
"batchModal": {
|
"batchModal": {
|
||||||
@@ -791,6 +798,14 @@
|
|||||||
"noData": "ไม่มีข้อมูลสำหรับ {table}",
|
"noData": "ไม่มีข้อมูลสำหรับ {table}",
|
||||||
"noFilterResults": "ไม่พบข้อมูลที่ตรงกับเงื่อนไข โปรดปรับตัวกรอง",
|
"noFilterResults": "ไม่พบข้อมูลที่ตรงกับเงื่อนไข โปรดปรับตัวกรอง",
|
||||||
"usage": "การวิเคราะห์การใช้งาน",
|
"usage": "การวิเคราะห์การใช้งาน",
|
||||||
|
"usageRangeLabel": "ช่วงเวลา",
|
||||||
|
"usageRanges": {
|
||||||
|
"7d": "7 วันล่าสุด",
|
||||||
|
"30d": "30 วันล่าสุด",
|
||||||
|
"90d": "3 เดือนล่าสุด",
|
||||||
|
"180d": "6 เดือนล่าสุด",
|
||||||
|
"365d": "12 เดือนล่าสุด"
|
||||||
|
},
|
||||||
"byUser": "ตามผู้ใช้",
|
"byUser": "ตามผู้ใช้",
|
||||||
"byAgent": "ตามตัวแทน",
|
"byAgent": "ตามตัวแทน",
|
||||||
"usageByUserTopHint": "แสดงผู้ใช้ {limit} อันดับแรกตามปริมาณการสนทนา",
|
"usageByUserTopHint": "แสดงผู้ใช้ {limit} อันดับแรกตามปริมาณการสนทนา",
|
||||||
|
|||||||
@@ -26,5 +26,10 @@
|
|||||||
"itemsUnit": "รายการ",
|
"itemsUnit": "รายการ",
|
||||||
"prevPage": "ก่อนหน้า",
|
"prevPage": "ก่อนหน้า",
|
||||||
"nextPage": "ถัดไป"
|
"nextPage": "ถัดไป"
|
||||||
|
},
|
||||||
|
"sort": {
|
||||||
|
"unsorted": "คลิกเพื่อเรียงลำดับ",
|
||||||
|
"asc": "เรียงจากน้อยไปมาก คลิกเพื่อสลับ",
|
||||||
|
"desc": "เรียงจากมากไปน้อย คลิกเพื่อสลับ"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -123,12 +123,18 @@
|
|||||||
"edit": "编辑部门",
|
"edit": "编辑部门",
|
||||||
"add": "添加部门",
|
"add": "添加部门",
|
||||||
"noDepts": "暂无部门配置",
|
"noDepts": "暂无部门配置",
|
||||||
|
"noSearchResults": "未找到匹配的部门",
|
||||||
|
"searchPlaceholder": "搜索名称、编码或公司…",
|
||||||
"headers": {
|
"headers": {
|
||||||
"name": "名称",
|
"name": "名称",
|
||||||
"code": "编码",
|
"code": "编码",
|
||||||
"company": "公司",
|
"company": "公司",
|
||||||
"actions": "操作"
|
"actions": "操作"
|
||||||
},
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "编辑",
|
||||||
|
"delete": "删除"
|
||||||
|
},
|
||||||
"fields": {
|
"fields": {
|
||||||
"name": "名称",
|
"name": "名称",
|
||||||
"namePlaceholder": "例如:信息技术部",
|
"namePlaceholder": "例如:信息技术部",
|
||||||
@@ -717,6 +723,7 @@
|
|||||||
"allRoles": "所有角色",
|
"allRoles": "所有角色",
|
||||||
"headers": {
|
"headers": {
|
||||||
"user": "用户",
|
"user": "用户",
|
||||||
|
"realName": "真实姓名",
|
||||||
"dept": "部门"
|
"dept": "部门"
|
||||||
},
|
},
|
||||||
"batchModal": {
|
"batchModal": {
|
||||||
@@ -787,6 +794,14 @@
|
|||||||
"noData": "暂无数据: {table}",
|
"noData": "暂无数据: {table}",
|
||||||
"noFilterResults": "没有匹配的数据,请调整筛选条件",
|
"noFilterResults": "没有匹配的数据,请调整筛选条件",
|
||||||
"usage": "使用分析",
|
"usage": "使用分析",
|
||||||
|
"usageRangeLabel": "统计范围",
|
||||||
|
"usageRanges": {
|
||||||
|
"7d": "近一周",
|
||||||
|
"30d": "近一月",
|
||||||
|
"90d": "近三月",
|
||||||
|
"180d": "近半年",
|
||||||
|
"365d": "近一年"
|
||||||
|
},
|
||||||
"byUser": "按用户统计",
|
"byUser": "按用户统计",
|
||||||
"byAgent": "按应用统计",
|
"byAgent": "按应用统计",
|
||||||
"usageByUserTopHint": "仅显示对话量前 {limit} 名用户",
|
"usageByUserTopHint": "仅显示对话量前 {limit} 名用户",
|
||||||
|
|||||||
@@ -26,5 +26,10 @@
|
|||||||
"itemsUnit": "条",
|
"itemsUnit": "条",
|
||||||
"prevPage": "上一页",
|
"prevPage": "上一页",
|
||||||
"nextPage": "下一页"
|
"nextPage": "下一页"
|
||||||
|
},
|
||||||
|
"sort": {
|
||||||
|
"unsorted": "点击排序",
|
||||||
|
"asc": "升序,点击切换为降序",
|
||||||
|
"desc": "降序,点击切换为升序"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -122,12 +122,18 @@
|
|||||||
"edit": "編輯部門",
|
"edit": "編輯部門",
|
||||||
"add": "添加部門",
|
"add": "添加部門",
|
||||||
"noDepts": "暫無部門配置",
|
"noDepts": "暫無部門配置",
|
||||||
|
"noSearchResults": "未找到匹配的部門",
|
||||||
|
"searchPlaceholder": "搜尋名稱、編碼或公司…",
|
||||||
"headers": {
|
"headers": {
|
||||||
"name": "名稱",
|
"name": "名稱",
|
||||||
"code": "編碼",
|
"code": "編碼",
|
||||||
"company": "公司",
|
"company": "公司",
|
||||||
"actions": "操作"
|
"actions": "操作"
|
||||||
},
|
},
|
||||||
|
"actions": {
|
||||||
|
"edit": "編輯",
|
||||||
|
"delete": "刪除"
|
||||||
|
},
|
||||||
"fields": {
|
"fields": {
|
||||||
"name": "名稱",
|
"name": "名稱",
|
||||||
"namePlaceholder": "例如:資訊技術部",
|
"namePlaceholder": "例如:資訊技術部",
|
||||||
@@ -721,6 +727,7 @@
|
|||||||
"allRoles": "所有角色",
|
"allRoles": "所有角色",
|
||||||
"headers": {
|
"headers": {
|
||||||
"user": "用戶",
|
"user": "用戶",
|
||||||
|
"realName": "真實姓名",
|
||||||
"dept": "部門"
|
"dept": "部門"
|
||||||
},
|
},
|
||||||
"batchModal": {
|
"batchModal": {
|
||||||
@@ -791,6 +798,14 @@
|
|||||||
"noData": "暫無數據: {table}",
|
"noData": "暫無數據: {table}",
|
||||||
"noFilterResults": "沒有匹配的數據,請調整篩選條件",
|
"noFilterResults": "沒有匹配的數據,請調整篩選條件",
|
||||||
"usage": "使用分析",
|
"usage": "使用分析",
|
||||||
|
"usageRangeLabel": "統計範圍",
|
||||||
|
"usageRanges": {
|
||||||
|
"7d": "近一週",
|
||||||
|
"30d": "近一月",
|
||||||
|
"90d": "近三月",
|
||||||
|
"180d": "近半年",
|
||||||
|
"365d": "近一年"
|
||||||
|
},
|
||||||
"byUser": "按用戶統計",
|
"byUser": "按用戶統計",
|
||||||
"byAgent": "按應用統計",
|
"byAgent": "按應用統計",
|
||||||
"usageByUserTopHint": "僅顯示對話量前 {limit} 名用戶",
|
"usageByUserTopHint": "僅顯示對話量前 {limit} 名用戶",
|
||||||
|
|||||||
@@ -26,5 +26,10 @@
|
|||||||
"itemsUnit": "條",
|
"itemsUnit": "條",
|
||||||
"prevPage": "上一頁",
|
"prevPage": "上一頁",
|
||||||
"nextPage": "下一頁"
|
"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
|
* shared/composables/useReportLayoutStorage.ts
|
||||||
* 报表页面布局偏好 localStorage 持久化。
|
* 用途:报表页面布局偏好 localStorage 持久化(按用户 + 表名隔离)。
|
||||||
*/
|
* 依赖:localStorage / sessionStorage 中的 hxops_user。
|
||||||
/**
|
* 逻辑:ReportsPage / useReportsAdmin 读写列宽、显隐与排序偏好;v3 起聊天日志默认列宽收窄。
|
||||||
* useReportLayoutStorage.ts
|
|
||||||
* 用途:为报表页面提供统一的布局偏好持久化能力(按用户 + 表名隔离)
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const getCurrentAuthUser = () => {
|
const getCurrentAuthUser = () => {
|
||||||
@@ -24,10 +22,20 @@ const getCurrentIdentity = () => {
|
|||||||
return user?.id ? `id_${user.id}` : `u_${user?.username || 'guest'}`;
|
return user?.id ? `id_${user.id}` : `u_${user?.username || 'guest'}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成报表布局偏好的 storage key。
|
||||||
|
* @param table - 报表表名(如 chat_logs)
|
||||||
|
*/
|
||||||
const getReportLayoutStorageKey = (table: string) => {
|
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 => {
|
export const loadReportLayoutPref = <T = any>(table: string): T | null => {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(getReportLayoutStorageKey(table));
|
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) => {
|
export const saveReportLayoutPref = (table: string, payload: unknown) => {
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(getReportLayoutStorageKey(table), JSON.stringify(payload));
|
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.
|
// 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/useGlobalMessageDialog';
|
||||||
export * from './composables/useReportLayoutStorage';
|
export * from './composables/useReportLayoutStorage';
|
||||||
export * from './composables/useAudioTranscription';
|
export * from './composables/useAudioTranscription';
|
||||||
|
export * from './composables/useTableSort';
|
||||||
|
export * from './utils/table-sort';
|
||||||
export * from './api/client';
|
export * from './api/client';
|
||||||
export * from './constants/routes';
|
export * from './constants/routes';
|
||||||
export type * from './types/schedule.types';
|
export type * from './types/schedule.types';
|
||||||
@@ -395,7 +395,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.admin-report-filter-input {
|
.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);
|
border-color: var(--border-default);
|
||||||
background-color: var(--bg-surface);
|
background-color: var(--bg-surface);
|
||||||
color: var(--text-primary);
|
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