feat(project): 添加vben5前端

This commit is contained in:
wcg
2026-01-04 13:45:07 +08:00
parent 2c0689fe02
commit 51ee3fb460
839 changed files with 74231 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
# \_core
此目录包含应用程序正常运行所需的基本视图。这些视图是应用程序布局中使用的视图。

View File

@@ -0,0 +1,9 @@
<script lang="ts" setup>
import { About } from '@vben/common-ui';
defineOptions({ name: 'About' });
</script>
<template>
<About />
</template>

View File

@@ -0,0 +1,144 @@
<script lang="ts" setup>
import type { LoginCodeParams, VbenFormSchema } from '@vben/common-ui';
import type { TenantResp } from '#/api';
import { computed, onMounted, ref, useTemplateRef } from 'vue';
import { AuthenticationCodeLogin, z } from '@vben/common-ui';
import { DEFAULT_TENANT_ID } from '@vben/constants';
import { $t } from '@vben/locales';
import { Alert, message } from 'ant-design-vue';
import { tenantList } from '#/api';
import { sendSmsCode } from '#/api/core/captcha';
import { useAuthStore } from '#/store';
defineOptions({ name: 'CodeLogin' });
const loading = ref(false);
const CODE_LENGTH = 4;
const tenantInfo = ref<TenantResp>({
tenantEnabled: false,
voList: [],
});
const codeLoginRef = useTemplateRef('codeLoginRef');
async function loadTenant() {
const resp = await tenantList();
tenantInfo.value = resp;
// 选中第一个租户
if (resp.tenantEnabled && resp.voList.length > 0) {
const firstTenantId = resp.voList[0]!.tenantId;
codeLoginRef.value?.getFormApi().setFieldValue('tenantId', firstTenantId);
}
}
onMounted(loadTenant);
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenSelect',
componentProps: {
class: 'bg-background h-[40px] focus:border-primary',
contentClass: 'max-h-[256px] overflow-y-auto',
options: tenantInfo.value.voList?.map((item) => ({
label: item.companyName,
value: item.tenantId,
})),
placeholder: $t('authentication.selectAccount'),
},
defaultValue: DEFAULT_TENANT_ID,
dependencies: {
if: () => tenantInfo.value.tenantEnabled,
triggerFields: [''],
},
fieldName: 'tenantId',
label: $t('authentication.selectAccount'),
rules: z.string().min(1, { message: $t('authentication.selectAccount') }),
},
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.mobile'),
},
fieldName: 'phoneNumber',
label: $t('authentication.mobile'),
rules: z
.string()
.min(1, { message: $t('authentication.mobileTip') })
.refine((v) => /^\d{11}$/.test(v), {
message: $t('authentication.mobileErrortip'),
}),
},
{
component: 'VbenPinInput',
componentProps(_, form) {
return {
createText: (countdown: number) => {
const text =
countdown > 0
? $t('authentication.sendText', [countdown])
: $t('authentication.sendCode');
return text;
},
// 验证码长度
codeLength: CODE_LENGTH,
placeholder: $t('authentication.code'),
handleSendCode: async () => {
const { valid, value } = await form.validateField('phoneNumber');
if (!valid) {
// 必须抛异常 不能直接return
throw new Error('未填写手机号');
}
// 调用接口发送
await sendSmsCode(value);
message.success('验证码发送成功');
},
};
},
fieldName: 'code',
label: $t('authentication.code'),
rules: z.string().length(CODE_LENGTH, {
message: $t('authentication.codeTip', [CODE_LENGTH]),
}),
},
];
});
const authStore = useAuthStore();
async function handleLogin(values: LoginCodeParams) {
try {
const requestParams: any = {
tenantId: values.tenantId,
phonenumber: values.phoneNumber,
smsCode: values.code,
grantType: 'sms',
};
console.log('login params', requestParams);
await authStore.authLogin(requestParams);
} catch (error) {
console.error(error);
}
}
</script>
<template>
<div>
<Alert
class="mb-4"
how-icon
message="测试手机号: 15888888888 正确验证码: 1234 演示使用 不会真的发送"
type="info"
/>
<AuthenticationCodeLogin
ref="codeLoginRef"
:form-schema="formSchema"
:loading="loading"
@submit="handleLogin"
/>
</div>
</template>

View File

@@ -0,0 +1,42 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';
import { computed, ref } from 'vue';
import { AuthenticationForgetPassword, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
defineOptions({ name: 'ForgetPassword' });
const loading = ref(false);
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenInput',
componentProps: {
placeholder: 'example@example.com',
},
fieldName: 'email',
label: $t('authentication.email'),
rules: z
.string()
.min(1, { message: $t('authentication.emailTip') })
.email($t('authentication.emailValidErrorTip')),
},
];
});
function handleSubmit(value: Recordable<any>) {
console.log('reset email:', value);
}
</script>
<template>
<AuthenticationForgetPassword
:form-schema="formSchema"
:loading="loading"
@submit="handleSubmit"
/>
</template>

View File

@@ -0,0 +1,180 @@
<script lang="ts" setup>
import type { LoginAndRegisterParams, VbenFormSchema } from '@vben/common-ui';
import type { TenantResp } from '#/api';
import type { CaptchaResponse } from '#/api/core/captcha';
import { computed, onMounted, ref, useTemplateRef } from 'vue';
import { AuthenticationLogin, z } from '@vben/common-ui';
import { DEFAULT_TENANT_ID } from '@vben/constants';
import { $t } from '@vben/locales';
import { omit } from 'lodash-es';
import { tenantList } from '#/api';
import { captchaImage } from '#/api/core/captcha';
import { useAuthStore } from '#/store';
import { useLoginTenantId } from '../oauth-common';
import OAuthLogin from './oauth-login.vue';
defineOptions({ name: 'Login' });
const authStore = useAuthStore();
const loginFormRef = useTemplateRef('loginFormRef');
const captchaInfo = ref<CaptchaResponse>({
isEnableCaptcha: false,
img: '',
uuid: '',
});
// 验证码loading
const captchaLoading = ref(false);
async function loadCaptcha() {
try {
captchaLoading.value = true;
const resp = await captchaImage();
if (resp.isEnableCaptcha) {
resp.img = `data:image/png;base64,${resp.img}`;
}
captchaInfo.value = resp;
} catch (error) {
console.error(error);
} finally {
captchaLoading.value = false;
}
}
const tenantInfo = ref<TenantResp>({
tenantEnabled: false,
voList: [],
});
async function loadTenant() {
const resp = await tenantList();
tenantInfo.value = resp;
// 选中第一个租户
if (resp.tenantEnabled && resp.voList.length > 0) {
const firstTenantId = resp.voList[0]!.tenantId;
loginFormRef.value?.getFormApi().setFieldValue('tenantId', firstTenantId);
}
}
onMounted(async () => {
await Promise.all([loadCaptcha(), loadTenant()]);
});
const { loginTenantId } = useLoginTenantId();
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenSelect',
componentProps: {
class: 'bg-background h-[40px] focus:border-primary',
contentClass: 'max-h-[256px] overflow-y-auto',
options: tenantInfo.value.voList?.map((item) => ({
label: item.companyName,
value: item.tenantId,
})),
placeholder: $t('authentication.selectAccount'),
},
defaultValue: DEFAULT_TENANT_ID,
dependencies: {
if: () => tenantInfo.value.tenantEnabled,
// 可以把这里当做watch
trigger: (model) => {
// 给oauth登录使用
loginTenantId.value = model?.tenantId ?? DEFAULT_TENANT_ID;
},
triggerFields: ['', 'tenantId'],
},
fieldName: 'tenantId',
label: $t('authentication.selectAccount'),
rules: z.string().min(1, { message: $t('authentication.selectAccount') }),
},
{
component: 'VbenInput',
componentProps: {
class: 'focus:border-primary',
placeholder: $t('authentication.usernameTip'),
},
defaultValue: 'cc',
fieldName: 'username',
label: $t('authentication.username'),
rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
},
{
component: 'VbenInputPassword',
componentProps: {
class: 'focus:border-primary',
placeholder: $t('authentication.password'),
},
defaultValue: '123456',
fieldName: 'password',
label: $t('authentication.password'),
rules: z.string().min(5, { message: $t('authentication.passwordTip') }),
},
{
component: 'VbenInputCaptcha',
componentProps: {
captcha: captchaInfo.value.img,
class: 'focus:border-primary',
onCaptchaClick: loadCaptcha,
placeholder: $t('authentication.code'),
loading: captchaLoading.value,
},
dependencies: {
if: () => captchaInfo.value.isEnableCaptcha,
triggerFields: [''],
},
fieldName: 'code',
label: $t('authentication.code'),
rules: z
.string()
.min(1, { message: $t('authentication.verifyRequiredTip') }),
},
];
});
async function handleAccountLogin(values: LoginAndRegisterParams) {
try {
const requestParam: any = omit(values, ['code']);
// 验证码
if (captchaInfo.value.isEnableCaptcha) {
requestParam.code = values.code;
requestParam.uuid = captchaInfo.value.uuid;
}
// 登录
await authStore.authLogin(requestParam);
} catch (error) {
console.error(error);
// 处理验证码错误
if (error instanceof Error) {
// 刷新验证码
loginFormRef.value?.getFormApi().setFieldValue('code', '');
await loadCaptcha();
}
}
}
</script>
<template>
<AuthenticationLogin
ref="loginFormRef"
:form-schema="formSchema"
:loading="authStore.loginLoading"
:show-register="false"
:show-third-party-login="true"
@submit="handleAccountLogin"
>
<!-- 可通过show-third-party-login控制是否显示第三方登录 -->
<template #third-party-login>
<OAuthLogin />
</template>
</AuthenticationLogin>
</template>

View File

@@ -0,0 +1,44 @@
<script setup lang="ts">
import { $t } from '@vben/locales';
import { Col, Row, Tooltip } from 'ant-design-vue';
import { accountBindList, handleAuthBinding } from '../oauth-common';
defineOptions({
name: 'OAuthLogin',
});
</script>
<template>
<div class="w-full sm:mx-auto md:max-w-md">
<div class="my-4 flex items-center justify-between">
<span class="border-input w-[35%] border-b dark:border-gray-600"></span>
<span class="text-muted-foreground text-center text-xs uppercase">
{{ $t('authentication.thirdPartyLogin') }}
</span>
<span class="border-input w-[35%] border-b dark:border-gray-600"></span>
</div>
<Row class="enter-x flex items-center justify-evenly">
<!-- todo 这里在点击登录时要disabled -->
<Col
v-for="item in accountBindList"
:key="item.source"
:span="4"
class="my-2"
>
<Tooltip :title="`${item.title}登录`">
<span class="flex cursor-pointer items-center justify-center">
<component
v-if="item.avatar"
:is="item.avatar"
:style="item?.style ?? {}"
class="size-[24px]"
@click="handleAuthBinding(item.source)"
/>
</span>
</Tooltip>
</Col>
</Row>
</div>
</template>

View File

@@ -0,0 +1,10 @@
<script lang="ts" setup>
import { AuthenticationQrCodeLogin } from '@vben/common-ui';
import { LOGIN_PATH } from '@vben/constants';
defineOptions({ name: 'QrCodeLogin' });
</script>
<template>
<AuthenticationQrCodeLogin :login-path="LOGIN_PATH" />
</template>

View File

@@ -0,0 +1,95 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';
import { computed, h, ref } from 'vue';
import { AuthenticationRegister, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
defineOptions({ name: 'Register' });
const loading = ref(false);
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.usernameTip'),
},
fieldName: 'username',
label: $t('authentication.username'),
rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
},
{
component: 'VbenInputPassword',
componentProps: {
passwordStrength: true,
placeholder: $t('authentication.password'),
},
fieldName: 'password',
label: $t('authentication.password'),
renderComponentContent() {
return {
strengthText: () => $t('authentication.passwordStrength'),
};
},
rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
},
{
component: 'VbenInputPassword',
componentProps: {
placeholder: $t('authentication.confirmPassword'),
},
dependencies: {
rules(values) {
const { password } = values;
return z
.string({ required_error: $t('authentication.passwordTip') })
.min(1, { message: $t('authentication.passwordTip') })
.refine((value) => value === password, {
message: $t('authentication.confirmPasswordTip'),
});
},
triggerFields: ['password'],
},
fieldName: 'confirmPassword',
label: $t('authentication.confirmPassword'),
},
{
component: 'VbenCheckbox',
fieldName: 'agreePolicy',
renderComponentContent: () => ({
default: () =>
h('span', [
$t('authentication.agree'),
h(
'a',
{
class: 'vben-link ml-1 ',
href: '',
},
`${$t('authentication.privacyPolicy')} & ${$t('authentication.terms')}`,
),
]),
}),
rules: z.boolean().refine((value) => !!value, {
message: $t('authentication.agreeTip'),
}),
},
];
});
function handleSubmit(value: Recordable<any>) {
console.log('register submit:', value);
}
</script>
<template>
<AuthenticationRegister
:form-schema="formSchema"
:loading="loading"
@submit="handleSubmit"
/>
</template>

View File

@@ -0,0 +1,7 @@
<script lang="ts" setup>
import { Fallback } from '@vben/common-ui';
</script>
<template>
<Fallback status="coming-soon" />
</template>

View File

@@ -0,0 +1,9 @@
<script lang="ts" setup>
import { Fallback } from '@vben/common-ui';
defineOptions({ name: 'Fallback403Demo' });
</script>
<template>
<Fallback status="403" />
</template>

View File

@@ -0,0 +1,9 @@
<script lang="ts" setup>
import { Fallback } from '@vben/common-ui';
defineOptions({ name: 'Fallback500Demo' });
</script>
<template>
<Fallback status="500" />
</template>

View File

@@ -0,0 +1,9 @@
<script lang="ts" setup>
import { Fallback } from '@vben/common-ui';
defineOptions({ name: 'Fallback404Demo' });
</script>
<template>
<Fallback status="404" />
</template>

View File

@@ -0,0 +1,9 @@
<script lang="ts" setup>
import { Fallback } from '@vben/common-ui';
defineOptions({ name: 'FallbackOfflineDemo' });
</script>
<template>
<Fallback status="offline" />
</template>

View File

@@ -0,0 +1,102 @@
import type { Component, CSSProperties } from 'vue';
import { markRaw, ref } from 'vue';
import { DEFAULT_TENANT_ID } from '@vben/constants';
import {
GiteeIcon,
GithubOAuthIcon,
SvgMaxKeyIcon,
SvgTopiamIcon,
SvgWechatIcon,
} from '@vben/icons';
import { createGlobalState } from '@vueuse/core';
import { authBinding } from '#/api/core/auth';
/**
* @description: oauth登录
* @param title 标题
* @param description 描述
* @param avatar 图标
* @param color 图标颜色可直接写英文颜色/hex
*/
export interface ListItem {
title: string;
description: string;
avatar?: Component;
style?: CSSProperties;
}
/**
* @description: 绑定账号
* @param source 来源 如gitee github 与后端的social-callback?source=xxx对应
* @param bound 是否已经绑定
*/
export interface BindItem extends ListItem {
source: string;
bound?: boolean;
}
/**
* 这里存储登录页的tenantId 由于个人中心也会用到 需要共享
* 所以使用`createGlobalState`
* @see https://vueuse.org/shared/createGlobalState/
*/
export const useLoginTenantId = createGlobalState(() => {
const loginTenantId = ref(DEFAULT_TENANT_ID);
return {
loginTenantId,
};
});
/**
* 绑定授权
* @param source
*/
export async function handleAuthBinding(source: string) {
const { loginTenantId } = useLoginTenantId();
// 这里返回打开授权页面的链接
const href = await authBinding(source, loginTenantId.value);
window.location.href = href;
}
/**
* 账号绑定 list
* 添加账号绑定只需要在这里增加即可
*/
export const accountBindList: BindItem[] = [
{
avatar: markRaw(GiteeIcon),
description: '绑定Gitee账号',
source: 'gitee',
title: 'Gitee',
style: { color: '#c71d23' },
},
{
avatar: markRaw(GithubOAuthIcon),
description: '绑定Github账号',
source: 'github',
title: 'Github',
},
{
avatar: markRaw(SvgMaxKeyIcon),
description: '绑定MaxKey账号',
source: 'maxkey',
title: 'MaxKey',
},
{
avatar: markRaw(SvgTopiamIcon),
description: '绑定topiam账号',
source: 'topiam',
title: 'Topiam',
},
{
avatar: markRaw(SvgWechatIcon),
description: '绑定wechat账号',
source: 'wechat',
title: 'Wechat',
},
];

View File

@@ -0,0 +1,150 @@
<script setup lang="tsx">
import type { BindItem } from '../../oauth-common';
import type { SocialInfo } from '#/api/system/social/model';
import { onMounted, ref } from 'vue';
import { Alert, Avatar, Card, Empty, Modal, Tooltip } from 'ant-design-vue';
import { authUnbinding } from '#/api';
import { socialList } from '#/api/system/social';
import { accountBindList, handleAuthBinding } from '../../oauth-common';
interface BindItemWithInfo extends BindItem {
info?: SocialInfo;
bind?: boolean;
}
const bindList = ref<BindItemWithInfo[]>([]);
async function loadData() {
const resp = await socialList();
const list: BindItemWithInfo[] = [...accountBindList];
list.forEach((item) => {
/**
* 平台转小写
*/
item.bound = resp
.map((social) => social.source.toLowerCase())
.includes(item.source.toLowerCase());
/**
* 添加info信息
*/
if (item.bound) {
item.info = resp.find(
(social) => social.source.toLowerCase() === item.source,
);
}
});
bindList.value = list;
}
onMounted(loadData);
/**
* 解绑账号
*/
function handleUnbind(record: BindItemWithInfo) {
if (!record.info) {
return;
}
Modal.confirm({
content: `确定解绑[${record.source}]平台的[${record.info.userName}]账号吗?`,
async onOk() {
await authUnbinding(record.info!.id);
await loadData();
},
title: '提示',
type: 'warning',
});
}
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
</script>
<template>
<div class="flex flex-col gap-4 pb-4">
<div
v-if="bindList.length > 0"
class="grid grid-cols-1 gap-4 lg:grid-cols-2 2xl:grid-cols-3"
>
<Card
class="transition-shadow duration-300 hover:shadow-md"
v-for="item in bindList"
:key="item.source"
>
<div class="flex w-full items-center gap-4">
<component
:is="item.avatar"
v-if="item.avatar"
:style="item?.style ?? {}"
class="size-[40px]"
/>
<div class="flex flex-1 items-center justify-between">
<div class="flex flex-col">
<h4 class="mb-[4px] text-[14px] text-black/85 dark:text-white/85">
{{ item.title }}
</h4>
<span class="text-black/45 dark:text-white/45">
<template v-if="!item.bound">
{{ item.description }}
</template>
<template v-if="item.bound && item.info">
<Tooltip>
<template #title>
<div class="flex flex-col items-center gap-2 p-2">
<Avatar :size="36" :src="item.info.avatar" />
<div>绑定时间: {{ item.info.createTime }}</div>
</div>
</template>
<div class="cursor-pointer">
已绑定: {{ item.info.nickName }}
</div>
</Tooltip>
</template>
</span>
</div>
<!-- TODO: 这里有优化空间? -->
<a-button
size="small"
:type="item.bound ? 'default' : 'link'"
@click="
item.bound ? handleUnbind(item) : handleAuthBinding(item.source)
"
>
{{ item.bound ? '取消绑定' : '绑定' }}
</a-button>
</div>
</div>
</Card>
</div>
<div
v-if="bindList.length === 0"
class="flex items-center justify-center rounded-lg border py-4"
>
<Empty :image="simpleImage" description="暂无可绑定的第三方账户" />
</div>
<Alert message="说明" type="info">
<template #description>
<p>
需要添加第三方账号在
<span class="font-bold">
apps\web-antd\src\views\_core\oauth-common.ts
</span>
中accountBindList按模板添加
</p>
</template>
</Alert>
</div>
</template>
<style lang="scss" scoped>
/**
list item 间距
*/
:deep(.ant-list-item) {
padding: 6px;
}
</style>

View File

@@ -0,0 +1,120 @@
<script setup lang="ts">
import type { Recordable } from '@vben/types';
import type { UserProfile } from '#/api/system/profile/model';
import { onMounted } from 'vue';
import { DictEnum } from '@vben/constants';
import { useUserStore } from '@vben/stores';
import { pick } from 'lodash-es';
import { useVbenForm, z } from '#/adapter/form';
import { userProfileUpdate } from '#/api/system/profile';
import { useAuthStore } from '#/store';
import { getDictOptions } from '#/utils/dict';
import { emitter } from '../mitt';
const props = defineProps<{ profile: UserProfile }>();
const userStore = useUserStore();
const authStore = useAuthStore();
const [BasicForm, formApi] = useVbenForm({
actionWrapperClass: 'text-left ml-[68px] mb-[16px]',
commonConfig: {
labelWidth: 60,
},
handleSubmit,
resetButtonOptions: {
show: false,
},
schema: [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'userId',
label: '用户ID',
rules: 'required',
},
{
component: 'Input',
fieldName: 'nickName',
label: '昵称',
rules: 'required',
},
{
component: 'Input',
fieldName: 'email',
label: '邮箱',
rules: z.string().email('请输入正确的邮箱'),
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: getDictOptions(DictEnum.SYS_USER_SEX),
optionType: 'button',
},
defaultValue: '0',
fieldName: 'sex',
label: '性别',
rules: 'required',
},
{
component: 'Input',
fieldName: 'phonenumber',
label: '电话',
rules: z.string().regex(/^1[3-9]\d{9}$/, '请输入正确的电话'),
},
],
submitButtonOptions: {
content: '更新信息',
},
});
function buttonLoading(loading: boolean) {
formApi.setState((prev) => ({
...prev,
submitButtonOptions: { ...prev.submitButtonOptions, loading },
}));
}
async function handleSubmit(values: Recordable<any>) {
try {
buttonLoading(true);
await userProfileUpdate(values);
// 更新store
const userInfo = await authStore.fetchUserInfo();
userStore.setUserInfo(userInfo);
// 左边reload
emitter.emit('updateProfile');
} catch (error) {
console.error(error);
} finally {
buttonLoading(false);
}
}
onMounted(() => {
const data = pick(props.profile.user, [
'userId',
'nickName',
'email',
'phonenumber',
'sex',
]);
formApi.setValues(data);
});
</script>
<template>
<div class="mt-[16px] md:w-full lg:w-1/2 2xl:w-2/5">
<BasicForm />
</div>
</template>

View File

@@ -0,0 +1,52 @@
<script setup lang="ts">
import type { Recordable } from '@vben/types';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { Popconfirm } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { forceLogout2, onlineDeviceList } from '#/api/monitor/online';
import { columns } from '#/views/monitor/online/data';
const gridOptions: VxeGridProps = {
columns,
keepSource: true,
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async () => {
return await onlineDeviceList();
},
},
},
rowConfig: {
keyField: 'tokenId',
},
};
const [BasicTable, tableApi] = useVbenVxeGrid({ gridOptions });
async function handleForceOffline(row: Recordable<any>) {
await forceLogout2(row.tokenId);
await tableApi.query();
}
</script>
<template>
<div>
<BasicTable table-title="我的在线设备">
<template #action="{ row }">
<Popconfirm
:title="`确认强制下线[${row.userName}]?`"
placement="left"
@confirm="handleForceOffline(row)"
>
<a-button danger size="small" type="link">强制下线</a-button>
</Popconfirm>
</template>
</BasicTable>
</div>
</template>

View File

@@ -0,0 +1,106 @@
<script setup lang="ts">
import type { UpdatePasswordParam } from '#/api/system/profile/model';
import { Modal } from 'ant-design-vue';
import { omit } from 'lodash-es';
import { useVbenForm, z } from '#/adapter/form';
import { userUpdatePassword } from '#/api/system/profile';
import { useAuthStore } from '#/store';
const [BasicForm, formApi] = useVbenForm({
actionWrapperClass: 'text-left mb-[16px] ml-[96px]',
commonConfig: {
labelWidth: 90,
},
handleSubmit,
resetButtonOptions: {
show: false,
},
schema: [
{
component: 'InputPassword',
fieldName: 'oldPassword',
label: '旧密码',
rules: z
.string({ message: '请输入密码' })
.min(5, '密码长度不能少于5个字符')
.max(20, '密码长度不能超过20个字符'),
},
{
component: 'InputPassword',
dependencies: {
rules(values) {
return z
.string({ message: '请输入新密码' })
.min(5, '密码长度不能少于5个字符')
.max(20, '密码长度不能超过20个字符')
.refine(
(value) => value !== values.oldPassword,
'新旧密码不能相同',
);
},
triggerFields: ['newPassword', 'oldPassword'],
},
fieldName: 'newPassword',
label: '新密码',
rules: 'required',
},
{
component: 'InputPassword',
dependencies: {
rules(values) {
return z
.string({ message: '请输入确认密码' })
.min(5, '密码长度不能少于5个字符')
.max(20, '密码长度不能超过20个字符')
.refine(
(value) => value === values.newPassword,
'新密码和确认密码不一致',
);
},
triggerFields: ['newPassword', 'confirmPassword'],
},
fieldName: 'confirmPassword',
label: '确认密码',
rules: 'required',
},
],
submitButtonOptions: {
content: '修改密码',
},
});
function buttonLoading(loading: boolean) {
formApi.setState((prev) => ({
...prev,
submitButtonOptions: { ...prev.submitButtonOptions, loading },
}));
}
const authStore = useAuthStore();
function handleSubmit(values: any) {
Modal.confirm({
content: '确认修改密码吗?',
onOk: async () => {
try {
buttonLoading(true);
const data = omit(values, ['confirmPassword']) as UpdatePasswordParam;
await userUpdatePassword(data);
await authStore.logout(true);
} catch (error) {
console.error(error);
} finally {
buttonLoading(false);
}
},
title: '提示',
});
}
</script>
<template>
<div class="mt-[16px] md:w-full lg:w-1/2 2xl:w-2/5">
<BasicForm />
</div>
</template>

View File

@@ -0,0 +1,54 @@
<script setup lang="ts">
import type { UserProfile } from '#/api/system/profile/model';
import { onMounted, onUnmounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';
import { userProfile } from '#/api/system/profile';
import { useAuthStore } from '#/store';
import { emitter } from './mitt';
import ProfilePanel from './profile-panel.vue';
import SettingPanel from './setting-panel.vue';
const profile = ref<UserProfile>();
async function loadProfile() {
const resp = await userProfile();
profile.value = resp;
}
onMounted(loadProfile);
const authStore = useAuthStore();
const userStore = useUserStore();
/**
* ToDo 接口重复
*/
async function handleUploadFinish() {
// 重新加载用户信息
await loadProfile();
// 更新store
const userInfo = await authStore.fetchUserInfo();
userStore.setUserInfo(userInfo);
}
onMounted(() => emitter.on('updateProfile', loadProfile));
onUnmounted(() => emitter.off('updateProfile'));
</script>
<template>
<Page>
<div class="flex flex-col gap-[16px] lg:flex-row">
<!-- 左侧 -->
<ProfilePanel :profile="profile" @upload-finish="handleUploadFinish" />
<!-- 右侧 -->
<SettingPanel
v-if="profile"
:profile="profile"
class="flex-1 overflow-hidden"
/>
</div>
</Page>
</template>

View File

@@ -0,0 +1,7 @@
import { mitt } from '@vben/utils';
type Events = {
updateProfile: void;
};
export const emitter = mitt<Events>();

View File

@@ -0,0 +1,84 @@
<script setup lang="ts">
import type { UserProfile } from '#/api/system/profile/model';
import { computed } from 'vue';
import { preferences, usePreferences } from '@vben/preferences';
import {
Card,
Descriptions,
DescriptionsItem,
Tag,
Tooltip,
} from 'ant-design-vue';
import { userUpdateAvatar } from '#/api/system/profile';
import { CropperAvatar } from '#/components/cropper';
const props = defineProps<{ profile?: UserProfile }>();
defineEmits<{
// 头像上传完毕
uploadFinish: [];
}>();
const avatar = computed(
() => props.profile?.user.avatar || preferences.app.defaultAvatar,
);
const { isDark } = usePreferences();
const poetrySrc = computed(() => {
const color = isDark.value ? 'white' : 'gray';
return `https://v2.jinrishici.com/one.svg?font-size=12&color=${color}`;
});
</script>
<template>
<Card :loading="!profile" class="h-full lg:w-1/3">
<div v-if="profile" class="flex flex-col items-center gap-[24px]">
<div class="flex flex-col items-center gap-[20px]">
<Tooltip title="点击上传头像">
<CropperAvatar
:show-btn="false"
:upload-api="userUpdateAvatar"
:value="avatar"
width="120"
@change="$emit('uploadFinish')"
/>
</Tooltip>
<div class="flex flex-col items-center gap-[8px]">
<span class="text-foreground text-xl font-bold">
{{ profile.user.nickName ?? '未知' }}
</span>
<!-- https://www.jinrishici.com/doc/#image -->
<img :src="poetrySrc" />
</div>
</div>
<div class="px-[24px]">
<Descriptions :column="1">
<DescriptionsItem label="账号">
{{ profile.user.userName }}
</DescriptionsItem>
<DescriptionsItem label="手机号码">
{{ profile.user.phonenumber || '未绑定手机号' }}
</DescriptionsItem>
<DescriptionsItem label="邮箱">
{{ profile.user.email || '未绑定邮箱' }}
</DescriptionsItem>
<DescriptionsItem label="部门">
<Tag color="processing">
{{ profile.user.deptName ?? '未分配部门' }}
</Tag>
<Tag v-if="profile.postGroup" color="processing">
{{ profile.postGroup }}
</Tag>
</DescriptionsItem>
<DescriptionsItem label="上次登录">
{{ profile.user.loginDate }}
</DescriptionsItem>
</Descriptions>
</div>
</div>
</Card>
</template>

View File

@@ -0,0 +1,39 @@
<script setup lang="ts">
import { TabPane, Tabs } from 'ant-design-vue';
import AccountBind from './components/account-bind.vue';
import BaseSetting from './components/base-setting.vue';
import OnlineDevice from './components/online-device.vue';
import SecureSetting from './components/secure-setting.vue';
const settingList = [
{
component: BaseSetting,
key: '1',
name: '基本设置',
},
{
component: SecureSetting,
key: '2',
name: '安全设置',
},
{
component: AccountBind,
key: '3',
name: '账号绑定',
},
{
component: OnlineDevice,
key: '4',
name: '在线设备',
},
];
</script>
<template>
<Tabs class="bg-background rounded-[var(--radius)] px-[16px] lg:flex-1">
<TabPane v-for="item in settingList" :key="item.key" :tab="item.name">
<component :is="item.component" v-bind="$attrs" />
</TabPane>
</Tabs>
</template>

View File

@@ -0,0 +1,84 @@
<script setup lang="ts">
import type { AuthApi } from '#/api';
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { DEFAULT_TENANT_ID } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { useAccessStore } from '@vben/stores';
import { message } from 'ant-design-vue';
import { authCallback } from '#/api';
import { useAuthStore } from '#/store';
import { accountBindList } from '../oauth-common';
const route = useRoute();
const code = route.query.code as string;
const state = route.query.state as string;
const stateJson = JSON.parse(atob(state));
// 来源
const source = route.query.source as string;
// 租户ID
const defaultTenantId = DEFAULT_TENANT_ID;
const tenantId = (stateJson.tenantId as string) ?? defaultTenantId;
const domain = stateJson.domain as string;
const accessStore = useAccessStore();
const authStore = useAuthStore();
const router = useRouter();
onMounted(async () => {
// 如果域名不相等 则重定向处理
const host = window.location.host;
if (domain !== host) {
const urlFull = new URL(window.location.href);
urlFull.host = domain;
window.location.href = urlFull.toString();
return;
}
try {
// 已经实现的平台
const currentClient = accountBindList.find(
(item) => item.source === source,
);
if (!currentClient) {
message.error({ content: `未找到${source}平台` });
return;
}
const data: AuthApi.OAuthLoginParams = {
grantType: 'social',
socialCode: code,
socialState: state,
source,
tenantId,
};
// 没有token为登录 有token是授权
if (accessStore.accessToken) {
await authCallback(data);
message.success(`${source}授权成功`);
} else {
// todo
await authStore.authLogin(data as any);
message.success(`${source}登录成功`);
}
} catch {
// 500 你还没有绑定第三方账号,绑定后才可以登录!
} finally {
setTimeout(() => {
router.push(preferences.app.defaultHomePath);
}, 1500);
}
});
</script>
<template>
<div></div>
</template>
<style scoped></style>

View File

@@ -0,0 +1,97 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { onMounted, ref } from 'vue';
const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);
onMounted(() => {
renderEcharts({
grid: {
bottom: 0,
containLabel: true,
left: '1%',
right: '1%',
top: '2 %',
},
series: [
{
areaStyle: {},
data: [
111, 2000, 6000, 16_000, 33_333, 55_555, 64_000, 33_333, 18_000,
36_000, 70_000, 42_444, 23_222, 13_000, 8000, 4000, 1200, 333, 222,
111,
],
itemStyle: {
color: '#5ab1ef',
},
smooth: true,
type: 'line',
},
{
areaStyle: {},
data: [
33, 66, 88, 333, 3333, 6200, 20_000, 3000, 1200, 13_000, 22_000,
11_000, 2221, 1201, 390, 198, 60, 30, 22, 11,
],
itemStyle: {
color: '#019680',
},
smooth: true,
type: 'line',
},
],
tooltip: {
axisPointer: {
lineStyle: {
color: '#019680',
width: 1,
},
},
trigger: 'axis',
},
// xAxis: {
// axisTick: {
// show: false,
// },
// boundaryGap: false,
// data: Array.from({ length: 18 }).map((_item, index) => `${index + 6}:00`),
// type: 'category',
// },
xAxis: {
axisTick: {
show: false,
},
boundaryGap: false,
data: Array.from({ length: 18 }).map((_item, index) => `${index + 6}:00`),
splitLine: {
lineStyle: {
type: 'solid',
width: 1,
},
show: true,
},
type: 'category',
},
yAxis: [
{
axisTick: {
show: false,
},
max: 80_000,
splitArea: {
show: true,
},
splitNumber: 4,
type: 'value',
},
],
});
});
</script>
<template>
<EchartsUI ref="chartRef" />
</template>

View File

@@ -0,0 +1,81 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { onMounted, ref } from 'vue';
const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);
onMounted(() => {
renderEcharts({
legend: {
bottom: 0,
data: ['访问', '趋势'],
},
radar: {
indicator: [
{
name: '网页',
},
{
name: '移动端',
},
{
name: 'Ipad',
},
{
name: '客户端',
},
{
name: '第三方',
},
{
name: '其它',
},
],
radius: '60%',
splitNumber: 8,
},
series: [
{
areaStyle: {
opacity: 1,
shadowBlur: 0,
shadowColor: 'rgba(0,0,0,.2)',
shadowOffsetX: 0,
shadowOffsetY: 10,
},
data: [
{
itemStyle: {
color: '#b6a2de',
},
name: '访问',
value: [90, 50, 86, 40, 50, 20],
},
{
itemStyle: {
color: '#5ab1ef',
},
name: '趋势',
value: [70, 75, 70, 76, 20, 85],
},
],
itemStyle: {
// borderColor: '#fff',
borderRadius: 10,
borderWidth: 2,
},
symbolSize: 0,
type: 'radar',
},
],
tooltip: {},
});
});
</script>
<template>
<EchartsUI ref="chartRef" />
</template>

View File

@@ -0,0 +1,45 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { onMounted, ref } from 'vue';
const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);
onMounted(() => {
renderEcharts({
series: [
{
animationDelay() {
return Math.random() * 400;
},
animationEasing: 'exponentialInOut',
animationType: 'scale',
center: ['50%', '50%'],
color: ['#5ab1ef', '#b6a2de', '#67e0e3', '#2ec7c9'],
data: [
{ name: '外包', value: 500 },
{ name: '定制', value: 310 },
{ name: '技术支持', value: 274 },
{ name: '远程', value: 400 },
].sort((a, b) => {
return a.value - b.value;
}),
name: '商业占比',
radius: '80%',
roseType: 'radius',
type: 'pie',
},
],
tooltip: {
trigger: 'item',
},
});
});
</script>
<template>
<EchartsUI ref="chartRef" />
</template>

View File

@@ -0,0 +1,64 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { onMounted, ref } from 'vue';
const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);
onMounted(() => {
renderEcharts({
legend: {
bottom: '2%',
left: 'center',
},
series: [
{
animationDelay() {
return Math.random() * 100;
},
animationEasing: 'exponentialInOut',
animationType: 'scale',
avoidLabelOverlap: false,
color: ['#5ab1ef', '#b6a2de', '#67e0e3', '#2ec7c9'],
data: [
{ name: '搜索引擎', value: 1048 },
{ name: '直接访问', value: 735 },
{ name: '邮件营销', value: 580 },
{ name: '联盟广告', value: 484 },
],
emphasis: {
label: {
fontSize: '12',
fontWeight: 'bold',
show: true,
},
},
itemStyle: {
// borderColor: '#fff',
borderRadius: 10,
borderWidth: 2,
},
label: {
position: 'center',
show: false,
},
labelLine: {
show: false,
},
name: '访问来源',
radius: ['40%', '65%'],
type: 'pie',
},
],
tooltip: {
trigger: 'item',
},
});
});
</script>
<template>
<EchartsUI ref="chartRef" />
</template>

View File

@@ -0,0 +1,54 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { onMounted, ref } from 'vue';
const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);
onMounted(() => {
renderEcharts({
grid: {
bottom: 0,
containLabel: true,
left: '1%',
right: '1%',
top: '2 %',
},
series: [
{
barMaxWidth: 80,
// color: '#4f69fd',
data: [
3000, 2000, 3333, 5000, 3200, 4200, 3200, 2100, 3000, 5100, 6000,
3200, 4800,
],
type: 'bar',
},
],
tooltip: {
axisPointer: {
lineStyle: {
// color: '#4f69fd',
width: 1,
},
},
trigger: 'axis',
},
xAxis: {
data: Array.from({ length: 12 }).map((_item, index) => `${index + 1}`),
type: 'category',
},
yAxis: {
max: 8000,
splitNumber: 4,
type: 'value',
},
});
});
</script>
<template>
<EchartsUI ref="chartRef" />
</template>

View File

@@ -0,0 +1,90 @@
<script lang="ts" setup>
import type { AnalysisOverviewItem } from '@vben/common-ui';
import type { TabOption } from '@vben/types';
import {
AnalysisChartCard,
AnalysisChartsTabs,
AnalysisOverview,
} from '@vben/common-ui';
import {
SvgBellIcon,
SvgCakeIcon,
SvgCardIcon,
SvgDownloadIcon,
} from '@vben/icons';
import AnalyticsTrends from './analytics-trends.vue';
import AnalyticsVisitsData from './analytics-visits-data.vue';
import AnalyticsVisitsSales from './analytics-visits-sales.vue';
import AnalyticsVisitsSource from './analytics-visits-source.vue';
import AnalyticsVisits from './analytics-visits.vue';
const overviewItems: AnalysisOverviewItem[] = [
{
icon: SvgCardIcon,
title: '用户量',
totalTitle: '总用户量',
totalValue: 120_000,
value: 2000,
},
{
icon: SvgCakeIcon,
title: '访问量',
totalTitle: '总访问量',
totalValue: 500_000,
value: 20_000,
},
{
icon: SvgDownloadIcon,
title: '下载量',
totalTitle: '总下载量',
totalValue: 120_000,
value: 8000,
},
{
icon: SvgBellIcon,
title: '使用量',
totalTitle: '总使用量',
totalValue: 50_000,
value: 5000,
},
];
const chartTabs: TabOption[] = [
{
label: '流量趋势',
value: 'trends',
},
{
label: '月访问量',
value: 'visits',
},
];
</script>
<template>
<div class="p-5">
<AnalysisOverview :items="overviewItems" />
<AnalysisChartsTabs :tabs="chartTabs" class="mt-5">
<template #trends>
<AnalyticsTrends />
</template>
<template #visits>
<AnalyticsVisits />
</template>
</AnalysisChartsTabs>
<div class="mt-5 w-full md:flex">
<AnalysisChartCard class="mt-5 md:mr-4 md:mt-0 md:w-1/3" title="访问数量">
<AnalyticsVisitsData />
</AnalysisChartCard>
<AnalysisChartCard class="mt-5 md:mr-4 md:mt-0 md:w-1/3" title="访问来源">
<AnalyticsVisitsSource />
</AnalysisChartCard>
<AnalysisChartCard class="mt-5 md:mt-0 md:w-1/3" title="访问来源">
<AnalyticsVisitsSales />
</AnalysisChartCard>
</div>
</div>
</template>

View File

@@ -0,0 +1,266 @@
<script lang="ts" setup>
import type {
WorkbenchProjectItem,
WorkbenchQuickNavItem,
WorkbenchTodoItem,
WorkbenchTrendItem,
} from '@vben/common-ui';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import {
AnalysisChartCard,
WorkbenchHeader,
WorkbenchProject,
WorkbenchQuickNav,
WorkbenchTodo,
WorkbenchTrends,
} from '@vben/common-ui';
import { preferences } from '@vben/preferences';
import { useUserStore } from '@vben/stores';
import { openWindow } from '@vben/utils';
import AnalyticsVisitsSource from '../analytics/analytics-visits-source.vue';
const userStore = useUserStore();
// 这是一个示例数据,实际项目中需要根据实际情况进行调整
// url 也可以是内部路由,在 navTo 方法中识别处理,进行内部跳转
// 例如url: /dashboard/workspace
const projectItems: WorkbenchProjectItem[] = [
{
color: '',
content: '不要等待机会,而要创造机会。',
date: '2021-04-01',
group: '开源组',
icon: 'carbon:logo-github',
title: 'Github',
url: 'https://github.com',
},
{
color: '#3fb27f',
content: '现在的你决定将来的你。',
date: '2021-04-01',
group: '算法组',
icon: 'ion:logo-vue',
title: 'Vue',
url: 'https://vuejs.org',
},
{
color: '#e18525',
content: '没有什么才能比努力更重要。',
date: '2021-04-01',
group: '上班摸鱼',
icon: 'ion:logo-html5',
title: 'Html5',
url: 'https://developer.mozilla.org/zh-CN/docs/Web/HTML',
},
{
color: '#bf0c2c',
content: '热情和欲望可以突破一切难关。',
date: '2021-04-01',
group: 'UI',
icon: 'ion:logo-angular',
title: 'Angular',
url: 'https://angular.io',
},
{
color: '#00d8ff',
content: '健康的身体是实现目标的基石。',
date: '2021-04-01',
group: '技术牛',
icon: 'bx:bxl-react',
title: 'React',
url: 'https://reactjs.org',
},
{
color: '#EBD94E',
content: '路是走出来的,而不是空想出来的。',
date: '2021-04-01',
group: '架构组',
icon: 'ion:logo-javascript',
title: 'Js',
url: 'https://developer.mozilla.org/zh-CN/docs/Web/JavaScript',
},
];
// 同样,这里的 url 也可以使用以 http 开头的外部链接
const quickNavItems: WorkbenchQuickNavItem[] = [
{
color: '#1fdaca',
icon: 'ion:home-outline',
title: '首页',
url: '/',
},
{
color: '#bf0c2c',
icon: 'ion:grid-outline',
title: '仪表盘',
url: '/dashboard',
},
{
color: '#e18525',
icon: 'ion:layers-outline',
title: '组件',
url: '/demos/features/icons',
},
{
color: '#3fb27f',
icon: 'ion:settings-outline',
title: '系统管理',
url: '/demos/features/login-expired', // 这里的 URL 是示例,实际项目中需要根据实际情况进行调整
},
{
color: '#4daf1bc9',
icon: 'ion:key-outline',
title: '权限管理',
url: '/demos/access/page-control',
},
{
color: '#00d8ff',
icon: 'ion:bar-chart-outline',
title: '图表',
url: '/analytics',
},
];
const todoItems = ref<WorkbenchTodoItem[]>([
{
completed: false,
content: `审查最近提交到Git仓库的前端代码确保代码质量和规范。`,
date: '2024-07-30 11:00:00',
title: '审查前端代码提交',
},
{
completed: true,
content: `检查并优化系统性能降低CPU使用率。`,
date: '2024-07-30 11:00:00',
title: '系统性能优化',
},
{
completed: false,
content: `进行系统安全检查,确保没有安全漏洞或未授权的访问。 `,
date: '2024-07-30 11:00:00',
title: '安全检查',
},
{
completed: false,
content: `更新项目中的所有npm依赖包确保使用最新版本。`,
date: '2024-07-30 11:00:00',
title: '更新项目依赖',
},
{
completed: false,
content: `修复用户报告的页面UI显示问题确保在不同浏览器中显示一致。 `,
date: '2024-07-30 11:00:00',
title: '修复UI显示问题',
},
]);
const trendItems: WorkbenchTrendItem[] = [
{
avatar: 'svg:avatar-1',
content: `在 <a>开源组</a> 创建了项目 <a>Vue</a>`,
date: '刚刚',
title: '威廉',
},
{
avatar: 'svg:avatar-2',
content: `关注了 <a>威廉</a> `,
date: '1个小时前',
title: '艾文',
},
{
avatar: 'svg:avatar-3',
content: `发布了 <a>个人动态</a> `,
date: '1天前',
title: '克里斯',
},
{
avatar: 'svg:avatar-4',
content: `发表文章 <a>如何编写一个Vite插件</a> `,
date: '2天前',
title: 'Vben',
},
{
avatar: 'svg:avatar-1',
content: `回复了 <a>杰克</a> 的问题 <a>如何进行项目优化?</a>`,
date: '3天前',
title: '皮特',
},
{
avatar: 'svg:avatar-2',
content: `关闭了问题 <a>如何运行项目</a> `,
date: '1周前',
title: '杰克',
},
{
avatar: 'svg:avatar-3',
content: `发布了 <a>个人动态</a> `,
date: '1周前',
title: '威廉',
},
{
avatar: 'svg:avatar-4',
content: `推送了代码到 <a>Github</a>`,
date: '2021-04-01 20:00',
title: '威廉',
},
{
avatar: 'svg:avatar-4',
content: `发表文章 <a>如何编写使用 Admin Vben</a> `,
date: '2021-03-01 20:00',
title: 'Vben',
},
];
const router = useRouter();
// 这是一个示例方法,实际项目中需要根据实际情况进行调整
// This is a sample method, adjust according to the actual project requirements
function navTo(nav: WorkbenchProjectItem | WorkbenchQuickNavItem) {
if (nav.url?.startsWith('http')) {
openWindow(nav.url);
return;
}
if (nav.url?.startsWith('/')) {
router.push(nav.url).catch((error) => {
console.error('Navigation failed:', error);
});
} else {
console.warn(`Unknown URL for navigation item: ${nav.title} -> ${nav.url}`);
}
}
</script>
<template>
<div class="p-5">
<WorkbenchHeader
:avatar="userStore.userInfo?.avatar || preferences.app.defaultAvatar"
>
<template #title>
早安, {{ userStore.userInfo?.realName }}, 开始您一天的工作吧
</template>
<template #description> 今日晴20 - 32 </template>
</WorkbenchHeader>
<div class="mt-5 flex flex-col lg:flex-row">
<div class="mr-4 w-full lg:w-3/5">
<WorkbenchProject :items="projectItems" title="项目" @click="navTo" />
<WorkbenchTrends :items="trendItems" class="mt-5" title="最新动态" />
</div>
<div class="w-full lg:w-2/5">
<WorkbenchQuickNav
:items="quickNavItems"
class="mt-5 lg:mt-0"
title="快捷导航"
@click="navTo"
/>
<WorkbenchTodo :items="todoItems" class="mt-5" title="待办事项" />
<AnalysisChartCard class="mt-5" title="访问来源">
<AnalyticsVisitsSource />
</AnalysisChartCard>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,60 @@
import type { DemoForm, DemoQuery, DemoVO } from './model';
import type { ID, IDS, PageResult } from '#/api/common';
import { commonExport } from '#/api/helper';
import { requestClient } from '#/api/request';
/**
* 查询测试单表列表
* @param params
* @returns 测试单表列表
*/
export function demoList(params?: DemoQuery) {
return requestClient.get<PageResult<DemoVO>>('/demo/demo/list', { params });
}
/**
* 导出测试单表列表
* @param params
* @returns 测试单表列表
*/
export function demoExport(params?: DemoQuery) {
return commonExport('/demo/demo/export', params ?? {});
}
/**
* 查询测试单表详情
* @param id id
* @returns 测试单表详情
*/
export function demoInfo(id: ID) {
return requestClient.get<DemoVO>(`/demo/demo/${id}`);
}
/**
* 新增测试单表
* @param data
* @returns void
*/
export function demoAdd(data: DemoForm) {
return requestClient.postWithMsg<void>('/demo/demo', data);
}
/**
* 更新测试单表
* @param data
* @returns void
*/
export function demoUpdate(data: DemoForm) {
return requestClient.putWithMsg<void>('/demo/demo', data);
}
/**
* 删除测试单表
* @param id id
* @returns void
*/
export function demoRemove(id: ID | IDS) {
return requestClient.deleteWithMsg<void>(`/demo/demo/${id}`);
}

View File

@@ -0,0 +1,82 @@
import type { BaseEntity, PageQuery } from '#/api/common';
export interface DemoVO {
/**
* 主键
*/
id: number | string;
/**
* 排序号
*/
orderNum: number;
/**
* key键
*/
testKey: string;
/**
* 值
*/
value: string;
/**
* 版本
*/
version: number;
}
export interface DemoForm extends BaseEntity {
/**
* 主键
*/
id?: number | string;
/**
* 排序号
*/
orderNum?: number;
/**
* key键
*/
testKey?: string;
/**
* 值
*/
value?: string;
/**
* 版本
*/
version?: number;
}
export interface DemoQuery extends PageQuery {
/**
* 排序号
*/
orderNum?: number;
/**
* key键
*/
testKey?: string;
/**
* 值
*/
value?: string;
/**
* 版本
*/
version?: number;
/**
* 日期范围参数
*/
params?: any;
}

View File

@@ -0,0 +1,93 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'orderNum',
label: '排序号',
},
{
component: 'Input',
fieldName: 'testKey',
label: 'key键',
},
{
component: 'Input',
fieldName: 'value',
label: '值',
},
{
component: 'Input',
fieldName: 'version',
label: '版本',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '主键',
field: 'id',
},
{
title: '排序号',
field: 'orderNum',
},
{
title: 'key键',
field: 'testKey',
},
{
title: '值',
field: 'value',
},
{
title: '版本',
field: 'version',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const modalSchema: FormSchemaGetter = () => [
{
label: '主键',
fieldName: 'id',
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
},
{
label: '排序号',
fieldName: 'orderNum',
component: 'Input',
rules: 'required',
},
{
label: 'key键',
fieldName: 'testKey',
component: 'Input',
rules: 'required',
},
{
label: '值',
fieldName: 'value',
component: 'Input',
rules: 'required',
},
{
label: '版本',
fieldName: 'version',
component: 'Input',
rules: 'required',
},
];

View File

@@ -0,0 +1,87 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { demoAdd, demoInfo, demoUpdate } from './api';
import { modalSchema } from './data';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
// 默认占满两列
formItemClass: 'col-span-2',
// 默认label宽度 px
labelWidth: 80,
// 通用配置项 会影响到所有表单项
componentProps: {
class: 'w-full',
},
},
schema: modalSchema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2',
});
const [BasicModal, modalApi] = useVbenModal({
fullscreenButton: false,
onCancel: handleCancel,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
modalApi.modalLoading(true);
const { id } = modalApi.getData() as { id?: number | string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await demoInfo(id);
await formApi.setValues(record);
}
modalApi.modalLoading(false);
},
});
async function handleConfirm() {
try {
modalApi.modalLoading(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
// getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? demoUpdate(data) : demoAdd(data));
emit('reload');
await handleCancel();
} catch (error) {
console.error(error);
} finally {
modalApi.modalLoading(false);
}
}
async function handleCancel() {
modalApi.close();
await formApi.resetForm();
}
</script>
<template>
<BasicModal :close-on-click-modal="false" :title="title" class="w-[550px]">
<BasicForm />
</BasicModal>
</template>

View File

@@ -0,0 +1,165 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { Recordable } from '@vben/types';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { ref } from 'vue';
import { Page, useVbenModal } from '@vben/common-ui';
import { getPopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import { commonDownloadExcel } from '#/utils/file/download';
import { demoExport, demoList, demoRemove } from './api';
import { columns, querySchema } from './data';
import demoModal from './demo-modal.vue';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await demoList({
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
isHover: true,
keyField: 'id',
},
};
const checked = ref(false);
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [DemoModal, modalApi] = useVbenModal({
connectedComponent: demoModal,
});
function handleAdd() {
modalApi.setData({});
modalApi.open();
}
async function handleEdit(record: Recordable<any>) {
modalApi.setData({ id: record.id });
modalApi.open();
}
async function handleDelete(row: Recordable<any>) {
await demoRemove(row.id);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: any) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await demoRemove(ids);
await tableApi.query();
checked.value = false;
},
});
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable>
<template #toolbar-actions>
<span class="pl-[7px] text-[16px]">测试单列表</span>
</template>
<template #toolbar-tools>
<Space>
<a-button
v-access:code="['system:demo:export']"
@click="
commonDownloadExcel(
demoExport,
'测试单数据',
tableApi.formApi.form.values,
)
"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:demo:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:demo:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:demo:edit']"
@click.stop="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<Popconfirm
:get-popup-container="getPopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:demo:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<DemoModal @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,50 @@
import type { TreeForm, TreeQuery, TreeVO } from './model';
import type { ID, IDS } from '#/api/common';
import { requestClient } from '#/api/request';
/**
* 查询测试树列表
* @param params
* @returns 测试树列表
*/
export function treeList(params?: TreeQuery) {
return requestClient.get<TreeVO[]>('/demo/tree/list', { params });
}
/**
* 查询测试树详情
* @param id id
* @returns 测试树详情
*/
export function treeInfo(id: ID) {
return requestClient.get<TreeVO>(`/demo/tree/${id}`);
}
/**
* 新增测试树
* @param data
* @returns void
*/
export function treeAdd(data: TreeForm) {
return requestClient.postWithMsg<void>('/demo/tree', data);
}
/**
* 更新测试树
* @param data
* @returns void
*/
export function treeUpdate(data: TreeForm) {
return requestClient.putWithMsg<void>('/demo/tree', data);
}
/**
* 删除测试树
* @param id id
* @returns void
*/
export function treeRemove(id: ID | IDS) {
return requestClient.deleteWithMsg<void>(`/demo/tree/${id}`);
}

View File

@@ -0,0 +1,102 @@
import type { BaseEntity } from '#/api/common';
export interface TreeVO {
/**
* 主键
*/
id: number | string;
/**
* 父id
*/
parentId: number | string;
/**
* 部门id
*/
deptId: number | string;
/**
* 用户id
*/
userId: number | string;
/**
* 值
*/
treeName: string;
/**
* 版本
*/
version: number;
/**
* 子对象
*/
children: TreeVO[];
}
export interface TreeForm extends BaseEntity {
/**
* 主键
*/
id?: number | string;
/**
* 父id
*/
parentId?: number | string;
/**
* 部门id
*/
deptId?: number | string;
/**
* 用户id
*/
userId?: number | string;
/**
* 值
*/
treeName?: string;
/**
* 版本
*/
version?: number;
}
export interface TreeQuery {
/**
* 父id
*/
parentId?: number | string;
/**
* 部门id
*/
deptId?: number | string;
/**
* 用户id
*/
userId?: number | string;
/**
* 值
*/
treeName?: string;
/**
* 版本
*/
version?: number;
/**
* 日期范围参数
*/
params?: any;
}

View File

@@ -0,0 +1,108 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'parentId',
label: '父id',
},
{
component: 'Input',
fieldName: 'deptId',
label: '部门id',
},
{
component: 'Input',
fieldName: 'userId',
label: '用户id',
},
{
component: 'Input',
fieldName: 'treeName',
label: '值',
},
{
component: 'Input',
fieldName: 'version',
label: '版本',
},
];
export const columns: VxeGridProps['columns'] = [
{
title: '主键',
field: 'id',
treeNode: true,
},
{
title: '父id',
field: 'parentId',
},
{
title: '部门id',
field: 'deptId',
},
{
title: '用户id',
field: 'userId',
},
{
title: '值',
field: 'treeName',
},
{
title: '版本',
field: 'version',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const modalSchema: FormSchemaGetter = () => [
{
label: '主键',
fieldName: 'id',
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
},
{
label: '父id',
fieldName: 'parentId',
component: 'TreeSelect',
rules: 'required',
},
{
label: '部门id',
fieldName: 'deptId',
component: 'Input',
rules: 'required',
},
{
label: '用户id',
fieldName: 'userId',
component: 'Input',
rules: 'required',
},
{
label: '值',
fieldName: 'treeName',
component: 'Input',
rules: 'required',
},
{
label: '版本',
fieldName: 'version',
component: 'Input',
rules: 'required',
},
];

View File

@@ -0,0 +1,146 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { Recordable } from '@vben/types';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { nextTick } from 'vue';
import { Page, useVbenModal } from '@vben/common-ui';
import { getPopupContainer, listToTree } from '@vben/utils';
import { Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { treeList, treeRemove } from './api';
import { columns, querySchema } from './data';
import treeModal from './tree-modal.vue';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const gridOptions: VxeGridProps = {
columns,
height: 'auto',
keepSource: true,
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async (_, formValues = {}) => {
const resp = await treeList({
...formValues,
});
const treeData = listToTree(resp, {
id: 'id',
pid: 'parentId',
children: 'children',
});
return { rows: treeData };
},
// 默认请求接口后展开全部 不需要可以删除这段
querySuccess: () => {
nextTick(() => {
expandAll();
});
},
},
},
rowConfig: {
keyField: 'id',
},
treeConfig: {
parentField: 'parentId',
rowField: 'id',
transform: false,
},
};
const [BasicTable, tableApi] = useVbenVxeGrid({ formOptions, gridOptions });
const [TreeModal, modalApi] = useVbenModal({
connectedComponent: treeModal,
});
function handleAdd() {
modalApi.setData({ update: false });
modalApi.open();
}
async function handleEdit(row: Recordable<any>) {
modalApi.setData({ id: row.id, update: true });
modalApi.open();
}
async function handleDelete(row: Recordable<any>) {
await treeRemove(row.id);
await tableApi.query();
}
function expandAll() {
tableApi.grid?.setAllTreeExpand(true);
}
function collapseAll() {
tableApi.grid?.setAllTreeExpand(false);
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable>
<template #toolbar-actions>
<span class="pl-[7px] text-[16px]">测试树列表</span>
</template>
<template #toolbar-tools>
<Space>
<a-button @click="collapseAll">
{{ $t('pages.common.collapse') }}
</a-button>
<a-button @click="expandAll">
{{ $t('pages.common.expand') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:tree:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:tree:edit']"
@click.stop="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<Popconfirm
:get-popup-container="getPopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:tree:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<TreeModal @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,104 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep, listToTree } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { treeAdd, treeInfo, treeList, treeUpdate } from './api';
import { modalSchema } from './data';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
// 默认占满两列
formItemClass: 'col-span-2',
// 默认label宽度 px
labelWidth: 80,
// 通用配置项 会影响到所有表单项
componentProps: {
class: 'w-full',
},
},
schema: modalSchema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2',
});
async function setupTreeSelect() {
const listData = await treeList();
const treeData = listToTree(listData, { id: 'id', pid: 'parentId' });
formApi.updateSchema([
{
fieldName: 'parentId',
componentProps: {
treeData,
treeLine: { showLeafIcon: false },
fieldNames: { label: 'treeName', value: 'id' },
treeDefaultExpandAll: true,
},
},
]);
}
const [BasicModal, modalApi] = useVbenModal({
fullscreenButton: false,
onCancel: handleCancel,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
modalApi.modalLoading(true);
const { id } = modalApi.getData() as { id?: number | string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await treeInfo(id);
await formApi.setValues(record);
}
await setupTreeSelect();
modalApi.modalLoading(false);
},
});
async function handleConfirm() {
try {
modalApi.modalLoading(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
// getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? treeUpdate(data) : treeAdd(data));
emit('reload');
await handleCancel();
} catch (error) {
console.error(error);
} finally {
modalApi.modalLoading(false);
}
}
async function handleCancel() {
modalApi.close();
await formApi.resetForm();
}
</script>
<template>
<BasicModal :close-on-click-modal="false" :title="title" class="w-[550px]">
<BasicForm />
</BasicModal>
</template>

View File

@@ -0,0 +1,7 @@
<!-- 建议通过菜单配置成外链/内嵌 达到相同的效果且灵活性更高 -->
<template>
<iframe
class="size-full"
src="http://localhost:9090/admin/applications"
></iframe>
</template>

View File

@@ -0,0 +1,63 @@
<script setup lang="ts">
import type { EchartsUIType } from '@vben/plugins/echarts';
import { onActivated, onMounted, ref, watch } from 'vue';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
interface Props {
data?: { name: string; value: string }[];
}
const props = withDefaults(defineProps<Props>(), {
data: () => [],
});
const chartRef = ref<EchartsUIType>();
const { renderEcharts, resize } = useEcharts(chartRef);
watch(
() => props.data,
() => {
if (!chartRef.value) return;
setEchartsOption(props.data);
},
{ immediate: true },
);
onMounted(() => {
setEchartsOption(props.data);
});
/**
* 从其他页面切换回来会有一个奇怪的动画效果 需要调用resize
* 该饼图组件需要关闭animation
*/
onActivated(() => resize(false));
type EChartsOption = Parameters<typeof renderEcharts>['0'];
function setEchartsOption(data: any[]) {
const option: EChartsOption = {
series: [
{
animationDuration: 1000,
animationEasing: 'cubicInOut',
center: ['50%', '50%'],
data,
name: '命令',
radius: [15, 95],
roseType: 'radius',
type: 'pie',
},
],
tooltip: {
formatter: '{a} <br/>{b} : {c} ({d}%)',
trigger: 'item',
},
};
renderEcharts(option);
}
</script>
<template>
<EchartsUI ref="chartRef" height="400px" width="100%" />
</template>

View File

@@ -0,0 +1,3 @@
export { default as CommandChart } from './command-chart.vue';
export { default as MemoryChart } from './memory-chart.vue';
export { default as RedisDescription } from './redis-description.vue';

View File

@@ -0,0 +1,89 @@
<script setup lang="ts">
import type { EchartsUIType } from '@vben/plugins/echarts';
import { onActivated, onMounted, ref, watch } from 'vue';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
interface Props {
data?: string;
}
const props = withDefaults(defineProps<Props>(), {
data: '0',
});
const memoryHtmlRef = ref<EchartsUIType>();
const { renderEcharts, resize } = useEcharts(memoryHtmlRef);
watch(
() => props.data,
() => {
if (!memoryHtmlRef.value) return;
setEchartsOption(props.data);
},
{ immediate: true },
);
onMounted(() => {
setEchartsOption(props.data);
});
// 从其他页面切换回来会有一个奇怪的动画效果 需要调用resize
onActivated(resize);
/**
* 获取最近的十的幂次
* 该函数用于寻找大于给定数字num的最近的10的幂次
* 主要解决的问题是确定一个数附近较大的十的幂次,这在某些算法中很有用
*
* @param num {number} 输入的数字,用于寻找最近的十的幂次
*/
function getNearestPowerOfTen(num: number) {
let power = 10;
while (power <= num) {
power *= 10;
}
return power;
}
type EChartsOption = Parameters<typeof renderEcharts>['0'];
function setEchartsOption(value: string) {
// x10
const formattedValue = Math.floor(Number.parseFloat(value));
// 最大值 10以内取10 100以内取100 以此类推
const max = getNearestPowerOfTen(formattedValue);
const options: EChartsOption = {
series: [
{
animation: true,
animationDuration: 1000,
data: [
{
name: '内存消耗',
value: Number.parseFloat(value),
},
],
detail: {
formatter: `${value}M`,
valueAnimation: true,
},
max,
min: 0,
name: '峰值',
progress: {
show: true,
},
type: 'gauge',
},
],
tooltip: {
formatter: `{b} <br/>{a} : ${value}M`,
},
};
renderEcharts(options);
}
</script>
<template>
<EchartsUI ref="memoryHtmlRef" height="400px" width="100%" />
</template>

View File

@@ -0,0 +1,58 @@
<script setup lang="ts">
import type { RedisInfo } from '#/api/monitor/cache';
import { Descriptions, DescriptionsItem } from 'ant-design-vue';
interface IRedisInfo extends RedisInfo {
dbSize: string;
}
defineProps<{ data: IRedisInfo }>();
</script>
<template>
<Descriptions
bordered
:column="{ lg: 4, md: 3, sm: 1, xl: 4, xs: 1 }"
size="small"
>
<DescriptionsItem label="redis版本">
{{ data.redis_version }}
</DescriptionsItem>
<DescriptionsItem label="redis模式">
{{ data.redis_mode === 'standalone' ? '单机模式' : '集群模式' }}
</DescriptionsItem>
<DescriptionsItem label="tcp端口">
{{ data.tcp_port }}
</DescriptionsItem>
<DescriptionsItem label="客户端数">
{{ data.connected_clients }}
</DescriptionsItem>
<DescriptionsItem label="运行时间">
{{ data.uptime_in_days }}
</DescriptionsItem>
<DescriptionsItem label="使用内存">
{{ data.used_memory_human }}
</DescriptionsItem>
<DescriptionsItem label="使用CPU">
{{ Number.parseFloat(data?.used_cpu_user_children ?? '0').toFixed(2) }}
</DescriptionsItem>
<DescriptionsItem label="内存配置">
{{ data.maxmemory_human }}
</DescriptionsItem>
<DescriptionsItem label="AOF是否开启">
{{ data.aof_enabled === '0' ? '否' : '是' }}
</DescriptionsItem>
<DescriptionsItem label="RDB是否成功">
{{ data.rdb_last_bgsave_status }}
</DescriptionsItem>
<DescriptionsItem label="key数量">
{{ data.dbSize }}
</DescriptionsItem>
<DescriptionsItem label="网络入口/出口">
{{
`${data.instantaneous_input_kbps}kps/${data.instantaneous_output_kbps}kps`
}}
</DescriptionsItem>
</Descriptions>
</template>

View File

@@ -0,0 +1,107 @@
<script setup lang="ts">
import type { RedisInfo } from '#/api/monitor/cache';
import { onMounted, reactive, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { CommandLineIcon, MemoryIcon, RedisIcon } from '@vben/icons';
import { Button, Card, Col, Row } from 'ant-design-vue';
import { redisCacheInfo } from '#/api/monitor/cache';
import { CommandChart, MemoryChart, RedisDescription } from './components';
const baseSpan = { lg: 12, md: 24, sm: 24, xl: 12, xs: 24 };
const chartData = reactive<{
command: { name: string; value: string }[];
memory: string;
}>({
command: [],
memory: '0',
});
interface IRedisInfo extends RedisInfo {
dbSize: string;
}
const redisInfo = ref<IRedisInfo>();
onMounted(async () => {
await loadInfo();
});
async function loadInfo() {
try {
const ret = await redisCacheInfo();
// 单位MB 保留两位小数
const usedMemory = (
Number.parseInt(ret.info.used_memory!) /
1024 /
1024
).toFixed(2);
chartData.memory = usedMemory;
// 命令统计
chartData.command = ret.commandStats;
console.log(chartData.command);
// redis信息
redisInfo.value = { ...ret.info, dbSize: String(ret.dbSize) };
} catch (error) {
console.warn(error);
}
}
</script>
<template>
<Page>
<Row :gutter="[15, 15]">
<Col :span="24">
<Card size="small">
<template #title>
<div class="flex items-center justify-start gap-[6px]">
<RedisIcon class="size-[16px]" />
<span>redis信息</span>
</div>
</template>
<template #extra>
<Button size="small" @click="loadInfo">
<div class="flex">
<span class="icon-[charm--refresh]"></span>
</div>
</Button>
</template>
<RedisDescription v-if="redisInfo" :data="redisInfo" />
</Card>
</Col>
<Col v-bind="baseSpan">
<Card size="small">
<template #title>
<div class="flex items-center gap-[6px]">
<CommandLineIcon class="size-[16px]" />
<span>命令统计</span>
</div>
</template>
<CommandChart
v-if="chartData.command.length > 0"
:data="chartData.command"
/>
</Card>
</Col>
<Col v-bind="baseSpan">
<Card size="small">
<template #title>
<div class="flex items-center justify-start gap-[6px]">
<MemoryIcon class="size-[16px]" />
<span>内存占用</span>
</div>
</template>
<MemoryChart
v-if="chartData.memory !== '0'"
:data="chartData.memory"
/>
</Card>
</Col>
</Row>
</Page>
</template>

View File

@@ -0,0 +1,318 @@
<script setup lang="ts">
import type { CacheName, CacheValue } from '#/api/monitor/cache';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import {
Button,
Card,
Col,
Form,
FormItem,
Input,
Modal,
Popconfirm,
Row,
Table,
Textarea,
} from 'ant-design-vue';
import { DeleteOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import {
clearCacheAll,
clearCacheKey,
clearCacheName,
getCacheValue,
listCacheKey,
listCacheName,
} from '#/api/monitor/cache';
import { message } from 'ant-design-vue';
const cacheNames = ref<CacheName[]>([]);
const cacheKeys = ref<string[]>([]);
const cacheForm = ref<Partial<CacheValue>>({});
const loading = ref(true);
const subLoading = ref(false);
const nowCacheName = ref('');
const tableHeight = computed(() => window.innerHeight - 200);
const cacheNameColumns = [
{
title: '序号',
key: 'index',
width: 60,
},
{
title: '缓存名称',
dataIndex: 'cacheName',
key: 'cacheName',
ellipsis: true,
},
{
title: '备注',
dataIndex: 'remark',
key: 'remark',
ellipsis: true,
},
{
title: '操作',
key: 'action',
width: 60,
fixed: 'right' as const,
},
];
const cacheKeyColumns = [
{
title: '序号',
key: 'index',
width: 60,
},
{
title: '缓存键名',
key: 'cacheKey',
ellipsis: true,
},
{
title: '操作',
key: 'action',
width: 60,
fixed: 'right' as const,
},
];
/** 查询缓存名称列表 */
async function getCacheNames() {
loading.value = true;
try {
cacheNames.value = await listCacheName();
} catch (error) {
console.warn(error);
} finally {
loading.value = false;
}
}
/** 刷新缓存名称列表 */
async function refreshCacheNames() {
await getCacheNames();
message.success('刷新缓存列表成功');
}
/** 清理指定名称缓存 */
async function handleClearCacheName(row: CacheName) {
try {
await clearCacheName(row.cacheName);
message.success(`清理缓存名称[${row.cacheName}]成功`);
await getCacheKeys();
} catch (error) {
console.warn(error);
}
}
/** 查询缓存键名列表 */
async function getCacheKeys(row?: CacheName) {
const cacheName = row !== undefined ? row.cacheName : nowCacheName.value;
if (cacheName === '') {
return;
}
subLoading.value = true;
try {
cacheKeys.value = await listCacheKey(cacheName);
nowCacheName.value = cacheName;
} catch (error) {
console.warn(error);
} finally {
subLoading.value = false;
}
}
/** 刷新缓存键名列表 */
async function refreshCacheKeys() {
await getCacheKeys();
message.success('刷新键名列表成功');
}
/** 清理指定键名缓存 */
async function handleClearCacheKey(cacheKey: string) {
try {
await clearCacheKey(nowCacheName.value, cacheKey);
message.success(`清理缓存键名[${cacheKey}]成功`);
await getCacheKeys();
} catch (error) {
console.warn(error);
}
}
/** 查询缓存内容详细 */
async function handleCacheValue(cacheKey: string) {
try {
cacheForm.value = await getCacheValue(nowCacheName.value, cacheKey);
} catch (error) {
console.warn(error);
}
}
/** 清理全部缓存 */
function handleClearCacheAll() {
Modal.confirm({
title: '提示',
content: '确认清理全部缓存吗?',
okType: 'danger',
onOk: async () => {
try {
await clearCacheAll();
message.success('清理全部缓存成功');
await getCacheNames();
cacheKeys.value = [];
cacheForm.value = {};
nowCacheName.value = '';
} catch (error) {
console.warn(error);
}
},
});
}
onMounted(() => {
getCacheNames();
});
</script>
<template>
<Page>
<Row :gutter="10">
<Col :span="8">
<Card :style="{ height: `${tableHeight}px` }">
<template #title>
<span>缓存列表</span>
</template>
<template #extra>
<Button type="text" size="small" @click="refreshCacheNames">
<template #icon>
<ReloadOutlined />
</template>
</Button>
</template>
<Table
:loading="loading"
:data-source="cacheNames"
:columns="cacheNameColumns"
:scroll="{ y: tableHeight - 120 }"
:pagination="false"
size="small"
:custom-row="(record: CacheName) => ({
onClick: () => getCacheKeys(record),
style: {
cursor: 'pointer',
},
})"
>
<template #bodyCell="{ column, record, index }">
<template v-if="column.key === 'index'">
{{ index + 1 }}
</template>
<template v-else-if="column.key === 'cacheName'">
{{ record.cacheName.replace(':', '') }}
</template>
<template v-else-if="column.key === 'action'">
<Popconfirm
title="确认清理此缓存名称吗"
@confirm="handleClearCacheName(record)"
>
<Button type="text" danger size="small">
<template #icon>
<DeleteOutlined />
</template>
</Button>
</Popconfirm>
</template>
</template>
</Table>
</Card>
</Col>
<Col :span="8">
<Card :style="{ height: `${tableHeight}px` }">
<template #title>
<span>键名列表</span>
</template>
<template #extra>
<Button type="text" size="small" @click="refreshCacheKeys">
<template #icon>
<ReloadOutlined />
</template>
</Button>
</template>
<Table
:loading="subLoading"
:data-source="cacheKeys"
:columns="cacheKeyColumns"
:scroll="{ y: tableHeight - 120 }"
:pagination="false"
size="small"
:custom-row="(record: string) => ({
onClick: () => handleCacheValue(record),
style: {
cursor: 'pointer',
},
})"
>
<template #bodyCell="{ column, record, index }">
<template v-if="column.key === 'index'">
{{ index + 1 }}
</template>
<template v-else-if="column.key === 'cacheKey'">
{{ record.replace(nowCacheName, '') }}
</template>
<template v-else-if="column.key === 'action'">
<Popconfirm
title="确认清理此缓存键名吗"
@confirm="handleClearCacheKey(record)"
>
<Button type="text" danger size="small">
<template #icon>
<DeleteOutlined />
</template>
</Button>
</Popconfirm>
</template>
</template>
</Table>
</Card>
</Col>
<Col :span="8">
<Card :bordered="false" :style="{ height: `${tableHeight}px` }">
<template #title>
<span>缓存内容</span>
</template>
<template #extra>
<Button type="link" danger size="small" @click="handleClearCacheAll">
清理全部
</Button>
</template>
<Form :model="cacheForm" layout="vertical">
<FormItem label="缓存名称:" name="cacheName">
<Input v-model:value="cacheForm.cacheName" readonly />
</FormItem>
<FormItem label="缓存键名:" name="cacheKey">
<Input v-model:value="cacheForm.cacheKey" readonly />
</FormItem>
<FormItem label="缓存内容:" name="cacheValue">
<Textarea
v-model:value="cacheForm.cacheValue"
:rows="8"
readonly
/>
</FormItem>
</Form>
</Card>
</Col>
</Row>
</Page>
</template>

View File

@@ -0,0 +1,87 @@
import type { VNode } from 'vue';
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { DictEnum } from '@vben/constants';
import { getDictOptions } from '#/utils/dict';
import { renderBrowserIcon, renderDict, renderOsIcon } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'loginIp',
label: 'IP地址',
},
{
component: 'Input',
fieldName: 'loginUser',
label: '用户账号',
},
{
component: 'RangePicker',
fieldName: 'dateTime',
label: '登录日期',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '用户账号',
field: 'loginUser',
},
{
title: 'IP地址',
field: 'loginIp',
},
{
title: 'IP地点',
field: 'loginLocation',
width: 200,
},
{
title: '浏览器',
field: 'browser',
slots: {
default: ({ row }) => {
return renderBrowserIcon(row.browser, true) as VNode;
},
},
},
{
title: '系统',
field: 'os',
slots: {
default: ({ row }) => {
/**
* Windows 10 or Windows Server 2016 太长了 分割一下 详情依旧能看到详细的
*/
let value = row.os;
if (value) {
const split = value.split(' or ');
if (split.length === 2) {
value = split[0];
}
}
return renderOsIcon(value, true) as VNode;
},
},
},
{
title: '信息',
field: 'logMsg',
},
{
title: '日期',
field: 'creationTime',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
width: 150,
},
];

View File

@@ -0,0 +1,217 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { LoginLog } from '#/api/monitor/logininfo/model';
import { ref } from 'vue';
import { Page, useVbenModal } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
loginInfoClean,
loginInfoExport,
loginInfoList,
loginInfoRemove,
userUnlock,
} from '#/api/monitor/logininfo';
import { commonDownloadExcel } from '#/utils/file/download';
import { confirmDeleteModal } from '#/utils/modal';
import { columns, querySchema } from './data';
import loginInfoModal from './login-info-modal.vue';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
// 日期选择格式化
fieldMappingTime: [
[
'dateTime',
['startTime', 'endTime'],
['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
],
],
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
trigger: 'row',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await loginInfoList({
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
},
id: 'monitor-logininfo-index',
};
const canUnlock = ref(false);
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
gridEvents: {
checkboxChange: () => {
// 新结构没有 status 字段,解锁功能可能需要根据业务逻辑调整
// 延迟执行以避免类型推断问题
setTimeout(() => {
const records = (tableApi as any).grid.getCheckboxRecords();
canUnlock.value = records.length === 1;
}, 0);
},
},
});
const [LoginInfoModal, modalApi] = useVbenModal({
connectedComponent: loginInfoModal,
});
function handlePreview(record: LoginLog) {
modalApi.setData(record);
modalApi.open();
}
function handleClear() {
confirmDeleteModal({
onValidated: async () => {
await loginInfoClean();
await tableApi.reload();
},
});
}
function handleDelete(row: LoginLog) {
loginInfoRemove([row.id]);
tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: LoginLog) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await loginInfoRemove(ids);
await tableApi.query();
},
});
}
async function handleUnlock() {
const records = tableApi.grid.getCheckboxRecords();
if (records.length !== 1) {
return;
}
const record = records[0];
if (!record) {
return;
}
await userUnlock(record.loginUser);
await tableApi.query();
canUnlock.value = false;
tableApi.grid.clearCheckboxRow();
}
function handleDownloadExcel() {
commonDownloadExcel(
loginInfoExport,
'登录日志',
tableApi.formApi.form.values,
{
fieldMappingTime: formOptions.fieldMappingTime,
},
);
}
</script>
<template>
<Page auto-content-height>
<BasicTable table-title="登录日志列表">
<template #toolbar-tools>
<Space>
<a-button
v-access:code="['monitor:logininfor:remove']"
@click="handleClear"
>
{{ $t('pages.common.clear') }}
</a-button>
<a-button
v-access:code="['monitor:logininfor:export']"
@click="handleDownloadExcel"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi as any)"
danger
type="primary"
v-access:code="['monitor:logininfor:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
:disabled="!canUnlock"
type="primary"
v-access:code="['monitor:logininfor:unlock']"
@click="handleUnlock"
>
{{ $t('pages.common.unlock') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button @click.stop="handlePreview(row)">
{{ $t('pages.common.info') }}
</ghost-button>
<Popconfirm
:get-popup-container="getVxePopupContainer"
placement="left"
title="确认删除?"
@confirm="() => handleDelete(row)"
>
<ghost-button
danger
v-access:code="['monitor:logininfor:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<LoginInfoModal />
</Page>
</template>

View File

@@ -0,0 +1,57 @@
<script setup lang="ts">
import type { LoginLog } from '#/api/monitor/logininfo/model';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { Descriptions, DescriptionsItem } from 'ant-design-vue';
import { renderBrowserIcon, renderDict, renderOsIcon } from '#/utils/render';
const loginInfo = ref<LoginLog>();
const [BasicModal, modalApi] = useVbenModal({
onOpenChange: (isOpen) => {
if (!isOpen) {
return null;
}
const record = modalApi.getData() as LoginLog;
loginInfo.value = record;
},
onClosed() {
loginInfo.value = undefined;
},
});
</script>
<template>
<BasicModal
:footer="false"
:fullscreen-button="false"
class="w-[550px]"
title="登录日志"
>
<Descriptions v-if="loginInfo" size="small" :column="1" bordered>
<DescriptionsItem label="账号信息">
{{
`账号: ${loginInfo.loginUser} / ${loginInfo.loginIp} / ${loginInfo.loginLocation}`
}}
</DescriptionsItem>
<DescriptionsItem label="登录时间">
{{ loginInfo.creationTime }}
</DescriptionsItem>
<DescriptionsItem label="登录信息">
<span class="font-semibold">
{{ loginInfo.logMsg }}
</span>
</DescriptionsItem>
<DescriptionsItem label="登录设备">
<component :is="renderOsIcon(loginInfo.os)" />
</DescriptionsItem>
<DescriptionsItem label="浏览器">
<component :is="renderBrowserIcon(loginInfo.browser)" />
</DescriptionsItem>
</Descriptions>
</BasicModal>
</template>

View File

@@ -0,0 +1,77 @@
import type { VNode } from 'vue';
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import dayjs from 'dayjs';
import { renderBrowserIcon, renderOsIcon } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'ipaddr',
label: 'IP地址',
},
{
component: 'Input',
fieldName: 'userName',
label: '用户账号',
},
];
export const columns: VxeGridProps['columns'] = [
{
title: '登录账号',
field: 'userName',
},
{
title: 'IP地址',
field: 'ipaddr',
},
{
title: '登录地址',
field: 'loginLocation',
},
{
title: '浏览器',
field: 'browser',
slots: {
default: ({ row }) => {
return renderBrowserIcon(row.browser, true) as VNode;
},
},
},
{
title: '系统',
field: 'os',
slots: {
default: ({ row }) => {
// Windows 10 or Windows Server 2016 太长了 分割一下 详情依旧能看到详细的
let value = row.os;
if (value) {
const split = value.split(' or ');
if (split.length === 2) {
value = split[0];
}
}
return renderOsIcon(value, true) as VNode;
},
},
},
{
title: '登录时间',
field: 'loginTime',
formatter: ({ cellValue }) => {
return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss');
},
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];

View File

@@ -0,0 +1,91 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { OnlineUser } from '#/api/monitor/online/model';
import { ref } from 'vue';
import { Page } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Popconfirm } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { forceLogout, onlineList } from '#/api/monitor/online';
import { columns, querySchema } from './data';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const onlineCount = ref(0);
const gridOptions: VxeGridProps = {
columns,
height: 'auto',
keepSource: true,
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async (_, formValues = {}) => {
const resp = await onlineList({
...formValues,
});
onlineCount.value = resp.total;
return resp;
},
},
},
scrollY: {
enabled: true,
gt: 0,
},
rowConfig: {
keyField: 'connnectionId',
},
id: 'monitor-online-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({ formOptions, gridOptions });
async function handleForceOffline(row: OnlineUser) {
await forceLogout(row.connnectionId ? [row.connnectionId] : []);
await tableApi.query();
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable>
<template #toolbar-actions>
<div class="mr-1 pl-1 text-[1rem]">
<div>
在线用户列表 (
<span class="text-primary font-bold">{{ onlineCount }}</span>
人在线)
</div>
</div>
</template>
<template #action="{ row }">
<Popconfirm
:get-popup-container="getVxePopupContainer"
:title="`确认强制下线[${row.userName}]?`"
placement="left"
@confirm="handleForceOffline(row)"
>
<ghost-button danger>强制下线</ghost-button>
</Popconfirm>
</template>
</BasicTable>
</Page>
</template>

View File

@@ -0,0 +1,67 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { DictEnum } from '@vben/constants';
import { getDictOptions } from '#/utils/dict';
import { renderDict } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'title',
label: '系统模块',
},
{
component: 'Input',
fieldName: 'operUser',
label: '操作人员',
},
{
component: 'Select',
componentProps: {
options: getDictOptions(DictEnum.SYS_OPER_TYPE),
},
fieldName: 'operType',
label: '操作类型',
},
{
component: 'Input',
fieldName: 'operIp',
label: '操作IP',
},
{
component: 'RangePicker',
fieldName: 'createTime',
label: '操作时间',
componentProps: {
valueFormat: 'YYYY-MM-DD HH:mm:ss',
},
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{ field: 'title', title: '系统模块' },
{
title: '操作类型',
field: 'operType',
slots: {
default: ({ row }) => {
return renderDict(row.operType, DictEnum.SYS_OPER_TYPE);
},
},
},
{ field: 'operUser', title: '操作人员' },
{ field: 'operIp', title: 'IP地址' },
{ field: 'operLocation', title: 'IP信息' },
{ field: 'creationTime', title: '操作日期', sortable: true },
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];

View File

@@ -0,0 +1,184 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PageQuery } from '#/api/common';
import type { OperationLog } from '#/api/monitor/operlog/model';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { Modal, Space } from 'ant-design-vue';
import {
addSortParams,
useVbenVxeGrid,
vxeCheckboxChecked,
} from '#/adapter/vxe-table';
import {
operLogClean,
operLogRemove,
operLogExport,
operLogList,
} from '#/api/monitor/operlog';
import { commonDownloadExcel } from '#/utils/file/download';
import { confirmDeleteModal } from '#/utils/modal';
import { columns, querySchema } from './data';
import operationPreviewDrawer from './operation-preview-drawer.vue';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
// 日期选择格式化
fieldMappingTime: [
[
'createTime',
['startTime', 'endTime'],
['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
],
],
};
const gridOptions: VxeGridProps<OperationLog> = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
trigger: 'row',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page, sorts }, formValues = {}) => {
const params: PageQuery = {
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
};
// 添加排序参数
addSortParams(params, sorts);
return await operLogList(params);
},
},
},
rowConfig: {
keyField: 'id',
},
sortConfig: {
// 远程排序
remote: true,
// 支持多字段排序 默认关闭
multiple: true,
},
id: 'monitor-operlog-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
gridEvents: {
// 排序 重新请求接口
sortChange: () => tableApi.query(),
},
});
const [OperationPreviewDrawer, drawerApi] = useVbenDrawer({
connectedComponent: operationPreviewDrawer,
});
/**
* 预览
* @param record 操作日志记录
*/
function handlePreview(record: OperationLog) {
drawerApi.setData({ record });
drawerApi.open();
}
/**
* 清空全部日志
*/
function handleClear() {
confirmDeleteModal({
onValidated: async () => {
await operLogClean();
await tableApi.reload();
},
});
}
/**
* 删除日志
*/
function handleDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: OperationLog) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条操作日志吗?`,
onOk: async () => {
await operLogRemove(ids);
await tableApi.query();
},
});
}
function handleDownloadExcel() {
commonDownloadExcel(operLogExport, '操作日志', tableApi.formApi.form.values, {
fieldMappingTime: formOptions.fieldMappingTime,
});
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="操作日志列表">
<template #toolbar-tools>
<Space>
<a-button
v-access:code="['monitor:operlog:remove']"
@click="handleClear"
>
{{ $t('pages.common.clear') }}
</a-button>
<a-button
v-access:code="['monitor:operlog:export']"
@click="handleDownloadExcel"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['monitor:operlog:remove']"
@click="handleDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<ghost-button
v-access:code="['monitor:operlog:list']"
@click.stop="handlePreview(row)"
>
{{ $t('pages.common.preview') }}
</ghost-button>
</template>
</BasicTable>
<OperationPreviewDrawer />
</Page>
</template>

View File

@@ -0,0 +1,80 @@
<script setup lang="ts">
import type { OperationLog } from '#/api/monitor/operlog/model';
import { computed, shallowRef } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { Descriptions, DescriptionsItem, Tag } from 'ant-design-vue';
import {
renderDict,
renderHttpMethodTag,
renderJsonPreview,
} from '#/utils/render';
const [BasicDrawer, drawerApi] = useVbenDrawer({
onOpenChange: handleOpenChange,
onClosed() {
currentLog.value = null;
},
});
const currentLog = shallowRef<null | OperationLog>(null);
function handleOpenChange(open: boolean) {
if (!open) {
return null;
}
const { record } = drawerApi.getData() as { record: OperationLog };
currentLog.value = record;
}
const actionInfo = computed(() => {
if (!currentLog.value) {
return '-';
}
const data = currentLog.value;
return `账号: ${data.operUser} / ${data.operIp} / ${data.operLocation}`;
});
</script>
<template>
<BasicDrawer :footer="false" class="w-[600px]" title="查看日志">
<Descriptions v-if="currentLog" size="small" bordered :column="1">
<DescriptionsItem label="日志编号" :label-style="{ minWidth: '120px' }">
{{ currentLog.id }}
</DescriptionsItem>
<DescriptionsItem label="操作模块">
<div class="flex items-center">
<Tag>{{ currentLog.title }}</Tag>
<component
:is="renderDict(currentLog.operType, DictEnum.SYS_OPER_TYPE)"
/>
</div>
</DescriptionsItem>
<DescriptionsItem label="操作信息">
{{ actionInfo }}
</DescriptionsItem>
<DescriptionsItem label="请求信息">
<component :is="renderHttpMethodTag(currentLog.requestMethod)" />
</DescriptionsItem>
<DescriptionsItem label="方法">
{{ currentLog.method }}
</DescriptionsItem>
<DescriptionsItem label="请求参数">
<div class="max-h-[300px] overflow-y-auto">
<component :is="renderJsonPreview(currentLog.requestParam)" />
</div>
</DescriptionsItem>
<DescriptionsItem v-if="currentLog.requestResult" label="响应参数">
<div class="max-h-[300px] overflow-y-auto">
<component :is="renderJsonPreview(currentLog.requestResult)" />
</div>
</DescriptionsItem>
<DescriptionsItem label="操作时间">
{{ `${currentLog.creationTime}` }}
</DescriptionsItem>
</Descriptions>
</BasicDrawer>
</template>

View File

@@ -0,0 +1,216 @@
<script setup lang="ts">
import type { ServerInfo } from '#/api/service/model';
import { onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import {
Button,
Card,
Col,
Descriptions,
DescriptionsItem,
Row,
Spin,
Table,
} from 'ant-design-vue';
import { getServerInfo } from '#/api/service';
const server = ref<ServerInfo>();
const loading = ref(false);
const diskColumns = [
{
title: '盘符路径',
dataIndex: 'diskName',
key: 'diskName',
},
{
title: '盘符类型',
dataIndex: 'typeName',
key: 'typeName',
},
{
title: '总大小',
dataIndex: 'totalSize',
key: 'totalSize',
},
{
title: '可用大小',
dataIndex: 'availableFreeSpace',
key: 'availableFreeSpace',
},
{
title: '已用大小',
dataIndex: 'used',
key: 'used',
},
{
title: '已用百分比',
dataIndex: 'availablePercent',
key: 'availablePercent',
},
];
async function loadData() {
loading.value = true;
try {
server.value = await getServerInfo();
} catch (error) {
console.warn(error);
} finally {
loading.value = false;
}
}
onMounted(() => {
loadData();
});
</script>
<template>
<Page>
<Spin :spinning="loading" tip="正在加载服务监控数据,请稍候...">
<Row :gutter="[15, 15]">
<Col :lg="12" :md="24" :sm="24" :xl="12" :xs="24">
<Card size="small">
<template #title>
<span>CPU</span>
</template>
<template #extra>
<Button size="small" @click="loadData">
<div class="flex">
<span class="icon-[charm--refresh]"></span>
</div>
</Button>
</template>
<Descriptions v-if="server?.cpu" bordered :column="1" size="small">
<DescriptionsItem label="核心数">
{{ server.cpu.coreTotal }}
</DescriptionsItem>
<DescriptionsItem label="逻辑处理器">
{{ server.cpu.logicalProcessors }}
</DescriptionsItem>
<DescriptionsItem label="系统使用率">
{{ server.cpu.cpuRate }}%
</DescriptionsItem>
<DescriptionsItem label="当前空闲率">
{{ 100 - server.cpu.cpuRate }}%
</DescriptionsItem>
</Descriptions>
</Card>
</Col>
<Col :lg="12" :md="24" :sm="24" :xl="12" :xs="24">
<Card size="small">
<template #title>
<span>内存</span>
</template>
<Descriptions v-if="server?.memory" bordered :column="1" size="small">
<DescriptionsItem label="总内存">
{{ server.memory.totalRAM }}
</DescriptionsItem>
<DescriptionsItem label="已用内存">
{{ server.memory.usedRam }}
</DescriptionsItem>
<DescriptionsItem label="剩余内存">
{{ server.memory.freeRam }}
</DescriptionsItem>
<DescriptionsItem label="使用率">
<span :class="{ 'text-danger': server.memory.ramRate > 80 }">
{{ server.memory.ramRate }}%
</span>
</DescriptionsItem>
</Descriptions>
</Card>
</Col>
<Col :span="24">
<Card size="small">
<template #title>
<span>服务器信息</span>
</template>
<Descriptions v-if="server?.sys" bordered :column="2" size="small">
<DescriptionsItem label="服务器名称">
{{ server.sys.computerName }}
</DescriptionsItem>
<DescriptionsItem label="操作系统">
{{ server.sys.osName }}
</DescriptionsItem>
<DescriptionsItem label="服务器IP">
{{ server.sys.serverIP }}
</DescriptionsItem>
<DescriptionsItem label="系统架构">
{{ server.sys.osArch }}
</DescriptionsItem>
</Descriptions>
</Card>
</Col>
<Col :span="24">
<Card size="small">
<template #title>
<span>应用信息</span>
</template>
<Descriptions v-if="server?.app" bordered :column="2" size="small">
<DescriptionsItem label="应用环境">
{{ server.app.name }}
</DescriptionsItem>
<DescriptionsItem label="应用版本">
{{ server.app.version }}
</DescriptionsItem>
<DescriptionsItem label="启动时间">
{{ server.app.startTime }}
</DescriptionsItem>
<DescriptionsItem label="运行时长">
{{ server.app.runTime }}
</DescriptionsItem>
<DescriptionsItem label="安装路径" :span="2">
{{ server.app.rootPath }}
</DescriptionsItem>
<DescriptionsItem label="项目路径" :span="2">
{{ server.app.webRootPath }}
</DescriptionsItem>
<DescriptionsItem label="运行参数" :span="2">
{{ server.app.name }}
</DescriptionsItem>
</Descriptions>
</Card>
</Col>
<Col :span="24">
<Card size="small">
<template #title>
<span>磁盘状态</span>
</template>
<Table
v-if="server?.disk"
:columns="diskColumns"
:data-source="server.disk"
:pagination="false"
size="small"
bordered
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'availablePercent'">
<span :class="{ 'text-danger': record.availablePercent > 80 }">
{{ record.availablePercent }}%
</span>
</template>
</template>
</Table>
</Card>
</Col>
</Row>
</Spin>
</Page>
</template>
<style scoped>
.text-danger {
color: #ff4d4f;
}
</style>

View File

@@ -0,0 +1,4 @@
<!-- 建议通过菜单配置成外链/内嵌 达到相同的效果且灵活性更高 -->
<template>
<iframe class="size-full" src="http://localhost:8800/snail-job"></iframe>
</template>

View File

@@ -0,0 +1,146 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { clientAdd, clientInfo, clientUpdate } from '#/api/system/client';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { drawerSchema } from './data';
import SecretInput from './secret-input.vue';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
formItemClass: 'col-span-2',
componentProps: {
class: 'w-full',
},
},
layout: 'vertical',
schema: drawerSchema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2 gap-x-4',
});
function setupForm(update: boolean) {
formApi.updateSchema([
{
dependencies: {
show: () => update,
triggerFields: [''],
},
fieldName: 'clientId',
},
{
componentProps: {
disabled: update,
},
fieldName: 'clientKey',
},
{
componentProps: {
disabled: update,
},
fieldName: 'clientSecret',
},
]);
}
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
// 提取生成状态字段Schema的函数
const getStatusSchema = (disabled: boolean) => [
{
componentProps: { disabled },
fieldName: 'status',
},
];
const [BasicDrawer, drawerApi] = useVbenDrawer({
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
async onOpenChange(isOpen) {
if (!isOpen) {
return null;
}
drawerApi.drawerLoading(true);
const { id } = drawerApi.getData() as { id?: number | string };
isUpdate.value = !!id;
// 初始化
setupForm(isUpdate.value);
if (isUpdate.value && id) {
const record = await clientInfo(id);
// 不能禁用id为1的记录
formApi.updateSchema(getStatusSchema(record.id === 1));
await formApi.setValues(record);
} else {
// 新增模式: 确保状态字段可用
formApi.updateSchema(getStatusSchema(false));
}
await markInitialized();
drawerApi.drawerLoading(false);
},
});
async function handleConfirm() {
try {
drawerApi.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? clientUpdate(data) : clientAdd(data));
resetInitialized();
emit('reload');
drawerApi.close();
} catch (error) {
console.error(error);
} finally {
drawerApi.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<BasicDrawer :title="title" class="w-[600px]">
<BasicForm>
<template #clientSecret="slotProps">
<SecretInput v-bind="slotProps" :disabled="isUpdate" />
</template>
</BasicForm>
</BasicDrawer>
</template>
<style lang="scss" scoped>
/**
自定义组件校验失败样式
*/
:deep(.form-valid-error .ant-input[name='clientSecret']) {
border-color: hsl(var(--destructive));
box-shadow: 0 0 0 2px rgb(255 38 5 / 6%);
}
</style>

View File

@@ -0,0 +1,196 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { DictEnum } from '@vben/constants';
import { getPopupContainer } from '@vben/utils';
import { getDictOptions } from '#/utils/dict';
import { renderDict, renderDictTags } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'clientKey',
label: '客户端key',
},
{
component: 'Input',
fieldName: 'clientSecret',
label: '客户端密钥',
},
{
component: 'Select',
componentProps: {
options: getDictOptions(DictEnum.SYS_NORMAL_DISABLE),
},
fieldName: 'status',
label: '状态',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '客户端ID',
field: 'clientId',
showOverflow: true,
},
{
title: '客户端key',
field: 'clientKey',
},
{
title: '客户端密钥',
field: 'clientSecret',
},
{
title: '授权类型',
field: 'grantTypeList',
slots: {
default: ({ row }) => {
if (!row.grantTypeList) {
return '无';
}
return renderDictTags(
row.grantTypeList,
getDictOptions(DictEnum.SYS_GRANT_TYPE),
true,
4,
);
},
},
},
{
title: '设备类型',
field: 'deviceType',
slots: {
default: ({ row }) => {
return renderDict(row.deviceType, DictEnum.SYS_DEVICE_TYPE);
},
},
},
{
title: 'token活跃时间',
field: 'activeTimeout',
formatter({ row }) {
return `${row.activeTimeout}`;
},
},
{
title: 'token超时时间',
field: 'timeout',
formatter({ row }) {
return `${row.timeout}`;
},
},
{
title: '状态',
field: 'status',
slots: {
default: 'status',
},
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const drawerSchema: FormSchemaGetter = () => [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'id',
label: 'id',
},
{
component: 'Input',
componentProps: {
disabled: true,
},
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'clientId',
label: '客户端ID',
},
{
component: 'Input',
fieldName: 'clientKey',
label: '客户端key',
rules: 'required',
},
{
component: 'Input',
fieldName: 'clientSecret',
label: '客户端密钥',
rules: 'required',
},
{
component: 'Select',
componentProps: {
getPopupContainer,
mode: 'multiple',
optionFilterProp: 'label',
options: getDictOptions(DictEnum.SYS_GRANT_TYPE),
},
fieldName: 'grantTypeList',
label: '授权类型',
rules: 'selectRequired',
},
{
component: 'Select',
componentProps: {
allowClear: false,
getPopupContainer,
options: getDictOptions(DictEnum.SYS_DEVICE_TYPE),
},
fieldName: 'deviceType',
label: '设备类型',
rules: 'selectRequired',
},
{
component: 'InputNumber',
componentProps: {
addonAfter: '秒',
placeholder: '请输入',
},
defaultValue: 1800,
fieldName: 'activeTimeout',
formItemClass: 'col-span-2 lg:col-span-1',
help: '指定时间无操作则过期(单位:秒), 默认30分钟(1800秒)',
label: 'Token活跃超时时间',
rules: 'required',
},
{
component: 'InputNumber',
componentProps: {
addonAfter: '秒',
},
defaultValue: 604_800,
fieldName: 'timeout',
formItemClass: 'col-span-2 lg:col-span-1 ',
help: '指定时间必定过期(单位:秒),默认七天(604800秒)',
label: 'Token固定超时时间',
rules: 'required',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: getDictOptions(DictEnum.SYS_NORMAL_DISABLE),
optionType: 'button',
},
defaultValue: '0',
fieldName: 'status',
label: '状态',
},
];

View File

@@ -0,0 +1,182 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Client } from '#/api/system/client/model';
import { useAccess } from '@vben/access';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
clientChangeStatus,
clientExport,
clientList,
clientRemove,
} from '#/api/system/client';
import { TableSwitch } from '#/components/table';
import { commonDownloadExcel } from '#/utils/file/download';
import clientDrawer from './client-drawer.vue';
import { columns, querySchema } from './data';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
checkMethod: ({ row }) => (row as Client)?.id !== 1,
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await clientList({
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
},
id: 'system-client-index',
showOverflow: false,
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [ClientDrawer, drawerApi] = useVbenDrawer({
connectedComponent: clientDrawer,
});
function handleAdd() {
drawerApi.setData({});
drawerApi.open();
}
async function handleEdit(record: Client) {
drawerApi.setData({ id: record.id });
drawerApi.open();
}
async function handleDelete(row: Client) {
await clientRemove([row.id]);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: Client) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await clientRemove(ids);
await tableApi.query();
},
});
}
function handleDownloadExcel() {
commonDownloadExcel(clientExport, '客户端数据', tableApi.formApi.form.values);
}
const { hasAccessByCodes } = useAccess();
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="客户端列表">
<template #toolbar-tools>
<Space>
<a-button
v-access:code="['system:client:export']"
@click="handleDownloadExcel"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:client:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:client:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #status="{ row }">
<!-- pc不允许禁用 禁用了直接登录不了 应该设置disabled -->
<!-- 登录提示: 认证权限类型已禁用 -->
<TableSwitch
v-model:value="row.status"
:api="() => clientChangeStatus(row)"
:disabled="row.id === 1 || !hasAccessByCodes(['system:client:edit'])"
@reload="tableApi.query()"
/>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:client:edit']"
@click.stop="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<Popconfirm
:disabled="row.id === 1"
:get-popup-container="getVxePopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<ghost-button
:disabled="row.id === 1"
danger
v-access:code="['system:client:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<ClientDrawer @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,52 @@
<script setup lang="ts">
import { IconifyIcon } from '@vben/icons';
import { buildUUID } from '@vben/utils';
import { Input } from 'ant-design-vue';
defineOptions({ name: 'SecretInput' });
withDefaults(defineProps<{ disabled?: boolean; placeholder?: string }>(), {
disabled: false,
placeholder: '请输入密钥或随机生成',
});
const value = defineModel<string>('value', {
required: false,
});
function refreshSecret() {
value.value = buildUUID();
}
/**
* 万一要在每次新增时打开Drawer刷新
* 需要调用实例方法
*/
defineExpose({ refreshSecret });
</script>
<template>
<Input v-model:value="value" :disabled="disabled" :placeholder="placeholder">
<template v-if="!disabled" #addonAfter>
<a-button type="primary" @click="refreshSecret">
<div class="flex items-center gap-[4px]">
<IconifyIcon icon="charm:refresh" />
<span>随机生成</span>
</div>
</a-button>
</template>
</Input>
</template>
<style lang="scss" scoped>
:deep(.ant-input-group-addon) {
padding: 0;
border: none;
}
:deep(.ant-btn-primary) {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
</style>

View File

@@ -0,0 +1,89 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { configAdd, configInfo, configUpdate } from '#/api/system/config';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { modalSchema } from './data';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
labelWidth: 80,
},
schema: modalSchema(),
showDefaultActions: false,
});
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [BasicModal, modalApi] = useVbenModal({
fullscreenButton: false,
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
modalApi.modalLoading(true);
const { id } = modalApi.getData() as { id?: string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await configInfo(id);
await formApi.setValues(record);
}
await markInitialized();
modalApi.modalLoading(false);
},
});
async function handleConfirm() {
try {
modalApi.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? configUpdate(data) : configAdd(data));
resetInitialized();
emit('reload');
modalApi.close();
} catch (error) {
console.error(error);
} finally {
modalApi.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<BasicModal :title="title" class="w-[550px]">
<BasicForm />
</BasicModal>
</template>

View File

@@ -0,0 +1,129 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { DictEnum } from '@vben/constants';
import { getPopupContainer } from '@vben/utils';
import { getDictOptions } from '#/utils/dict';
import { renderDict } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'configName',
label: '参数名称',
},
{
component: 'Input',
fieldName: 'configKey',
label: '参数键名',
},
{
component: 'Select',
componentProps: {
getPopupContainer,
options: getDictOptions(DictEnum.SYS_YES_NO),
},
fieldName: 'configType',
label: '系统内置',
},
{
component: 'RangePicker',
fieldName: 'creationTime',
label: '创建时间',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '参数名称',
field: 'configName',
},
{
title: '参数KEY',
field: 'configKey',
},
{
title: '参数Value',
field: 'configValue',
},
{
title: '系统内置',
field: 'configType',
width: 120,
slots: {
default: ({ row }) => {
return renderDict(row.configType, DictEnum.SYS_YES_NO);
},
},
},
{
title: '备注',
field: 'remark',
},
{
title: '创建时间',
field: 'creationTime',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const modalSchema: FormSchemaGetter = () => [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'id',
label: '参数主键',
},
{
component: 'Input',
fieldName: 'configName',
label: '参数名称',
rules: 'required',
},
{
component: 'Input',
fieldName: 'configKey',
label: '参数键名',
rules: 'required',
},
{
component: 'Textarea',
formItemClass: 'items-start',
fieldName: 'configValue',
label: '参数键值',
componentProps: {
autoSize: true,
},
rules: 'required',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: getDictOptions(DictEnum.SYS_YES_NO),
optionType: 'button',
},
defaultValue: 'N',
fieldName: 'configType',
label: '是否内置',
rules: 'required',
},
{
component: 'Textarea',
fieldName: 'remark',
formItemClass: 'items-start',
label: '备注',
},
];

View File

@@ -0,0 +1,177 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { SysConfig } from '#/api/system/config/model';
import { Page, useVbenModal } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
configExport,
configList,
configRefreshCache,
configRemove,
} from '#/api/system/config';
import { commonDownloadExcel } from '#/utils/file/download';
import configModal from './config-modal.vue';
import { columns, querySchema } from './data';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
// 日期选择格式化
fieldMappingTime: [
[
'creationTime',
['startTime', 'endTime'],
['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
],
],
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await configList({
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
},
id: 'system-config-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [ConfigModal, modalApi] = useVbenModal({
connectedComponent: configModal,
});
function handleAdd() {
modalApi.setData({});
modalApi.open();
}
async function handleEdit(record: SysConfig) {
modalApi.setData({ id: record.id });
modalApi.open();
}
async function handleDelete(row: SysConfig) {
await configRemove([row.id]);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: SysConfig) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await configRemove(ids);
await tableApi.query();
},
});
}
function handleDownloadExcel() {
commonDownloadExcel(configExport, '参数配置', tableApi.formApi.form.values, {
fieldMappingTime: formOptions.fieldMappingTime,
});
}
async function handleRefreshCache() {
await configRefreshCache();
await tableApi.query();
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="参数列表">
<template #toolbar-tools>
<Space>
<a-button @click="handleRefreshCache"> 刷新缓存 </a-button>
<a-button
v-access:code="['system:config:export']"
@click="handleDownloadExcel"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:config:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:config:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:config:edit']"
@click.stop="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<Popconfirm
:get-popup-container="getVxePopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:config:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<ConfigModal @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,139 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { DictEnum } from '@vben/constants';
import { getPopupContainer } from '@vben/utils';
import { renderDict } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'deptName',
label: '部门名称',
},
{
component: 'Select',
componentProps: {
getPopupContainer,
options: [
{ label: '启用', value: true },
{ label: '禁用', value: false },
],
},
fieldName: 'state',
label: '部门状态',
},
];
export const columns: VxeGridProps['columns'] = [
{
field: 'deptName',
title: '部门名称',
treeNode: true,
},
{
field: 'deptCode',
title: '部门编码',
},
{
field: 'orderNum',
title: '排序',
},
{
field: 'leaderName',
title: '负责人',
},
{
field: 'state',
title: '状态',
slots: {
default: ({ row }) => {
return renderDict(String(row.state), DictEnum.SYS_NORMAL_DISABLE);
},
},
},
{
field: 'creationTime',
title: '创建时间',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const drawerSchema: FormSchemaGetter = () => [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'id',
},
{
component: 'TreeSelect',
componentProps: {
getPopupContainer,
},
dependencies: {
show: (model) => model.parentId !== '00000000-0000-0000-0000-000000000000',
triggerFields: ['parentId'],
},
fieldName: 'parentId',
label: '上级部门',
rules: 'selectRequired',
},
{
component: 'Input',
fieldName: 'deptName',
label: '部门名称',
rules: 'required',
},
{
component: 'InputNumber',
fieldName: 'orderNum',
label: '显示排序',
rules: 'required',
defaultValue: 0,
},
{
component: 'Input',
fieldName: 'deptCode',
label: '部门编码',
},
{
component: 'Select',
componentProps: {
allowClear: true,
getPopupContainer,
placeholder: '请选择负责人',
},
fieldName: 'leader',
label: '负责人',
},
{
component: 'Textarea',
fieldName: 'remark',
label: '备注',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: '启用', value: true },
{ label: '禁用', value: false },
],
optionType: 'button',
},
defaultValue: true,
fieldName: 'state',
label: '状态',
},
];

View File

@@ -0,0 +1,177 @@
<script setup lang="ts">
import type { Dept } from '#/api/system/dept/model';
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { addFullName, cloneDeep, listToTree } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import {
deptAdd,
deptInfo,
deptList,
deptNodeList,
deptUpdate,
} from '#/api/system/dept';
import { listUserByDeptId } from '#/api/system/user';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { drawerSchema } from './data';
const emit = defineEmits<{ reload: [] }>();
interface DrawerProps {
id?: number | string;
update: boolean;
}
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 80,
},
schema: drawerSchema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2',
});
async function getDeptTree(deptId?: number | string, exclude = false) {
let ret: Dept[] = [];
ret = await (!deptId || exclude ? deptList({}) : deptNodeList(deptId));
const treeData = listToTree(ret, { id: 'id', pid: 'parentId' });
// 添加部门名称 如 xx-xx-xx
addFullName(treeData, 'deptName', ' / ');
return treeData;
}
async function initDeptSelect(deptId?: number | string) {
// 需要动态更新TreeSelect组件 这里允许为空
const treeData = await getDeptTree(deptId, !isUpdate.value);
formApi.updateSchema([
{
componentProps: {
fieldNames: { label: 'deptName', value: 'id' },
showSearch: true,
treeData,
treeDefaultExpandAll: true,
treeLine: { showLeafIcon: false },
// 选中后显示在输入框的值
treeNodeLabelProp: 'fullName',
},
fieldName: 'parentId',
},
]);
}
/**
* 部门管理员下拉框 更新时才会enable
* @param deptId
*/
async function initDeptUsers(deptId: number | string) {
const ret = await listUserByDeptId(deptId);
const options = ret.map((user) => ({
label: `${user.userName} | ${user.nick}`,
value: user.id,
}));
formApi.updateSchema([
{
componentProps: {
disabled: ret.length === 0,
options,
placeholder: ret.length === 0 ? '该部门暂无用户' : '请选择部门负责人',
},
fieldName: 'leader',
},
]);
}
async function setLeaderOptions() {
formApi.updateSchema([
{
componentProps: {
disabled: true,
options: [],
placeholder: '仅在更新时可选部门负责人',
},
fieldName: 'leader',
},
]);
}
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [BasicDrawer, drawerApi] = useVbenDrawer({
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
async onOpenChange(isOpen) {
if (!isOpen) {
return null;
}
drawerApi.drawerLoading(true);
const { id, update } = drawerApi.getData() as DrawerProps;
isUpdate.value = update;
if (id) {
await formApi.setFieldValue('parentId', id);
if (update) {
const record = await deptInfo(id);
await formApi.setValues(record);
}
}
await (update && id ? initDeptUsers(id) : setLeaderOptions());
/** 部门选择 下拉框 */
await initDeptSelect(id);
await markInitialized();
drawerApi.drawerLoading(false);
},
});
async function handleConfirm() {
try {
drawerApi.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? deptUpdate(data) : deptAdd(data));
resetInitialized();
emit('reload');
drawerApi.close();
} catch (error) {
console.error(error);
} finally {
drawerApi.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<BasicDrawer :title="title" class="w-[600px]">
<BasicForm />
</BasicDrawer>
</template>

View File

@@ -0,0 +1,186 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Dept } from '#/api/system/dept/model';
import { nextTick } from 'vue';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { eachTree, getVxePopupContainer } from '@vben/utils';
import { Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deptList, deptRemove } from '#/api/system/dept';
import { columns, querySchema } from './data';
import deptDrawer from './dept-drawer.vue';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
// 空GUID用于判断根节点
const EMPTY_GUID = '00000000-0000-0000-0000-000000000000';
const gridOptions: VxeGridProps = {
columns,
height: 'auto',
keepSource: true,
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async (_, formValues = {}) => {
const resp = await deptList({
...formValues,
});
// 将根节点的 parentId 置为 null以便 vxe-table 正确识别根节点
const items = resp.map((item) => ({
...item,
parentId: item.parentId === EMPTY_GUID ? null : item.parentId,
}));
return { items };
},
// 默认请求接口后展开全部 不需要可以删除这段
querySuccess: () => {
// 默认展开 需要加上标记
// eslint-disable-next-line no-use-before-define
eachTree(tableApi.grid.getData(), (item) => (item.expand = true));
nextTick(() => {
setExpandOrCollapse(true);
});
},
},
},
rowConfig: {
keyField: 'id',
},
treeConfig: {
parentField: 'parentId',
rowField: 'id',
transform: true,
},
id: 'system-dept-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
gridEvents: {
cellDblclick: (e) => {
const { row = {} } = e;
if (!row?.children) {
return;
}
const isExpanded = row?.expand;
tableApi.grid.setTreeExpand(row, !isExpanded);
row.expand = !isExpanded;
},
// 需要监听使用箭头展开的情况 否则展开/折叠的数据不一致
toggleTreeExpand: (e) => {
const { row = {}, expanded } = e;
row.expand = expanded;
},
},
});
const [DeptDrawer, drawerApi] = useVbenDrawer({
connectedComponent: deptDrawer,
});
function handleAdd() {
drawerApi.setData({ update: false });
drawerApi.open();
}
function handleSubAdd(row: Dept) {
const { id } = row;
drawerApi.setData({ id, update: false });
drawerApi.open();
}
async function handleEdit(record: Dept) {
drawerApi.setData({ id: record.id, update: true });
drawerApi.open();
}
async function handleDelete(row: Dept) {
await deptRemove(row.id);
await tableApi.query();
}
/**
* 全部展开/折叠
* @param expand 是否展开
*/
function setExpandOrCollapse(expand: boolean) {
eachTree(tableApi.grid.getData(), (item) => (item.expand = expand));
tableApi.grid?.setAllTreeExpand(expand);
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="部门列表" table-title-help="双击展开/收起子菜单">
<template #toolbar-tools>
<Space>
<a-button @click="setExpandOrCollapse(false)">
{{ $t('pages.common.collapse') }}
</a-button>
<a-button @click="setExpandOrCollapse(true)">
{{ $t('pages.common.expand') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:dept:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:dept:edit']"
@click="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<ghost-button
class="btn-success"
v-access:code="['system:dept:add']"
@click="handleSubAdd(row)"
>
{{ $t('pages.common.add') }}
</ghost-button>
<Popconfirm
:get-popup-container="getVxePopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:dept:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<DeptDrawer @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,6 @@
<template>
<div>
ele版本会使用这个文件 只是为了不报错`未找到对应组件`才新建的这个文件
无实际意义
</div>
</template>

View File

@@ -0,0 +1,136 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { DictData } from '#/api/system/dict/dict-data-model';
import { DictEnum } from '@vben/constants';
import { renderDict, renderDictTag } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'dictLabel',
label: '字典标签',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '字典标签',
field: 'cssClass',
slots: {
default: ({ row }) => {
const { dictValue } = row as DictData;
return renderDictTag(dictValue, [row]);
},
},
},
{
title: '字典键值',
field: 'dictValue',
},
{
title: '状态',
field: 'state',
width: 120,
slots: {
default: ({ row }) => {
return renderDict(String(row.state), DictEnum.SYS_NORMAL_DISABLE);
},
},
},
{
title: '字典排序',
field: 'orderNum',
},
{
title: '备注',
field: 'remark',
},
{
title: '创建时间',
field: 'creationTime',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const drawerSchema: FormSchemaGetter = () => [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'id',
},
{
component: 'Input',
componentProps: {
disabled: true,
},
fieldName: 'dictType',
label: '字典类型',
},
{
component: 'Input',
fieldName: 'listClass',
label: '标签样式',
},
{
component: 'Input',
fieldName: 'dictLabel',
label: '数据标签',
rules: 'required',
},
{
component: 'Input',
fieldName: 'dictValue',
label: '数据键值',
rules: 'required',
},
{
component: 'Textarea',
componentProps: {
placeholder: '可使用tailwind类名 如bg-blue w-full h-full等',
},
fieldName: 'cssClass',
formItemClass: 'items-start',
help: '标签的css样式, 可添加已经编译的css类名',
label: 'css类名',
},
{
component: 'InputNumber',
fieldName: 'orderNum',
label: '显示排序',
rules: 'required',
defaultValue: 0,
},
{
component: 'Textarea',
fieldName: 'remark',
formItemClass: 'items-start',
label: '备注',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: '启用', value: true },
{ label: '禁用', value: false },
],
optionType: 'button',
},
defaultValue: true,
fieldName: 'state',
label: '状态',
},
];

View File

@@ -0,0 +1,146 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import {
dictDataAdd,
dictDataUpdate,
dictDetailInfo,
} from '#/api/system/dict/dict-data';
import { tagTypes } from '#/components/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { drawerSchema } from './data';
import TagStylePicker from './tag-style-picker.vue';
const emit = defineEmits<{ reload: [] }>();
interface DrawerProps {
id?: string;
dictType: string;
}
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 80,
},
schema: drawerSchema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2',
});
/**
* 标签样式选择器
* default: 预设标签样式
* custom: 自定义标签样式
*/
const selectType = ref('default');
/**
* 根据标签样式判断是自定义还是默认
* @param listClass 标签样式
*/
function setupSelectType(listClass: string | null | undefined) {
if (!listClass) {
selectType.value = 'default';
return;
}
// 判断是自定义还是预设
const isDefault = Reflect.has(tagTypes, listClass);
selectType.value = isDefault ? 'default' : 'custom';
}
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [BasicDrawer, drawerApi] = useVbenDrawer({
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
async onOpenChange(isOpen) {
if (!isOpen) {
return null;
}
drawerApi.drawerLoading(true);
const { id, dictType } = drawerApi.getData() as DrawerProps;
isUpdate.value = !!id;
await formApi.setFieldValue('dictType', dictType);
if (id && isUpdate.value) {
const record = await dictDetailInfo(id);
setupSelectType(record.listClass || '');
await formApi.setValues(record);
}
await markInitialized();
drawerApi.drawerLoading(false);
},
});
async function handleConfirm() {
try {
drawerApi.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
const data = cloneDeep(await formApi.getValues());
// 需要置空的情况 undefined不会提交给后端 需要改为空字符串
if (!data.listClass) {
data.listClass = '';
}
await (isUpdate.value ? dictDataUpdate(data) : dictDataAdd(data));
resetInitialized();
emit('reload');
drawerApi.close();
} catch (error) {
console.error(error);
} finally {
drawerApi.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
selectType.value = 'default';
resetInitialized();
}
/**
* 取消标签选中 必须设置为undefined才行
*/
async function handleDeSelect() {
await formApi.setFieldValue('listClass', undefined);
}
</script>
<template>
<BasicDrawer :title="title" class="w-[600px]">
<BasicForm>
<template #listClass="slotProps">
<TagStylePicker
v-bind="slotProps"
v-model:select-type="selectType"
@deselect="handleDeSelect"
/>
</template>
</BasicForm>
</BasicDrawer>
</template>

View File

@@ -0,0 +1,186 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PageQuery } from '#/api/common';
import type { DictData } from '#/api/system/dict/dict-data-model';
import { ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
dictDataExport,
dictDataList,
dictDataRemove,
} from '#/api/system/dict/dict-data';
import { commonDownloadExcel } from '#/utils/file/download';
import { emitter } from '../mitt';
import { columns, querySchema } from './data';
import dictDataDrawer from './dict-data-drawer.vue';
const dictType = ref('');
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
const params: PageQuery = {
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
};
if (dictType.value) {
params.dictType = dictType.value;
}
return await dictDataList(params);
},
},
},
rowConfig: {
keyField: 'id',
},
id: 'system-dict-data-index',
};
// @ts-expect-error TS2589: DictData + proxyConfig causes deep instantiation; generics are manageable at runtime.
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [DictDataDrawer, drawerApi] = useVbenDrawer({
connectedComponent: dictDataDrawer,
});
function handleAdd() {
drawerApi.setData({ dictType: dictType.value });
drawerApi.open();
}
async function handleEdit(record: DictData) {
drawerApi.setData({
dictType: dictType.value,
id: record.id,
});
drawerApi.open();
}
async function handleDelete(row: DictData) {
await dictDataRemove([row.id]);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: DictData) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await dictDataRemove(ids);
await tableApi.query();
},
});
}
function handleDownloadExcel() {
commonDownloadExcel(dictDataExport, '字典数据', tableApi.formApi.form.values);
}
emitter.on('rowClick', async (value) => {
dictType.value = value;
await tableApi.query();
});
</script>
<template>
<div>
<BasicTable id="dict-data" table-title="字典数据列表">
<template #toolbar-tools>
<Space>
<a-button
v-access:code="['system:dict:export']"
@click="handleDownloadExcel"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:dict:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
:disabled="dictType === ''"
type="primary"
v-access:code="['system:dict:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:dict:edit']"
@click="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<Popconfirm
:get-popup-container="
(node) => getVxePopupContainer(node, 'dict-data')
"
placement="left"
title="确认删除"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:dict:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<DictDataDrawer @reload="tableApi.query()" />
</div>
</template>

View File

@@ -0,0 +1,86 @@
<script setup lang="ts">
import type { RadioChangeEvent } from 'ant-design-vue';
import { computed } from 'vue';
import { usePreferences } from '@vben/preferences';
import { RadioGroup, Select } from 'ant-design-vue';
import { ColorPicker } from 'vue3-colorpicker';
import { tagSelectOptions } from '#/components/dict';
import 'vue3-colorpicker/style.css';
/**
* 需要禁止透传
* 不禁止会有奇怪的bug 会绑定到selectType上
* TODO: 未知原因 有待研究
*/
defineOptions({ inheritAttrs: false });
defineEmits<{ deselect: [] }>();
const options = [
{ label: '默认颜色', value: 'default' },
{ label: '自定义颜色', value: 'custom' },
] as const;
/**
* 主要是加了const报错
*/
const computedOptions = computed(
() => options as unknown as { label: string; value: string }[],
);
type SelectType = (typeof options)[number]['value'];
const selectType = defineModel<SelectType>('selectType', {
default: 'default',
});
/**
* color必须为hex颜色或者undefined
*/
const color = defineModel<string | undefined>('value', {
default: undefined,
});
function handleSelectTypeChange(e: RadioChangeEvent) {
// 必须给默认hex颜色 不能为空字符串
color.value = e.target.value === 'custom' ? '#1677ff' : undefined;
}
const { isDark } = usePreferences();
const theme = computed(() => {
return isDark.value ? 'black' : 'white';
});
</script>
<template>
<div class="flex flex-1 items-center gap-[6px]">
<RadioGroup
v-model:value="selectType"
:options="computedOptions"
button-style="solid"
option-type="button"
@change="handleSelectTypeChange"
/>
<Select
v-if="selectType === 'default'"
v-model:value="color"
:allow-clear="true"
:options="tagSelectOptions()"
class="flex-1"
placeholder="请选择标签样式"
@deselect="$emit('deselect')"
/>
<ColorPicker
v-if="selectType === 'custom'"
disable-alpha
format="hex"
v-model:pure-color="color"
:theme="theme"
/>
</div>
</template>

View File

@@ -0,0 +1,21 @@
<script setup lang="ts">
import { onUnmounted } from 'vue';
import { Page } from '@vben/common-ui';
import DictDataPanel from './data/index.vue';
import { emitter } from './mitt';
import DictTypePanel from './type/index.vue';
onUnmounted(() => emitter.off('rowClick'));
</script>
<template>
<Page
:auto-content-height="true"
content-class="flex flex-col lg:flex-row gap-4"
>
<DictTypePanel class="flex-1 overflow-hidden" />
<DictDataPanel class="flex-1 overflow-hidden" />
</Page>
</template>

View File

@@ -0,0 +1,10 @@
import { mitt } from '@vben/utils';
/**
* dictType: string
*/
type Events = {
rowClick: string;
};
export const emitter = mitt<Events>();

View File

@@ -0,0 +1,104 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { DictEnum } from '@vben/constants';
import { z } from '#/adapter/form';
import { renderDict } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'dictName',
label: '字典名称',
},
{
component: 'Input',
fieldName: 'dictType',
label: '字典类型',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '字典名称',
field: 'dictName',
},
{
title: '字典类型',
field: 'dictType',
},
{
title: '状态',
field: 'state',
width: 120,
slots: {
default: ({ row }) => {
return renderDict(String(row.state), DictEnum.SYS_NORMAL_DISABLE);
},
},
},
{
title: '备注',
field: 'remark',
},
{
title: '创建时间',
field: 'creationTime',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const modalSchema: FormSchemaGetter = () => [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'id',
label: 'id',
},
{
component: 'Input',
fieldName: 'dictName',
label: '字典名称',
rules: 'required',
},
{
component: 'Input',
fieldName: 'dictType',
help: '使用英文/下划线命名, 如:sys_normal_disable',
label: '字典类型',
rules: z
.string()
.regex(/^[a-z_]+$/i, { message: '字典类型只能使用英文/下划线命名' }),
},
{
component: 'Textarea',
fieldName: 'remark',
label: '备注',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: '启用', value: true },
{ label: '禁用', value: false },
],
optionType: 'button',
},
defaultValue: true,
fieldName: 'state',
label: '状态',
},
];

View File

@@ -0,0 +1,93 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import {
dictTypeAdd,
dictTypeInfo,
dictTypeUpdate,
} from '#/api/system/dict/dict-type';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { modalSchema } from './data';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
layout: 'vertical',
commonConfig: {
labelWidth: 100,
},
schema: modalSchema(),
showDefaultActions: false,
});
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [BasicModal, modalApi] = useVbenModal({
fullscreenButton: false,
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
modalApi.modalLoading(true);
const { id } = modalApi.getData() as { id?: string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await dictTypeInfo(id);
await formApi.setValues(record);
}
await markInitialized();
modalApi.modalLoading(false);
},
});
async function handleConfirm() {
try {
modalApi.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? dictTypeUpdate(data) : dictTypeAdd(data));
resetInitialized();
emit('reload');
modalApi.close();
} catch (error) {
console.error(error);
} finally {
modalApi.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<BasicModal :title="title">
<BasicForm />
</BasicModal>
</template>

View File

@@ -0,0 +1,281 @@
<!-- 使用vxe实现成本最小 且自带虚拟滚动 -->
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { DictType } from '#/api/system/dict/dict-type-model';
import { h, ref, shallowRef, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { cn } from '@vben/utils';
import {
DeleteOutlined,
EditOutlined,
ExportOutlined,
PlusOutlined,
SyncOutlined,
} from '@ant-design/icons-vue';
import {
Alert,
Input,
Modal,
Popconfirm,
Space,
Tooltip,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
dictTypeExport,
dictTypeList,
dictTypeRemove,
refreshDictTypeCache,
} from '#/api/system/dict/dict-type';
import { commonDownloadExcel } from '#/utils/file/download';
import { emitter } from '../mitt';
import dictTypeModal from './dict-type-modal.vue';
const tableAllData = shallowRef<DictType[]>([]);
const gridOptions: VxeGridProps = {
columns: [
{
title: 'name',
field: 'render',
slots: { default: 'render' },
},
],
height: 'auto',
keepSource: true,
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async () => {
const resp = await dictTypeList();
total.value = resp.total;
tableAllData.value = resp.rows;
return resp;
},
},
},
rowConfig: {
keyField: 'id',
// 高亮当前行
isCurrent: true,
},
cellConfig: {
height: 60,
},
showHeader: false,
toolbarConfig: {
enabled: false,
},
// 开启虚拟滚动
scrollY: {
enabled: false,
gt: 0,
},
rowClassName: 'cursor-pointer',
id: 'system-dict-data-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
gridOptions,
gridEvents: {
cellClick: ({ row }) => {
handleRowClick(row);
},
},
});
const [DictTypeModal, modalApi] = useVbenModal({
connectedComponent: dictTypeModal,
});
function handleAdd() {
modalApi.setData({});
modalApi.open();
}
async function handleEdit(record: DictType) {
modalApi.setData({ id: record.id });
modalApi.open();
}
async function handleDelete(row: DictType) {
await dictTypeRemove([row.id]);
await tableApi.query();
}
async function handleReset() {
currentRowId.value = '';
searchValue.value = '';
await tableApi.query();
}
function handleDownloadExcel() {
commonDownloadExcel(dictTypeExport, '字典类型数据');
}
function handleRefreshCache() {
Modal.confirm({
title: '提示',
content: '确认刷新字典类型缓存吗?',
okButtonProps: {
danger: true,
},
onOk: async () => {
await refreshDictTypeCache();
await tableApi.query();
},
});
}
const lastDictType = ref<string>('');
const currentRowId = ref<null | string>(null);
function handleRowClick(row: DictType) {
if (lastDictType.value === row.dictType) {
return;
}
currentRowId.value = row.id;
emitter.emit('rowClick', row.dictType);
}
const searchValue = ref('');
const total = ref(0);
watch(searchValue, (value) => {
if (!tableApi) {
return;
}
if (value) {
const names = tableAllData.value.filter((item) =>
item.dictName.includes(searchValue.value),
);
const types = tableAllData.value.filter((item) =>
item.dictType.includes(searchValue.value),
);
const filtered = [...new Set([...names, ...types])];
total.value = filtered.length;
tableApi.grid.loadData(filtered);
} else {
total.value = tableAllData.value.length;
tableApi.grid.loadData(tableAllData.value);
}
});
</script>
<template>
<div
:class="
cn(
'bg-background flex max-h-[100vh] w-[360px] flex-col overflow-y-hidden',
'rounded-lg',
'dict-type-card',
)
"
>
<div :class="cn('flex items-center justify-between', 'border-b px-4 py-2')">
<span class="font-semibold">字典项列表</span>
<Space>
<Tooltip title="刷新缓存">
<a-button
v-access:code="['system:dict:edit']"
:icon="h(SyncOutlined)"
@click="handleRefreshCache"
/>
</Tooltip>
<Tooltip :title="$t('pages.common.export')">
<a-button
v-access:code="['system:dict:export']"
:icon="h(ExportOutlined)"
@click="handleDownloadExcel"
/>
</Tooltip>
<Tooltip :title="$t('pages.common.add')">
<a-button
v-access:code="['system:dict:add']"
:icon="h(PlusOutlined)"
@click="handleAdd"
/>
</Tooltip>
</Space>
</div>
<div class="flex flex-1 flex-col overflow-y-hidden p-4">
<Alert
class="mb-4"
show-icon
message="如果你的数据量大 自行开启虚拟滚动"
/>
<Input
placeholder="搜索字典项名称/类型"
v-model:value="searchValue"
allow-clear
>
<template #addonAfter>
<Tooltip title="重置/刷新">
<SyncOutlined
v-access:code="['system:dict:edit']"
@click="handleReset"
/>
</Tooltip>
</template>
</Input>
<BasicTable class="flex-1 overflow-hidden">
<template #render="{ row: item }">
<div :class="cn('flex items-center justify-between px-2 py-2')">
<div class="flex flex-col items-baseline overflow-hidden">
<span class="font-medium">{{ item.dictName }}</span>
<div
class="max-w-full overflow-hidden text-ellipsis whitespace-nowrap"
>
{{ item.dictType }}
</div>
</div>
<div class="flex items-center gap-3 text-[17px]">
<EditOutlined
class="text-primary"
v-access:code="['system:dict:edit']"
@click.stop="handleEdit(item)"
/>
<Popconfirm
placement="left"
:title="`确认删除 [${item.dictName}]?`"
@confirm="handleDelete(item)"
>
<DeleteOutlined
v-access:code="['system:dict:remove']"
class="text-destructive"
@click.stop=""
/>
</Popconfirm>
</div>
</div>
</template>
</BasicTable>
</div>
<div class="border-t px-4 py-3"> {{ total }} 条数据</div>
<DictTypeModal @reload="tableApi.query()" />
</div>
</template>
<style lang="scss">
.dict-type-card {
.vxe-grid {
padding: 12px 0 0;
.vxe-body--row {
&.row--current {
// 选中行背景色
background-color: hsl(var(--accent-hover)) !important;
}
}
}
.ant-alert {
padding: 6px 12px;
}
}
</style>

View File

@@ -0,0 +1,210 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { DictType } from '#/api/system/dict/dict-type-model';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
dictTypeExport,
dictTypeList,
dictTypeRemove,
refreshDictTypeCache,
} from '#/api/system/dict/dict-type';
import { commonDownloadExcel } from '#/utils/file/download';
import { emitter } from '../mitt';
import { columns, querySchema } from './data';
import dictTypeModal from './dict-type-modal.vue';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 70,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await dictTypeList({
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
// 高亮当前行
isCurrent: true,
},
id: 'system-dict-type-index',
rowClassName: 'hover:cursor-pointer',
};
const lastDictType = ref('');
// @ts-expect-error TS2589: DictType + proxyConfig causes deep instantiation; generics are manageable at runtime.
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
gridEvents: {
cellClick: (e) => {
const { row } = e;
if (lastDictType.value === row.dictType) {
return;
}
emitter.emit('rowClick', row.dictType);
lastDictType.value = row.dictType;
},
},
});
const [DictTypeModal, modalApi] = useVbenModal({
connectedComponent: dictTypeModal,
});
function handleAdd() {
modalApi.setData({});
modalApi.open();
}
async function handleEdit(record: DictType) {
modalApi.setData({ id: record.id });
modalApi.open();
}
async function handleDelete(row: DictType) {
await dictTypeRemove([row.id]);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: DictType) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await dictTypeRemove(ids);
await tableApi.query();
},
});
}
async function handleRefreshCache() {
await refreshDictTypeCache();
await tableApi.query();
}
function handleDownloadExcel() {
commonDownloadExcel(
dictTypeExport,
'字典类型数据',
tableApi.formApi.form.values,
);
}
</script>
<template>
<div>
<BasicTable id="dict-type" table-title="字典类型列表">
<template #toolbar-tools>
<Space>
<a-button
v-access:code="['system:dict:edit']"
@click="handleRefreshCache"
>
刷新缓存
</a-button>
<a-button
v-access:code="['system:dict:export']"
@click="handleDownloadExcel"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:dict:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:dict:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:dict:edit']"
@click.stop="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<Popconfirm
:get-popup-container="
(node) => getVxePopupContainer(node, 'dict-type')
"
placement="left"
title="确认删除"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:dict:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<DictTypeModal @reload="tableApi.query()" />
</div>
</template>
<style lang="scss">
div#dict-type {
.vxe-body--row {
&.row--current {
// 选中行bold
@apply font-semibold;
}
}
}
</style>

View File

@@ -0,0 +1,434 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { h } from 'vue';
import { DictEnum } from '@vben/constants';
import { FolderIcon, MenuIcon, OkButtonIcon, VbenIcon } from '@vben/icons';
import { $t } from '@vben/locales';
import { getPopupContainer } from '@vben/utils';
import { z } from '#/adapter/form';
import { renderDict } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'menuName',
label: '菜单名称 ',
},
{
component: 'Select',
componentProps: {
getPopupContainer,
options: [
{ label: '启用', value: true },
{ label: '禁用', value: false },
],
},
fieldName: 'state',
label: '菜单状态 ',
},
{
component: 'Select',
componentProps: {
getPopupContainer,
options: [
{ label: '显示', value: true },
{ label: '隐藏', value: false },
],
},
fieldName: 'isShow',
label: '显示状态',
},
];
// 菜单类型
export const menuTypeOptions = [
{ label: '目录', value: 'Catalogue' },
{ label: '菜单', value: 'Menu' },
{ label: '按钮', value: 'Component' },
];
export const yesNoOptions = [
{ label: '是', value: '0' },
{ label: '否', value: '1' },
];
/**
* 判断是否为菜单类型Menu/C
*/
function isMenuType(menuType: string): boolean {
const type = menuType?.toLowerCase();
return type === 'c' || type === 'menu';
}
/**
* 判断是否为目录类型Catalogue/M
*/
function isCatalogueType(menuType: string): boolean {
const type = menuType?.toLowerCase();
return type === 'm' || type === 'catalogue' || type === 'catalog' || type === 'directory' || type === 'folder';
}
/**
* 判断是否为按钮类型Component/F
*/
function isComponentType(menuType: string): boolean {
const type = menuType?.toLowerCase();
return type === 'f' || type === 'component' || type === 'button';
}
// M目录 C菜单 F按钮
const menuTypes: Record<string, { icon: typeof MenuIcon; value: string }> = {
c: { icon: MenuIcon, value: '菜单' },
menu: { icon: MenuIcon, value: '菜单' },
Menu: { icon: MenuIcon, value: '菜单' },
catalog: { icon: FolderIcon, value: '目录' },
directory: { icon: FolderIcon, value: '目录' },
folder: { icon: FolderIcon, value: '目录' },
m: { icon: FolderIcon, value: '目录' },
catalogue: { icon: FolderIcon, value: '目录' },
component: { icon: OkButtonIcon, value: '按钮' },
f: { icon: OkButtonIcon, value: '按钮' },
button: { icon: OkButtonIcon, value: '按钮' },
};
export const columns: VxeGridProps['columns'] = [
{
title: '菜单名称',
field: 'menuName',
treeNode: true,
width: 200,
slots: {
// 需要i18n支持 否则返回原始值
default: ({ row }) => $t(row.menuName),
},
},
{
title: '图标',
field: 'menuIcon',
width: 80,
slots: {
default: ({ row }) => {
if (row?.menuIcon === '#' || !row?.menuIcon) {
return '';
}
return (
<span class={'flex justify-center'}>
<VbenIcon icon={row.menuIcon} />
</span>
);
},
},
},
{
title: '排序',
field: 'orderNum',
width: 120,
},
{
title: '组件类型',
field: 'menuType',
width: 150,
slots: {
default: ({ row }) => {
const typeKey = `${row.menuType ?? ''}`.toString().trim().toLowerCase();
const current = menuTypes[typeKey];
if (!current) {
return '未知';
}
return (
<span class="flex items-center justify-center gap-1">
{h(current.icon, { class: 'size-[18px]' })}
<span>{current.value}</span>
</span>
);
},
},
},
{
title: '权限标识',
field: 'permissionCode',
},
{
title: '组件路径',
field: 'component',
},
{
title: '状态',
field: 'state',
width: 100,
slots: {
default: ({ row }) => {
return renderDict(String(row.state), DictEnum.SYS_NORMAL_DISABLE);
},
},
},
{
title: '显示',
field: 'isShow',
width: 100,
slots: {
default: ({ row }) => {
return row.isShow ? '显示' : '隐藏';
},
},
},
{
title: '创建时间',
field: 'creationTime',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const drawerSchema: FormSchemaGetter = () => [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'id',
},
{
component: 'TreeSelect',
defaultValue: 0,
fieldName: 'parentId',
label: '上级菜单',
rules: 'selectRequired',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: menuTypeOptions,
optionType: 'button',
},
defaultValue: 'M',
dependencies: {
componentProps: (_, api) => {
// 切换时清空校验
// 直接抄的源码 没有清空校验的方法
Object.keys(api.errors.value).forEach((key) => {
api.setFieldError(key, undefined);
});
return {};
},
triggerFields: ['menuType'],
},
fieldName: 'menuType',
label: '菜单类型',
},
{
component: 'Input',
dependencies: {
// 类型不为按钮时显示
show: (values) => !isComponentType(values.menuType),
triggerFields: ['menuType'],
},
renderComponentContent: (model) => ({
addonBefore: () => <VbenIcon icon={model.menuIcon} />,
addonAfter: () => (
<a href="https://icon-sets.iconify.design/" target="_blank">
</a>
),
}),
fieldName: 'menuIcon',
help: '点击搜索图标跳转到iconify & 粘贴',
label: '菜单图标',
},
{
component: 'Input',
fieldName: 'menuName',
label: '菜单名称',
help: '支持i18n写法, 如: menu.system.user',
rules: 'required',
},
{
component: 'InputNumber',
fieldName: 'orderNum',
help: '排序, 数字越小越靠前',
label: '显示排序',
defaultValue: 0,
rules: 'required',
},
{
component: 'Input',
componentProps: (model) => {
const placeholder = model.isLink
? '填写链接地址http(s):// 使用新页面打开'
: '填写`路由地址`或者`链接地址` 链接默认使用内部iframe内嵌打开';
return {
placeholder,
};
},
dependencies: {
rules: (model) => {
if (!model.isLink) {
return z
.string({ message: '请输入路由地址' })
.min(1, '请输入路由地址')
.refine((val) => !val.startsWith('/'), {
message: '路由地址不需要带/',
});
}
// 为链接
return z
.string({ message: '请输入链接地址' })
.regex(/^https?:\/\//, { message: '请输入正确的链接地址' });
},
// 类型不为按钮时显示
show: (values) => !isComponentType(values?.menuType),
triggerFields: ['isLink', 'menuType'],
},
fieldName: 'router',
help: `路由地址不带/, 如: menu, user\n 链接为http(s)://开头\n 链接默认使用内部iframe打开, 可通过{是否外链}控制打开方式`,
label: '路由地址',
},
{
component: 'Input',
componentProps: (model) => {
return {
// 为链接时组件disabled
disabled: model.isLink,
};
},
defaultValue: '',
dependencies: {
rules: (model) => {
// 非链接时为必填项
if (model.router && !/^https?:\/\//.test(model.router)) {
return z
.string()
.min(1, { message: '非链接时必填组件路径' })
.refine((val) => !val.startsWith('/') && !val.endsWith('/'), {
message: '组件路径开头/末尾不需要带/',
});
}
// 为链接时非必填
return z.string().optional();
},
// 类型为菜单时显示
show: (values) => isMenuType(values.menuType),
triggerFields: ['menuType', 'router'],
},
fieldName: 'component',
help: '填写./src/views下的组件路径, 如system/menu/index',
label: '组件路径',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: '是', value: true },
{ label: '否', value: false },
],
optionType: 'button',
},
defaultValue: false,
dependencies: {
// 类型不为按钮时显示
show: (values) => !isComponentType(values.menuType),
triggerFields: ['menuType'],
},
fieldName: 'isLink',
help: '外链为http(s)://开头\n 选择否时, 使用iframe从内部打开页面, 否则新窗口打开',
label: '是否外链',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: '显示', value: true },
{ label: '隐藏', value: false },
],
optionType: 'button',
},
defaultValue: true,
dependencies: {
// 类型不为按钮时显示
show: (values) => !isComponentType(values.menuType),
triggerFields: ['menuType'],
},
fieldName: 'isShow',
help: '隐藏后不会出现在菜单栏, 但仍然可以访问',
label: '是否显示',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: '启用', value: true },
{ label: '禁用', value: false },
],
optionType: 'button',
},
defaultValue: true,
dependencies: {
// 类型不为按钮时显示
show: (values) => !isComponentType(values.menuType),
triggerFields: ['menuType'],
},
fieldName: 'state',
help: '停用后不会出现在菜单栏, 也无法访问',
label: '菜单状态',
},
{
component: 'Input',
dependencies: {
// 类型为菜单/按钮时显示
show: (values) => !isCatalogueType(values.menuType),
triggerFields: ['menuType'],
},
fieldName: 'permissionCode',
help: `控制器中定义的权限字符\n 如: @SaCheckPermission("system:user:import")`,
label: '权限标识',
},
{
component: 'Input',
componentProps: (model) => ({
// 为链接时组件disabled
disabled: model.isLink,
placeholder: '必须为json字符串格式',
}),
dependencies: {
// 类型为菜单时显示
show: (values) => isMenuType(values.menuType),
triggerFields: ['menuType'],
},
fieldName: 'query',
help: 'vue-router中的query属性\n 如{"name": "xxx", "age": 16}',
label: '路由参数',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: '是', value: true },
{ label: '否', value: false },
],
optionType: 'button',
},
defaultValue: false,
dependencies: {
// 类型为菜单时显示
show: (values) => isMenuType(values.menuType),
triggerFields: ['menuType'],
},
fieldName: 'isCache',
help: '路由的keepAlive属性',
label: '是否缓存',
},
];

View File

@@ -0,0 +1,263 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Menu } from '#/api/system/menu/model';
import { computed, ref } from 'vue';
import { useAccess } from '@vben/access';
import { Fallback, Page, useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { eachTree, getVxePopupContainer, treeToList } from '@vben/utils';
import { Popconfirm, Space, Switch, Tooltip } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { menuCascadeRemove, menuList, menuRemove } from '#/api/system/menu';
import { columns, querySchema } from './data';
import menuDrawer from './menu-drawer.vue';
// 空GUID用于判断根节点
const EMPTY_GUID = '00000000-0000-0000-0000-000000000000';
type MenuRow = Omit<Menu, 'parentId'> & {
menuId: string;
parentId: string | null;
};
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const gridOptions: VxeGridProps<Record<string, any>> = {
columns,
height: 'auto',
keepSource: true,
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async (_, formValues = {}) => {
const resp = await menuList({
...formValues,
});
// 统一处理数据:确保 menuId 和 parentId 存在,并将根节点的 parentId 置为 null
const items = (resp || []).map((item) => {
const menuId = String(item.id ?? '');
const parentId = item.parentId ? String(item.parentId) : null;
return {
...item,
menuId,
// 将根节点的 parentId 置为 null以便 vxe-table 正确识别根节点
parentId:
!parentId ||
parentId === EMPTY_GUID ||
parentId === menuId
? null
: parentId,
} as MenuRow;
});
return { items };
},
},
},
rowConfig: {
keyField: 'menuId',
},
/**
* 开启虚拟滚动
* 数据量小可以选择关闭
* 如果遇到样式问题(空白、错位 滚动等)可以选择关闭虚拟滚动
*/
scrollY: {
enabled: true,
gt: 0,
},
treeConfig: {
parentField: 'parentId',
rowField: 'menuId',
transform: true,
},
id: 'system-menu-index',
};
// @ts-expect-error TS2589: MenuRow 与 proxyConfig 组合导致类型实例化层级过深;运行时泛型已被擦除,可控,先压制报错。
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
gridEvents: {
cellDblclick: (e) => {
const { row = {} } = e;
if (!row?.children) {
return;
}
const isExpanded = row?.expand;
tableApi.grid.setTreeExpand(row, !isExpanded);
row.expand = !isExpanded;
},
// 需要监听使用箭头展开的情况 否则展开/折叠的数据不一致
toggleTreeExpand: (e) => {
const { row = {}, expanded } = e;
row.expand = expanded;
},
},
});
const [MenuDrawer, drawerApi] = useVbenDrawer({
connectedComponent: menuDrawer,
});
function handleAdd() {
drawerApi.setData({});
drawerApi.open();
}
function handleSubAdd(row: MenuRow) {
const { menuId } = row;
drawerApi.setData({ id: menuId, update: false });
drawerApi.open();
}
async function handleEdit(record: MenuRow) {
drawerApi.setData({ id: record.menuId, update: true });
drawerApi.open();
}
/**
* 是否级联删除
*/
const cascadingDeletion = ref(false);
async function handleDelete(row: MenuRow) {
if (cascadingDeletion.value) {
// 级联删除
const menuAndChildren = treeToList<MenuRow[]>([row], { id: 'menuId' });
const menuIds = menuAndChildren.map((item) => String(item.menuId));
await menuCascadeRemove(menuIds);
} else {
// 单删除
await menuRemove([String(row.menuId)]);
}
await tableApi.query();
}
function removeConfirmTitle(row: MenuRow) {
const menuName = $t(row.menuName);
if (!cascadingDeletion.value) {
return `是否确认删除 [${menuName}] ?`;
}
const menuAndChildren = treeToList<MenuRow[]>([row], { id: 'menuId' });
if (menuAndChildren.length === 1) {
return `是否确认删除 [${menuName}] ?`;
}
return `是否确认删除 [${menuName}] 及 [${menuAndChildren.length - 1}]个子项目 ?`;
}
/**
* 编辑/添加成功后刷新表格
*/
async function afterEditOrAdd() {
tableApi.query();
}
/**
* 全部展开/折叠
* @param expand 是否展开
*/
function setExpandOrCollapse(expand: boolean) {
eachTree(tableApi.grid.getData(), (item) => (item.expand = expand));
tableApi.grid?.setAllTreeExpand(expand);
}
/**
* 与后台逻辑相同
* 只有租户管理和超级管理能访问菜单管理
* 注意: 只有超管才能对菜单进行`增删改`操作
* 注意: 只有超管才能对菜单进行`增删改`操作
* 注意: 只有超管才能对菜单进行`增删改`操作
*/
const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
return hasAccessByRoles(['admin', 'superadmin']);
});
</script>
<template>
<Page v-if="isAdmin" :auto-content-height="true">
<BasicTable table-title="菜单列表" table-title-help="双击展开/收起子菜单">
<template #toolbar-tools>
<Space>
<Tooltip title="删除菜单以及子菜单">
<div
v-access:role="['superadmin']"
v-access:code="['system:menu:remove']"
class="flex items-center"
>
<span class="mr-2 text-sm text-[#666666]">级联删除</span>
<Switch v-model:checked="cascadingDeletion" />
</div>
</Tooltip>
<a-button @click="setExpandOrCollapse(false)">
{{ $t('pages.common.collapse') }}
</a-button>
<a-button @click="setExpandOrCollapse(true)">
{{ $t('pages.common.expand') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:menu:add']"
v-access:role="['superadmin']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:menu:edit']"
v-access:role="['superadmin']"
@click="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<!-- '按钮类型'无法再添加子菜单 -->
<ghost-button
v-if="row.menuType !== 'F'"
class="btn-success"
v-access:code="['system:menu:add']"
v-access:role="['superadmin']"
@click="handleSubAdd(row)"
>
{{ $t('pages.common.add') }}
</ghost-button>
<Popconfirm
:get-popup-container="getVxePopupContainer"
placement="left"
:title="removeConfirmTitle(row)"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:menu:remove']"
v-access:role="['superadmin']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<MenuDrawer @reload="afterEditOrAdd" />
</Page>
<Fallback v-else description="您没有菜单管理的访问权限" status="403" />
</template>

View File

@@ -0,0 +1,159 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import {
addFullName,
cloneDeep,
getPopupContainer,
listToTree,
} from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { menuAdd, menuInfo, menuList, menuUpdate } from '#/api/system/menu';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { drawerSchema } from './data';
// 空GUID用于判断根节点
const EMPTY_GUID = '00000000-0000-0000-0000-000000000000';
interface ModalProps {
id?: string;
update: boolean;
}
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 90,
},
schema: drawerSchema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2',
});
async function setupMenuSelect() {
// menu
const menuArray = await menuList();
// support i18n
menuArray.forEach((item) => {
item.menuName = $t(item.menuName);
});
// const folderArray = menuArray.filter((item) => item.menuType === 'M');
/**
* 这里需要过滤掉按钮类型
* 不允许在按钮下添加数据
*/
const filteredList = menuArray.filter((item) => item.menuType !== 'F');
const menuTree = listToTree(filteredList, { id: 'id', pid: 'parentId' });
const fullMenuTree = [
{
id: EMPTY_GUID,
menuName: $t('menu.root'),
children: menuTree,
},
];
addFullName(fullMenuTree, 'menuName', ' / ');
formApi.updateSchema([
{
componentProps: {
fieldNames: {
label: 'menuName',
value: 'id',
},
getPopupContainer,
// 设置弹窗滚动高度 默认256
listHeight: 300,
showSearch: true,
treeData: fullMenuTree,
treeDefaultExpandAll: false,
// 默认展开的树节点
treeDefaultExpandedKeys: [EMPTY_GUID],
treeLine: { showLeafIcon: false },
// 筛选的字段
treeNodeFilterProp: 'menuName',
treeNodeLabelProp: 'fullName',
},
fieldName: 'parentId',
},
]);
}
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [BasicDrawer, drawerApi] = useVbenDrawer({
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
async onOpenChange(isOpen) {
if (!isOpen) {
return null;
}
drawerApi.drawerLoading(true);
const { id, update } = drawerApi.getData() as ModalProps;
isUpdate.value = update;
// 加载菜单树选择
await setupMenuSelect();
if (id) {
await formApi.setFieldValue('parentId', id);
if (update) {
const record = await menuInfo(id);
await formApi.setValues(record);
}
}
await markInitialized();
drawerApi.drawerLoading(false);
},
});
async function handleConfirm() {
try {
drawerApi.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? menuUpdate(data) : menuAdd(data));
resetInitialized();
emit('reload');
drawerApi.close();
} catch (error) {
console.error(error);
} finally {
drawerApi.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<BasicDrawer :title="title" class="w-[600px]">
<BasicForm />
</BasicDrawer>
</template>

View File

@@ -0,0 +1,128 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { DictEnum } from '@vben/constants';
import { getPopupContainer } from '@vben/utils';
import { getDictOptions } from '#/utils/dict';
import { renderDict } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'title',
label: '公告标题',
},
{
component: 'Input',
fieldName: 'creatorId',
label: '创建人',
},
{
component: 'Select',
componentProps: {
getPopupContainer,
options: getDictOptions(DictEnum.SYS_NOTICE_TYPE),
},
fieldName: 'type',
label: '公告类型',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '公告标题',
field: 'title',
},
{
title: '公告类型',
field: 'type',
width: 120,
slots: {
default: ({ row }) => {
return renderDict(row.type, DictEnum.SYS_NOTICE_TYPE);
},
},
},
{
title: '状态',
field: 'state',
width: 120,
slots: {
default: ({ row }) => {
return renderDict(row.state ? '1' : '0', DictEnum.SYS_NOTICE_STATUS);
},
},
},
{
title: '创建人',
field: 'creatorId',
width: 150,
},
{
title: '创建时间',
field: 'creationTime',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const modalSchema: FormSchemaGetter = () => [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'id',
label: '主键',
},
{
component: 'Input',
fieldName: 'title',
label: '公告标题',
rules: 'required',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: getDictOptions(DictEnum.SYS_NOTICE_STATUS),
optionType: 'button',
},
defaultValue: '0',
fieldName: 'state',
label: '公告状态',
rules: 'required',
formItemClass: 'col-span-1',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: getDictOptions(DictEnum.SYS_NOTICE_TYPE),
optionType: 'button',
},
defaultValue: '1',
fieldName: 'type',
label: '公告类型',
rules: 'required',
formItemClass: 'col-span-1',
},
{
component: 'RichTextarea',
componentProps: {
width: '100%',
},
fieldName: 'content',
label: '公告内容',
rules: 'required',
},
];

View File

@@ -0,0 +1,148 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Notice } from '#/api/system/notice/model';
import { Page, useVbenModal } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import { noticeList, noticeRemove } from '#/api/system/notice';
import { columns, querySchema } from './data';
import noticeModal from './notice-modal.vue';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await noticeList({
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
},
id: 'system-notice-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [NoticeModal, modalApi] = useVbenModal({
connectedComponent: noticeModal,
});
function handleAdd() {
modalApi.setData({});
modalApi.open();
}
async function handleEdit(record: Notice) {
modalApi.setData({ id: record.id });
modalApi.open();
}
async function handleDelete(row: Notice) {
await noticeRemove([row.id]);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: Notice) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await noticeRemove(ids);
await tableApi.query();
},
});
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="通知公告列表">
<template #toolbar-tools>
<Space>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:notice:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:notice:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:notice:edit']"
@click="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<Popconfirm
:get-popup-container="getVxePopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:notice:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<NoticeModal @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,178 @@
<!--
2025年03月08日重构为原生表单(反向重构??)
该文件作为例子 使用原生表单而非useVbenForm
-->
<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { Form, FormItem, Input, RadioGroup } from 'ant-design-vue';
import { pick } from 'lodash-es';
import { noticeAdd, noticeInfo, noticeUpdate } from '#/api/system/notice';
import { Tinymce } from '#/components/tinymce';
import { getDictOptions } from '#/utils/dict';
import { useBeforeCloseDiff } from '#/utils/popup';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
/**
* 定义表单数据类型
*/
interface FormData {
id?: string;
title?: string;
state?: boolean | string;
type?: string;
content?: string;
}
/**
* 定义默认值 用于reset
*/
const defaultValues: FormData = {
id: undefined,
title: '',
state: '0',
type: '1',
content: '',
};
/**
* 表单数据ref
*/
const formData = ref(defaultValues);
type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
[key: string]: RuleObject[];
};
/**
* 表单校验规则
*/
const formRules = ref<AntdFormRules<FormData>>({
state: [{ required: true, message: $t('ui.formRules.selectRequired') }],
content: [{ required: true, message: $t('ui.formRules.required') }],
type: [{ required: true, message: $t('ui.formRules.selectRequired') }],
title: [{ required: true, message: $t('ui.formRules.required') }],
});
/**
* useForm解构出表单方法
*/
const { validate, validateInfos, resetFields } = Form.useForm(
formData,
formRules,
);
function customFormValueGetter() {
return JSON.stringify(formData.value);
}
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: customFormValueGetter,
currentGetter: customFormValueGetter,
},
);
const [BasicModal, modalApi] = useVbenModal({
class: 'w-[800px]',
fullscreenButton: true,
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
onOpenChange: async (isOpen) => {
if (!isOpen) {
return null;
}
modalApi.modalLoading(true);
const { id } = modalApi.getData() as { id?: string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await noticeInfo(id);
// 只赋值存在的字段并处理state的转换boolean转string用于RadioGroup
const filterRecord = pick(record, Object.keys(defaultValues));
formData.value = {
...filterRecord,
state: typeof filterRecord.state === 'boolean' ? (filterRecord.state ? '1' : '0') : filterRecord.state,
};
}
await markInitialized();
modalApi.modalLoading(false);
},
});
async function handleConfirm() {
try {
modalApi.lock(true);
await validate();
// 可能会做数据处理 使用cloneDeep深拷贝
const data = cloneDeep(formData.value);
// 转换state从string到booleanRadioGroup返回string但API需要boolean
if (typeof data.state === 'string') {
data.state = data.state === '1' || data.state === 'true';
}
await (isUpdate.value ? noticeUpdate(data) : noticeAdd(data));
resetInitialized();
emit('reload');
modalApi.close();
} catch (error) {
console.error(error);
} finally {
modalApi.lock(false);
}
}
async function handleClosed() {
formData.value = defaultValues;
resetFields();
resetInitialized();
}
</script>
<template>
<BasicModal :title="title">
<Form layout="vertical">
<FormItem label="公告标题" v-bind="validateInfos.title">
<Input
:placeholder="$t('ui.formRules.required')"
v-model:value="formData.title"
/>
</FormItem>
<div class="grid sm:grid-cols-1 lg:grid-cols-2">
<FormItem label="公告状态" v-bind="validateInfos.state">
<RadioGroup
button-style="solid"
option-type="button"
v-model:value="formData.state"
:options="getDictOptions(DictEnum.SYS_NOTICE_STATUS)"
/>
</FormItem>
<FormItem label="公告类型" v-bind="validateInfos.type">
<RadioGroup
button-style="solid"
option-type="button"
v-model:value="formData.type"
:options="getDictOptions(DictEnum.SYS_NOTICE_TYPE)"
/>
</FormItem>
</div>
<FormItem label="公告内容" v-bind="validateInfos.content">
<Tinymce v-model="formData.content" />
</FormItem>
</Form>
</BasicModal>
</template>

View File

@@ -0,0 +1,223 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { DictEnum } from '@vben/constants';
import { Tag } from 'ant-design-vue';
import { z } from '#/adapter/form';
import { getDictOptions } from '#/utils/dict';
const accessPolicyOptions = [
{ color: 'orange', label: '私有', value: '0' },
{ color: 'green', label: '公开', value: '1' },
{ color: 'blue', label: '自定义', value: '2' },
];
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'configKey',
label: '配置名称',
},
{
component: 'Input',
fieldName: 'bucketName',
label: '桶名称',
},
{
component: 'Select',
componentProps: {
options: [
{ label: '是', value: '0' },
{ label: '否', value: '1' },
],
},
fieldName: 'status',
label: '是否默认',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '配置名称',
field: 'configKey',
},
{
title: '访问站点',
field: 'endpoint',
showOverflow: true,
},
{
title: '桶名称',
field: 'bucketName',
},
{
title: '域',
field: 'region',
},
{
title: '权限桶类型',
field: 'accessPolicy',
slots: {
default: ({ row }) => {
const current = accessPolicyOptions.find(
(item) => item.value === row.accessPolicy,
);
if (current) {
return <Tag color={current.color}>{current.label}</Tag>;
}
return '未知类型';
},
},
},
{
title: '是否默认',
field: 'status',
slots: {
default: 'status',
},
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const drawerSchema: FormSchemaGetter = () => [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'ossConfigId',
},
{
component: 'Divider',
componentProps: {
orientation: 'center',
},
fieldName: 'divider1',
hideLabel: true,
renderComponentContent: () => ({
default: () => '基本信息',
}),
},
{
component: 'Input',
fieldName: 'configKey',
label: '配置名称',
rules: 'required',
},
{
component: 'Input',
fieldName: 'endpoint',
label: '服务地址',
renderComponentContent: (formModel) => ({
addonBefore: () => (formModel.isHttps === 'Y' ? 'https://' : 'http://'),
}),
rules: z
.string()
.refine((domain) => domain && !/^https?:\/\/.*/.test(domain), {
message: '请输入正确的域名, 不需要http(s)',
}),
},
{
component: 'Input',
fieldName: 'domain',
label: '自定义域名',
},
{
component: 'Input',
fieldName: 'tip',
label: '占位作为提示使用',
hideLabel: true,
},
{
component: 'Divider',
componentProps: {
orientation: 'center',
},
fieldName: 'divider2',
hideLabel: true,
renderComponentContent: () => ({
default: () => '认证信息',
}),
},
{
component: 'Input',
fieldName: 'accessKey',
label: 'accessKey',
rules: 'required',
},
{
component: 'Input',
fieldName: 'secretKey',
label: 'secretKey',
rules: 'required',
},
{
component: 'Divider',
componentProps: {
orientation: 'center',
},
fieldName: 'divider3',
hideLabel: true,
renderComponentContent: () => ({
default: () => '其他信息',
}),
},
{
component: 'Input',
fieldName: 'bucketName',
label: '桶名称',
rules: 'required',
},
{
component: 'Input',
fieldName: 'prefix',
label: '前缀',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: accessPolicyOptions,
optionType: 'button',
},
defaultValue: '0',
fieldName: 'accessPolicy',
formItemClass: 'col-span-3 lg:col-span-2',
label: '权限桶类型',
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: getDictOptions(DictEnum.SYS_YES_NO),
optionType: 'button',
},
defaultValue: 'N',
fieldName: 'isHttps',
formItemClass: 'col-span-3 lg:col-span-1',
label: '是否https',
rules: 'required',
},
{
component: 'Input',
fieldName: 'region',
label: '区域',
},
{
component: 'Textarea',
fieldName: 'remark',
formItemClass: 'items-start',
label: '备注',
},
];

View File

@@ -0,0 +1,166 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { OssConfig } from '#/api/system/oss-config/model';
import { useAccess } from '@vben/access';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
ossConfigChangeStatus,
ossConfigList,
ossConfigRemove,
} from '#/api/system/oss-config';
import { TableSwitch } from '#/components/table';
import { columns, querySchema } from './data';
import ossConfigDrawer from './oss-config-drawer.vue';
const formOptions: VbenFormProps = {
schema: querySchema(),
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await ossConfigList({
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'ossConfigId',
},
id: 'system-oss-config-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [OssConfigDrawer, drawerApi] = useVbenDrawer({
connectedComponent: ossConfigDrawer,
});
function handleAdd() {
drawerApi.setData({});
drawerApi.open();
}
async function handleEdit(record: OssConfig) {
drawerApi.setData({ id: record.ossConfigId });
drawerApi.open();
}
async function handleDelete(row: OssConfig) {
await ossConfigRemove([row.ossConfigId]);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: OssConfig) => row.ossConfigId);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await ossConfigRemove(ids);
await tableApi.query();
},
});
}
const { hasAccessByCodes } = useAccess();
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="oss配置列表">
<template #toolbar-tools>
<Space>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:ossConfig:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:ossConfig:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #status="{ row }">
<TableSwitch
v-model:value="row.status"
:api="() => ossConfigChangeStatus(row)"
:disabled="!hasAccessByCodes(['system:ossConfig:edit'])"
checked-text=""
un-checked-text=""
@reload="tableApi.query()"
/>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:ossConfig:edit']"
@click="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</ghost-button>
<Popconfirm
:get-popup-container="getVxePopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:ossConfig:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<OssConfigDrawer @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,115 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { Alert } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import {
ossConfigAdd,
ossConfigInfo,
ossConfigUpdate,
} from '#/api/system/oss-config';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { drawerSchema } from './data';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
formItemClass: 'col-span-3',
labelWidth: 100,
},
schema: drawerSchema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-3',
});
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [BasicDrawer, drawerApi] = useVbenDrawer({
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
async onOpenChange(isOpen) {
if (!isOpen) {
return null;
}
drawerApi.drawerLoading(true);
const { id } = drawerApi.getData() as { id?: number | string };
isUpdate.value = !!id;
if (isUpdate.value && id) {
const record = await ossConfigInfo(id);
await formApi.setValues(record);
}
await markInitialized();
drawerApi.drawerLoading(false);
},
});
async function handleConfirm() {
try {
drawerApi.lock(true);
/**
* 这里解构出来的values只能获取到自定义校验参数的值
* 需要自行调用formApi.getValues()获取表单值
*/
const { valid } = await formApi.validate();
if (!valid) {
return;
}
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? ossConfigUpdate(data) : ossConfigAdd(data));
resetInitialized();
emit('reload');
drawerApi.close();
} catch (error) {
console.error(error);
} finally {
drawerApi.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<BasicDrawer :title="title" class="w-[650px]">
<BasicForm>
<template #tip>
<div class="ml-7 w-full">
<Alert
message="私有桶使用自定义域名无法预览, 但可以正常上传/下载"
show-icon
type="warning"
/>
</div>
</template>
</BasicForm>
</BasicDrawer>
</template>
<style lang="scss" scoped>
:deep(.ant-divider) {
margin: 8px 0;
}
</style>

View File

@@ -0,0 +1,11 @@
<!--
后端版本>=5.4.0 这个从本地路由变为从后台返回
未修改文件名 而是新加了这个文件
-->
<script setup lang="ts">
import OssConfigPage from '#/views/system/oss-config/index.vue';
</script>
<template>
<OssConfigPage />
</template>

View File

@@ -0,0 +1,2 @@
/** 支持的图片列表 */
export const supportImageList = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

View File

@@ -0,0 +1,75 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'fileName',
label: '文件名',
},
{
component: 'Input',
fieldName: 'originalName',
label: '原名',
},
{
component: 'Input',
fieldName: 'fileSuffix',
label: '拓展名',
},
{
component: 'Input',
fieldName: 'service',
label: '服务商',
},
{
component: 'RangePicker',
fieldName: 'createTime',
label: '创建时间',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '文件名',
field: 'fileName',
showOverflow: true,
},
{
title: '文件原名',
field: 'originalName',
showOverflow: true,
},
{
title: '文件拓展名',
field: 'fileSuffix',
},
{
title: '文件预览',
field: 'url',
showOverflow: true,
slots: { default: 'url' },
},
{
title: '创建时间',
field: 'createTime',
sortable: true,
},
{
title: '上传人',
field: 'createByName',
},
{
title: '服务商',
field: 'service',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];

View File

@@ -0,0 +1 @@
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghgg0Aj8i0JO4OzsrPv69Wv+hi2qPHr0qNvf39+iI97soRIh4f3z58/u7du3SXX7Xt7Z2enevHmzfQe+oSN2apSAPj09TSrb+XKI/f379+08+A0cNRE2ANkupk+ACNPvkSPcAAEibACyXUyfABGm3yNHuAECRNgAZLuYPgEirKlHu7u7XdyytGwHAd8jjNyng4OD7vnz51dbPT8/7z58+NB9+/bt6jU/TI+AGWHEnrx48eJ/EsSmHzx40L18+fLyzxF3ZVMjEyDCiEDjMYZZS5wiPXnyZFbJaxMhQIQRGzHvWR7XCyOCXsOmiDAi1HmPMMQjDpbpEiDCiL358eNHurW/5SnWdIBbXiDCiA38/Pnzrce2YyZ4//59F3ePLNMl4PbpiL2J0L979+7yDtHDhw8vtzzvdGnEXdvUigSIsCLAWavHp/+qM0BcXMd/q25n1vF57TYBp0a3mUzilePj4+7k5KSLb6gt6ydAhPUzXnoPR0dHl79WGTNCfBnn1uvSCJdegQhLI1vvCk+fPu2ePXt2tZOYEV6/fn31dz+shwAR1sP1cqvLntbEN9MxA9xcYjsxS1jWR4AIa2Ibzx0tc44fYX/16lV6NDFLXH+YL32jwiACRBiEbf5KcXoTIsQSpzXx4N28Ja4BQoK7rgXiydbHjx/P25TaQAJEGAguWy0+2Q8PD6/Ki4R8EVl+bzBOnZY95fq9rj9zAkTI2SxdidBHqG9+skdw43borCXO/ZcJdraPWdv22uIEiLA4q7nvvCug8WTqzQveOH26fodo7g6uFe/a17W3+nFBAkRYENRdb1vkkz1CH9cPsVy/jrhr27PqMYvENYNlHAIesRiBYwRy0V+8iXP8+/fvX11Mr7L7ECueb/r48eMqm7FuI2BGWDEG8cm+7G3NEOfmdcTQw4h9/55lhm7DekRYKQPZF2ArbXTAyu4kDYB2YxUzwg0gi/41ztHnfQG26HbGel/crVrm7tNY+/1btkOEAZ2M05r4FB7r9GbAIdxaZYrHdOsgJ/wCEQY0J74TmOKnbxxT9n3FgGGWWsVdowHtjt9Nnvf7yQM2aZU/TIAIAxrw6dOnAWtZZcoEnBpNuTuObWMEiLAx1HY0ZQJEmHJ3HNvGCBBhY6jtaMoEiJB0Z29vL6ls58vxPcO8/zfrdo5qvKO+d3Fx8Wu8zf1dW4p/cPzLly/dtv9Ts/EbcvGAHhHyfBIhZ6NSiIBTo0LNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg==

View File

@@ -0,0 +1,41 @@
<script setup lang="ts">
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { FileUpload } from '#/components/upload';
const emit = defineEmits<{ reload: [] }>();
const fileList = ref<string[]>([]);
const [BasicModal, modalApi] = useVbenModal({
onOpenChange: (isOpen) => {
if (isOpen) {
return null;
}
if (fileList.value.length > 0) {
fileList.value = [];
emit('reload');
modalApi.close();
return null;
}
},
});
</script>
<template>
<BasicModal
:close-on-click-modal="false"
:footer="false"
:fullscreen-button="false"
title="文件上传"
>
<div class="flex flex-col gap-4">
<FileUpload
v-model:value="fileList"
:enable-drag-upload="true"
:max-count="3"
/>
</div>
</BasicModal>
</template>

View File

@@ -0,0 +1,37 @@
<script setup lang="ts">
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ImageUpload } from '#/components/upload';
const emit = defineEmits<{ reload: [] }>();
const fileList = ref<string[]>([]);
const [BasicModal, modalApi] = useVbenModal({
onOpenChange: (isOpen) => {
if (isOpen) {
return null;
}
if (fileList.value.length > 0) {
fileList.value = [];
emit('reload');
modalApi.close();
return null;
}
},
});
</script>
<template>
<BasicModal
:close-on-click-modal="false"
:footer="false"
:fullscreen-button="false"
title="图片上传"
>
<div class="flex flex-col gap-4">
<ImageUpload v-model:value="fileList" :max-count="3" />
</div>
</BasicModal>
</template>

View File

@@ -0,0 +1,293 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PageQuery } from '#/api/common';
import type { OssFile } from '#/api/system/oss/model';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Page, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';
import {
Image,
message,
Modal,
Popconfirm,
Space,
Spin,
Switch,
Tooltip,
} from 'ant-design-vue';
import {
addSortParams,
useVbenVxeGrid,
vxeCheckboxChecked,
} from '#/adapter/vxe-table';
import { configInfoByKey } from '#/api/system/config';
import { ossDownload, ossList, ossRemove } from '#/api/system/oss';
import { calculateFileSize } from '#/utils/file';
import { downloadByData } from '#/utils/file/download';
import { supportImageList } from './constant';
import { columns, querySchema } from './data';
import fallbackImageBase64 from './fallback-image.txt?raw';
import fileUploadModal from './file-upload-modal.vue';
import imageUploadModal from './image-upload-modal.vue';
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
// 日期选择格式化
fieldMappingTime: [
[
'createTime',
['params[beginCreateTime]', 'params[endCreateTime]'],
['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
],
],
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page, sorts }, formValues = {}) => {
const params: PageQuery = {
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
};
// 添加排序参数
addSortParams(params, sorts);
return await ossList(params);
},
},
},
headerCellConfig: {
height: 44,
},
cellConfig: {
height: 65,
},
rowConfig: {
keyField: 'ossId',
},
sortConfig: {
// 远程排序
remote: true,
// 支持多字段排序 默认关闭
multiple: false,
},
id: 'system-oss-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
gridEvents: {
// 排序 重新请求接口
sortChange: () => tableApi.query(),
},
});
async function handleDownload(row: OssFile) {
const downloadSize = ref($t('pages.common.downloadLoading'));
const hideLoading = message.loading({
content: () => downloadSize.value,
duration: 0,
});
try {
const data = await ossDownload(row.ossId, (e) => {
// 计算下载进度
const percent = Math.floor((e.loaded / e.total!) * 100);
// 已经下载
const current = calculateFileSize(e.loaded);
// 总大小
const total = calculateFileSize(e.total!);
downloadSize.value = `已下载: ${current}/${total} (${percent}%)`;
});
downloadByData(data, row.originalName);
message.success('下载完成');
} finally {
hideLoading();
}
}
async function handleDelete(row: OssFile) {
await ossRemove([row.ossId]);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: OssFile) => row.ossId);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await ossRemove(ids);
await tableApi.query();
},
});
}
const router = useRouter();
function handleToSettings() {
router.push('/system/oss-config/index');
}
const preview = ref(false);
onMounted(async () => {
const previewStr = await configInfoByKey('sys.oss.previewListResource');
preview.value = previewStr === 'true';
});
/**
* 根据拓展名判断是否是图片
* @param ext 拓展名
*/
function isImageFile(ext: string) {
return supportImageList.some((item) =>
ext.toLocaleLowerCase().includes(item),
);
}
/**
* 判断是否是pdf文件
* @param ext 扩展名
*/
function isPdfFile(ext: string) {
return ext.toLocaleLowerCase().includes('pdf');
}
/**
* pdf预览 使用浏览器接管
* @param url 文件地址
*/
function pdfPreview(url: string) {
window.open(url);
}
const [ImageUploadModal, imageUploadApi] = useVbenModal({
connectedComponent: imageUploadModal,
});
const [FileUploadModal, fileUploadApi] = useVbenModal({
connectedComponent: fileUploadModal,
});
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="文件列表">
<template #toolbar-tools>
<Space>
<Tooltip title="预览图片">
<Switch v-model:checked="preview" />
</Tooltip>
<a-button
v-access:code="['system:ossConfig:list']"
@click="handleToSettings"
>
配置管理
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:oss:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
v-access:code="['system:oss:upload']"
@click="fileUploadApi.open"
>
文件上传
</a-button>
<a-button
v-access:code="['system:oss:upload']"
@click="imageUploadApi.open"
>
图片上传
</a-button>
</Space>
</template>
<template #url="{ row }">
<!-- placeholder为图片未加载时显示的占位图 -->
<!-- fallback为图片加载失败时显示 -->
<!-- 需要设置key属性 否则切换翻页会有延迟 -->
<Image
:key="row.ossId"
v-if="preview && isImageFile(row.url)"
:src="row.url"
height="50px"
:fallback="fallbackImageBase64"
>
<template #placeholder>
<div class="flex size-full items-center justify-center">
<Spin />
</div>
</template>
</Image>
<!-- pdf预览 使用浏览器开新窗口 -->
<span
v-else-if="preview && isPdfFile(row.url)"
class="icon-[vscode-icons--file-type-pdf2] size-10 cursor-pointer"
@click.stop="pdfPreview(row.url)"
></span>
<span v-else>{{ row.url }}</span>
</template>
<template #action="{ row }">
<Space>
<ghost-button
v-access:code="['system:oss:download']"
@click="handleDownload(row)"
>
{{ $t('pages.common.download') }}
</ghost-button>
<Popconfirm
:get-popup-container="getVxePopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<ghost-button
danger
v-access:code="['system:oss:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</ghost-button>
</Popconfirm>
</Space>
</template>
</BasicTable>
<ImageUploadModal @reload="tableApi.query" />
<FileUploadModal @reload="tableApi.query" />
</Page>
</template>

View File

@@ -0,0 +1,131 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { DictEnum } from '@vben/constants';
import { getPopupContainer } from '@vben/utils';
import { getDictOptions } from '#/utils/dict';
import { renderDict } from '#/utils/render';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'postCode',
label: '岗位编码',
},
{
component: 'Input',
fieldName: 'postName',
label: '岗位名称',
},
{
component: 'Select',
componentProps: {
getPopupContainer,
options: [
{ label: '启用', value: true },
{ label: '禁用', value: false },
],
},
fieldName: 'state',
label: '状态',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '岗位编码',
field: 'postCode',
},
{
title: '岗位名称',
field: 'postName',
},
{
title: '排序',
field: 'orderNum',
},
{
title: '状态',
field: 'state',
slots: {
default: ({ row }) => {
return renderDict(String(row.state), DictEnum.SYS_NORMAL_DISABLE);
},
},
},
{
title: '创建时间',
field: 'creationTime',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];
export const drawerSchema: FormSchemaGetter = () => [
{
component: 'Input',
dependencies: {
show: () => false,
triggerFields: [''],
},
fieldName: 'id',
label: 'id',
},
{
component: 'TreeSelect',
componentProps: {
getPopupContainer,
},
fieldName: 'deptId',
label: '所属部门',
rules: 'selectRequired',
},
{
component: 'Input',
fieldName: 'postName',
label: '岗位名称',
rules: 'required',
},
{
component: 'Input',
fieldName: 'postCode',
label: '岗位编码',
rules: 'required',
},
{
component: 'InputNumber',
fieldName: 'orderNum',
label: '岗位排序',
rules: 'required',
defaultValue: 0,
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: '启用', value: true },
{ label: '禁用', value: false },
],
optionType: 'button',
},
defaultValue: true,
fieldName: 'state',
label: '岗位状态',
rules: 'required',
},
{
component: 'Textarea',
fieldName: 'remark',
formItemClass: 'items-start',
label: '备注',
},
];

View File

@@ -0,0 +1,185 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Post } from '#/api/system/post/model';
import { ref } from 'vue';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import { postExport, postList, postRemove } from '#/api/system/post';
import { commonDownloadExcel } from '#/utils/file/download';
import DeptTree from '#/views/system/user/dept-tree.vue';
import { columns, querySchema } from './data';
import postDrawer from './post-drawer.vue';
// 左边部门用
const selectDeptId = ref<string[]>([]);
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
handleReset: async () => {
selectDeptId.value = [];
// eslint-disable-next-line no-use-before-define
const { formApi, reload } = tableApi;
await formApi.resetForm();
const formValues = formApi.form.values;
formApi.setLatestSubmissionValues(formValues);
await reload(formValues);
},
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
trigger: 'cell',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
// 部门树选择处理
if (selectDeptId.value.length === 1) {
formValues.deptId = selectDeptId.value[0];
} else {
Reflect.deleteProperty(formValues, 'deptId');
}
return await postList({
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
},
id: 'system-post-index',
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [PostDrawer, drawerApi] = useVbenDrawer({
connectedComponent: postDrawer,
});
function handleAdd() {
drawerApi.setData({});
drawerApi.open();
}
async function handleEdit(record: Post) {
drawerApi.setData({ id: record.id });
drawerApi.open();
}
async function handleDelete(row: Post) {
await postRemove([row.id]);
await tableApi.query();
}
function handleMultiDelete() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: Post) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认删除选中的${ids.length}条记录吗?`,
onOk: async () => {
await postRemove(ids);
await tableApi.query();
},
});
}
function handleDownloadExcel() {
commonDownloadExcel(postExport, '岗位信息', tableApi.formApi.form.values);
}
</script>
<template>
<Page :auto-content-height="true" content-class="flex gap-[8px] w-full">
<DeptTree
v-model:select-dept-id="selectDeptId"
class="w-[260px]"
@reload="() => tableApi.reload()"
@select="() => tableApi.reload()"
/>
<BasicTable class="flex-1 overflow-hidden" table-title="岗位列表">
<template #toolbar-tools>
<Space>
<a-button
v-access:code="['system:post:export']"
@click="handleDownloadExcel"
>
{{ $t('pages.common.export') }}
</a-button>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:post:remove']"
@click="handleMultiDelete"
>
{{ $t('pages.common.delete') }}
</a-button>
<a-button
type="primary"
v-access:code="['system:post:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Space>
<GhostButton
v-access:code="['system:post:edit']"
@click="handleEdit(row)"
>
{{ $t('pages.common.edit') }}
</GhostButton>
<Popconfirm
:get-popup-container="getVxePopupContainer"
placement="left"
title="确认删除?"
@confirm="handleDelete(row)"
>
<GhostButton
danger
v-access:code="['system:post:remove']"
@click.stop=""
>
{{ $t('pages.common.delete') }}
</GhostButton>
</Popconfirm>
</Space>
</template>
</BasicTable>
<PostDrawer @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,113 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { addFullName, cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { postAdd, postInfo, postUpdate } from '#/api/system/post';
import { getDeptTree } from '#/api/system/user';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { drawerSchema } from './data';
const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);
const title = computed(() => {
return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
const [BasicForm, formApi] = useVbenForm({
commonConfig: {
formItemClass: 'col-span-2',
componentProps: {
class: 'w-full',
},
labelWidth: 80,
},
schema: drawerSchema(),
showDefaultActions: false,
wrapperClass: 'grid-cols-2',
});
async function setupDeptSelect() {
const deptTree = await getDeptTree();
// 选中后显示在输入框的值 即父节点 / 子节点
addFullName(deptTree, 'deptName', ' / ');
formApi.updateSchema([
{
componentProps: {
fieldNames: { label: 'deptName', value: 'id' },
treeData: deptTree,
treeDefaultExpandAll: true,
treeLine: { showLeafIcon: false },
// 选中后显示在输入框的值
treeNodeLabelProp: 'fullName',
},
fieldName: 'deptId',
},
]);
}
const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
{
initializedGetter: defaultFormValueGetter(formApi),
currentGetter: defaultFormValueGetter(formApi),
},
);
const [BasicDrawer, drawerApi] = useVbenDrawer({
onBeforeClose,
onClosed: handleClosed,
onConfirm: handleConfirm,
async onOpenChange(isOpen) {
if (!isOpen) {
return null;
}
drawerApi.drawerLoading(true);
const { id } = drawerApi.getData() as { id?: string };
isUpdate.value = !!id;
// 初始化
await setupDeptSelect();
// 更新 && 赋值
if (isUpdate.value && id) {
const record = await postInfo(id);
await formApi.setValues(record);
}
await markInitialized();
drawerApi.drawerLoading(false);
},
});
async function handleConfirm() {
try {
drawerApi.lock(true);
const { valid } = await formApi.validate();
if (!valid) {
return;
}
const data = cloneDeep(await formApi.getValues());
await (isUpdate.value ? postUpdate(data) : postAdd(data));
resetInitialized();
emit('reload');
drawerApi.close();
} catch (error) {
console.error(error);
} finally {
drawerApi.lock(false);
}
}
async function handleClosed() {
await formApi.resetForm();
resetInitialized();
}
</script>
<template>
<BasicDrawer :title="title" class="w-[600px]">
<BasicForm />
</BasicDrawer>
</template>

View File

@@ -0,0 +1,43 @@
import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
export const querySchema: FormSchemaGetter = () => [
{
component: 'Input',
fieldName: 'userName',
label: '用户账号',
},
{
component: 'Input',
fieldName: 'phonenumber',
label: '手机号码',
},
];
export const columns: VxeGridProps['columns'] = [
{ type: 'checkbox', width: 60 },
{
title: '用户账号',
field: 'userName',
},
{
title: '用户昵称',
field: 'nickName',
},
{
title: '邮箱',
field: 'email',
},
{
title: '手机号',
field: 'phonenumber',
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: '操作',
resizable: false,
width: 'auto',
},
];

View File

@@ -0,0 +1,161 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { User } from '#/api/system/user/model';
import { useRoute, useRouter } from 'vue-router';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { message, Modal, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
roleAllocatedList,
roleAuthCancelAll,
} from '#/api/system/role';
import { columns, querySchema } from './data';
import roleAssignDrawer from './role-assign-drawer.vue';
const route = useRoute();
const router = useRouter();
const roleId = route.params.roleId as string;
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
componentProps: {
allowClear: true,
},
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
// trigger: 'row',
},
columns,
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
// 校验roleId是否为空
if (!roleId || roleId === ':roleId') {
message.error('角色信息丢失,请重新点击分配');
// 重定向回角色列表
router.push('/system/role');
return {
items: [],
total: 0,
};
}
return await roleAllocatedList(roleId, {
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
},
id: 'system-role-assign-index',
};
// @ts-expect-error TS2589: User 与 proxyConfig 组合导致类型实例化层级过深;运行时泛型已被擦除,可控,先压制报错。
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
const [RoleAssignDrawer, drawerApi] = useVbenDrawer({
connectedComponent: roleAssignDrawer,
});
function handleAdd() {
drawerApi.setData({});
drawerApi.open();
}
/**
* 取消授权 一条记录
*/
async function handleAuthCancel(record: User) {
await roleAuthCancelAll(roleId, [record.id]);
await tableApi.query();
}
/**
* 批量取消授权
*/
function handleMultipleAuthCancel() {
const rows = tableApi.grid.getCheckboxRecords();
const ids = rows.map((row: User) => row.id);
Modal.confirm({
title: '提示',
okType: 'danger',
content: `确认取消选中的${ids.length}条授权记录吗?`,
onOk: async () => {
await roleAuthCancelAll(roleId, ids);
await tableApi.query();
tableApi.grid.clearCheckboxRow();
},
});
}
</script>
<template>
<Page :auto-content-height="true">
<BasicTable table-title="已分配的用户列表">
<template #toolbar-tools>
<Space>
<a-button
:disabled="!vxeCheckboxChecked(tableApi)"
danger
type="primary"
v-access:code="['system:role:remove']"
@click="handleMultipleAuthCancel"
>
取消授权
</a-button>
<a-button
type="primary"
v-access:code="['system:role:add']"
@click="handleAdd"
>
{{ $t('pages.common.add') }}
</a-button>
</Space>
</template>
<template #action="{ row }">
<Popconfirm
:get-popup-container="getVxePopupContainer"
:title="`是否取消授权用户[${row.userName} - ${row.nick}]?`"
placement="left"
@confirm="handleAuthCancel(row)"
>
<ghost-button
danger
v-access:code="['system:role:remove']"
@click.stop=""
>
取消授权
</ghost-button>
</Popconfirm>
</template>
</BasicTable>
<RoleAssignDrawer @reload="tableApi.query()" />
</Page>
</template>

View File

@@ -0,0 +1,87 @@
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useRoute } from 'vue-router';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { roleSelectAll, roleUnallocatedList } from '#/api/system/role';
import { columns, querySchema } from './data';
const emit = defineEmits<{ reload: [] }>();
const [BasicDrawer, drawerApi] = useVbenDrawer({
onConfirm: handleSubmit,
onCancel: handleReset,
destroyOnClose: true,
});
const route = useRoute();
const roleId = route.params.roleId as string;
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
},
schema: querySchema(),
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
};
const gridOptions: VxeGridProps = {
checkboxConfig: {
// 高亮
highlight: true,
// 翻页时保留选中状态
reserve: true,
// 点击行选中
trigger: 'row',
},
columns: columns?.filter((item) => item.field !== 'action'),
height: 'auto',
keepSource: true,
pagerConfig: {},
proxyConfig: {
ajax: {
query: async ({ page }, formValues = {}) => {
return await roleUnallocatedList(roleId, {
SkipCount: page.currentPage,
MaxResultCount: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
},
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
});
async function handleSubmit() {
const records = tableApi.grid.getCheckboxRecords();
const userIds = records.map((item) => item.id);
if (userIds.length > 0) {
await roleSelectAll(roleId, userIds);
}
handleReset();
emit('reload');
}
function handleReset() {
drawerApi.close();
}
</script>
<template>
<BasicDrawer class="w-[800px]" title="选择用户">
<BasicTable />
</BasicDrawer>
</template>

Some files were not shown because too many files have changed in this diff Show More