refactor(structure): reorganize app layout

BREAKING CHANGE: root backend/frontend directories and old run/manage entrypoints were removed. Use apps/backend, apps/frontend, and python main.py commands instead.
This commit is contained in:
2026-05-03 16:43:11 +08:00
parent 7e8852877e
commit d4d6f87730
112 changed files with 347 additions and 1596 deletions
+134
View File
@@ -0,0 +1,134 @@
<template>
<Layout>
<div class="admin-logs-container">
<a-card>
<template #title>
<div class="card-header">
<div>
<FileTextOutlined />
<span>系统日志</span>
</div>
<a-button type="primary" @click="handleRefresh">
<template #icon><ReloadOutlined /></template>
刷新
</a-button>
</div>
</template>
<a-alert
message="日志查看"
description="显示最新的系统日志信息(默认显示最近 200 行)"
type="info"
:closable="false"
show-icon
style="margin-bottom: 20px"
/>
<div v-if="adminStore.loading" class="loading-container">
<a-skeleton :active="true" :paragraph="{ rows: 10 }" />
</div>
<div v-else class="logs-content">
<a-textarea
v-model:value="logContent"
:rows="25"
:readonly="true"
placeholder="暂无日志内容"
class="log-textarea"
/>
<div class="log-info">
<span> {{ logLines }} </span>
<span>最后更新: {{ lastUpdate }}</span>
</div>
</div>
</a-card>
</div>
</Layout>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { FileTextOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useAdminStore } from '@/stores/admin';
import { formatDateTime } from '@/utils/helpers';
const adminStore = useAdminStore();
const logContent = ref('');
const lastUpdate = ref('');
const logLines = computed(() => {
if (!logContent.value) return 0;
const content =
typeof logContent.value === 'string' ? logContent.value : String(logContent.value);
return content.split('\n').length;
});
const handleRefresh = async () => {
try {
const data = await adminStore.fetchLogs({ lines: 200 });
if (data.logs) {
// 确保是字符串
logContent.value = typeof data.logs === 'string' ? data.logs : String(data.logs);
lastUpdate.value = formatDateTime(new Date());
message.success({ content: '刷新成功', duration: 2 });
} else {
logContent.value = '无日志内容';
}
} catch (error) {
message.error({ content: error.message || '刷新失败', duration: 4 });
}
};
onMounted(() => {
handleRefresh();
});
</script>
<style scoped>
.admin-logs-container {
max-width: 1400px;
margin: 0 auto;
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.card-header > div {
display: flex;
align-items: center;
gap: 8px;
}
.loading-container {
padding: 20px;
}
.logs-content {
font-family: 'Courier New', Courier, monospace;
}
.log-info {
display: flex;
justify-content: space-between;
margin-top: 10px;
font-size: 12px;
color: #909399;
}
.log-textarea :deep(textarea) {
font-family: 'Courier New', Courier, monospace;
font-size: 13px;
line-height: 1.6;
white-space: pre;
overflow-x: auto;
word-break: normal;
overflow-wrap: normal;
}
</style>
@@ -0,0 +1,190 @@
<template>
<Layout>
<div class="admin-records-container">
<a-card>
<template #title>
<div class="card-header">
<div>
<UnorderedListOutlined />
<span>所有打卡记录</span>
</div>
<a-button type="primary" @click="handleRefresh">
<template #icon><ReloadOutlined /></template>
刷新
</a-button>
</div>
</template>
<!-- Desktop table -->
<a-table
v-if="!isMobile"
:data-source="checkInStore.allRecords"
:columns="columns"
:loading="checkInStore.loading"
:pagination="false"
:row-key="record => record.id"
:scroll="{ x: 'max-content' }"
bordered
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'check_in_time'">
{{ formatDateTime(record.check_in_time) }}
</template>
<template v-else-if="column.key === 'status'">
<a-tag v-if="record.status === 'success'" color="success">✅ 打卡成功</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default"
>🕐 时间范围外</a-tag
>
<a-tag v-else-if="record.status === 'unknown'" color="warning">❗ 打卡异常</a-tag>
<a-tag v-else color="error">❌ 打卡失败</a-tag>
</template>
<template v-else-if="column.key === 'trigger_type'">
<a-tag v-if="record.trigger_type === 'manual'" color="blue">手动</a-tag>
<a-tag v-else-if="record.trigger_type === 'scheduled'" color="cyan">定时</a-tag>
<a-tag v-else-if="record.trigger_type === 'admin'" color="orange">管理员</a-tag>
<a-tag v-else>{{ record.trigger_type }}</a-tag>
</template>
</template>
</a-table>
<!-- Mobile card view -->
<a-space v-else direction="vertical" :size="16" style="width: 100%">
<a-card
v-for="record in checkInStore.allRecords"
:key="record.id"
size="small"
:loading="checkInStore.loading"
>
<a-descriptions :column="1" size="small" bordered>
<a-descriptions-item label="ID">{{ record.id }}</a-descriptions-item>
<a-descriptions-item label="用户ID">{{ record.user_id }}</a-descriptions-item>
<a-descriptions-item label="用户邮箱">{{
record.user_email || '-'
}}</a-descriptions-item>
<a-descriptions-item label="任务名称">{{
record.task_name || '-'
}}</a-descriptions-item>
<a-descriptions-item label="接龙ID">{{
record.thread_id || '-'
}}</a-descriptions-item>
<a-descriptions-item label="打卡时间">{{
formatDateTime(record.check_in_time)
}}</a-descriptions-item>
<a-descriptions-item label="状态">
<a-tag v-if="record.status === 'success'" color="success">✅ 打卡成功</a-tag>
<a-tag v-else-if="record.status === 'out_of_time'" color="default"
>🕐 时间范围外</a-tag
>
<a-tag v-else-if="record.status === 'unknown'" color="warning">❗ 打卡异常</a-tag>
<a-tag v-else color="error">❌ 打卡失败</a-tag>
</a-descriptions-item>
<a-descriptions-item label="触发方式">
<a-tag v-if="record.trigger_type === 'manual'" color="blue">手动</a-tag>
<a-tag v-else-if="record.trigger_type === 'scheduled'" color="cyan">定时</a-tag>
<a-tag v-else-if="record.trigger_type === 'admin'" color="orange">管理员</a-tag>
<a-tag v-else>{{ record.trigger_type }}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="消息">{{
record.response_text || '-'
}}</a-descriptions-item>
</a-descriptions>
</a-card>
</a-space>
<!-- Empty state -->
<a-empty
v-if="!checkInStore.loading && checkInStore.allRecords.length === 0"
description="暂无打卡记录"
/>
<!-- Pagination -->
<div v-if="checkInStore.total > 0" class="pagination-container">
<a-pagination
v-model:current="checkInStore.currentPage"
v-model:page-size="checkInStore.pageSize"
:total="checkInStore.total"
:page-size-options="['10', '20', '50', '100']"
show-size-changer
show-quick-jumper
:show-total="total => `${total} 条记录`"
@change="handlePageChange"
@show-size-change="handleSizeChange"
/>
</div>
</a-card>
</div>
</Layout>
</template>
<script setup>
import { onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { UnorderedListOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useCheckInStore } from '@/stores/checkIn';
import { useBreakpoint } from '@/composables/useBreakpoint';
import { formatDateTime } from '@/utils/helpers';
const checkInStore = useCheckInStore();
const { isMobile } = useBreakpoint();
// Table columns configuration
const columns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: '用户ID', dataIndex: 'user_id', key: 'user_id', width: 100 },
{ title: '用户邮箱', dataIndex: 'user_email', key: 'user_email', width: 180, ellipsis: true },
{ title: '任务名称', dataIndex: 'task_name', key: 'task_name', width: 150, ellipsis: true },
{ title: '接龙ID', dataIndex: 'thread_id', key: 'thread_id', width: 150, ellipsis: true },
{ title: '打卡时间', dataIndex: 'check_in_time', key: 'check_in_time', width: 180 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 120 },
{ title: '触发方式', dataIndex: 'trigger_type', key: 'trigger_type', width: 120 },
{ title: '消息', dataIndex: 'response_text', key: 'response_text', ellipsis: true },
];
const handleRefresh = async () => {
try {
await checkInStore.fetchAllRecords();
message.success('刷新成功');
} catch (error) {
message.error(error.message || '刷新失败');
}
};
const handlePageChange = () => {
checkInStore.fetchAllRecords();
};
const handleSizeChange = () => {
checkInStore.currentPage = 1;
checkInStore.fetchAllRecords();
};
onMounted(() => {
checkInStore.fetchAllRecords();
});
</script>
<style scoped>
.admin-records-container {
max-width: 1600px;
margin: 0 auto;
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.card-header > div {
display: flex;
align-items: center;
gap: 8px;
}
.pagination-container {
margin-top: 20px;
display: flex;
justify-content: flex-end;
}
</style>
+181
View File
@@ -0,0 +1,181 @@
<template>
<Layout>
<div class="admin-stats-container">
<a-row :gutter="20">
<a-col :span="24">
<a-card>
<template #title>
<div class="card-header">
<BarChartOutlined />
<span>系统统计信息</span>
<a-button type="primary" @click="handleRefresh">
<template #icon><ReloadOutlined /></template>
刷新
</a-button>
</div>
</template>
<div v-if="adminStore.loading" class="loading-container">
<a-skeleton :active="true" :paragraph="{ rows: 5 }" />
</div>
<div v-else-if="adminStore.stats" class="stats-content">
<a-row :gutter="[20, 20]">
<a-col :xs="24" :sm="12" :md="6">
<a-statistic title="总用户数" :value="adminStore.totalUsers">
<template #prefix>
<UserOutlined />
</template>
</a-statistic>
</a-col>
<a-col :xs="24" :sm="12" :md="6">
<a-statistic
title="已审批用户数"
:value="adminStore.activeUsers"
:value-style="{ color: '#52c41a' }"
>
<template #prefix>
<CheckOutlined />
</template>
</a-statistic>
</a-col>
<a-col :xs="24" :sm="12" :md="6">
<a-statistic title="总打卡次数" :value="adminStore.totalRecords">
<template #prefix>
<UnorderedListOutlined />
</template>
</a-statistic>
</a-col>
<a-col :xs="24" :sm="12" :md="6">
<a-statistic
title="今日打卡"
:value="adminStore.todayRecords"
:value-style="{ color: '#1890ff' }"
>
<template #prefix>
<CalendarOutlined />
</template>
</a-statistic>
</a-col>
</a-row>
<a-divider />
<a-descriptions title="详细信息" :column="{ xs: 1, sm: 1, md: 2 }" bordered>
<a-descriptions-item label="管理员数量">
{{ adminStore.stats?.users?.admin || 0 }}
</a-descriptions-item>
<a-descriptions-item label="普通用户数量">
{{ adminStore.stats?.users?.regular || 0 }}
</a-descriptions-item>
<a-descriptions-item label="今日成功打卡">
<a-tag color="success">{{
adminStore.stats?.check_in_records?.today_success || 0
}}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="今日失败打卡">
<a-tag color="error">{{
adminStore.stats?.check_in_records?.today_failure || 0
}}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="今日时间范围外">
<a-tag color="default">{{
adminStore.stats?.check_in_records?.today_out_of_time || 0
}}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="今日异常打卡">
<a-tag color="warning">{{
adminStore.stats?.check_in_records?.today_unknown || 0
}}</a-tag>
</a-descriptions-item>
<a-descriptions-item label="总成功率" :span="2">
<a-progress
:percent="calculateSuccessRate()"
:stroke-color="getProgressColor(calculateSuccessRate())"
/>
</a-descriptions-item>
</a-descriptions>
</div>
</a-card>
</a-col>
</a-row>
</div>
</Layout>
</template>
<script setup>
import { onMounted } from 'vue';
import { message } from 'ant-design-vue';
import {
BarChartOutlined,
ReloadOutlined,
UserOutlined,
CheckOutlined,
UnorderedListOutlined,
CalendarOutlined,
} from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useAdminStore } from '@/stores/admin';
const adminStore = useAdminStore();
const getProgressColor = percentage => {
if (percentage >= 90) return '#52c41a';
if (percentage >= 70) return '#faad14';
return '#ff4d4f';
};
const calculateSuccessRate = () => {
const total = adminStore.stats?.check_in_records?.total || 0;
const todaySuccess = adminStore.stats?.check_in_records?.today_success || 0;
if (total === 0) return 0;
// Calculate success rate based on all records (not just today)
// We need to get success count from backend or calculate differently
// For now, use today's success rate as approximation
const todayTotal = adminStore.stats?.check_in_records?.today || 0;
if (todayTotal === 0) return 0;
return Math.round((todaySuccess / todayTotal) * 100);
};
const handleRefresh = async () => {
try {
await adminStore.fetchStats();
message.success('刷新成功');
} catch (error) {
message.error(error.message || '刷新失败');
}
};
onMounted(() => {
adminStore.fetchStats();
});
</script>
<style scoped>
.admin-stats-container {
max-width: 1200px;
margin: 0 auto;
}
.card-header {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
}
.card-header :deep(.ant-btn) {
margin-left: auto;
}
.loading-container {
padding: 20px;
}
.stats-content {
padding: 20px 0;
}
</style>
@@ -0,0 +1,796 @@
<template>
<Layout>
<div class="templates-view">
<div class="max-w-6xl mx-auto">
<!-- Header -->
<div class="mb-8">
<div class="flex items-center justify-between mb-6">
<div>
<h1 class="text-3xl font-bold text-gradient mb-2">任务模板管理</h1>
<p class="text-on-surface-variant">JSON 映射架构 - 配置即结构</p>
</div>
<button class="md3-button-filled" @click="showCreateDialog">
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 4v16m8-8H4"
/>
</svg>
新建模板
</button>
</div>
</div>
<!-- Templates List -->
<div v-if="loading && templates.length === 0" class="space-y-4">
<a-card v-for="i in 3" :key="i" class="md3-card">
<a-skeleton :active="true" :paragraph="{ rows: 2 }" />
</a-card>
</div>
<a-card
v-else-if="templates.length === 0"
class="md3-card text-center"
style="padding: 48px 20px"
>
<svg
class="w-20 h-20 mx-auto text-on-surface-variant opacity-30 mb-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg>
<h3 class="text-xl font-semibold text-on-surface mb-2">暂无模板</h3>
<p class="text-on-surface-variant mb-4">创建第一个模板让用户更轻松地创建打卡任务</p>
<button class="md3-button-filled" @click="showCreateDialog">新建模板</button>
</a-card>
<div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<a-card
v-for="template in templates"
:key="template.id"
class="md3-card hover:shadow-xl transition-all animate-slide-up"
>
<div class="flex items-start justify-between mb-3">
<div class="flex-1">
<h3 class="text-lg font-semibold text-on-surface mb-2">{{ template.name }}</h3>
<a-divider style="margin: 8px 0" />
<p class="text-sm text-on-surface-variant mb-2">
{{ template.description || '无描述' }}
</p>
<span :class="template.is_active ? 'md3-badge-success' : 'md3-badge-info'">
{{ template.is_active ? '已启用' : '已禁用' }}
</span>
</div>
</div>
<div class="mt-3 pt-3 border-t border-outline-variant space-y-2">
<!-- 第一行预览在左半部分居中编辑在右半部分居中 -->
<div class="grid grid-cols-2 gap-2">
<div class="flex justify-center">
<button
class="md3-button-outlined text-sm flex-shrink-0"
@click="previewTemplate(template)"
>
<svg
class="w-4 h-4 mr-1.5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
/>
</svg>
预览
</button>
</div>
<div class="flex justify-center">
<button
class="md3-button-outlined text-sm flex-shrink-0"
@click="editTemplate(template)"
>
<svg
class="w-4 h-4 mr-1.5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
/>
</svg>
编辑
</button>
</div>
</div>
<!-- 第二行删除在右半部分居中与编辑对齐 -->
<div class="grid grid-cols-2 gap-2">
<div></div>
<div class="flex justify-center">
<button
class="md3-button-outlined text-sm !text-red-600 dark:!text-red-500 !border-red-600 dark:!border-red-500 hover:!bg-red-50 dark:hover:!bg-red-900/20 flex-shrink-0"
@click="deleteTemplate(template)"
>
<svg
class="w-4 h-4 mr-1.5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
删除
</button>
</div>
</div>
</div>
</a-card>
</div>
<!-- Create/Edit Dialog -->
<a-modal
v-model:open="dialogVisible"
:title="dialogMode === 'create' ? '新建模板' : '编辑模板'"
:width="dialogWidth"
:style="isMobile ? { top: 0, maxWidth: '100vw' } : {}"
:mask-closable="false"
class="template-editor-modal"
>
<a-form ref="formRef" :model="formData" layout="vertical">
<a-form-item label="模板名称" required>
<a-input
v-model:value="formData.name"
placeholder="请输入模板名称"
:maxlength="100"
show-count
/>
</a-form-item>
<a-form-item label="模板描述">
<a-textarea
v-model:value="formData.description"
:rows="2"
placeholder="请输入模板描述"
/>
</a-form-item>
<a-form-item label="父模板">
<a-select
v-model:value="formData.parent_id"
placeholder="可选,继承父模板的字段配置"
allow-clear
style="width: 100%"
>
<a-select-option
v-for="template in availableParentTemplates"
:key="template.id"
:value="template.id"
:disabled="template.id === currentTemplateId"
>
{{ template.name }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="是否启用">
<a-switch v-model:checked="formData.is_active" />
</a-form-item>
<a-divider orientation="left">
<span class="text-lg font-bold">Payload 配置 (JSON 映射)</span>
</a-divider>
<a-alert
message="💡 JSON 映射架构"
type="info"
:closable="false"
show-icon
class="mb-4"
>
<template #description>
<p class="text-sm mb-2">
<strong>配置即结构</strong>模板配置完全映射到生成的 Payload 结构
</p>
<p class="text-sm mb-2"><strong>字段名保持原样</strong>不进行任何大小写转换</p>
<p class="text-sm"><strong>ThreadId</strong> 由用户填写无需在模板中配置</p>
</template>
</a-alert>
<!-- 字段配置编辑器 -->
<div class="field-config-editor">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-bold text-on-surface">字段配置</h3>
<a-dropdown>
<a-button type="primary">
添加字段
<DownOutlined />
</a-button>
<template #overlay>
<a-menu @click="handleAddField">
<a-menu-item key="field">
<svg
class="w-4 h-4 inline mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"
/>
</svg>
普通字段
</a-menu-item>
<a-menu-item key="array">
<svg
class="w-4 h-4 inline mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 6h16M4 10h16M4 14h16M4 18h16"
/>
</svg>
数组字段
</a-menu-item>
<a-menu-item key="object">
<svg
class="w-4 h-4 inline mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg>
对象字段
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</div>
<!-- 递归渲染字段树 -->
<div
v-if="Object.keys(formData.field_config).length === 0"
class="text-center py-12 border-2 border-dashed border-outline-variant rounded-lg bg-surface-container"
>
<svg
class="w-16 h-16 mx-auto text-on-surface-variant opacity-40 mb-3"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
/>
</svg>
<h3 class="text-lg font-semibold text-on-surface mb-2">暂无字段配置</h3>
<p class="text-sm text-on-surface-variant">点击上方"添加字段"开始配置模板</p>
</div>
<div v-else class="space-y-3">
<FieldTreeNode
v-for="(config, key) in formData.field_config"
:key="`${fieldConfigVersion}-${key}`"
:field-key="key"
:field-config="config"
:path="[key]"
@update="event => updateField(event.path, event.value)"
@delete="path => deleteField(path)"
@move="event => moveField(event.path, event.direction)"
/>
</div>
</div>
<!-- JSON 预览 -->
<a-divider orientation="left">
<span class="text-lg font-bold">JSON 预览</span>
</a-divider>
<div
class="bg-surface-container text-green-400 p-4 rounded-lg font-mono text-sm overflow-auto max-h-96"
>
<pre>{{ JSON.stringify(formData.field_config, null, 2) }}</pre>
</div>
</a-form>
<template #footer>
<a-button @click="dialogVisible = false">取消</a-button>
<a-button type="primary" :loading="submitting" @click="handleSubmit">
{{ dialogMode === 'create' ? '创建' : '更新' }}
</a-button>
</template>
</a-modal>
<!-- Add Field Dialog -->
<a-modal
v-model:open="addFieldDialogVisible"
:title="`添加${fieldTypeLabel}`"
:width="isMobile ? '100%' : 500"
:style="isMobile ? { top: 0, maxWidth: '100vw' } : {}"
>
<a-form @submit.prevent="confirmAddField">
<a-form-item label="字段名">
<a-input
v-model:value="newFieldName"
placeholder="例如: Id, Group1, DateTarget"
@keyup.enter="confirmAddField"
/>
<span class="text-xs text-on-surface-variant mt-1 block">
💡 字段名将保持原样不会进行大小写转换
</span>
</a-form-item>
</a-form>
<template #footer>
<a-button @click="addFieldDialogVisible = false">取消</a-button>
<a-button type="primary" @click="confirmAddField">确定</a-button>
</template>
</a-modal>
<!-- Preview Dialog -->
<a-modal
v-model:open="previewDialogVisible"
title="模板预览"
:width="previewDialogWidth"
:style="isMobile ? { top: 0, maxWidth: '100vw' } : {}"
>
<div v-if="previewData" class="space-y-4">
<div class="bg-surface-container rounded p-4">
<h4 class="font-semibold mb-2 text-on-surface">生成的 Payload使用默认值</h4>
<pre
class="text-xs bg-surface text-on-surface p-3 rounded border border-outline-variant overflow-auto max-h-96"
>{{ JSON.stringify(previewData.preview_payload, null, 2) }}</pre
>
</div>
<div class="bg-surface-container rounded p-4">
<h4 class="font-semibold mb-2 text-on-surface">字段配置</h4>
<pre
class="text-xs bg-surface text-on-surface p-3 rounded border border-outline-variant overflow-auto max-h-96"
>{{ JSON.stringify(previewData.field_config, null, 2) }}</pre
>
</div>
</div>
<template #footer>
<a-button @click="previewDialogVisible = false">关闭</a-button>
</template>
</a-modal>
</div>
</div>
</Layout>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { DownOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import FieldTreeNode from '@/components/FieldTreeNode.vue';
import { useTemplateStore } from '@/stores/template';
import { useBreakpoint } from '@/composables/useBreakpoint';
const templateStore = useTemplateStore();
const { isMobile, isTablet } = useBreakpoint();
// 计算对话框宽度 - 响应式设计
const dialogWidth = computed(() => {
if (isMobile.value) return '100%';
if (isTablet.value) return 900;
return 1200;
});
const previewDialogWidth = computed(() => {
if (isMobile.value) return '100%';
if (isTablet.value) return 800;
return 1000;
});
const templates = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogMode = ref('create');
const currentTemplateId = ref(null);
const submitting = ref(false);
const previewDialogVisible = ref(false);
const previewData = ref(null);
const addFieldDialogVisible = ref(false);
const newFieldName = ref('');
const newFieldType = ref('field');
const fieldConfigVersion = ref(0); // 用于强制刷新字段列表
const formData = ref({
name: '',
description: '',
parent_id: null,
is_active: true,
field_config: {},
});
const availableParentTemplates = computed(() => {
if (dialogMode.value === 'create') {
return templates.value;
}
return templates.value.filter(t => t.id !== currentTemplateId.value);
});
const fieldTypeLabel = computed(() => {
const labels = {
field: '普通字段',
array: '数组字段',
object: '对象字段',
};
return labels[newFieldType.value] || '字段';
});
function createDefaultFieldConfig() {
return {
display_name: '',
field_type: 'text',
default_value: '',
required: false,
hidden: false,
placeholder: '',
value_type: 'string',
options: [],
};
}
const fetchTemplates = async () => {
loading.value = true;
try {
templates.value = await templateStore.fetchTemplates();
} catch (error) {
message.error(error.message || '获取模板列表失败');
} finally {
loading.value = false;
}
};
const showCreateDialog = () => {
dialogMode.value = 'create';
currentTemplateId.value = null;
formData.value = {
name: '',
description: '',
parent_id: null,
is_active: true,
field_config: {},
};
dialogVisible.value = true;
};
const editTemplate = template => {
dialogMode.value = 'edit';
currentTemplateId.value = template.id;
const fieldConfig = JSON.parse(template.field_config);
formData.value = {
name: template.name,
description: template.description || '',
parent_id: template.parent_id || null,
is_active: template.is_active,
field_config: fieldConfig,
};
dialogVisible.value = true;
};
const handleSubmit = async () => {
if (!formData.value.name) {
message.warning('请输入模板名称');
return;
}
submitting.value = true;
try {
const templateData = {
name: formData.value.name,
description: formData.value.description,
parent_id: formData.value.parent_id,
is_active: formData.value.is_active,
field_config: JSON.stringify(formData.value.field_config),
};
if (dialogMode.value === 'create') {
await templateStore.createTemplate(templateData);
message.success('模板创建成功');
} else {
await templateStore.updateTemplate(currentTemplateId.value, templateData);
message.success('模板更新成功');
}
dialogVisible.value = false;
await fetchTemplates();
} catch (error) {
message.error(error.message || '操作失败');
} finally {
submitting.value = false;
}
};
const deleteTemplate = template => {
Modal.confirm({
title: '确认删除',
content: `确定要删除模板"${template.name}"吗?此操作不可撤销。`,
okText: '删除',
cancelText: '取消',
okType: 'danger',
onOk: async () => {
try {
await templateStore.deleteTemplate(template.id);
message.success('模板删除成功');
await fetchTemplates();
} catch (error) {
message.error(error.message || '删除失败');
}
},
});
};
const previewTemplate = async template => {
try {
previewData.value = await templateStore.previewTemplate(template.id);
previewDialogVisible.value = true;
} catch (error) {
message.error(error.message || '预览失败');
}
};
const handleAddField = ({ key }) => {
newFieldType.value = key;
newFieldName.value = '';
addFieldDialogVisible.value = true;
};
const confirmAddField = () => {
if (!newFieldName.value) {
message.warning('请输入字段名');
return;
}
if (formData.value.field_config[newFieldName.value]) {
message.warning('该字段已存在');
return;
}
// 创建一个新对象,确保新字段被添加到末尾
const newConfig = { ...formData.value.field_config };
// 创建对应类型的字段
if (newFieldType.value === 'field') {
newConfig[newFieldName.value] = createDefaultFieldConfig();
} else if (newFieldType.value === 'array') {
newConfig[newFieldName.value] = [];
} else if (newFieldType.value === 'object') {
newConfig[newFieldName.value] = {};
}
// 替换整个 field_config 以确保顺序和响应性
formData.value.field_config = newConfig;
fieldConfigVersion.value++; // 强制刷新
addFieldDialogVisible.value = false;
message.success('字段添加成功');
};
const updateField = (path, newValue) => {
// 通过路径更新嵌套字段
let target = formData.value.field_config;
for (let i = 0; i < path.length - 1; i++) {
target = target[path[i]];
}
target[path[path.length - 1]] = newValue;
};
const deleteField = path => {
// 通过路径删除嵌套字段
if (!path || path.length === 0) return;
// 创建一个新的 field_config 副本以触发响应性
const newConfig = JSON.parse(JSON.stringify(formData.value.field_config));
let target = newConfig;
// 导航到父对象/数组
for (let i = 0; i < path.length - 1; i++) {
if (!target || typeof target !== 'object') {
console.error('❌ 删除失败:路径无效', path, 'at index', i);
return;
}
target = target[path[i]];
}
if (!target || typeof target !== 'object') {
console.error('❌ 删除失败:父对象不存在', path);
return;
}
const lastKey = path[path.length - 1];
// 如果父容器是数组,使用 splice;如果是对象,使用 delete
if (Array.isArray(target)) {
target.splice(lastKey, 1);
} else {
delete target[lastKey];
}
// 替换整个 field_config 以触发 Vue 响应性
formData.value.field_config = newConfig;
fieldConfigVersion.value++; // 强制刷新
};
const moveField = (path, direction) => {
// 通过路径移动字段
if (!path || path.length === 0) return;
// 如果是根级别字段,直接重建整个 field_config
if (path.length === 1) {
const fieldKey = path[0];
const keys = Object.keys(formData.value.field_config);
const currentIndex = keys.indexOf(fieldKey);
if (currentIndex === -1) {
console.error('❌ 字段不存在:', fieldKey);
return;
}
let targetIndex = currentIndex;
if (direction === 'up' && currentIndex > 0) {
targetIndex = currentIndex - 1;
} else if (direction === 'down' && currentIndex < keys.length - 1) {
targetIndex = currentIndex + 1;
} else {
return;
}
// 交换键的位置
const temp = keys[currentIndex];
keys[currentIndex] = keys[targetIndex];
keys[targetIndex] = temp;
// 重建整个 field_config - 使用深拷贝确保完全新的对象
const newConfig = {};
keys.forEach(key => {
// 深拷贝每个字段配置
newConfig[key] = JSON.parse(JSON.stringify(formData.value.field_config[key]));
});
// 替换整个 formData,而不只是 field_config
formData.value = {
...formData.value,
field_config: newConfig,
};
fieldConfigVersion.value++;
return;
}
// 嵌套字段的情况(保留原有逻辑)
const newConfig = JSON.parse(JSON.stringify(formData.value.field_config));
// 导航到目标的父容器
let parent = newConfig;
for (let i = 0; i < path.length - 1; i++) {
parent = parent[path[i]];
if (!parent) {
console.error('❌ 路径无效:', path);
return;
}
}
const fieldKey = path[path.length - 1];
if (Array.isArray(parent)) {
// 数组情况:直接交换元素
const index = Number(fieldKey);
if (direction === 'up' && index > 0) {
const temp = parent[index];
parent[index] = parent[index - 1];
parent[index - 1] = temp;
} else if (direction === 'down' && index < parent.length - 1) {
const temp = parent[index];
parent[index] = parent[index + 1];
parent[index + 1] = temp;
} else {
return;
}
} else {
// 对象情况:重建对象以改变键顺序
const keys = Object.keys(parent);
const currentIndex = keys.indexOf(fieldKey);
if (currentIndex === -1) {
console.error('❌ 字段不存在:', fieldKey);
return;
}
let targetIndex = currentIndex;
if (direction === 'up' && currentIndex > 0) {
targetIndex = currentIndex - 1;
} else if (direction === 'down' && currentIndex < keys.length - 1) {
targetIndex = currentIndex + 1;
} else {
return;
}
// 交换键数组中的位置
const temp = keys[currentIndex];
keys[currentIndex] = keys[targetIndex];
keys[targetIndex] = temp;
// 重建父对象
const reorderedParent = {};
keys.forEach(key => {
reorderedParent[key] = parent[key];
});
// 替换父容器的所有属性
Object.keys(parent).forEach(key => delete parent[key]);
Object.assign(parent, reorderedParent);
}
// 强制触发响应性更新
formData.value.field_config = newConfig;
fieldConfigVersion.value++;
};
onMounted(() => {
fetchTemplates();
});
</script>
<style scoped>
.field-config-editor {
min-height: 200px;
}
.template-editor-modal :deep(.ant-modal-body) {
max-height: 70vh;
overflow-y: auto;
}
</style>
+607
View File
@@ -0,0 +1,607 @@
<template>
<Layout>
<div class="admin-users-container">
<a-card>
<template #title>
<div class="card-header">
<div>
<UserOutlined />
<span>用户管理</span>
</div>
<a-space class="actions">
<a-button type="primary" @click="handleCreate">
<template #icon><PlusOutlined /></template>
创建用户
</a-button>
<a-button @click="handleRefresh">
<template #icon><ReloadOutlined /></template>
刷新
</a-button>
</a-space>
</div>
</template>
<!-- Tab 切换 -->
<a-tabs v-model:active-key="activeTab" @change="handleTabChange">
<!-- 待审批用户 Tab -->
<a-tab-pane key="pending" tab="待审批用户">
<!-- 桌面端表格 -->
<a-table
v-if="!isMobile"
:data-source="pendingUsers"
:columns="pendingColumns"
:loading="loading"
:row-key="record => record.id"
:scroll="{ x: 'max-content' }"
bordered
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'created_at'">
{{ formatDateTime(record.created_at) }}
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="primary" size="small" @click="handleApprove(record)">
通过
</a-button>
<a-button danger size="small" @click="handleReject(record)"> 拒绝 </a-button>
</a-space>
</template>
</template>
</a-table>
<!-- 移动端卡片视图 -->
<a-space v-else direction="vertical" :size="16" style="width: 100%">
<a-card v-for="user in pendingUsers" :key="user.id" size="small" :loading="loading">
<a-descriptions :column="1" size="small" bordered>
<a-descriptions-item label="ID">{{ user.id }}</a-descriptions-item>
<a-descriptions-item label="用户名">{{ user.alias }}</a-descriptions-item>
<a-descriptions-item label="邮箱">{{ user.email || '-' }}</a-descriptions-item>
<a-descriptions-item label="注册时间">{{
formatDateTime(user.created_at)
}}</a-descriptions-item>
</a-descriptions>
<a-space class="mt-3" style="width: 100%">
<a-button type="primary" size="small" block @click="handleApprove(user)"
>通过</a-button
>
<a-button danger size="small" block @click="handleReject(user)">拒绝</a-button>
</a-space>
</a-card>
<a-empty v-if="!loading && pendingUsers.length === 0" description="暂无数据" />
</a-space>
</a-tab-pane>
<!-- 所有用户 Tab -->
<a-tab-pane key="all" tab="所有用户">
<!-- 桌面端表格 -->
<a-table
v-if="!isMobile"
:data-source="userStore.users"
:columns="allColumns"
:loading="loading"
:row-key="record => record.id"
:row-selection="rowSelection"
:scroll="{ x: 'max-content' }"
bordered
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'role'">
<a-tag :color="record.role === 'admin' ? 'error' : 'blue'">
{{ record.role === 'admin' ? '管理员' : '用户' }}
</a-tag>
</template>
<template v-else-if="column.key === 'is_approved'">
<a-tag :color="record.is_approved ? 'success' : 'warning'">
{{ record.is_approved ? '已审批' : '待审批' }}
</a-tag>
</template>
<template v-else-if="column.key === 'jwt_exp'">
{{
record.jwt_exp && record.jwt_exp !== '0'
? formatDateTime(parseInt(record.jwt_exp) * 1000)
: '-'
}}
</template>
<template v-else-if="column.key === 'created_at'">
{{ formatDateTime(record.created_at) }}
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="primary" size="small" @click="handleEdit(record)">
编辑
</a-button>
<a-button danger size="small" @click="handleDelete(record)"> 删除 </a-button>
</a-space>
</template>
</template>
</a-table>
<!-- 移动端卡片视图 -->
<a-space v-else direction="vertical" :size="16" style="width: 100%">
<a-card
v-for="user in userStore.users"
:key="user.id"
size="small"
:loading="loading"
>
<a-descriptions :column="1" size="small" bordered>
<a-descriptions-item label="ID">{{ user.id }}</a-descriptions-item>
<a-descriptions-item label="用户名">{{ user.alias }}</a-descriptions-item>
<a-descriptions-item label="邮箱">{{ user.email || '-' }}</a-descriptions-item>
<a-descriptions-item label="角色">
<a-tag :color="user.role === 'admin' ? 'error' : 'blue'">
{{ user.role === 'admin' ? '管理员' : '用户' }}
</a-tag>
</a-descriptions-item>
<a-descriptions-item label="审批状态">
<a-tag :color="user.is_approved ? 'success' : 'warning'">
{{ user.is_approved ? '已审批' : '待审批' }}
</a-tag>
</a-descriptions-item>
<a-descriptions-item label="Token过期">
{{
user.jwt_exp && user.jwt_exp !== '0'
? formatDateTime(parseInt(user.jwt_exp) * 1000)
: '-'
}}
</a-descriptions-item>
<a-descriptions-item label="创建时间">{{
formatDateTime(user.created_at)
}}</a-descriptions-item>
</a-descriptions>
<a-space class="mt-3" style="width: 100%">
<a-button type="primary" size="small" block @click="handleEdit(user)"
>编辑</a-button
>
<a-button danger size="small" block @click="handleDelete(user)">删除</a-button>
</a-space>
</a-card>
</a-space>
<!-- 批量操作 -->
<div v-if="selectedUsers.length > 0" class="batch-actions">
<a-alert
:message="`已选择 ${selectedUsers.length} 个用户`"
type="info"
:closable="false"
>
<template #description>
<a-space style="margin-top: 10px">
<a-button type="primary" size="small" @click="handleBatchApprove">
批量审批
</a-button>
<a-button danger size="small" @click="handleBatchDelete"> 批量删除 </a-button>
</a-space>
</template>
</a-alert>
</div>
</a-tab-pane>
</a-tabs>
</a-card>
<!-- 创建/编辑用户对话框 -->
<a-modal
v-model:open="dialogVisible"
:title="dialogMode === 'create' ? '创建用户' : '编辑用户'"
:width="isMobile ? '100%' : 600"
:style="isMobile ? { top: 0, maxWidth: '100vw' } : {}"
>
<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
<a-form-item label="用户名" name="alias">
<a-input v-model:value="formData.alias" placeholder="请输入用户名" />
</a-form-item>
<a-form-item label="邮箱" name="email">
<a-input v-model:value="formData.email" placeholder="请输入邮箱" />
</a-form-item>
<a-form-item label="角色" name="role">
<a-select v-model:value="formData.role" placeholder="请选择角色">
<a-select-option value="user">用户</a-select-option>
<a-select-option value="admin">管理员</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="审批状态" name="is_approved">
<a-switch v-model:checked="formData.is_approved" />
<span class="form-hint">是否已审批通过</span>
</a-form-item>
<a-form-item label="密码" name="password">
<a-input-password
v-model:value="formData.password"
:placeholder="dialogMode === 'create' ? '请输入密码' : '留空则不修改密码'"
/>
<span v-if="dialogMode === 'edit'" class="form-hint"> 留空则不修改密码 </span>
</a-form-item>
<a-form-item v-if="dialogMode === 'edit'" label="重置密码">
<a-switch v-model:checked="formData.reset_password" />
<span v-if="formData.reset_password" class="form-hint-danger">
⚠️ 将重置为默认密码
</span>
</a-form-item>
</a-form>
<template #footer>
<a-button @click="dialogVisible = false">取消</a-button>
<a-button type="primary" :loading="submitting" @click="handleSubmit"> 确定 </a-button>
</template>
</a-modal>
</div>
</Layout>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { UserOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import Layout from '@/components/Layout.vue';
import { useBreakpoint } from '@/composables/useBreakpoint';
import { useUserStore } from '@/stores/user';
import { adminAPI } from '@/api/index';
const userStore = useUserStore();
const { isMobile } = useBreakpoint();
// 状态
const loading = ref(false);
const activeTab = ref('all'); // 默认展示所有用户
const pendingUsers = ref([]);
const selectedUsers = ref([]);
const selectedRowKeys = ref([]);
const dialogVisible = ref(false);
const dialogMode = ref('create');
const submitting = ref(false);
// 表单
const formRef = ref(null);
const formData = ref({
alias: '',
role: 'user',
is_approved: true,
email: '',
password: '',
reset_password: false,
});
// 表单验证规则
const formRules = {
alias: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
],
role: [{ required: true, message: '请选择角色', trigger: 'change' }],
email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
};
// 时间格式化
const formatDateTime = timestamp => {
if (!timestamp) return '-';
const date = new Date(timestamp);
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
};
// 待审批用户表格列
const pendingColumns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: '用户名', dataIndex: 'alias', key: 'alias', ellipsis: true },
{ title: '邮箱', dataIndex: 'email', key: 'email', ellipsis: true },
{ title: '注册时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'actions', width: 200, fixed: 'right' },
];
// 所有用户表格列
const allColumns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: '用户名', dataIndex: 'alias', key: 'alias', ellipsis: true },
{ title: '邮箱', dataIndex: 'email', key: 'email', ellipsis: true },
{ title: '角色', dataIndex: 'role', key: 'role', width: 100 },
{ title: '审批状态', dataIndex: 'is_approved', key: 'is_approved', width: 100 },
{ title: 'Token 过期时间', dataIndex: 'jwt_exp', key: 'jwt_exp', width: 180 },
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 180 },
{ title: '操作', key: 'actions', width: 200, fixed: 'right' },
];
// 行选择配置
const rowSelection = {
selectedRowKeys: selectedRowKeys,
onChange: (keys, rows) => {
selectedRowKeys.value = keys;
selectedUsers.value = rows;
},
};
// 获取待审批用户
const fetchPendingUsers = async () => {
loading.value = true;
try {
pendingUsers.value = await adminAPI.getPendingUsers();
} catch (error) {
message.error(error.message || '获取待审批用户失败');
} finally {
loading.value = false;
}
};
// Tab 切换
const handleTabChange = tab => {
if (tab === 'pending') {
fetchPendingUsers();
} else {
handleRefresh();
}
};
// 审批通过用户
const handleApprove = async user => {
Modal.confirm({
title: '审批确认',
content: `确认通过用户 "${user.alias}" 的审批吗?`,
okText: '确认',
cancelText: '取消',
onOk: async () => {
try {
await adminAPI.approveUser(user.id);
message.success('审批成功');
fetchPendingUsers();
} catch (error) {
message.error(error.message || '审批失败');
}
},
});
};
// 拒绝用户
const handleReject = async user => {
Modal.confirm({
title: '拒绝确认',
content: `确认拒绝用户 "${user.alias}" 的申请吗?拒绝后将删除该用户。`,
okText: '确认',
cancelText: '取消',
okType: 'danger',
onOk: async () => {
try {
await adminAPI.rejectUser(user.id);
message.success('已拒绝并删除用户');
fetchPendingUsers();
} catch (error) {
message.error(error.message || '操作失败');
}
},
});
};
// 刷新数据
const handleRefresh = async () => {
if (activeTab.value === 'pending') {
await fetchPendingUsers();
} else {
loading.value = true;
try {
await userStore.fetchUsers();
message.success('刷新成功');
} catch (error) {
message.error(error.message || '刷新失败');
} finally {
loading.value = false;
}
}
};
// 创建用户
const handleCreate = () => {
dialogMode.value = 'create';
formData.value = {
alias: '',
role: 'user',
is_approved: true,
email: '',
password: '',
reset_password: false,
};
dialogVisible.value = true;
};
// 编辑用户
const handleEdit = user => {
dialogMode.value = 'edit';
formData.value = {
id: user.id,
alias: user.alias,
role: user.role,
is_approved: user.is_approved,
email: user.email || '',
password: '',
reset_password: false,
};
dialogVisible.value = true;
};
// 提交表单
const handleSubmit = async () => {
if (!formRef.value) return;
try {
await formRef.value.validate();
submitting.value = true;
// 检查密码设置冲突
if (dialogMode.value === 'edit' && formData.value.password && formData.value.reset_password) {
message.warning('不能同时设置新密码和重置密码,请选择其一');
submitting.value = false;
return;
}
if (dialogMode.value === 'create') {
// 创建用户时,只发送后端 UserCreate schema 接受的字段
const createData = {
alias: formData.value.alias,
role: formData.value.role,
is_approved: formData.value.is_approved,
};
// 如果有邮箱,添加邮箱字段(空字符串转为 null)
if (formData.value.email && formData.value.email.trim()) {
createData.email = formData.value.email.trim();
}
// 如果有密码,添加密码字段
if (formData.value.password && formData.value.password.trim()) {
createData.password = formData.value.password.trim();
}
await userStore.createUser(createData);
message.success('创建成功');
} else {
// 编辑用户时,处理空字符串字段
const updateData = {
...formData.value,
// 将空字符串的邮箱转为 null
email:
formData.value.email && formData.value.email.trim() ? formData.value.email.trim() : null,
// 将空字符串的密码转为 null
password:
formData.value.password && formData.value.password.trim()
? formData.value.password.trim()
: null,
};
await userStore.updateUser(formData.value.id, updateData);
message.success('更新成功');
}
dialogVisible.value = false;
await handleRefresh();
} catch (error) {
message.error(error.message || '操作失败');
} finally {
submitting.value = false;
}
};
// 删除用户
const handleDelete = user => {
Modal.confirm({
title: '警告',
content: `确定要删除用户 "${user.alias}" `,
okText: '确定',
cancelText: '取消',
okType: 'danger',
onOk: async () => {
try {
await userStore.deleteUser(user.id);
message.success('删除成功');
await handleRefresh();
} catch (error) {
message.error(error.message || '删除失败');
}
},
});
};
// 批量审批
const handleBatchApprove = () => {
Modal.confirm({
title: '批量审批确认',
content: `确认批量审批 ${selectedUsers.value.length} 个用户吗`,
okText: '确认',
cancelText: '取消',
onOk: async () => {
const userIds = selectedUsers.value.map(u => u.id);
let successCount = 0;
let failureCount = 0;
for (const userId of userIds) {
try {
await adminAPI.approveUser(userId);
successCount++;
} catch {
failureCount++;
}
}
message.success(`批量审批完成成功 ${successCount}失败 ${failureCount}`);
await handleRefresh();
},
});
};
// 批量删除
const handleBatchDelete = () => {
Modal.confirm({
title: '批量删除警告',
content: `确定要删除选中的 ${selectedUsers.value.length} 个用户吗此操作不可恢复`,
okText: '确定',
cancelText: '取消',
okType: 'danger',
onOk: async () => {
const userIds = selectedUsers.value.map(u => u.id);
let successCount = 0;
let failureCount = 0;
for (const userId of userIds) {
try {
await userStore.deleteUser(userId);
successCount++;
} catch {
failureCount++;
}
}
message.success(`批量删除完成成功 ${successCount}失败 ${failureCount}`);
await handleRefresh();
},
});
};
onMounted(() => {
// 默认加载所有用户
handleRefresh();
});
</script>
<style scoped>
.admin-users-container {
max-width: 1600px;
margin: 0 auto;
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.card-header > div {
display: flex;
align-items: center;
gap: 8px;
}
.batch-actions {
margin-top: 15px;
}
.form-hint {
margin-left: 10px;
font-size: 12px;
color: #909399;
}
.form-hint-danger {
color: #f56c6c;
font-weight: 500;
display: block;
margin-left: 0;
margin-top: 4px;
}
.mt-3 {
margin-top: 12px;
}
</style>