mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 20:29:19 +08:00
refactor: 调整页面组件位置
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, Input, message, Space, Typography } from 'ant-design-vue';
|
||||
|
||||
defineOptions({ name: 'FingerprintDisplay' });
|
||||
|
||||
const props = defineProps<{
|
||||
fingerprint: string;
|
||||
hostname?: string;
|
||||
machineId?: string;
|
||||
}>();
|
||||
|
||||
const CopyIcon = createIconifyIcon('lucide:copy');
|
||||
|
||||
const copying = ref(false);
|
||||
|
||||
async function copyFingerprint() {
|
||||
if (!props.fingerprint) return;
|
||||
copying.value = true;
|
||||
try {
|
||||
await navigator.clipboard.writeText(props.fingerprint);
|
||||
message.success('机器指纹已复制');
|
||||
} catch {
|
||||
message.error('复制失败,请手动选择复制');
|
||||
} finally {
|
||||
copying.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-lg border border-dashed border-primary/30 bg-primary/5 p-4">
|
||||
<Typography.Text type="secondary" class="mb-2 block text-sm">
|
||||
请将以下机器指纹发送给运营方签发 License
|
||||
</Typography.Text>
|
||||
<Input :value="fingerprint" readonly class="font-mono text-xs" />
|
||||
<Space class="mt-3" wrap>
|
||||
<Button
|
||||
type="primary"
|
||||
ghost
|
||||
size="small"
|
||||
:loading="copying"
|
||||
@click="copyFingerprint"
|
||||
>
|
||||
<CopyIcon class="mr-1 size-4" />
|
||||
复制指纹
|
||||
</Button>
|
||||
<Typography.Text v-if="hostname" type="secondary" class="text-xs">
|
||||
主机名:{{ hostname }}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script setup lang="ts">
|
||||
import type { LicenseVO } from '#/api/system/license';
|
||||
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
import { Card, Spin } from 'ant-design-vue';
|
||||
|
||||
import { getSystemFingerprintApi } from '#/api/system/license';
|
||||
|
||||
import FingerprintDisplay from './FingerprintDisplay.vue';
|
||||
|
||||
defineOptions({ name: 'FingerprintInfo' });
|
||||
|
||||
const loading = ref(false);
|
||||
const fingerprint = ref<LicenseVO.Fingerprint | null>(null);
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
try {
|
||||
fingerprint.value = await getSystemFingerprintApi();
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card title="机器指纹" :bordered="false">
|
||||
<Spin :spinning="loading">
|
||||
<FingerprintDisplay
|
||||
v-if="fingerprint"
|
||||
:fingerprint="fingerprint.fingerprint"
|
||||
:hostname="fingerprint.hostname"
|
||||
:machine-id="fingerprint.machineId"
|
||||
/>
|
||||
<div v-else-if="!loading" class="text-gray-400">暂无指纹信息</div>
|
||||
</Spin>
|
||||
<p class="mt-4 text-sm text-gray-500">
|
||||
迁机或重新签发 License 时,请将新环境的机器指纹提供给运营方。
|
||||
</p>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -0,0 +1,160 @@
|
||||
<script setup lang="ts">
|
||||
import type { LicenseVO } from '#/api/system/license';
|
||||
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Descriptions,
|
||||
Form,
|
||||
Input,
|
||||
message,
|
||||
Space,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import {
|
||||
getLicenseInfoApi,
|
||||
updateLicenseApi,
|
||||
} from '#/api/system/license';
|
||||
|
||||
import FingerprintInfo from './FingerprintInfo.vue';
|
||||
|
||||
defineOptions({ name: 'LicenseInfo' });
|
||||
|
||||
const loading = ref(false);
|
||||
const updating = ref(false);
|
||||
const license = ref<LicenseVO.LicenseSummary | null>(null);
|
||||
const renewKey = ref('');
|
||||
|
||||
const statusTag = computed(() => {
|
||||
const status = license.value?.status;
|
||||
if (status === 'active') return { color: 'success', text: '有效' };
|
||||
if (status === 'expiring') return { color: 'warning', text: '即将过期' };
|
||||
if (status === 'expired') return { color: 'error', text: '已过期' };
|
||||
if (status === 'dev-disabled') return { color: 'default', text: '开发模式' };
|
||||
return { color: 'default', text: status || '未知' };
|
||||
});
|
||||
|
||||
const editionLabel: Record<string, string> = {
|
||||
trial: '试用版',
|
||||
enterprise: '企业版',
|
||||
unlimited: '无限版',
|
||||
};
|
||||
|
||||
async function loadLicense() {
|
||||
loading.value = true;
|
||||
try {
|
||||
license.value = await getLicenseInfoApi();
|
||||
} catch (error: any) {
|
||||
license.value = null;
|
||||
if (!error?.message?.includes('无有效')) {
|
||||
message.error(error?.message || '获取 License 信息失败');
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRenew() {
|
||||
if (!renewKey.value.trim()) {
|
||||
message.warning('请输入新的 License Key');
|
||||
return;
|
||||
}
|
||||
updating.value = true;
|
||||
const hide = message.loading('正在更新 License...', 0);
|
||||
try {
|
||||
license.value = await updateLicenseApi({ licenseKey: renewKey.value.trim() });
|
||||
renewKey.value = '';
|
||||
message.success('License 更新成功');
|
||||
} finally {
|
||||
hide();
|
||||
updating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value?: string) {
|
||||
return value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '-';
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadLicense();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="License 管理" description="查看授权信息与续期更新">
|
||||
<div class="grid gap-4 lg:grid-cols-2">
|
||||
<Card title="授权信息" :loading="loading">
|
||||
<template v-if="license">
|
||||
<Descriptions :column="1" bordered size="small">
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag :color="statusTag.color">{{ statusTag.text }}</Tag>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="授权公司">
|
||||
{{ license.companyName || '-' }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="版本">
|
||||
{{ editionLabel[license.edition || ''] || license.edition || '-' }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="机器指纹">
|
||||
<Typography.Text code class="text-xs break-all">
|
||||
{{ license.machineFingerprint || '-' }}
|
||||
</Typography.Text>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="授权功能">
|
||||
<Space wrap>
|
||||
<Tag v-for="f in license.features" :key="f">{{ f }}</Tag>
|
||||
<span v-if="!license.features?.length">-</span>
|
||||
</Space>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="签发时间">
|
||||
{{ formatDate(license.issuedAt) }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="过期时间">
|
||||
{{ formatDate(license.expiresAt) }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item
|
||||
v-if="license.daysRemaining != null"
|
||||
label="剩余天数"
|
||||
>
|
||||
{{ license.daysRemaining }} 天
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</template>
|
||||
<Typography.Text v-else type="secondary">
|
||||
暂无有效 License(本地开发可能未启用校验)
|
||||
</Typography.Text>
|
||||
<Button class="mt-4" size="small" @click="loadLicense">刷新</Button>
|
||||
</Card>
|
||||
|
||||
<Card title="续期 / 更新 License">
|
||||
<Typography.Paragraph type="secondary" class="text-sm">
|
||||
运营方签发新 License 后,将完整 JWT 粘贴到下方并提交。
|
||||
</Typography.Paragraph>
|
||||
<Form layout="vertical" @finish="handleRenew">
|
||||
<Form.Item label="新 License Key" required>
|
||||
<Input.TextArea
|
||||
v-model:value="renewKey"
|
||||
:rows="5"
|
||||
placeholder="粘贴新的 License JWT"
|
||||
class="font-mono text-xs"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button type="primary" html-type="submit" :loading="updating">
|
||||
更新 License
|
||||
</Button>
|
||||
</Form>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<FingerprintInfo />
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
@@ -0,0 +1,201 @@
|
||||
<script setup lang="ts">
|
||||
import type { LicenseVO } from '#/api/system/license';
|
||||
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Descriptions,
|
||||
Form,
|
||||
Input,
|
||||
message,
|
||||
Space,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'ant-design-vue';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import {
|
||||
activateLicenseApi,
|
||||
getLicenseInfoApi,
|
||||
getSystemFingerprintApi,
|
||||
} from '#/api/system/license';
|
||||
|
||||
import FingerprintDisplay from './FingerprintDisplay.vue';
|
||||
|
||||
defineOptions({ name: 'SystemLicensePage' });
|
||||
|
||||
const loading = ref(false);
|
||||
const fingerprintLoading = ref(false);
|
||||
const submitting = ref(false);
|
||||
const license = ref<LicenseVO.LicenseSummary | null>(null);
|
||||
const fingerprint = ref<LicenseVO.Fingerprint | null>(null);
|
||||
const licenseKey = ref('');
|
||||
|
||||
const statusTag = computed(() => {
|
||||
const status = license.value?.status;
|
||||
if (status === 'active') return { color: 'success', text: '有效' };
|
||||
if (status === 'expiring') return { color: 'warning', text: '即将过期' };
|
||||
if (status === 'expired') return { color: 'error', text: '已过期' };
|
||||
if (status === 'dev-disabled') return { color: 'default', text: '开发模式(未强制校验)' };
|
||||
if (status === 'inactive') return { color: 'default', text: '未激活' };
|
||||
return { color: 'default', text: status || '未知' };
|
||||
});
|
||||
|
||||
const editionLabel: Record<string, string> = {
|
||||
trial: '试用版',
|
||||
enterprise: '企业版',
|
||||
unlimited: '无限版',
|
||||
};
|
||||
|
||||
const hasLicense = computed(() =>
|
||||
Boolean(license.value?.companyName || license.value?.edition),
|
||||
);
|
||||
|
||||
async function loadLicense() {
|
||||
loading.value = true;
|
||||
try {
|
||||
license.value = await getLicenseInfoApi();
|
||||
} catch (error: any) {
|
||||
license.value = { status: 'inactive', features: [] };
|
||||
message.error(error?.message || '获取授权信息失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFingerprint() {
|
||||
fingerprintLoading.value = true;
|
||||
try {
|
||||
fingerprint.value = await getSystemFingerprintApi();
|
||||
} catch (error: any) {
|
||||
fingerprint.value = null;
|
||||
message.error(error?.message || '获取机器指纹失败');
|
||||
} finally {
|
||||
fingerprintLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleActivate() {
|
||||
if (!licenseKey.value.trim()) {
|
||||
message.warning('请输入 License Key');
|
||||
return;
|
||||
}
|
||||
submitting.value = true;
|
||||
const hide = message.loading('正在提交授权...', 0);
|
||||
try {
|
||||
license.value = await activateLicenseApi({
|
||||
licenseKey: licenseKey.value.trim(),
|
||||
});
|
||||
licenseKey.value = '';
|
||||
message.success('授权提交成功');
|
||||
} finally {
|
||||
hide();
|
||||
submitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value?: string) {
|
||||
return value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '-';
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadLicense();
|
||||
loadFingerprint();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="授权管理" description="查看机器指纹,激活或更新 License">
|
||||
<div class="grid gap-4 lg:grid-cols-2">
|
||||
<Card title="机器指纹" :loading="fingerprintLoading">
|
||||
<FingerprintDisplay
|
||||
v-if="fingerprint"
|
||||
:fingerprint="fingerprint.fingerprint"
|
||||
:hostname="fingerprint.hostname"
|
||||
:machine-id="fingerprint.machineId"
|
||||
/>
|
||||
<Typography.Text v-else type="secondary">
|
||||
暂无指纹信息
|
||||
</Typography.Text>
|
||||
<Button class="mt-4" size="small" @click="loadFingerprint">
|
||||
刷新指纹
|
||||
</Button>
|
||||
</Card>
|
||||
|
||||
<Card :title="hasLicense ? '更新授权' : '激活授权'">
|
||||
<Typography.Paragraph type="secondary" class="text-sm">
|
||||
将上方机器指纹提供给运营方,获取 License 后粘贴到下方完成激活或续期。
|
||||
</Typography.Paragraph>
|
||||
<Form layout="vertical" @finish="handleActivate">
|
||||
<Form.Item label="License Key" required>
|
||||
<Input.TextArea
|
||||
v-model:value="licenseKey"
|
||||
:rows="6"
|
||||
placeholder="粘贴运营方签发的 License JWT"
|
||||
class="font-mono text-xs"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button type="primary" html-type="submit" :loading="submitting">
|
||||
{{ hasLicense ? '更新 License' : '激活 License' }}
|
||||
</Button>
|
||||
</Form>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card class="mt-4" title="当前授权信息" :loading="loading">
|
||||
<template v-if="hasLicense">
|
||||
<Descriptions :column="2" bordered size="small">
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag :color="statusTag.color">{{ statusTag.text }}</Tag>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="授权公司">
|
||||
{{ license?.companyName || '-' }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="版本">
|
||||
{{
|
||||
editionLabel[license?.edition || ''] || license?.edition || '-'
|
||||
}}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="公司上限">
|
||||
{{ license?.maxCompanies ?? '-' }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="授权指纹" :span="2">
|
||||
<Typography.Text code class="text-xs break-all">
|
||||
{{ license?.machineFingerprint || '-' }}
|
||||
</Typography.Text>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="授权功能" :span="2">
|
||||
<Space wrap>
|
||||
<Tag v-for="f in license?.features" :key="f">{{ f }}</Tag>
|
||||
<span v-if="!license?.features?.length">-</span>
|
||||
</Space>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="签发时间">
|
||||
{{ formatDate(license?.issuedAt) }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="过期时间">
|
||||
{{ formatDate(license?.expiresAt) }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item
|
||||
v-if="license?.daysRemaining != null"
|
||||
label="剩余天数"
|
||||
>
|
||||
{{ license.daysRemaining }} 天
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</template>
|
||||
<Typography.Text v-else type="secondary">
|
||||
{{
|
||||
license?.status === 'dev-disabled'
|
||||
? '当前为开发模式,尚未强制校验 License。仍可在此激活以便生产切换。'
|
||||
: '尚未激活 License,请先获取机器指纹并完成授权。'
|
||||
}}
|
||||
</Typography.Text>
|
||||
<Button class="mt-4" size="small" @click="loadLicense">刷新</Button>
|
||||
</Card>
|
||||
</Page>
|
||||
</template>
|
||||
@@ -0,0 +1,429 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
|
||||
import { IconifyIcon } from '@vben/icons';
|
||||
import { useDebounceFn } from '@vueuse/core';
|
||||
|
||||
import { Input, Select, Spin } from 'ant-design-vue';
|
||||
|
||||
interface Props {
|
||||
modelValue?: string;
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
(e: 'update:modelValue', value: string): void;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
const emit = defineEmits<Emits>();
|
||||
|
||||
const ICONIFY = 'https://api.iconify.design';
|
||||
|
||||
const GLOBAL_PREFIX = '__global__';
|
||||
|
||||
/** 常用图标集(Iconify prefix),可继续扩充 */
|
||||
const COLLECTION_OPTIONS = [
|
||||
{
|
||||
label: '全局搜索(不限图标集,仅关键词)',
|
||||
value: GLOBAL_PREFIX,
|
||||
},
|
||||
{ label: 'Lucide', value: 'lucide' },
|
||||
{ label: 'Material Design Icons', value: 'mdi' },
|
||||
{ label: 'Carbon', value: 'carbon' },
|
||||
{ label: 'Tabler', value: 'tabler' },
|
||||
{ label: 'Phosphor', value: 'ph' },
|
||||
{ label: 'Remix Icon', value: 'ri' },
|
||||
{ label: 'Heroicons', value: 'heroicons' },
|
||||
{ label: 'Material Symbols', value: 'material-symbols' },
|
||||
{ label: 'Ant Design Icons', value: 'ant-design' },
|
||||
{ label: 'Bootstrap Icons', value: 'bi' },
|
||||
{ label: 'MingCute', value: 'mingcute' },
|
||||
{ label: 'Logos', value: 'logos' },
|
||||
{ label: 'Simple Icons', value: 'simple-icons' },
|
||||
{ label: 'Font Awesome 6', value: 'fa6-solid' },
|
||||
{ label: 'Iconoir', value: 'iconoir' },
|
||||
];
|
||||
|
||||
const searchKeyword = ref('');
|
||||
const selectedCollection = ref('lucide');
|
||||
const selectedIcon = ref(props.modelValue || '');
|
||||
const currentPage = ref(1);
|
||||
const pageSize = 36;
|
||||
|
||||
const browseFlat = ref<string[]>([]);
|
||||
const searchResultIcons = ref<string[]>([]);
|
||||
const loading = ref(false);
|
||||
const loadError = ref('');
|
||||
|
||||
const collectionCache = new Map<string, string[]>();
|
||||
|
||||
function flattenCollectionBody(
|
||||
prefix: string,
|
||||
data: {
|
||||
uncategorized?: string[];
|
||||
categories?: Record<string, string[]>;
|
||||
},
|
||||
): string[] {
|
||||
const set = new Set<string>();
|
||||
for (const n of data.uncategorized || []) {
|
||||
set.add(`${prefix}:${n}`);
|
||||
}
|
||||
if (data.categories) {
|
||||
for (const arr of Object.values(data.categories)) {
|
||||
for (const n of arr) {
|
||||
set.add(`${prefix}:${n}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...set].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
async function fetchCollectionIcons(prefix: string): Promise<string[]> {
|
||||
const hit = collectionCache.get(prefix);
|
||||
if (hit) {
|
||||
return hit;
|
||||
}
|
||||
const res = await fetch(
|
||||
`${ICONIFY}/collection?prefix=${encodeURIComponent(prefix)}`,
|
||||
);
|
||||
if (!res.ok) {
|
||||
throw new Error(`Iconify collection ${res.status}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
const list = flattenCollectionBody(prefix, data);
|
||||
collectionCache.set(prefix, list);
|
||||
return list;
|
||||
}
|
||||
|
||||
const isGlobalMode = computed(
|
||||
() => selectedCollection.value === GLOBAL_PREFIX,
|
||||
);
|
||||
|
||||
async function refreshIcons() {
|
||||
const q = searchKeyword.value.trim();
|
||||
const prefix = selectedCollection.value;
|
||||
loading.value = true;
|
||||
loadError.value = '';
|
||||
try {
|
||||
if (q) {
|
||||
let url = `${ICONIFY}/search?query=${encodeURIComponent(q)}&limit=400`;
|
||||
if (!isGlobalMode.value) {
|
||||
url += `&prefix=${encodeURIComponent(prefix)}`;
|
||||
}
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) {
|
||||
throw new Error(`Iconify search ${res.status}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
searchResultIcons.value = Array.isArray(data.icons) ? data.icons : [];
|
||||
} else {
|
||||
searchResultIcons.value = [];
|
||||
if (isGlobalMode.value) {
|
||||
browseFlat.value = [];
|
||||
} else {
|
||||
browseFlat.value = await fetchCollectionIcons(prefix);
|
||||
}
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
loadError.value = e instanceof Error ? e.message : '加载失败';
|
||||
browseFlat.value = [];
|
||||
searchResultIcons.value = [];
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const debouncedRefresh = useDebounceFn(refreshIcons, 320);
|
||||
|
||||
const activeSource = computed(() => {
|
||||
return searchKeyword.value.trim()
|
||||
? searchResultIcons.value
|
||||
: browseFlat.value;
|
||||
});
|
||||
|
||||
const displayedIconNames = computed(() => {
|
||||
const source = activeSource.value;
|
||||
const start = (currentPage.value - 1) * pageSize;
|
||||
return source.slice(start, start + pageSize);
|
||||
});
|
||||
|
||||
const totalPages = computed(() => {
|
||||
const n = activeSource.value.length;
|
||||
return Math.max(1, Math.ceil(n / pageSize));
|
||||
});
|
||||
|
||||
const visiblePages = computed(() => {
|
||||
const pages: number[] = [];
|
||||
const total = totalPages.value;
|
||||
const current = currentPage.value;
|
||||
|
||||
if (total <= 7) {
|
||||
for (let i = 1; i <= total; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else if (current <= 4) {
|
||||
for (let i = 1; i <= 5; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else if (current >= total - 3) {
|
||||
for (let i = total - 4; i <= total; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
for (let i = current - 2; i <= current + 2; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
return pages;
|
||||
});
|
||||
|
||||
const showEllipsis = computed(() => {
|
||||
return (
|
||||
totalPages.value > 7 &&
|
||||
currentPage.value > 4 &&
|
||||
currentPage.value < totalPages.value - 3
|
||||
);
|
||||
});
|
||||
|
||||
const selectIcon = (iconName: string) => {
|
||||
selectedIcon.value = iconName;
|
||||
emit('update:modelValue', iconName);
|
||||
};
|
||||
|
||||
const goToPage = (page: number) => {
|
||||
if (page >= 1 && page <= totalPages.value) {
|
||||
currentPage.value = page;
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(newVal) => {
|
||||
selectedIcon.value = newVal || '';
|
||||
},
|
||||
);
|
||||
|
||||
watch(selectedCollection, () => {
|
||||
currentPage.value = 1;
|
||||
debouncedRefresh();
|
||||
});
|
||||
|
||||
watch(searchKeyword, () => {
|
||||
currentPage.value = 1;
|
||||
debouncedRefresh();
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
void refreshIcons();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="icon-selector">
|
||||
<div class="mb-2 flex flex-col gap-2 px-2">
|
||||
<Select
|
||||
v-model:value="selectedCollection"
|
||||
:options="COLLECTION_OPTIONS"
|
||||
class="w-full"
|
||||
placeholder="图标集"
|
||||
/>
|
||||
<Input
|
||||
v-model:value="searchKeyword"
|
||||
placeholder="搜索图标(留空则浏览当前图标集)"
|
||||
allow-clear
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Spin :spinning="loading">
|
||||
<div
|
||||
v-if="loadError"
|
||||
class="text-destructive px-2 py-4 text-center text-sm"
|
||||
>
|
||||
{{ loadError }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="
|
||||
!searchKeyword.trim() &&
|
||||
isGlobalMode &&
|
||||
displayedIconNames.length === 0
|
||||
"
|
||||
class="text-muted-foreground px-2 py-8 text-center text-sm"
|
||||
>
|
||||
「全局搜索」模式下请在上框输入关键词;或切换到具体图标集以分页浏览。
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="grid max-h-[360px] w-full grid-cols-6 justify-items-center overflow-y-auto"
|
||||
>
|
||||
<button
|
||||
v-for="name in displayedIconNames"
|
||||
:key="name"
|
||||
type="button"
|
||||
class="focus-visible:ring-ring hover:bg-accent hover:text-accent-foreground text-foreground/80 inline-flex h-8 w-8 items-center justify-center whitespace-nowrap rounded-full px-1 text-lg font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:class="{
|
||||
'bg-primary text-primary-foreground': selectedIcon === name,
|
||||
}"
|
||||
:title="name"
|
||||
@click="selectIcon(name)"
|
||||
>
|
||||
<IconifyIcon :icon="name" class="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</Spin>
|
||||
|
||||
<div
|
||||
class="flex-center flex justify-end overflow-hidden border-t py-2 pr-3"
|
||||
>
|
||||
<nav size="small">
|
||||
<div class="flex w-full items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="currentPage === 1"
|
||||
@click="goToPage(1)"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="lucide lucide-chevrons-left size-4"
|
||||
>
|
||||
<path d="m11 17-5-5 5-5" />
|
||||
<path d="m18 17-5-5 5-5" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="currentPage === 1"
|
||||
@click="goToPage(currentPage - 1)"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="lucide lucide-chevron-left size-4"
|
||||
>
|
||||
<path d="m15 18-6-6 6-6" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<template v-for="page in visiblePages" :key="page">
|
||||
<button
|
||||
type="button"
|
||||
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-xs font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:class="{
|
||||
'bg-primary text-primary-foreground': currentPage === page,
|
||||
}"
|
||||
@click="goToPage(page)"
|
||||
>
|
||||
{{ page }}
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<div
|
||||
v-if="showEllipsis"
|
||||
class="flex size-5 items-center justify-center"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="lucide lucide-ellipsis size-4"
|
||||
>
|
||||
<circle cx="12" cy="12" r="1" />
|
||||
<circle cx="19" cy="12" r="1" />
|
||||
<circle cx="5" cy="12" r="1" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="currentPage === totalPages"
|
||||
@click="goToPage(currentPage + 1)"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="lucide lucide-chevron-right size-4"
|
||||
>
|
||||
<path d="m9 18 6-6-6-6" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="focus-visible:ring-ring border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex size-5 items-center justify-center whitespace-nowrap rounded-md border p-0 text-sm font-medium shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="currentPage === totalPages"
|
||||
@click="goToPage(totalPages)"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="lucide lucide-chevrons-right size-4"
|
||||
>
|
||||
<path d="m6 17 5-5-5-5" />
|
||||
<path d="m13 17 5-5-5-5" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.icon-selector {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
button {
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
button:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,709 @@
|
||||
<script setup lang="ts">
|
||||
import type { MenuVO } from '#/api/system/menu/types';
|
||||
import type { PermissionVO } from '#/api/system/permission/types';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
import { createIconifyIcon, IconifyIcon } from '@vben/icons';
|
||||
|
||||
import {
|
||||
Cascader,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
message,
|
||||
Popover,
|
||||
Radio,
|
||||
Switch,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createMenuApi,
|
||||
getAllMenusApi,
|
||||
getMenuDetailApi,
|
||||
updateMenuApi,
|
||||
} from '#/api/system/menu';
|
||||
import {
|
||||
addMenuPermissionApi,
|
||||
removeMenuPermissionApi,
|
||||
} from '#/api/system/menu-permission';
|
||||
import { getPermissionTreeApi } from '#/api/system/permission';
|
||||
|
||||
import IconSelector from './IconSelector.vue';
|
||||
|
||||
type MenuFormSuccessPayload =
|
||||
| { mode: 'update'; menu: MenuVO.MenuInfo }
|
||||
| { mode: 'create' };
|
||||
|
||||
const emit = defineEmits<{
|
||||
cancel: [];
|
||||
success: [payload?: MenuFormSuccessPayload];
|
||||
}>();
|
||||
|
||||
// 创建Vben Modal实例
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
title: '菜单管理',
|
||||
draggable: true, // 开启拖拽
|
||||
contentClass: 'px-6 py-4', // 使用Tailwind CSS设置内边距
|
||||
onConfirm: handleSubmit,
|
||||
onCancel: close,
|
||||
onOpenChange: (isOpen: boolean) => {
|
||||
if (isOpen) {
|
||||
fetchParentMenuOptions();
|
||||
fetchPermissionOptions();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// 响应式数据
|
||||
const isEdit = ref(false);
|
||||
const currentRecord = ref<MenuVO.MenuInfo | null>(null);
|
||||
const formRef = ref();
|
||||
|
||||
// 内部表单数据类型
|
||||
interface FormData {
|
||||
parentId?: number;
|
||||
superMenu: boolean;
|
||||
name: string;
|
||||
title: string;
|
||||
path: string;
|
||||
component: string;
|
||||
redirect: string;
|
||||
icon: string;
|
||||
order: number;
|
||||
type: string;
|
||||
visible: boolean;
|
||||
status: boolean;
|
||||
keepAlive: boolean;
|
||||
}
|
||||
|
||||
// 表单数据
|
||||
const formData = ref<FormData>({
|
||||
parentId: undefined,
|
||||
superMenu: false,
|
||||
name: '',
|
||||
title: '',
|
||||
path: '',
|
||||
component: '',
|
||||
redirect: '',
|
||||
icon: '',
|
||||
order: 0,
|
||||
type: 'menu',
|
||||
visible: true,
|
||||
status: true,
|
||||
keepAlive: false,
|
||||
});
|
||||
|
||||
interface MenuCascaderOption {
|
||||
value: number;
|
||||
label: string;
|
||||
disabled?: boolean;
|
||||
children?: MenuCascaderOption[];
|
||||
}
|
||||
|
||||
/** 父菜单级联选项(树) */
|
||||
const parentMenuTreeOptions = ref<MenuCascaderOption[]>([]);
|
||||
/** 级联选中路径,与 formData.parentId(末级 id)同步 */
|
||||
const parentMenuPath = ref<number[]>([]);
|
||||
/** 权限树(级联多选) */
|
||||
const permissionTreeOptions = ref<MenuCascaderOption[]>([]);
|
||||
/** 多选级联:每项为从根到选中节点的一条路径 */
|
||||
const permissionPaths = ref<number[][]>([]);
|
||||
const selectedPermissions = ref<number[]>([]);
|
||||
const originalPermissions = ref<number[]>([]);
|
||||
|
||||
/** 无图标时占位,点击仍打开选择器 */
|
||||
const GridIcon = createIconifyIcon('lucide:grid-3x3');
|
||||
|
||||
/** 编辑中不能选自己及子孙为父 */
|
||||
function collectExcludedMenuIdsForParent(
|
||||
flat: MenuVO.MenuInfo[],
|
||||
editingId?: number,
|
||||
): Set<number> {
|
||||
if (editingId == null) {
|
||||
return new Set();
|
||||
}
|
||||
const excluded = new Set<number>([editingId]);
|
||||
const childrenByParent = new Map<number, number[]>();
|
||||
for (const m of flat) {
|
||||
const p = m.parentId;
|
||||
if (p == null || p === undefined || Number(p) === 0) {
|
||||
continue;
|
||||
}
|
||||
const pk = Number(p);
|
||||
if (!childrenByParent.has(pk)) {
|
||||
childrenByParent.set(pk, []);
|
||||
}
|
||||
childrenByParent.get(pk)!.push(m.id);
|
||||
}
|
||||
const stack = [...(childrenByParent.get(editingId) || [])];
|
||||
while (stack.length) {
|
||||
const id = stack.pop()!;
|
||||
if (excluded.has(id)) {
|
||||
continue;
|
||||
}
|
||||
excluded.add(id);
|
||||
stack.push(...(childrenByParent.get(id) || []));
|
||||
}
|
||||
return excluded;
|
||||
}
|
||||
|
||||
function buildMenuCascaderOptions(
|
||||
flat: MenuVO.MenuInfo[],
|
||||
excludeIds: Set<number>,
|
||||
): MenuCascaderOption[] {
|
||||
const visible = flat.filter((m) => !excludeIds.has(m.id));
|
||||
const visibleIds = new Set(visible.map((m) => m.id));
|
||||
|
||||
type BuildNode = { menu: MenuVO.MenuInfo; children: BuildNode[] };
|
||||
const nodeById = new Map<number, BuildNode>();
|
||||
for (const m of visible) {
|
||||
nodeById.set(m.id, { menu: m, children: [] });
|
||||
}
|
||||
const roots: BuildNode[] = [];
|
||||
for (const m of visible) {
|
||||
const node = nodeById.get(m.id)!;
|
||||
const p = m.parentId;
|
||||
const hasValidParent =
|
||||
p != null && p !== undefined && Number(p) !== 0 && visibleIds.has(Number(p));
|
||||
if (hasValidParent) {
|
||||
nodeById.get(Number(p))!.children.push(node);
|
||||
} else {
|
||||
roots.push(node);
|
||||
}
|
||||
}
|
||||
const sortNodes = (arr: BuildNode[]) =>
|
||||
arr.sort((a, b) => (a.menu.order ?? 0) - (b.menu.order ?? 0));
|
||||
function toOptions(nodes: BuildNode[]): MenuCascaderOption[] {
|
||||
sortNodes(nodes);
|
||||
return nodes.map(({ menu, children }) => {
|
||||
sortNodes(children);
|
||||
const sub = toOptions(children);
|
||||
return {
|
||||
value: menu.id,
|
||||
label: menu.title || menu.name,
|
||||
children: sub.length ? sub : undefined,
|
||||
};
|
||||
});
|
||||
}
|
||||
sortNodes(roots);
|
||||
return toOptions(roots);
|
||||
}
|
||||
|
||||
function findMenuPathById(
|
||||
options: MenuCascaderOption[],
|
||||
menuId: number,
|
||||
currentPath: number[] = [],
|
||||
): null | number[] {
|
||||
for (const option of options) {
|
||||
const nextPath = [...currentPath, option.value];
|
||||
if (option.value === menuId) {
|
||||
return nextPath;
|
||||
}
|
||||
if (option.children?.length) {
|
||||
const found = findMenuPathById(option.children, menuId, nextPath);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function syncParentMenuPath() {
|
||||
const pid = formData.value.parentId;
|
||||
if (pid == null || pid === undefined) {
|
||||
parentMenuPath.value = [];
|
||||
return;
|
||||
}
|
||||
const path = findMenuPathById(parentMenuTreeOptions.value, Number(pid));
|
||||
parentMenuPath.value = path ?? [];
|
||||
}
|
||||
|
||||
function onParentMenuCascaderChange(value: unknown) {
|
||||
const arr = Array.isArray(value)
|
||||
? (value as unknown[])
|
||||
.map((v) => Number(v))
|
||||
.filter((n) => Number.isFinite(n) && n > 0)
|
||||
: [];
|
||||
parentMenuPath.value = arr;
|
||||
formData.value.parentId = arr.length ? arr[arr.length - 1] : undefined;
|
||||
}
|
||||
|
||||
// 获取父菜单选项(扁平列表建树,供级联)
|
||||
async function fetchParentMenuOptions() {
|
||||
try {
|
||||
const data = await getAllMenusApi();
|
||||
const editingId = isEdit.value ? currentRecord.value?.id : undefined;
|
||||
const exclude = collectExcludedMenuIdsForParent(data, editingId);
|
||||
parentMenuTreeOptions.value = buildMenuCascaderOptions(data, exclude);
|
||||
syncParentMenuPath();
|
||||
} catch (error) {
|
||||
console.error('获取菜单列表失败:', error);
|
||||
parentMenuTreeOptions.value = [];
|
||||
parentMenuPath.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
function mapPermissionTreeToCascaderOptions(
|
||||
nodes: PermissionVO.PermissionInfoVO[] | undefined,
|
||||
): MenuCascaderOption[] {
|
||||
if (!nodes?.length) {
|
||||
return [];
|
||||
}
|
||||
return [...nodes]
|
||||
.sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
|
||||
.map((p) => {
|
||||
const children = mapPermissionTreeToCascaderOptions(p.children);
|
||||
return {
|
||||
value: p.id,
|
||||
label: p.name,
|
||||
disabled: p.status !== 1,
|
||||
children: children.length ? children : undefined,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function syncSelectedPermissionsFromPaths() {
|
||||
const ids = new Set<number>();
|
||||
for (const path of permissionPaths.value) {
|
||||
if (path.length) {
|
||||
ids.add(path[path.length - 1]!);
|
||||
}
|
||||
}
|
||||
selectedPermissions.value = [...ids];
|
||||
}
|
||||
|
||||
function syncPermissionPathsFromIds() {
|
||||
const opts = permissionTreeOptions.value;
|
||||
const ids = selectedPermissions.value;
|
||||
if (!opts.length || !ids.length) {
|
||||
permissionPaths.value = [];
|
||||
return;
|
||||
}
|
||||
const paths: number[][] = [];
|
||||
for (const id of ids) {
|
||||
const path = findMenuPathById(opts, id);
|
||||
if (path?.length) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
permissionPaths.value = paths;
|
||||
}
|
||||
|
||||
function coerceMultipleCascaderPaths(val: unknown): number[][] {
|
||||
if (!Array.isArray(val)) {
|
||||
return [];
|
||||
}
|
||||
return (val as unknown[])
|
||||
.map((item) => {
|
||||
if (!Array.isArray(item)) {
|
||||
return [];
|
||||
}
|
||||
return item
|
||||
.map((x) => Number(x))
|
||||
.filter((n) => Number.isFinite(n) && n > 0);
|
||||
})
|
||||
.filter((p) => p.length > 0);
|
||||
}
|
||||
|
||||
function onPermissionPathsUpdate(val: unknown) {
|
||||
permissionPaths.value = coerceMultipleCascaderPaths(val);
|
||||
syncSelectedPermissionsFromPaths();
|
||||
}
|
||||
|
||||
// 获取权限选项(树形接口 → 级联多选)
|
||||
async function fetchPermissionOptions() {
|
||||
try {
|
||||
const data = await getPermissionTreeApi();
|
||||
permissionTreeOptions.value = mapPermissionTreeToCascaderOptions(data);
|
||||
syncPermissionPathsFromIds();
|
||||
} catch (error) {
|
||||
console.error('获取权限树失败:', error);
|
||||
permissionTreeOptions.value = [];
|
||||
permissionPaths.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
// 打开模态框
|
||||
function open(edit: boolean, record?: MenuVO.MenuInfo) {
|
||||
isEdit.value = edit;
|
||||
currentRecord.value = record || null;
|
||||
|
||||
// 更新模态框标题
|
||||
modalApi.setState({
|
||||
title: edit ? '编辑菜单' : '添加菜单',
|
||||
});
|
||||
|
||||
modalApi.open();
|
||||
|
||||
if (edit && record) {
|
||||
// 编辑模式,填充表单数据
|
||||
formData.value = {
|
||||
parentId: record.parentId || undefined,
|
||||
superMenu: record.superMenu === 1, // 转换为boolean
|
||||
name: record.name,
|
||||
title: record.title || '',
|
||||
path: record.path || '',
|
||||
component: record.component || '',
|
||||
redirect: record.redirect || '',
|
||||
icon: record.icon || '',
|
||||
order: record.order || 0,
|
||||
type: record.type,
|
||||
visible: record.visible === 1, // 转换为boolean
|
||||
status: record.status === 1, // 转换为boolean
|
||||
keepAlive: record.keepAlive === 1, // 转换为boolean
|
||||
};
|
||||
|
||||
// 设置权限数据
|
||||
if ((record as any).permissions && (record as any).permissions.length > 0) {
|
||||
selectedPermissions.value = (record as any).permissions.map(
|
||||
(p: any) => p.id,
|
||||
);
|
||||
originalPermissions.value = [...selectedPermissions.value];
|
||||
} else {
|
||||
selectedPermissions.value = [];
|
||||
originalPermissions.value = [];
|
||||
}
|
||||
} else if (!edit && record) {
|
||||
// 添加下级菜单模式,自动选中父菜单
|
||||
formData.value = {
|
||||
parentId: record.id, // 自动设置为当前菜单的ID作为父菜单
|
||||
superMenu: false,
|
||||
name: '',
|
||||
title: '',
|
||||
path: '',
|
||||
component: '',
|
||||
redirect: '',
|
||||
icon: '',
|
||||
order: 0,
|
||||
type: 'menu',
|
||||
visible: true,
|
||||
status: true,
|
||||
keepAlive: false,
|
||||
};
|
||||
} else {
|
||||
// 新增根菜单模式,重置表单
|
||||
formData.value = {
|
||||
parentId: undefined,
|
||||
superMenu: false,
|
||||
name: '',
|
||||
title: '',
|
||||
path: '',
|
||||
component: '',
|
||||
redirect: '',
|
||||
icon: '',
|
||||
order: 0,
|
||||
type: 'menu',
|
||||
visible: true,
|
||||
status: true,
|
||||
keepAlive: false,
|
||||
};
|
||||
|
||||
// 重置权限数据
|
||||
selectedPermissions.value = [];
|
||||
originalPermissions.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭模态框
|
||||
function close() {
|
||||
modalApi.close();
|
||||
formRef.value?.resetFields();
|
||||
parentMenuPath.value = [];
|
||||
parentMenuTreeOptions.value = [];
|
||||
permissionPaths.value = [];
|
||||
permissionTreeOptions.value = [];
|
||||
selectedPermissions.value = [];
|
||||
originalPermissions.value = [];
|
||||
emit('cancel');
|
||||
}
|
||||
|
||||
// 处理权限变更
|
||||
async function handlePermissionChange() {
|
||||
if (!currentRecord.value) return;
|
||||
|
||||
const menuId = currentRecord.value.id;
|
||||
const currentPermissions = selectedPermissions.value;
|
||||
const originalPermissionsList = originalPermissions.value;
|
||||
|
||||
// 找出新增的权限
|
||||
const addedPermissions = currentPermissions.filter(
|
||||
(id) => !originalPermissionsList.includes(id),
|
||||
);
|
||||
|
||||
// 找出移除的权限
|
||||
const removedPermissions = originalPermissionsList.filter(
|
||||
(id) => !currentPermissions.includes(id),
|
||||
);
|
||||
|
||||
try {
|
||||
// 添加新权限
|
||||
for (const permissionId of addedPermissions) {
|
||||
await addMenuPermissionApi({
|
||||
menuId,
|
||||
permissionId,
|
||||
});
|
||||
}
|
||||
|
||||
// 移除权限
|
||||
for (const permissionId of removedPermissions) {
|
||||
await removeMenuPermissionApi({
|
||||
menuId,
|
||||
permissionId,
|
||||
});
|
||||
}
|
||||
|
||||
// 更新原始权限列表
|
||||
originalPermissions.value = [...currentPermissions];
|
||||
|
||||
if (addedPermissions.length > 0 || removedPermissions.length > 0) {
|
||||
message.success('权限更新成功');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('权限更新失败:', error);
|
||||
message.error('权限更新失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 提交表单
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
await formRef.value?.validate();
|
||||
|
||||
// 设置模态框为loading状态
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
|
||||
// 转换boolean值为number值
|
||||
const submitData = {
|
||||
...formData.value,
|
||||
superMenu: formData.value.superMenu ? 1 : 0,
|
||||
visible: formData.value.visible ? 1 : 0,
|
||||
status: formData.value.status ? 1 : 0,
|
||||
keepAlive: formData.value.keepAlive ? 1 : 0,
|
||||
};
|
||||
|
||||
if (isEdit.value && currentRecord.value) {
|
||||
const menuId = currentRecord.value.id;
|
||||
await updateMenuApi(menuId, submitData);
|
||||
message.success('更新菜单成功');
|
||||
|
||||
// 处理权限变更
|
||||
await handlePermissionChange();
|
||||
|
||||
// 详情含最新权限,供列表行就地合并,避免整表 reload 导致树折叠
|
||||
const menu = await getMenuDetailApi(menuId);
|
||||
emit('success', { mode: 'update', menu });
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
// 创建菜单(结构变化多,仍整表刷新)
|
||||
const newMenu = await createMenuApi(submitData);
|
||||
message.success('创建菜单成功');
|
||||
|
||||
if (selectedPermissions.value.length > 0 && newMenu?.id) {
|
||||
for (const permissionId of selectedPermissions.value) {
|
||||
await addMenuPermissionApi({
|
||||
menuId: newMenu.id,
|
||||
permissionId,
|
||||
});
|
||||
}
|
||||
message.success('权限分配成功');
|
||||
}
|
||||
|
||||
emit('success', { mode: 'create' });
|
||||
close();
|
||||
} catch (error) {
|
||||
console.error('提交菜单失败:', error);
|
||||
message.error('提交菜单失败');
|
||||
} finally {
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
}
|
||||
}
|
||||
|
||||
// 暴露方法
|
||||
defineExpose({
|
||||
open,
|
||||
close,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal>
|
||||
<Form
|
||||
ref="formRef"
|
||||
:model="formData"
|
||||
:label-col="{ span: 6 }"
|
||||
:wrapper-col="{ span: 18 }"
|
||||
class="space-y-5"
|
||||
>
|
||||
<Form.Item
|
||||
label="菜单类型"
|
||||
name="type"
|
||||
:rules="[{ required: true, message: '请选择菜单类型' }]"
|
||||
>
|
||||
<Radio.Group
|
||||
v-model:value="formData.type"
|
||||
button-style="solid"
|
||||
class="w-full"
|
||||
>
|
||||
<Radio.Button value="catalog" class="flex-1">目录</Radio.Button>
|
||||
<Radio.Button value="menu" class="flex-1">菜单</Radio.Button>
|
||||
<Radio.Button value="button" class="flex-1">按钮</Radio.Button>
|
||||
<Radio.Button value="embedded" class="flex-1">内联</Radio.Button>
|
||||
<Radio.Button value="link" class="flex-1">外链</Radio.Button>
|
||||
</Radio.Group>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="父菜单" name="parentId">
|
||||
<Cascader
|
||||
:value="parentMenuPath"
|
||||
:options="parentMenuTreeOptions"
|
||||
allow-clear
|
||||
change-on-select
|
||||
class="w-full"
|
||||
expand-trigger="hover"
|
||||
placeholder="请选择父菜单(任意层级可选)"
|
||||
:field-names="{
|
||||
label: 'label',
|
||||
value: 'value',
|
||||
children: 'children',
|
||||
}"
|
||||
@change="onParentMenuCascaderChange"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="权限列表" name="permissions">
|
||||
<Cascader
|
||||
:value="permissionPaths"
|
||||
:options="permissionTreeOptions"
|
||||
allow-clear
|
||||
change-on-select
|
||||
class="w-full"
|
||||
expand-trigger="hover"
|
||||
max-tag-count="responsive"
|
||||
multiple
|
||||
placeholder="请选择权限(任意层级可选,可多选)"
|
||||
show-search
|
||||
:field-names="{
|
||||
label: 'label',
|
||||
value: 'value',
|
||||
children: 'children',
|
||||
}"
|
||||
@update:value="onPermissionPathsUpdate"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="菜单名称"
|
||||
name="name"
|
||||
:rules="[{ required: true, message: '请输入菜单名称' }]"
|
||||
>
|
||||
<Input v-model:value="formData.name" placeholder="请输入菜单名称" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="菜单标题" name="title">
|
||||
<Input v-model:value="formData.title" placeholder="请输入菜单标题" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="路由路径" name="path">
|
||||
<Input v-model:value="formData.path" placeholder="请输入路由路径" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="页面组件" name="component">
|
||||
<Input
|
||||
v-model:value="formData.component"
|
||||
placeholder="请输入页面组件"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="重定向地址" name="redirect">
|
||||
<Input
|
||||
v-model:value="formData.redirect"
|
||||
placeholder="请输入重定向地址"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 外层只负责标签;name 仅绑在触发 Input 上,避免 Popover 浮层内控件被同一 Form.Item 收集导致 FormItemContext 刷屏 -->
|
||||
<Form.Item label="路由图标">
|
||||
<Popover
|
||||
placement="bottomRight"
|
||||
trigger="click"
|
||||
overlay-class-name="icon-selector-popover"
|
||||
>
|
||||
<template #content>
|
||||
<IconSelector v-model="formData.icon" />
|
||||
</template>
|
||||
<!-- Popover Trigger 需要落在真实 DOM 上;no-style 的 Form.Item 常无包裹节点,会导致点击无响应 -->
|
||||
<div class="w-full">
|
||||
<Form.Item name="icon" no-style>
|
||||
<Input
|
||||
v-model:value="formData.icon"
|
||||
placeholder="点击选择或查看 Iconify 图标名"
|
||||
readonly
|
||||
style="cursor: pointer"
|
||||
>
|
||||
<template #prefix>
|
||||
<span class="inline-flex items-center pr-1">
|
||||
<IconifyIcon
|
||||
v-if="formData.icon"
|
||||
:icon="formData.icon"
|
||||
class="size-4 shrink-0 text-foreground"
|
||||
/>
|
||||
<GridIcon v-else class="size-4 shrink-0 opacity-40" />
|
||||
</span>
|
||||
</template>
|
||||
</Input>
|
||||
</Form.Item>
|
||||
</div>
|
||||
</Popover>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="排序" name="order">
|
||||
<InputNumber
|
||||
v-model:value="formData.order"
|
||||
placeholder="请输入排序"
|
||||
:min="0"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="是否显示" name="visible">
|
||||
<Switch
|
||||
v-model:checked="formData.visible"
|
||||
checked-children="显示"
|
||||
un-checked-children="隐藏"
|
||||
class="w-12"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="状态" name="status">
|
||||
<Switch
|
||||
v-model:checked="formData.status"
|
||||
checked-children="启用"
|
||||
un-checked-children="禁用"
|
||||
class="w-12"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="是否缓存" name="keepAlive">
|
||||
<Switch
|
||||
v-model:checked="formData.keepAlive"
|
||||
checked-children="缓存"
|
||||
un-checked-children="不缓存"
|
||||
class="w-12"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="超级菜单" name="superMenu">
|
||||
<Switch
|
||||
v-model:checked="formData.superMenu"
|
||||
checked-children="是"
|
||||
un-checked-children="否"
|
||||
class="w-12"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</template>
|
||||
@@ -0,0 +1,473 @@
|
||||
<script lang="ts" setup>
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { MenuVO } from '#/api/system/menu/types';
|
||||
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon, IconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
batchSortMenuApi,
|
||||
deleteMenuApi,
|
||||
getAllMenusApi,
|
||||
} from '#/api/system/menu';
|
||||
|
||||
import MenuFormModal from './components/MenuFormModal.vue';
|
||||
|
||||
defineOptions({ name: 'MenuManagement' });
|
||||
// 创建图标组件
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
const EditIcon = createIconifyIcon('lucide:edit');
|
||||
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||
const PlusCircleIcon = createIconifyIcon('lucide:plus-circle');
|
||||
const ExpandIcon = createIconifyIcon('lucide:chevrons-down');
|
||||
const CollapseIcon = createIconifyIcon('lucide:chevrons-up');
|
||||
|
||||
// 响应式数据
|
||||
const loading = ref(false);
|
||||
const menuFormModalRef = ref();
|
||||
|
||||
/** 与 proxy query 返回的 `items` 同一数组引用,用于就地更新行,避免依赖 getTableData 结构差异导致误判走 reload */
|
||||
const lastMenuFlatItems = ref<MenuVO.MenuInfo[]>([]);
|
||||
|
||||
function normalizeMenuParentId(v: unknown): number | null {
|
||||
if (v === null || v === undefined) {
|
||||
return null;
|
||||
}
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
function sameMenuParent(a: unknown, b: unknown) {
|
||||
return normalizeMenuParentId(a) === normalizeMenuParentId(b);
|
||||
}
|
||||
|
||||
// VbenVxeGrid 表格配置
|
||||
const gridOptions: VxeGridProps<any> = {
|
||||
columns: [
|
||||
{
|
||||
type: 'seq' as const,
|
||||
minWidth: 60,
|
||||
title: '序号',
|
||||
},
|
||||
{
|
||||
field: 'name',
|
||||
title: '菜单名称',
|
||||
minWidth: 200,
|
||||
showOverflow: 'tooltip' as const,
|
||||
treeNode: true, // 启用树节点显示
|
||||
dragSort: true, // 启用拖拽排序
|
||||
// 移除自定义插槽,让拖拽控件正常显示
|
||||
},
|
||||
{
|
||||
field: 'title',
|
||||
title: '菜单标题',
|
||||
minWidth: 150,
|
||||
showOverflow: 'tooltip' as const,
|
||||
},
|
||||
{
|
||||
field: 'icon',
|
||||
title: '图标',
|
||||
width: 72,
|
||||
align: 'center' as const,
|
||||
slots: { default: 'icon' },
|
||||
},
|
||||
{
|
||||
field: 'path',
|
||||
title: '路由路径',
|
||||
minWidth: 200,
|
||||
showOverflow: 'tooltip' as const,
|
||||
},
|
||||
{
|
||||
field: 'component',
|
||||
title: '页面组件',
|
||||
minWidth: 180,
|
||||
showOverflow: 'tooltip' as const,
|
||||
},
|
||||
{
|
||||
title: '权限列表',
|
||||
minWidth: 200,
|
||||
slots: { default: 'permissions' },
|
||||
},
|
||||
{
|
||||
title: '类型',
|
||||
minWidth: 100,
|
||||
slots: { default: 'menuType' },
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
minWidth: 100,
|
||||
slots: { default: 'menuStatus' },
|
||||
},
|
||||
{
|
||||
field: 'createTime',
|
||||
title: '创建时间',
|
||||
minWidth: 160,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
minWidth: 280,
|
||||
fixed: 'right' as const,
|
||||
showOverflow: false,
|
||||
slots: { default: 'action' },
|
||||
},
|
||||
],
|
||||
height: 'auto',
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: {
|
||||
isHover: true,
|
||||
drag: true, // 启用行拖拽
|
||||
height: 52,
|
||||
},
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
rowDragConfig: {
|
||||
isPeerDrag: true, // 启用同层级拖拽限制
|
||||
},
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
refresh: true,
|
||||
zoom: true,
|
||||
export: true, // 启用导出功能
|
||||
},
|
||||
data: [],
|
||||
treeConfig: {
|
||||
transform: true,
|
||||
rowField: 'id',
|
||||
parentField: 'parentId',
|
||||
},
|
||||
// 配置远程加载
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
const data = await getAllMenusApi();
|
||||
lastMenuFlatItems.value = data;
|
||||
// 直接返回扁平化数据,让 vxe-table 自动构建树形结构
|
||||
return {
|
||||
items: data,
|
||||
total: data.length,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('获取菜单列表失败:', error);
|
||||
message.error('获取菜单列表失败');
|
||||
lastMenuFlatItems.value = [];
|
||||
return {
|
||||
items: [],
|
||||
total: 0,
|
||||
};
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// 刷新表格数据
|
||||
function refreshTable() {
|
||||
if (gridApi) {
|
||||
gridApi.reload();
|
||||
}
|
||||
}
|
||||
|
||||
function getGridMenuFlatFallback(): MenuVO.MenuInfo[] {
|
||||
const grid = gridApi?.grid as any;
|
||||
if (!grid?.getTableData) {
|
||||
return [];
|
||||
}
|
||||
const td = grid.getTableData();
|
||||
return (td?.fullData ?? td?.tableData ?? []) as MenuVO.MenuInfo[];
|
||||
}
|
||||
|
||||
/** 就地合并更新后的菜单行,保持树展开状态;父级变更时需整表重建树结构 */
|
||||
function patchMenuRowFromServer(menu: MenuVO.MenuInfo) {
|
||||
if (!menu?.id) {
|
||||
refreshTable();
|
||||
return;
|
||||
}
|
||||
const idNum = Number(menu.id);
|
||||
const list =
|
||||
lastMenuFlatItems.value.length > 0
|
||||
? lastMenuFlatItems.value
|
||||
: getGridMenuFlatFallback();
|
||||
const row = list.find((r) => Number(r.id) === idNum);
|
||||
if (!row) {
|
||||
refreshTable();
|
||||
return;
|
||||
}
|
||||
if (!sameMenuParent(row.parentId, menu.parentId)) {
|
||||
refreshTable();
|
||||
return;
|
||||
}
|
||||
Object.assign(row, menu);
|
||||
row.permissions = menu.permissions ? [...menu.permissions] : [];
|
||||
}
|
||||
|
||||
// 处理添加菜单
|
||||
function handleAdd() {
|
||||
menuFormModalRef.value?.open(false);
|
||||
}
|
||||
|
||||
// 处理添加下级菜单
|
||||
function handleAddChild(record: MenuVO.MenuInfo) {
|
||||
menuFormModalRef.value?.open(false, record);
|
||||
}
|
||||
|
||||
// 处理编辑菜单
|
||||
function handleEdit(record: MenuVO.MenuInfo) {
|
||||
menuFormModalRef.value?.open(true, record);
|
||||
}
|
||||
|
||||
// 处理删除菜单
|
||||
async function handleDelete(record: MenuVO.MenuInfo) {
|
||||
try {
|
||||
await deleteMenuApi(record.id);
|
||||
message.success('删除成功');
|
||||
refreshTable();
|
||||
} catch (error) {
|
||||
console.error('删除菜单失败:', error);
|
||||
message.error('删除菜单失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 处理模态框成功:更新菜单只合并当前行;新建仍整表刷新
|
||||
function handleModalSuccess(
|
||||
payload?: { mode: 'update'; menu: MenuVO.MenuInfo } | { mode: 'create' },
|
||||
) {
|
||||
if (payload?.mode === 'update' && payload.menu) {
|
||||
patchMenuRowFromServer(payload.menu);
|
||||
return;
|
||||
}
|
||||
refreshTable();
|
||||
}
|
||||
|
||||
// 防重复调用标志
|
||||
let isUpdating = false;
|
||||
|
||||
// 处理拖拽排序
|
||||
const handleDragSort = async (_params: any) => {
|
||||
// 防止重复调用
|
||||
if (isUpdating) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
isUpdating = true;
|
||||
|
||||
// 获取当前表格数据
|
||||
const tableDataResult = gridApi.grid.getTableData();
|
||||
const tableData = tableDataResult?.tableData || [];
|
||||
|
||||
// 构建排序数据
|
||||
const sortItems = tableData.map((item: MenuVO.MenuInfo, index: number) => ({
|
||||
menuId: item.id,
|
||||
order: index + 1, // 排序值从1开始
|
||||
}));
|
||||
|
||||
// 调用排序接口
|
||||
await batchSortMenuApi({ sortItems });
|
||||
|
||||
// 排序成功后不需要重新加载数据,因为表格数据已经更新
|
||||
} catch (error: any) {
|
||||
console.error('拖拽排序失败:', error);
|
||||
if (error?.message) {
|
||||
message.error(error.message);
|
||||
} else {
|
||||
message.error('排序更新失败');
|
||||
}
|
||||
// 排序失败时重新加载数据,恢复原始状态
|
||||
gridApi.reload();
|
||||
} finally {
|
||||
isUpdating = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 全部展开树形表格
|
||||
function expandAllTree() {
|
||||
if (gridApi) {
|
||||
const vxeTable = (gridApi as any).grid;
|
||||
if (vxeTable && typeof vxeTable.setAllTreeExpand === 'function') {
|
||||
vxeTable.setAllTreeExpand(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 全部收起树形表格
|
||||
function collapseAllTree() {
|
||||
if (gridApi) {
|
||||
const vxeTable = (gridApi as any).grid;
|
||||
if (vxeTable && typeof vxeTable.setAllTreeExpand === 'function') {
|
||||
vxeTable.setAllTreeExpand(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取菜单类型标签
|
||||
function getMenuTypeLabel(type: string) {
|
||||
const typeMap: Record<string, string> = {
|
||||
catalog: '目录',
|
||||
menu: '菜单',
|
||||
button: '按钮',
|
||||
embedded: '内联',
|
||||
link: '外链',
|
||||
};
|
||||
return typeMap[type] || type;
|
||||
}
|
||||
|
||||
// 获取菜单类型颜色
|
||||
function getMenuTypeColor(type: string) {
|
||||
const colorMap: Record<string, string> = {
|
||||
catalog: 'blue',
|
||||
menu: 'green',
|
||||
button: 'orange',
|
||||
embedded: 'purple',
|
||||
link: 'cyan',
|
||||
};
|
||||
return colorMap[type] || 'default';
|
||||
}
|
||||
|
||||
// 创建 VbenVxeGrid 实例
|
||||
const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
showSearchForm: false,
|
||||
tableTitle: '菜单管理',
|
||||
gridEvents: {
|
||||
// 拖拽排序事件
|
||||
rowDragend: handleDragSort,
|
||||
} as any,
|
||||
});
|
||||
|
||||
// 添加Grid组件的ref
|
||||
const gridRef = ref();
|
||||
|
||||
// 在组件挂载后绑定拖拽事件
|
||||
onMounted(() => {
|
||||
// 延迟绑定,确保Grid组件完全初始化
|
||||
setTimeout(() => {
|
||||
if (gridRef.value) {
|
||||
// 尝试直接绑定VxeTable的拖拽事件
|
||||
const vxeGrid = gridRef.value;
|
||||
if (vxeGrid && vxeGrid.$refs && vxeGrid.$refs.grid) {
|
||||
const grid = vxeGrid.$refs.grid;
|
||||
// 绑定拖拽事件
|
||||
grid.on('row-drag-end', (params: any) => {
|
||||
handleDragSort(params);
|
||||
});
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="菜单管理" auto-content-height>
|
||||
<!-- VbenVxeGrid 表格 -->
|
||||
<Grid ref="gridRef" :loading="loading" class="menu-grid">
|
||||
<!-- 工具栏工具 -->
|
||||
<template #toolbar-tools>
|
||||
<Space>
|
||||
<Button type="primary" @click="handleAdd">
|
||||
<PlusIcon />
|
||||
添加菜单
|
||||
</Button>
|
||||
<Button @click="expandAllTree">
|
||||
<ExpandIcon />
|
||||
全部展开
|
||||
</Button>
|
||||
<Button @click="collapseAllTree">
|
||||
<CollapseIcon />
|
||||
全部收起
|
||||
</Button>
|
||||
<div class="text-sm text-gray-500">
|
||||
💡 提示:可直接拖拽菜单名称列进行排序
|
||||
</div>
|
||||
</Space>
|
||||
</template>
|
||||
|
||||
<!-- 菜单名称列 - 移除自定义插槽以支持拖拽控件正常显示 -->
|
||||
|
||||
<!-- 图标列 -->
|
||||
<template #icon="{ row }: { row: MenuVO.MenuInfo }">
|
||||
<div
|
||||
v-if="row.icon"
|
||||
class="flex items-center justify-center"
|
||||
:title="row.icon"
|
||||
>
|
||||
<IconifyIcon :icon="row.icon" class="size-4 text-blue-600" />
|
||||
</div>
|
||||
<span v-else class="text-gray-400">-</span>
|
||||
</template>
|
||||
|
||||
<!-- 菜单类型列 -->
|
||||
<template #menuType="{ row }: { row: any }">
|
||||
<Tag :color="getMenuTypeColor(row.type)">
|
||||
{{ getMenuTypeLabel(row.type) }}
|
||||
</Tag>
|
||||
</template>
|
||||
|
||||
<!-- 菜单状态列 -->
|
||||
<template #menuStatus="{ row }: { row: any }">
|
||||
<Tag :color="row.status === 1 ? 'green' : 'red'">
|
||||
{{ row.status === 1 ? '启用' : '禁用' }}
|
||||
</Tag>
|
||||
</template>
|
||||
|
||||
<!-- 权限名称列 -->
|
||||
<template #permissions="{ row }: { row: any }">
|
||||
<div
|
||||
v-if="row.permissions && row.permissions.length > 0"
|
||||
class="flex flex-wrap gap-1"
|
||||
>
|
||||
<Tag
|
||||
v-for="permission in row.permissions"
|
||||
:key="permission.id"
|
||||
:color="permission.status === 1 ? 'blue' : 'default'"
|
||||
size="small"
|
||||
>
|
||||
{{ permission.name }}
|
||||
</Tag>
|
||||
</div>
|
||||
<span v-else class="text-gray-400">-</span>
|
||||
</template>
|
||||
|
||||
<!-- 操作列 -->
|
||||
<template #action="{ row }: { row: any }">
|
||||
<Space size="small" :wrap="false">
|
||||
<Button type="link" size="small" @click="handleAddChild(row)">
|
||||
<PlusCircleIcon class="h-3 w-3" />
|
||||
增加下级
|
||||
</Button>
|
||||
<Button type="link" size="small" @click="handleEdit(row)">
|
||||
<EditIcon class="h-3 w-3" />
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确定要删除这个菜单吗?"
|
||||
@confirm="handleDelete(row)"
|
||||
>
|
||||
<Button type="link" size="small" danger>
|
||||
<TrashIcon class="h-3 w-3" />
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
</template>
|
||||
</Grid>
|
||||
|
||||
<!-- 菜单表单模态框 -->
|
||||
<MenuFormModal ref="menuFormModalRef" @success="handleModalSuccess" />
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:deep(.menu-grid .vxe-body--column) {
|
||||
vertical-align: middle;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,636 @@
|
||||
<script setup lang="ts">
|
||||
import type { CompanyVO } from '#/api/organization/company/types';
|
||||
import type { ShopVO } from '#/api/ecommerce/shop/types';
|
||||
import type { OrderStatVO } from '#/api/system/order-stat';
|
||||
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
DatePicker,
|
||||
Descriptions,
|
||||
Divider,
|
||||
Empty,
|
||||
Flex,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
message,
|
||||
Pagination,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Switch,
|
||||
Table,
|
||||
Tag,
|
||||
} from 'ant-design-vue';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import { getCompanyPageApi } from '#/api/organization/company';
|
||||
import { getShopPageApi } from '#/api/ecommerce/shop';
|
||||
import {
|
||||
createOrderStatRebuildApi,
|
||||
getOrderStatRebuildStatusApi,
|
||||
reconcileOrderStatApi,
|
||||
} from '#/api/system/order-stat';
|
||||
import {
|
||||
SIDEBAR_LIST_SHELL_CLASS,
|
||||
sidebarListRowClass,
|
||||
} from '#/utils/sidebar-list-styles';
|
||||
|
||||
defineOptions({ name: 'OrderStatManage' });
|
||||
|
||||
const BuildingIcon = createIconifyIcon('lucide:building-2');
|
||||
const RefreshIcon = createIconifyIcon('lucide:refresh-cw');
|
||||
const PlayIcon = createIconifyIcon('lucide:play');
|
||||
const SearchIcon = createIconifyIcon('lucide:search-check');
|
||||
|
||||
const companySearchForm = ref({
|
||||
name: '',
|
||||
status: undefined as number | undefined,
|
||||
});
|
||||
|
||||
const companyList = ref<CompanyVO.CompanyInfoVO[]>([]);
|
||||
const companyLoading = ref(false);
|
||||
const companyPagination = ref({ current: 1, pageSize: 20, total: 0 });
|
||||
|
||||
const currentCompany = ref<CompanyVO.CompanyInfoVO | null>(null);
|
||||
const shopId = ref<number | undefined>();
|
||||
const shopOptions = ref<{ label: string; value: number }[]>([]);
|
||||
const shopLoading = ref(false);
|
||||
|
||||
const selectedCompanyLabel = computed(() => {
|
||||
if (!currentCompany.value) {
|
||||
return '请先选择公司';
|
||||
}
|
||||
return currentCompany.value.name;
|
||||
});
|
||||
|
||||
/** 默认近 30 天 */
|
||||
const defaultRange: [dayjs.Dayjs, dayjs.Dayjs] = [
|
||||
dayjs().subtract(29, 'day'),
|
||||
dayjs(),
|
||||
];
|
||||
|
||||
const rebuildRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([...defaultRange]);
|
||||
const rebuildSubmitting = ref(false);
|
||||
const lastTaskId = ref<number | undefined>();
|
||||
const rebuildTask = ref<OrderStatVO.RebuildTask | null>(null);
|
||||
const pollTaskId = ref<string>('');
|
||||
const pollLoading = ref(false);
|
||||
const autoPoll = ref(true);
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const reconcileRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([...defaultRange]);
|
||||
const sampleSize = ref(100);
|
||||
const reconcileLoading = ref(false);
|
||||
const reconcileReport = ref<OrderStatVO.ReconcileReport | null>(null);
|
||||
const onlyMismatch = ref(false);
|
||||
|
||||
const statusColorMap: Record<string, string> = {
|
||||
pending: 'default',
|
||||
running: 'processing',
|
||||
done: 'success',
|
||||
failed: 'error',
|
||||
};
|
||||
|
||||
const statusLabelMap: Record<string, string> = {
|
||||
pending: '待执行',
|
||||
running: '执行中',
|
||||
done: '已完成',
|
||||
failed: '失败',
|
||||
};
|
||||
|
||||
function formatRange(range: [dayjs.Dayjs, dayjs.Dayjs]): [string, string] {
|
||||
return [range[0].format('YYYY-MM-DD'), range[1].format('YYYY-MM-DD')];
|
||||
}
|
||||
|
||||
function currentCompanyId(): number | null {
|
||||
return currentCompany.value?.id ?? null;
|
||||
}
|
||||
|
||||
async function searchCompanies() {
|
||||
companyLoading.value = true;
|
||||
try {
|
||||
const result = await getCompanyPageApi({
|
||||
page: companyPagination.value.current,
|
||||
pageSize: companyPagination.value.pageSize,
|
||||
filters: {
|
||||
name: companySearchForm.value.name || undefined,
|
||||
status: companySearchForm.value.status,
|
||||
},
|
||||
});
|
||||
companyList.value = result.records;
|
||||
companyPagination.value.total = result.total;
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '获取公司列表失败');
|
||||
} finally {
|
||||
companyLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadShops(cid: number) {
|
||||
shopLoading.value = true;
|
||||
try {
|
||||
const result = await getShopPageApi({
|
||||
page: 1,
|
||||
pageSize: 500,
|
||||
filters: {},
|
||||
});
|
||||
shopOptions.value = (result.records || [])
|
||||
.filter((s: ShopVO.Info) => s.companyId === cid)
|
||||
.map((s: ShopVO.Info) => ({
|
||||
label: `${s.name}(ID:${s.id})`,
|
||||
value: s.id,
|
||||
}));
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载店铺列表失败');
|
||||
} finally {
|
||||
shopLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resetRightPanelState() {
|
||||
shopId.value = undefined;
|
||||
shopOptions.value = [];
|
||||
reconcileReport.value = null;
|
||||
rebuildTask.value = null;
|
||||
lastTaskId.value = undefined;
|
||||
pollTaskId.value = '';
|
||||
stopPoll();
|
||||
}
|
||||
|
||||
async function selectCompany(company: CompanyVO.CompanyInfoVO) {
|
||||
currentCompany.value = company;
|
||||
resetRightPanelState();
|
||||
await loadShops(company.id);
|
||||
}
|
||||
|
||||
function resetCompanySearch() {
|
||||
companySearchForm.value = { name: '', status: undefined };
|
||||
companyPagination.value.current = 1;
|
||||
searchCompanies();
|
||||
}
|
||||
|
||||
function handleCompanyPageChange(page: number, pageSize: number) {
|
||||
companyPagination.value.current = page;
|
||||
companyPagination.value.pageSize = pageSize;
|
||||
searchCompanies();
|
||||
}
|
||||
|
||||
function companyRowClass(companyId: number) {
|
||||
const active = currentCompany.value?.id === companyId;
|
||||
return sidebarListRowClass(active, 'w-full cursor-pointer text-left');
|
||||
}
|
||||
|
||||
async function handleCreateRebuild() {
|
||||
const cid = currentCompanyId();
|
||||
if (!cid) return;
|
||||
rebuildSubmitting.value = true;
|
||||
try {
|
||||
const [startDate, endDate] = formatRange(rebuildRange.value);
|
||||
const taskId = await createOrderStatRebuildApi({
|
||||
companyId: cid,
|
||||
shopId: shopId.value ?? null,
|
||||
startDate,
|
||||
endDate,
|
||||
});
|
||||
lastTaskId.value = taskId;
|
||||
pollTaskId.value = String(taskId);
|
||||
message.success(`rebuild 任务已创建,任务 ID:${taskId}`);
|
||||
await fetchRebuildStatus(taskId);
|
||||
startPollIfNeeded();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '创建 rebuild 失败');
|
||||
} finally {
|
||||
rebuildSubmitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRebuildStatus(id?: number) {
|
||||
const tid = id ?? Number(pollTaskId.value);
|
||||
if (!tid || Number.isNaN(tid)) {
|
||||
message.warning('请输入有效的任务 ID');
|
||||
return;
|
||||
}
|
||||
pollLoading.value = true;
|
||||
try {
|
||||
rebuildTask.value = await getOrderStatRebuildStatusApi(tid);
|
||||
if (rebuildTask.value?.status === 'done') {
|
||||
stopPoll();
|
||||
message.success('rebuild 已完成');
|
||||
} else if (rebuildTask.value?.status === 'failed') {
|
||||
stopPoll();
|
||||
message.error(rebuildTask.value.errorMessage || 'rebuild 失败');
|
||||
}
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '查询任务失败');
|
||||
} finally {
|
||||
pollLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startPollIfNeeded() {
|
||||
stopPoll();
|
||||
if (!autoPoll.value) return;
|
||||
const status = rebuildTask.value?.status;
|
||||
if (status === 'done' || status === 'failed') return;
|
||||
pollTimer = setInterval(() => {
|
||||
const tid = Number(pollTaskId.value);
|
||||
if (tid && !Number.isNaN(tid)) {
|
||||
fetchRebuildStatus(tid);
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
function stopPoll() {
|
||||
if (pollTimer) {
|
||||
clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
watch(autoPoll, (on) => {
|
||||
if (on) {
|
||||
startPollIfNeeded();
|
||||
} else {
|
||||
stopPoll();
|
||||
}
|
||||
});
|
||||
|
||||
async function handleReconcile() {
|
||||
const cid = currentCompanyId();
|
||||
if (!cid) return;
|
||||
reconcileLoading.value = true;
|
||||
reconcileReport.value = null;
|
||||
try {
|
||||
const [startDate, endDate] = formatRange(reconcileRange.value);
|
||||
reconcileReport.value = await reconcileOrderStatApi({
|
||||
companyId: cid,
|
||||
startDate,
|
||||
endDate,
|
||||
sampleSize: sampleSize.value || 100,
|
||||
});
|
||||
if (reconcileReport.value.passed) {
|
||||
message.success('对账通过');
|
||||
} else {
|
||||
message.warning(
|
||||
`存在 ${reconcileReport.value.mismatchCount} 条差异(抽样 ${reconcileReport.value.sampleCount})`,
|
||||
);
|
||||
}
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '对账失败');
|
||||
} finally {
|
||||
reconcileLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const reconcileTableData = () => {
|
||||
const items = reconcileReport.value?.items ?? [];
|
||||
if (!onlyMismatch.value) return items;
|
||||
return items.filter((i) => !i.match);
|
||||
};
|
||||
|
||||
const reconcileColumns = [
|
||||
{ title: '店铺 ID', dataIndex: 'shopId', width: 100 },
|
||||
{ title: '自然日', dataIndex: 'statDate', width: 120 },
|
||||
{
|
||||
title: '汇总销售额',
|
||||
dataIndex: 'statSales',
|
||||
width: 140,
|
||||
customRender: ({ text }: { text: number }) => formatMoney(text),
|
||||
},
|
||||
{
|
||||
title: '明细聚合销售额',
|
||||
dataIndex: 'aggSales',
|
||||
width: 160,
|
||||
customRender: ({ text }: { text: number }) => formatMoney(text),
|
||||
},
|
||||
{
|
||||
title: '差额',
|
||||
dataIndex: 'diff',
|
||||
width: 120,
|
||||
customRender: ({ text, record }: { text: number; record: OrderStatVO.ReconcileItem }) =>
|
||||
record.match ? '0.00' : formatMoney(text),
|
||||
},
|
||||
{
|
||||
title: '结果',
|
||||
dataIndex: 'match',
|
||||
width: 90,
|
||||
customRender: ({ text }: { text: boolean }) =>
|
||||
text ? '一致' : '不一致',
|
||||
},
|
||||
];
|
||||
|
||||
function formatMoney(v: number | undefined) {
|
||||
if (v == null) return '-';
|
||||
return Number(v).toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopPoll();
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
searchCompanies();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="订单统计汇总管理" :auto-content-height="true">
|
||||
<template #description>
|
||||
<div class="text-foreground/80 mt-2">
|
||||
左侧选择公司,右侧进行历史灌数、任务进度查询与抽样对账(需
|
||||
<code class="text-xs">ecom:shop:read</code> 或超管)。
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Flex gap="middle" class="h-full min-h-0">
|
||||
<!-- 左:公司列表 -->
|
||||
<Card
|
||||
class="flex h-full w-[420px] shrink-0 flex-col"
|
||||
:body-style="{
|
||||
height: '100%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '8px',
|
||||
minHeight: 0,
|
||||
padding: '12px',
|
||||
}"
|
||||
>
|
||||
<template #title>
|
||||
<span class="flex items-center gap-2 text-base font-semibold">
|
||||
<BuildingIcon class="h-4 w-4" />
|
||||
公司
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<Flex wrap="wrap" align="center" class="shrink-0 gap-2">
|
||||
<Input
|
||||
v-model:value="companySearchForm.name"
|
||||
placeholder="公司名称"
|
||||
allow-clear
|
||||
class="min-w-[140px] flex-1"
|
||||
@press-enter="searchCompanies"
|
||||
/>
|
||||
<Select
|
||||
v-model:value="companySearchForm.status"
|
||||
placeholder="状态"
|
||||
allow-clear
|
||||
class="w-[88px]"
|
||||
:options="[
|
||||
{ label: '启用', value: 1 },
|
||||
{ label: '禁用', value: 0 },
|
||||
]"
|
||||
/>
|
||||
<Button type="primary" size="small" @click="searchCompanies">
|
||||
搜索
|
||||
</Button>
|
||||
<Button size="small" @click="resetCompanySearch">重置</Button>
|
||||
</Flex>
|
||||
|
||||
<Spin :spinning="companyLoading" class="flex min-h-0 flex-1 flex-col">
|
||||
<div :class="SIDEBAR_LIST_SHELL_CLASS">
|
||||
<Empty
|
||||
v-if="!companyLoading && companyList.length === 0"
|
||||
class="py-8"
|
||||
description="暂无公司"
|
||||
/>
|
||||
<div v-else class="space-y-1">
|
||||
<button
|
||||
v-for="company in companyList"
|
||||
:key="company.id"
|
||||
type="button"
|
||||
:class="companyRowClass(company.id)"
|
||||
@click="selectCompany(company)"
|
||||
>
|
||||
<span class="block truncate">{{ company.name }}</span>
|
||||
<span
|
||||
class="mt-0.5 block truncate text-xs font-normal text-muted-foreground"
|
||||
>
|
||||
ID: {{ company.id }} ·
|
||||
{{ company.status === 1 ? '启用' : '禁用' }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Flex justify="center" class="mt-2 shrink-0 pt-1">
|
||||
<Pagination
|
||||
v-model:current="companyPagination.current"
|
||||
v-model:page-size="companyPagination.pageSize"
|
||||
:total="companyPagination.total"
|
||||
size="small"
|
||||
:show-size-changer="true"
|
||||
:show-quick-jumper="true"
|
||||
@change="handleCompanyPageChange"
|
||||
/>
|
||||
</Flex>
|
||||
</Spin>
|
||||
</Card>
|
||||
|
||||
<!-- 右:汇总运维 -->
|
||||
<Card
|
||||
class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
|
||||
:body-style="{
|
||||
height: '100%',
|
||||
minHeight: 0,
|
||||
padding: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}"
|
||||
>
|
||||
<template #title>
|
||||
<span class="text-base font-semibold">汇总运维</span>
|
||||
</template>
|
||||
|
||||
<div
|
||||
class="shrink-0 border-t border-border px-4 py-2 text-xs text-muted-foreground"
|
||||
>
|
||||
当前:{{ selectedCompanyLabel }}
|
||||
<template v-if="currentCompany">
|
||||
<Tag
|
||||
class="ml-2"
|
||||
:color="currentCompany.status === 1 ? 'green' : 'red'"
|
||||
>
|
||||
{{ currentCompany.status === 1 ? '启用' : '禁用' }}
|
||||
</Tag>
|
||||
<span class="ml-3 hidden sm:inline">
|
||||
历史灌数按 shop×自然日重算;店铺不选则全店
|
||||
</span>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!currentCompany"
|
||||
class="flex min-h-0 flex-1 items-center justify-center"
|
||||
>
|
||||
<Empty description="请从左侧选择公司以操作汇总表" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="min-h-0 flex-1 overflow-y-auto px-4 py-3 sm:px-5"
|
||||
>
|
||||
<Form layout="vertical" class="max-w-xl">
|
||||
<Form.Item label="店铺范围(可选)">
|
||||
<Select
|
||||
v-model:value="shopId"
|
||||
allow-clear
|
||||
:loading="shopLoading"
|
||||
:options="shopOptions"
|
||||
placeholder="不选则该公司下全部店铺"
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
<Divider orientation="left" class="!mt-0">
|
||||
历史灌数(Rebuild)
|
||||
</Divider>
|
||||
<Form layout="vertical" class="max-w-xl">
|
||||
<Form.Item label="灌数日期区间" required>
|
||||
<DatePicker.RangePicker
|
||||
v-model:value="rebuildRange"
|
||||
class="w-full"
|
||||
:allow-clear="false"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Space>
|
||||
<Button
|
||||
type="primary"
|
||||
:loading="rebuildSubmitting"
|
||||
@click="handleCreateRebuild"
|
||||
>
|
||||
<template #icon><PlayIcon /></template>
|
||||
创建灌数任务
|
||||
</Button>
|
||||
</Space>
|
||||
<div v-if="lastTaskId" class="mt-2 text-sm text-muted-foreground">
|
||||
最近任务 ID:<Tag color="blue">{{ lastTaskId }}</Tag>
|
||||
</div>
|
||||
</Form>
|
||||
|
||||
<Divider orientation="left">任务进度</Divider>
|
||||
<Space class="mb-3 max-w-xl" wrap>
|
||||
<Input
|
||||
v-model:value="pollTaskId"
|
||||
placeholder="任务 ID"
|
||||
style="width: 160px"
|
||||
/>
|
||||
<Button :loading="pollLoading" @click="fetchRebuildStatus()">
|
||||
<template #icon><RefreshIcon /></template>
|
||||
查询
|
||||
</Button>
|
||||
<span class="text-sm text-muted-foreground">
|
||||
自动刷新(3s)
|
||||
<Switch v-model:checked="autoPoll" class="ml-2" size="small" />
|
||||
</span>
|
||||
</Space>
|
||||
<Spin :spinning="pollLoading && !rebuildTask">
|
||||
<Descriptions
|
||||
v-if="rebuildTask"
|
||||
bordered
|
||||
class="max-w-2xl"
|
||||
:column="1"
|
||||
size="small"
|
||||
>
|
||||
<Descriptions.Item label="任务 ID">
|
||||
{{ rebuildTask.id }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag :color="statusColorMap[rebuildTask.status] || 'default'">
|
||||
{{ statusLabelMap[rebuildTask.status] || rebuildTask.status }}
|
||||
</Tag>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="公司 / 店铺">
|
||||
{{ rebuildTask.companyId }} /
|
||||
{{ rebuildTask.shopId ?? '全部店铺' }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="区间">
|
||||
{{ rebuildTask.startDate }} ~ {{ rebuildTask.endDate }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="进度日期">
|
||||
{{ rebuildTask.progressDate ?? '-' }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item
|
||||
v-if="rebuildTask.errorMessage"
|
||||
label="错误信息"
|
||||
>
|
||||
<span class="text-red-500">{{ rebuildTask.errorMessage }}</span>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="更新时间">
|
||||
{{ rebuildTask.updateTime ?? '-' }}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<div
|
||||
v-else
|
||||
class="max-w-2xl py-4 text-center text-sm text-muted-foreground"
|
||||
>
|
||||
创建任务后将自动填入 ID,也可手动输入后查询
|
||||
</div>
|
||||
</Spin>
|
||||
|
||||
<Divider orientation="left">抽样对账(Reconcile)</Divider>
|
||||
<Form layout="vertical" class="max-w-xl">
|
||||
<Form.Item label="对账日期区间" required>
|
||||
<DatePicker.RangePicker
|
||||
v-model:value="reconcileRange"
|
||||
class="w-full"
|
||||
:allow-clear="false"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="抽样条数">
|
||||
<InputNumber
|
||||
v-model:value="sampleSize"
|
||||
:min="1"
|
||||
:max="500"
|
||||
class="w-full"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button
|
||||
type="primary"
|
||||
:loading="reconcileLoading"
|
||||
@click="handleReconcile"
|
||||
>
|
||||
<template #icon><SearchIcon /></template>
|
||||
执行对账
|
||||
</Button>
|
||||
</Form>
|
||||
|
||||
<div v-if="reconcileReport" class="mt-4">
|
||||
<Space class="mb-3" wrap>
|
||||
<Tag :color="reconcileReport.passed ? 'success' : 'error'">
|
||||
{{ reconcileReport.passed ? '对账通过' : '存在差异' }}
|
||||
</Tag>
|
||||
<span class="text-sm">
|
||||
抽样 {{ reconcileReport.sampleCount }} 条,差异
|
||||
{{ reconcileReport.mismatchCount }} 条
|
||||
</span>
|
||||
<span class="text-sm text-muted-foreground">
|
||||
仅看不一致
|
||||
<Switch v-model:checked="onlyMismatch" class="ml-1" size="small" />
|
||||
</span>
|
||||
</Space>
|
||||
<Table
|
||||
:columns="reconcileColumns"
|
||||
:data-source="reconcileTableData()"
|
||||
:pagination="{ pageSize: 10, showSizeChanger: true }"
|
||||
:row-key="(r: OrderStatVO.ReconcileItem) => `${r.shopId}-${r.statDate}`"
|
||||
size="small"
|
||||
:scroll="{ x: 720 }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</Flex>
|
||||
</Page>
|
||||
</template>
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
<script lang="ts" setup>
|
||||
import type { PermissionVO } from '#/api/system/permission';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import { Form, Input, message, Select, Switch, TreeSelect } from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createPermissionApi,
|
||||
getSystemPermissionTreeApi,
|
||||
updatePermissionApi,
|
||||
} from '#/api/system/permission';
|
||||
|
||||
interface Emits {
|
||||
(e: 'success'): void;
|
||||
}
|
||||
|
||||
defineOptions({ name: 'PermissionFormModal' });
|
||||
|
||||
const emit = defineEmits<Emits>();
|
||||
|
||||
// 创建 Vben Modal 实例
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
title: '权限管理',
|
||||
draggable: true,
|
||||
contentClass: 'px-6 py-4',
|
||||
onConfirm: handleSubmit,
|
||||
onCancel: close,
|
||||
onOpenChange: (isOpen: boolean) => {
|
||||
if (!isOpen) {
|
||||
resetForm();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// 响应式数据
|
||||
const formRef = ref();
|
||||
const isEdit = ref(false);
|
||||
const currentPermissionData = ref<null | PermissionVO.PermissionInfoVO>(null);
|
||||
|
||||
// 内部表单数据类型
|
||||
interface FormData {
|
||||
code: string;
|
||||
name: string;
|
||||
type: string;
|
||||
parentId: number | null;
|
||||
sortOrder: number;
|
||||
status: boolean;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
// 父级权限选项(树形)
|
||||
const parentPermissionOptions = ref<any[]>([]);
|
||||
|
||||
// 表单数据
|
||||
const formData = ref<FormData>({
|
||||
code: '',
|
||||
name: '',
|
||||
type: 'api',
|
||||
parentId: null,
|
||||
sortOrder: 0,
|
||||
status: true,
|
||||
remark: '',
|
||||
});
|
||||
|
||||
// 权限类型选项
|
||||
const typeOptions = [
|
||||
{ label: '接口权限', value: 'api' },
|
||||
{ label: '按钮权限', value: 'button' },
|
||||
{ label: '数据权限', value: 'data' },
|
||||
];
|
||||
|
||||
// 加载父级权限树(用于选择父级)
|
||||
async function loadParentPermissions() {
|
||||
try {
|
||||
const tree = await getSystemPermissionTreeApi();
|
||||
parentPermissionOptions.value = buildTreeOptions(tree || []);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// 将权限树转为 TreeSelect 选项格式(排除自己)
|
||||
function buildTreeOptions(
|
||||
nodes: PermissionVO.PermissionInfoVO[],
|
||||
disabledIds: Set<number> = new Set(),
|
||||
): any[] {
|
||||
return nodes.map((node) => {
|
||||
const disabled = disabledIds.has(node.id!);
|
||||
return {
|
||||
title: `${node.name} (${node.code})`,
|
||||
value: node.id,
|
||||
key: node.id,
|
||||
disabled,
|
||||
children: node.children ? buildTreeOptions(node.children, disabledIds) : undefined,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// 重置表单
|
||||
function resetForm() {
|
||||
formData.value = {
|
||||
code: '',
|
||||
name: '',
|
||||
type: 'api',
|
||||
parentId: null,
|
||||
sortOrder: 0,
|
||||
status: true,
|
||||
remark: '',
|
||||
};
|
||||
formRef.value?.resetFields();
|
||||
parentPermissionOptions.value = [];
|
||||
}
|
||||
|
||||
// 关闭模态框
|
||||
function close() {
|
||||
modalApi.close();
|
||||
formRef.value?.resetFields();
|
||||
}
|
||||
|
||||
// 暴露给父组件的方法
|
||||
function open(permissionData?: null | PermissionVO.PermissionInfoVO) {
|
||||
isEdit.value = !!permissionData;
|
||||
currentPermissionData.value = permissionData || null;
|
||||
|
||||
modalApi.setState({
|
||||
title: isEdit.value ? '编辑权限' : '添加权限',
|
||||
});
|
||||
|
||||
resetForm();
|
||||
|
||||
if (permissionData) {
|
||||
// 编辑时排除自己和子孙节点(不能选自己或子孙做父级)
|
||||
const disabledIds = collectDescendantIds(permissionData);
|
||||
formData.value = {
|
||||
code: permissionData.code,
|
||||
name: permissionData.name,
|
||||
type: permissionData.type,
|
||||
parentId: permissionData.parentId ?? null,
|
||||
sortOrder: permissionData.sortOrder ?? 0,
|
||||
status: permissionData.status === 1,
|
||||
remark: permissionData.remark || '',
|
||||
};
|
||||
// 加载父级选项(编辑时传入禁用自己及子孙的集合)
|
||||
loadParentPermissionsWithDisabled(disabledIds);
|
||||
} else {
|
||||
loadParentPermissions();
|
||||
}
|
||||
|
||||
modalApi.open();
|
||||
}
|
||||
|
||||
// 递归收集子孙节点ID
|
||||
function collectDescendantIds(node: PermissionVO.PermissionInfoVO): Set<number> {
|
||||
const ids = new Set<number>([node.id!]);
|
||||
if (node.children) {
|
||||
for (const child of node.children) {
|
||||
const childIds = collectDescendantIds(child);
|
||||
childIds.forEach((id) => ids.add(id));
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
// 加载父级选项(带禁用信息)
|
||||
async function loadParentPermissionsWithDisabled(disabledIds: Set<number>) {
|
||||
try {
|
||||
const tree = await getSystemPermissionTreeApi();
|
||||
parentPermissionOptions.value = buildTreeOptions(tree || [], disabledIds);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// 处理表单提交
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
await formRef.value?.validate();
|
||||
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
|
||||
const submitData = {
|
||||
...formData.value,
|
||||
status: formData.value.status ? 1 : 0,
|
||||
};
|
||||
|
||||
if (isEdit.value && currentPermissionData.value) {
|
||||
await updatePermissionApi(currentPermissionData.value.id, submitData);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
await createPermissionApi(submitData);
|
||||
message.success('创建成功');
|
||||
}
|
||||
|
||||
close();
|
||||
emit('success');
|
||||
} catch (error: any) {
|
||||
console.error('保存权限失败:', error);
|
||||
const errorMessage =
|
||||
error?.response?.data?.message || error?.message || '保存权限失败';
|
||||
message.error(errorMessage);
|
||||
} finally {
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
}
|
||||
}
|
||||
|
||||
// 暴露方法给父组件
|
||||
defineExpose({
|
||||
open,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal>
|
||||
<Form
|
||||
ref="formRef"
|
||||
:model="formData"
|
||||
:label-col="{ span: 6 }"
|
||||
:wrapper-col="{ span: 18 }"
|
||||
class="space-y-5"
|
||||
>
|
||||
<Form.Item
|
||||
label="权限码"
|
||||
name="code"
|
||||
:rules="[
|
||||
{ required: true, message: '请输入权限码' },
|
||||
{ min: 2, max: 50, message: '权限码长度为2-50个字符' },
|
||||
{
|
||||
pattern: /^[a-zA-Z0-9:_-]+$/,
|
||||
message: '权限码只能包含字母、数字、冒号、下划线和连字符',
|
||||
},
|
||||
]"
|
||||
>
|
||||
<Input v-model:value="formData.code" placeholder="请输入权限码,如 user:add" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="权限名称"
|
||||
name="name"
|
||||
:rules="[
|
||||
{ required: true, message: '请输入权限名称' },
|
||||
{ min: 2, max: 50, message: '权限名称长度为2-50个字符' },
|
||||
]"
|
||||
>
|
||||
<Input v-model:value="formData.name" placeholder="请输入权限名称" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="权限类型"
|
||||
name="type"
|
||||
:rules="[{ required: true, message: '请选择权限类型' }]"
|
||||
>
|
||||
<Select
|
||||
v-model:value="formData.type"
|
||||
placeholder="请选择权限类型"
|
||||
:options="typeOptions"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="父级权限" name="parentId">
|
||||
<TreeSelect
|
||||
v-model:value="formData.parentId"
|
||||
placeholder="请选择父级权限(顶级则不选)"
|
||||
:tree-data="parentPermissionOptions"
|
||||
:dropdown-match-select-width="false"
|
||||
allow-clear
|
||||
tree-checkable
|
||||
:tree-default-expand-all="false"
|
||||
:max-tag-count="2"
|
||||
class="w-full"
|
||||
tree-node-filter-prop="title"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="排序值" name="sortOrder">
|
||||
<Input
|
||||
v-model:value="formData.sortOrder"
|
||||
type="number"
|
||||
placeholder="数字越小越靠前"
|
||||
:min="0"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="状态" name="status">
|
||||
<Switch
|
||||
v-model:checked="formData.status"
|
||||
checked-children="启用"
|
||||
un-checked-children="禁用"
|
||||
class="w-12"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="备注" name="remark">
|
||||
<Input.TextArea
|
||||
v-model:value="formData.remark"
|
||||
placeholder="请输入备注信息"
|
||||
:rows="3"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</template>
|
||||
@@ -0,0 +1,287 @@
|
||||
<script setup lang="ts">
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { PermissionVO } from '#/api/system/permission';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
batchSortPermissionApi,
|
||||
deletePermissionApi,
|
||||
getSystemPermissionTreeApi,
|
||||
} from '#/api/system/permission';
|
||||
|
||||
import PermissionFormModal from './components/PermissionFormModal.vue';
|
||||
|
||||
defineOptions({ name: 'PermissionManagement' });
|
||||
|
||||
// 创建图标组件
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
|
||||
// 响应式数据
|
||||
const loading = ref(false);
|
||||
const permissionFormModalRef = ref();
|
||||
|
||||
// 扁平化树数据(VxeTable treeConfig.transform 需要扁平数据)
|
||||
function flattenTree(
|
||||
nodes: PermissionVO.PermissionInfoVO[],
|
||||
result: PermissionVO.PermissionInfoVO[] = [],
|
||||
): PermissionVO.PermissionInfoVO[] {
|
||||
for (const node of nodes) {
|
||||
result.push(node);
|
||||
if (node.children && node.children.length > 0) {
|
||||
flattenTree(node.children, result);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// VxeGrid 树形表格配置
|
||||
const gridOptions: VxeGridProps<any> = {
|
||||
columns: [
|
||||
{
|
||||
type: 'seq' as const,
|
||||
minWidth: 60,
|
||||
title: '序号',
|
||||
},
|
||||
{
|
||||
field: 'name',
|
||||
title: '权限名称',
|
||||
minWidth: 200,
|
||||
showOverflow: 'tooltip' as const,
|
||||
treeNode: true, // 启用树节点显示
|
||||
},
|
||||
{
|
||||
field: 'code',
|
||||
title: '权限码',
|
||||
minWidth: 200,
|
||||
showOverflow: 'tooltip' as const,
|
||||
},
|
||||
{
|
||||
field: 'type',
|
||||
title: '权限类型',
|
||||
minWidth: 120,
|
||||
slots: { default: 'type' },
|
||||
},
|
||||
{
|
||||
field: 'sortOrder',
|
||||
title: '排序',
|
||||
minWidth: 80,
|
||||
},
|
||||
{
|
||||
field: 'status',
|
||||
title: '状态',
|
||||
minWidth: 80,
|
||||
slots: { default: 'status' },
|
||||
},
|
||||
{
|
||||
field: 'remark',
|
||||
title: '备注',
|
||||
minWidth: 200,
|
||||
showOverflow: 'tooltip' as const,
|
||||
},
|
||||
{
|
||||
field: 'createTime',
|
||||
title: '创建时间',
|
||||
minWidth: 160,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 120,
|
||||
fixed: 'right' as const,
|
||||
slots: { default: 'action' },
|
||||
},
|
||||
],
|
||||
height: 'auto',
|
||||
border: true,
|
||||
stripe: true,
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
rowConfig: {
|
||||
isHover: true,
|
||||
drag: true,
|
||||
height: 52,
|
||||
},
|
||||
rowDragConfig: {
|
||||
isPeerDrag: false,
|
||||
},
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
refresh: true,
|
||||
zoom: true,
|
||||
},
|
||||
data: [],
|
||||
treeConfig: {
|
||||
transform: true,
|
||||
rowField: 'id',
|
||||
parentField: 'parentId',
|
||||
},
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
const treeData = await getSystemPermissionTreeApi();
|
||||
const flatData = flattenTree(treeData || []);
|
||||
return { items: flatData, total: flatData.length };
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '获取权限树失败');
|
||||
return { items: [], total: 0 };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// 表格实例
|
||||
const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
gridEvents: {
|
||||
rowDragend: handleDragSort,
|
||||
} as any,
|
||||
});
|
||||
|
||||
// 防重调用标志
|
||||
let isDragging = false;
|
||||
|
||||
// 处理拖拽排序
|
||||
async function handleDragSort() {
|
||||
if (isDragging) return;
|
||||
isDragging = true;
|
||||
try {
|
||||
const vxeGrid = (gridApi as any).grid;
|
||||
if (!vxeGrid) return;
|
||||
const tableData = vxeGrid.getTableData?.()?.fullData || [];
|
||||
if (!tableData.length) return;
|
||||
// 按 tree 的顺序构建排序数据(VxeTable tree 内部已更新顺序)
|
||||
const sortItems = tableData.map((item: any, index: number) => ({
|
||||
permissionId: item.id,
|
||||
sortOrder: index + 1,
|
||||
}));
|
||||
await batchSortPermissionApi(sortItems);
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '排序更新失败');
|
||||
gridApi.reload();
|
||||
} finally {
|
||||
isDragging = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 刷新表格
|
||||
function refreshTable() {
|
||||
if (gridApi) gridApi.reload();
|
||||
}
|
||||
|
||||
// 打开新增
|
||||
function handleAdd() {
|
||||
permissionFormModalRef.value?.open();
|
||||
}
|
||||
|
||||
// 打开编辑
|
||||
function handleEdit(row: PermissionVO.PermissionInfoVO) {
|
||||
permissionFormModalRef.value?.open(row);
|
||||
}
|
||||
|
||||
// 删除
|
||||
async function handleDelete(row: PermissionVO.PermissionInfoVO) {
|
||||
try {
|
||||
await deletePermissionApi(row.id);
|
||||
message.success('删除成功');
|
||||
refreshTable();
|
||||
} catch (error: any) {
|
||||
message.error(
|
||||
error?.response?.data?.message || error?.message || '删除失败',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 表单弹窗成功回调
|
||||
function handleModalSuccess() {
|
||||
refreshTable();
|
||||
}
|
||||
|
||||
// 类型文本
|
||||
const getTypeText = (type: string) => {
|
||||
const typeMap: Record<string, string> = {
|
||||
api: '接口权限',
|
||||
button: '按钮权限',
|
||||
data: '数据权限',
|
||||
module: '模块分组',
|
||||
};
|
||||
return typeMap[type] || type;
|
||||
};
|
||||
|
||||
const getTypeColor = (type: string) => {
|
||||
const colorMap: Record<string, string> = {
|
||||
api: 'blue',
|
||||
button: 'green',
|
||||
data: 'orange',
|
||||
module: 'purple',
|
||||
};
|
||||
return colorMap[type] || 'default';
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="系统权限" auto-content-height>
|
||||
<template #description>
|
||||
<div class="text-foreground/80 mt-2">
|
||||
平台完整权限树结构,支持拖拽排序
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Grid class="permission-grid">
|
||||
<template #toolbar-tools>
|
||||
<Space>
|
||||
<Button type="primary" @click="handleAdd">
|
||||
<PlusIcon />
|
||||
添加权限
|
||||
</Button>
|
||||
</Space>
|
||||
</template>
|
||||
|
||||
<template #type="{ row }">
|
||||
<Tag :color="getTypeColor(row.type)">
|
||||
{{ getTypeText(row.type) }}
|
||||
</Tag>
|
||||
</template>
|
||||
|
||||
<template #status="{ row }">
|
||||
<Tag :color="row.status === 1 ? 'green' : 'red'">
|
||||
{{ row.status === 1 ? '启用' : '禁用' }}
|
||||
</Tag>
|
||||
</template>
|
||||
|
||||
<template #action="{ row }">
|
||||
<Space>
|
||||
<Button size="small" @click="handleEdit(row)">编辑</Button>
|
||||
<Popconfirm
|
||||
title="确定要删除这个权限吗?"
|
||||
@confirm="handleDelete(row)"
|
||||
>
|
||||
<Button size="small" danger>删除</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
</template>
|
||||
</Grid>
|
||||
|
||||
<!-- 权限表单弹窗 -->
|
||||
<PermissionFormModal
|
||||
ref="permissionFormModalRef"
|
||||
@success="handleModalSuccess"
|
||||
/>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:deep(.permission-grid .vxe-body--column) {
|
||||
vertical-align: middle;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,251 @@
|
||||
<script lang="ts" setup>
|
||||
import type { UserDTO, UserVO } from '#/api/system/user/types';
|
||||
|
||||
import { computed, reactive, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import { Button, Form, Input, message, Spin, Upload } from 'ant-design-vue';
|
||||
|
||||
import { getUserInfoApi, updateUserInfoApi } from '#/api/system/user';
|
||||
import { uploadFileToOss } from '#/utils/oss-upload';
|
||||
|
||||
defineOptions({ name: 'PersonalProfile' });
|
||||
|
||||
const loading = ref(false);
|
||||
const submitting = ref(false);
|
||||
const userInfo = ref<UserVO.UserInfoVO | null>(null);
|
||||
const avatarLoading = ref(false);
|
||||
|
||||
// 待上传的头像文件(用户选择后先缓存,保存时再上传)
|
||||
const pendingAvatarFile = ref<File | null>(null);
|
||||
|
||||
// 计算属性:头像显示优先级:本地预览 > 已保存的头像 > 初始头像
|
||||
const avatarSrc = computed(() => {
|
||||
if (pendingAvatarFile.value) {
|
||||
return URL.createObjectURL(pendingAvatarFile.value);
|
||||
}
|
||||
if (userInfo.value?.avatar) {
|
||||
return userInfo.value.avatar;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
// 表单数据(与更新接口 DTO 一致,头像 ID 用 undefined 表示未变更/未上传)
|
||||
const formData = reactive<UserDTO.UpdateUserInfoDTO>({
|
||||
loginCode: '',
|
||||
realName: '',
|
||||
phone: '',
|
||||
remark: '',
|
||||
});
|
||||
|
||||
const formRef = ref<any>(null);
|
||||
|
||||
async function fetchUserInfo() {
|
||||
try {
|
||||
loading.value = true;
|
||||
const data = await getUserInfoApi();
|
||||
userInfo.value = data;
|
||||
formData.loginCode = data.loginCode || '';
|
||||
formData.realName = data.realName || '';
|
||||
formData.phone = data.phone || '';
|
||||
formData.remark = data.remark || '';
|
||||
// 重置待上传的头像
|
||||
pendingAvatarFile.value = null;
|
||||
} catch (error) {
|
||||
console.error('获取用户信息失败:', error);
|
||||
message.error('获取用户信息失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleAvatarChange({ file }: { file: any }) {
|
||||
// 获取实际文件对象
|
||||
const actualFile = file.originFileObj || file;
|
||||
if (!actualFile) return;
|
||||
|
||||
if (!actualFile.type.startsWith('image/')) {
|
||||
message.error('只能上传图片文件');
|
||||
return;
|
||||
}
|
||||
if (actualFile.size > 2 * 1024 * 1024) {
|
||||
message.error('图片大小不能超过 2MB');
|
||||
return;
|
||||
}
|
||||
|
||||
// 缓存头像文件,预览由 computed avatarSrc 自动处理
|
||||
pendingAvatarFile.value = actualFile;
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
await formRef.value?.validate();
|
||||
submitting.value = true;
|
||||
|
||||
// 如果有待上传的头像,先上传
|
||||
if (pendingAvatarFile.value) {
|
||||
avatarLoading.value = true;
|
||||
try {
|
||||
const fileInfo = await uploadFileToOss(pendingAvatarFile.value, {
|
||||
category: 'user-avatar',
|
||||
errorMessage: '头像上传失败',
|
||||
});
|
||||
formData.avatarImageId = fileInfo.id;
|
||||
} finally {
|
||||
avatarLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
await updateUserInfoApi(formData);
|
||||
message.success('保存成功');
|
||||
formData.avatarImageId = undefined;
|
||||
await fetchUserInfo();
|
||||
} catch (error: any) {
|
||||
if (error?.errorFields) {
|
||||
return;
|
||||
}
|
||||
console.error('保存失败:', error);
|
||||
message.error('保存失败');
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
if (userInfo.value) {
|
||||
formData.loginCode = userInfo.value.loginCode || '';
|
||||
formData.realName = userInfo.value.realName || '';
|
||||
formData.phone = userInfo.value.phone || '';
|
||||
formData.remark = userInfo.value.remark || '';
|
||||
}
|
||||
formData.avatarImageId = undefined;
|
||||
formRef.value?.resetFields();
|
||||
pendingAvatarFile.value = null;
|
||||
}
|
||||
|
||||
fetchUserInfo();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page
|
||||
title="个人信息"
|
||||
auto-content-height
|
||||
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<div class="mx-auto max-w-2xl">
|
||||
<Spin :spinning="loading">
|
||||
<div
|
||||
class="overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<!-- 头部 -->
|
||||
<div class="border-b border-slate-100 bg-slate-50/50 px-8 py-6 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
||||
<h2 class="text-xl font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
个人信息
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
编辑您的个人信息和头像
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 表单 -->
|
||||
<div class="px-8 py-6">
|
||||
<Form
|
||||
ref="formRef"
|
||||
:model="formData"
|
||||
layout="vertical"
|
||||
class="space-y-6"
|
||||
>
|
||||
<!-- 头像 -->
|
||||
<div class="flex items-center">
|
||||
<div class="mr-6">
|
||||
<Upload
|
||||
@change="handleAvatarChange"
|
||||
:show-upload-list="false"
|
||||
accept="image/*"
|
||||
>
|
||||
<div class="relative cursor-pointer">
|
||||
<Spin
|
||||
v-if="avatarLoading"
|
||||
class="absolute inset-0 z-10 flex items-center justify-center bg-white/80"
|
||||
/>
|
||||
<img
|
||||
v-if="avatarSrc"
|
||||
:src="avatarSrc"
|
||||
alt="头像"
|
||||
class="h-24 w-24 rounded-full object-cover"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex h-24 w-24 items-center justify-center rounded-full bg-slate-200 text-2xl text-slate-400 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
{{ userInfo?.realName?.charAt(0) || '?' }}
|
||||
</div>
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity hover:opacity-100"
|
||||
>
|
||||
<span class="text-sm text-white">点击更换</span>
|
||||
</div>
|
||||
</div>
|
||||
</Upload>
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-medium text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
头像
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
点击选择新头像,保存后生效,建议大小不超过 2MB
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 用户名 -->
|
||||
<Form.Item
|
||||
label="用户名"
|
||||
name="loginCode"
|
||||
:rules="[{ required: true, message: '请输入用户名' }]"
|
||||
>
|
||||
<Input v-model:value="formData.loginCode" placeholder="请输入用户名" />
|
||||
</Form.Item>
|
||||
|
||||
<!-- 真实姓名 -->
|
||||
<Form.Item
|
||||
label="真实姓名"
|
||||
name="realName"
|
||||
:rules="[{ required: true, message: '请输入真实姓名' }]"
|
||||
>
|
||||
<Input v-model:value="formData.realName" placeholder="请输入真实姓名" />
|
||||
</Form.Item>
|
||||
|
||||
<!-- 手机号 -->
|
||||
<Form.Item label="手机号" name="phone">
|
||||
<Input
|
||||
v-model:value="formData.phone"
|
||||
placeholder="请输入手机号"
|
||||
:maxlength="11"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 备注 -->
|
||||
<Form.Item label="备注" name="remark">
|
||||
<Input.TextArea
|
||||
v-model:value="formData.remark"
|
||||
placeholder="请输入备注"
|
||||
:rows="3"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</div>
|
||||
|
||||
<!-- 底部按钮 -->
|
||||
<div class="flex justify-end gap-3 border-t border-slate-100 bg-slate-50/50 px-8 py-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
||||
<Button @click="handleReset">重置</Button>
|
||||
<Button type="primary" :loading="submitting" @click="handleSubmit">
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Spin>
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
<script lang="ts" setup>
|
||||
import { reactive, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import type { FormItemProps } from 'ant-design-vue';
|
||||
|
||||
import { Button, Form, Input, message, Spin } from 'ant-design-vue';
|
||||
|
||||
import { changePasswordApi } from '#/api/core/auth';
|
||||
|
||||
defineOptions({ name: 'ChangePassword' });
|
||||
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
|
||||
const formRef = ref<any>(null);
|
||||
const formData = reactive({
|
||||
oldPassword: '',
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
});
|
||||
|
||||
/** 放在 script 中,避免模板内联 validator 里 Promise 被误解析为组件属性 */
|
||||
const confirmPasswordRules: NonNullable<FormItemProps['rules']> = [
|
||||
{
|
||||
required: true,
|
||||
async validator(_rule: unknown, value: string) {
|
||||
if (!value?.trim()) {
|
||||
throw new Error('请确认密码');
|
||||
}
|
||||
if (value !== formData.newPassword) {
|
||||
throw new Error('两次输入的密码不一致');
|
||||
}
|
||||
},
|
||||
trigger: 'change',
|
||||
},
|
||||
];
|
||||
|
||||
async function handleSubmit() {
|
||||
try {
|
||||
await formRef.value?.validate();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
try {
|
||||
await changePasswordApi({
|
||||
oldPassword: formData.oldPassword,
|
||||
newPassword: formData.newPassword,
|
||||
});
|
||||
message.success('密码修改成功');
|
||||
formRef.value?.resetFields();
|
||||
router.push('/system/profile');
|
||||
} catch (err: any) {
|
||||
message.error(err?.message || '密码修改失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
formRef.value?.resetFields();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page
|
||||
title="修改密码"
|
||||
auto-content-height
|
||||
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<div class="mx-auto max-w-2xl">
|
||||
<div
|
||||
class="overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||
>
|
||||
<!-- 头部 -->
|
||||
<div class="border-b border-slate-100 bg-slate-50/50 px-8 py-6 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
||||
<h2 class="text-xl font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||
修改密码
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||
请妥善保管您的新密码
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 表单 -->
|
||||
<div class="px-8 py-6">
|
||||
<Spin :spinning="loading">
|
||||
<Form
|
||||
ref="formRef"
|
||||
:model="formData"
|
||||
layout="vertical"
|
||||
class="space-y-6"
|
||||
>
|
||||
<!-- 旧密码 -->
|
||||
<Form.Item
|
||||
label="旧密码"
|
||||
name="oldPassword"
|
||||
:rules="[{ required: true, message: '请输入旧密码' }]"
|
||||
>
|
||||
<Input.Password
|
||||
v-model:value="formData.oldPassword"
|
||||
placeholder="请输入旧密码"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 新密码 -->
|
||||
<Form.Item
|
||||
label="新密码"
|
||||
name="newPassword"
|
||||
:rules="[{ required: true, message: '请输入新密码' }]"
|
||||
>
|
||||
<Input.Password
|
||||
v-model:value="formData.newPassword"
|
||||
placeholder="请输入新密码"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<!-- 确认密码 -->
|
||||
<Form.Item
|
||||
label="确认密码"
|
||||
name="confirmPassword"
|
||||
:rules="confirmPasswordRules"
|
||||
>
|
||||
<Input.Password
|
||||
v-model:value="formData.confirmPassword"
|
||||
placeholder="请再次输入新密码"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Spin>
|
||||
</div>
|
||||
|
||||
<!-- 底部按钮 -->
|
||||
<div class="flex justify-end gap-3 border-t border-slate-100 bg-slate-50/50 px-8 py-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
||||
<Button @click="handleReset">重置</Button>
|
||||
<Button type="primary" :loading="loading" @click="handleSubmit">
|
||||
确定
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
@@ -0,0 +1,198 @@
|
||||
<script setup lang="ts">
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { PermissionVO } from '#/api/system/permission/types';
|
||||
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import { Spin, Tag, message } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import { getSystemPermissionTreeApi } from '#/api/system/permission';
|
||||
|
||||
defineOptions({ name: 'SystemPermissionPage' });
|
||||
|
||||
const loading = ref(false);
|
||||
const permissionData = ref<PermissionVO.PermissionInfoVO[]>([]);
|
||||
|
||||
// 获取系统权限树
|
||||
async function loadSystemPermissions() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await getSystemPermissionTreeApi();
|
||||
permissionData.value = result || [];
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '获取系统权限树失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 扁平化树数据(用于多级表格展示)
|
||||
interface FlatNode {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
type: string;
|
||||
status: number;
|
||||
sortOrder: number;
|
||||
parentId: number | null;
|
||||
level: number;
|
||||
children?: FlatNode[];
|
||||
hasChildren: boolean;
|
||||
}
|
||||
|
||||
function flattenTree(nodes: PermissionVO.PermissionInfoVO[], level = 0, result: FlatNode[] = []): FlatNode[] {
|
||||
for (const node of nodes) {
|
||||
const flat: FlatNode = {
|
||||
id: node.id!,
|
||||
name: node.name!,
|
||||
code: node.code!,
|
||||
type: node.type!,
|
||||
status: node.status!,
|
||||
sortOrder: node.sortOrder || 0,
|
||||
parentId: node.parentId ?? null,
|
||||
level,
|
||||
hasChildren: !!(node.children && node.children.length > 0),
|
||||
children: node.children ? flattenTree(node.children, level + 1, []) : undefined,
|
||||
};
|
||||
result.push(flat);
|
||||
if (node.children && node.children.length > 0) {
|
||||
flattenTree(node.children, level + 1, result);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// 表格配置
|
||||
const gridOptions: VxeGridProps<FlatNode> = {
|
||||
border: true,
|
||||
stripe: true,
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
columnConfig: {
|
||||
resizable: true,
|
||||
},
|
||||
rowConfig: {
|
||||
isHover: true,
|
||||
},
|
||||
columns: [
|
||||
{
|
||||
type: 'seq',
|
||||
width: 60,
|
||||
title: '序号',
|
||||
},
|
||||
{
|
||||
field: 'name',
|
||||
title: '权限名称',
|
||||
minWidth: 200,
|
||||
slots: { default: 'name' },
|
||||
},
|
||||
{
|
||||
field: 'code',
|
||||
title: '权限码',
|
||||
minWidth: 200,
|
||||
slots: { default: 'code' },
|
||||
},
|
||||
{
|
||||
field: 'type',
|
||||
title: '类型',
|
||||
width: 120,
|
||||
slots: { default: 'type' },
|
||||
},
|
||||
{
|
||||
field: 'sortOrder',
|
||||
title: '排序',
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
field: 'status',
|
||||
title: '状态',
|
||||
width: 100,
|
||||
slots: { default: 'status' },
|
||||
},
|
||||
],
|
||||
data: [],
|
||||
};
|
||||
|
||||
const [Grid] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
});
|
||||
|
||||
function getTypeText(type: string) {
|
||||
const map: Record<string, string> = {
|
||||
api: '接口权限',
|
||||
button: '按钮权限',
|
||||
data: '数据权限',
|
||||
module: '模块分组',
|
||||
};
|
||||
return map[type] || type;
|
||||
}
|
||||
|
||||
function getTypeTagColor(type: string) {
|
||||
const map: Record<string, string> = {
|
||||
api: 'processing',
|
||||
button: 'success',
|
||||
data: 'warning',
|
||||
module: 'purple',
|
||||
};
|
||||
return map[type] || 'default';
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadSystemPermissions().then(() => {
|
||||
const flatData = flattenTree(permissionData.value);
|
||||
const grid = (Grid as any).grid;
|
||||
if (grid) {
|
||||
grid.loadData(flatData);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="系统权限" auto-content-height>
|
||||
<template #description>
|
||||
<div class="text-foreground/80 mt-2">
|
||||
系统管理模块下的完整权限树,用于查看系统权限结构(平台超管专用)
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Spin :spinning="loading">
|
||||
<Grid>
|
||||
<template #name="{ row }">
|
||||
<span
|
||||
class="font-medium"
|
||||
:class="row.type === 'module' ? 'text-[var(--text-primary)]' : 'text-[var(--text-secondary)]'"
|
||||
:style="{ paddingLeft: (row.level * 20) + 'px' }"
|
||||
>
|
||||
<span v-if="row.hasChildren" class="mr-1">📁</span>
|
||||
<span v-else class="mr-1">📄</span>
|
||||
{{ row.name }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<template #code="{ row }">
|
||||
<code class="text-xs text-gray-500">{{ row.code }}</code>
|
||||
</template>
|
||||
|
||||
<template #type="{ row }">
|
||||
<Tag :color="getTypeTagColor(row.type)">
|
||||
{{ getTypeText(row.type) }}
|
||||
</Tag>
|
||||
</template>
|
||||
|
||||
<template #status="{ row }">
|
||||
<Tag :color="row.status === 1 ? 'green' : 'red'">
|
||||
{{ row.status === 1 ? '启用' : '禁用' }}
|
||||
</Tag>
|
||||
</template>
|
||||
</Grid>
|
||||
|
||||
<div v-if="!loading && permissionData.length === 0" class="py-12 text-center text-gray-400">
|
||||
暂无系统权限数据
|
||||
</div>
|
||||
</Spin>
|
||||
</Page>
|
||||
</template>
|
||||
Reference in New Issue
Block a user