Initial commit: OneOS frontend based on yudao-ui-admin-vben
Some checks failed
CI / Test (ubuntu-latest) (push) Has been cancelled
CI / Test (windows-latest) (push) Has been cancelled
CI / Lint (ubuntu-latest) (push) Has been cancelled
CI / Lint (windows-latest) (push) Has been cancelled
CI / Check (ubuntu-latest) (push) Has been cancelled
CI / Check (windows-latest) (push) Has been cancelled
CI / CI OK (push) Has been cancelled
CodeQL / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Website on push / Deploy Push Playground Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Docs Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Antd Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Element Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Naive Ftp (push) Has been cancelled
Deploy Website on push / Rerun on failure (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled

This commit is contained in:
k kfluous
2026-03-11 22:18:23 +08:00
commit 2650d1cdf0
5166 changed files with 641242 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,173 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';
import type { AuthApi } from '#/api';
import { computed, onMounted, ref } from 'vue';
import { AuthenticationCodeLogin, z } from '@vben/common-ui';
import { isTenantEnable } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
import { ElMessage } from 'element-plus';
import { sendSmsCode } from '#/api';
import { getTenantByWebsite, getTenantSimpleList } from '#/api/core/auth';
import { useAuthStore } from '#/store';
defineOptions({ name: 'CodeLogin' });
const authStore = useAuthStore();
const accessStore = useAccessStore();
const tenantEnable = isTenantEnable();
const loading = ref(false);
const CODE_LENGTH = 4;
const loginRef = ref();
/** 获取租户列表,并默认选中 */
const tenantList = ref<AuthApi.TenantResult[]>([]); // 租户列表
async function fetchTenantList() {
if (!tenantEnable) {
return;
}
try {
// 获取租户列表、域名对应租户
const websiteTenantPromise = getTenantByWebsite(window.location.hostname);
tenantList.value = await getTenantSimpleList();
// 选中租户:域名 > store 中的租户 > 首个租户
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
}
// 如果没有从域名获取到租户,尝试从 store 中获取
if (!tenantId && accessStore.tenantId) {
tenantId = accessStore.tenantId;
}
// 如果还是没有租户,使用列表中的第一个
if (!tenantId && tenantList.value?.[0]?.id) {
tenantId = tenantList.value[0].id;
}
// 设置选中的租户编号
accessStore.setTenantId(tenantId);
loginRef.value.getFormApi().setFieldValue('tenantId', tenantId?.toString());
} catch (error) {
console.error('获取租户列表失败:', error);
}
}
/** 组件挂载时获取租户信息 */
onMounted(() => {
fetchTenantList();
});
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenSelect',
componentProps: {
options: tenantList.value.map((item) => ({
label: item.name,
value: item.id.toString(),
})),
placeholder: $t('authentication.tenantTip'),
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z.string().min(1, { message: $t('authentication.tenantTip') }),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,
trigger(values) {
if (values.tenantId) {
accessStore.setTenantId(Number(values.tenantId));
}
},
},
},
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.mobile'),
},
fieldName: 'mobile',
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: {
codeLength: CODE_LENGTH,
createText: (countdown: number) => {
const text =
countdown > 0
? $t('authentication.sendText', [countdown])
: $t('authentication.sendCode');
return text;
},
placeholder: $t('authentication.code'),
handleSendCode: async () => {
loading.value = true;
try {
const formApi = loginRef.value?.getFormApi();
if (!formApi) {
throw new Error('表单未准备好');
}
// 验证手机号
await formApi.validateField('mobile');
const isMobileValid = await formApi.isFieldValid('mobile');
if (!isMobileValid) {
throw new Error('请输入有效的手机号码');
}
// 发送验证码
const { mobile } = await formApi.getValues();
const scene = 21; // 场景:短信验证码登录
await sendSmsCode({ mobile, scene });
ElMessage.success('验证码发送成功');
} finally {
loading.value = false;
}
},
},
fieldName: 'code',
label: $t('authentication.code'),
rules: z.string().length(CODE_LENGTH, {
message: $t('authentication.codeTip', [CODE_LENGTH]),
}),
},
];
});
/**
* 异步处理登录操作
* Asynchronously handle the login process
* @param values 登录表单数据
*/
async function handleLogin(values: Recordable<any>) {
try {
await authStore.authLogin('mobile', values);
} catch (error) {
console.error('Error in handleLogin:', error);
}
}
</script>
<template>
<AuthenticationCodeLogin
ref="loginRef"
:form-schema="formSchema"
:loading="loading"
@submit="handleLogin"
/>
</template>

View File

@@ -0,0 +1,216 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';
import type { AuthApi } from '#/api';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { AuthenticationForgetPassword, z } from '@vben/common-ui';
import { isTenantEnable } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
import { ElMessage } from 'element-plus';
import { sendSmsCode, smsResetPassword } from '#/api';
import { getTenantByWebsite, getTenantSimpleList } from '#/api/core/auth';
defineOptions({ name: 'ForgetPassword' });
const accessStore = useAccessStore();
const router = useRouter();
const tenantEnable = isTenantEnable();
const loading = ref(false);
const CODE_LENGTH = 4;
const forgetPasswordRef = ref();
/** 获取租户列表,并默认选中 */
const tenantList = ref<AuthApi.TenantResult[]>([]); // 租户列表
async function fetchTenantList() {
if (!tenantEnable) {
return;
}
try {
// 获取租户列表、域名对应租户
const websiteTenantPromise = getTenantByWebsite(window.location.hostname);
tenantList.value = await getTenantSimpleList();
// 选中租户:域名 > store 中的租户 > 首个租户
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
}
// 如果没有从域名获取到租户,尝试从 store 中获取
if (!tenantId && accessStore.tenantId) {
tenantId = accessStore.tenantId;
}
// 如果还是没有租户,使用列表中的第一个
if (!tenantId && tenantList.value?.[0]?.id) {
tenantId = tenantList.value[0].id;
}
// 设置选中的租户编号
accessStore.setTenantId(tenantId);
forgetPasswordRef.value
.getFormApi()
.setFieldValue('tenantId', tenantId?.toString());
} catch (error) {
console.error('获取租户列表失败:', error);
}
}
/** 组件挂载时获取租户信息 */
onMounted(() => {
fetchTenantList();
});
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenSelect',
componentProps: {
options: tenantList.value.map((item) => ({
label: item.name,
value: item.id.toString(),
})),
placeholder: $t('authentication.tenantTip'),
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z.string().min(1, { message: $t('authentication.tenantTip') }),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,
trigger(values) {
if (values.tenantId) {
accessStore.setTenantId(Number(values.tenantId));
}
},
},
},
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.mobile'),
},
fieldName: 'mobile',
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: {
codeLength: CODE_LENGTH,
createText: (countdown: number) => {
const text =
countdown > 0
? $t('authentication.sendText', [countdown])
: $t('authentication.sendCode');
return text;
},
placeholder: $t('authentication.code'),
handleSendCode: async () => {
loading.value = true;
try {
const formApi = forgetPasswordRef.value?.getFormApi();
if (!formApi) {
throw new Error('表单未准备好');
}
// 验证手机号
await formApi.validateField('mobile');
const isMobileValid = await formApi.isFieldValid('mobile');
if (!isMobileValid) {
throw new Error('请输入有效的手机号码');
}
// 发送验证码
const { mobile } = await formApi.getValues();
const scene = 23; // 场景:重置密码
await sendSmsCode({ mobile, scene });
ElMessage.success('验证码发送成功');
} finally {
loading.value = false;
}
},
},
fieldName: 'code',
label: $t('authentication.code'),
rules: z.string().length(CODE_LENGTH, {
message: $t('authentication.codeTip', [CODE_LENGTH]),
}),
},
{
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'),
},
];
});
/**
* 处理重置密码操作
* @param values 表单数据
*/
async function handleSubmit(values: Recordable<any>) {
loading.value = true;
try {
const { mobile, code, password } = values;
await smsResetPassword({ mobile, code, password });
ElMessage.success($t('authentication.resetPasswordSuccess'));
// 重置成功后跳转到首页
await router.push('/');
} catch (error) {
console.error('重置密码失败:', error);
} finally {
loading.value = false;
}
}
</script>
<template>
<AuthenticationForgetPassword
ref="forgetPasswordRef"
:form-schema="formSchema"
:loading="loading"
@submit="handleSubmit"
/>
</template>

View File

@@ -0,0 +1,192 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { AuthApi } from '#/api/core/auth';
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { AuthenticationLogin, Verification, z } from '@vben/common-ui';
import { isCaptchaEnable, isTenantEnable } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
import {
checkCaptcha,
getCaptcha,
getTenantByWebsite,
getTenantSimpleList,
socialAuthRedirect,
} from '#/api/core/auth';
import { useAuthStore } from '#/store';
defineOptions({ name: 'Login' });
const { query } = useRoute();
const authStore = useAuthStore();
const accessStore = useAccessStore();
const tenantEnable = isTenantEnable();
const captchaEnable = isCaptchaEnable();
const loginRef = ref();
const verifyRef = ref();
const captchaType = 'blockPuzzle'; // 验证码类型:'blockPuzzle' | 'clickWord'
/** 获取租户列表,并默认选中 */
const tenantList = ref<AuthApi.TenantResult[]>([]); // 租户列表
async function fetchTenantList() {
if (!tenantEnable) {
return;
}
try {
// 获取租户列表、域名对应租户
const websiteTenantPromise = getTenantByWebsite(window.location.hostname);
tenantList.value = await getTenantSimpleList();
// 选中租户:域名 > store 中的租户 > 首个租户
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
}
// 如果没有从域名获取到租户,尝试从 store 中获取
if (!tenantId && accessStore.tenantId) {
tenantId = accessStore.tenantId;
}
// 如果还是没有租户,使用列表中的第一个
if (!tenantId && tenantList.value?.[0]?.id) {
tenantId = tenantList.value[0].id;
}
// 设置选中的租户编号
accessStore.setTenantId(tenantId);
loginRef.value.getFormApi().setFieldValue('tenantId', tenantId?.toString());
} catch (error) {
console.error('获取租户列表失败:', error);
}
}
/** 处理登录 */
async function handleLogin(values: any) {
// 如果开启验证码,则先验证验证码
if (captchaEnable) {
verifyRef.value.show();
return;
}
// 无验证码,直接登录
await authStore.authLogin('username', values);
}
/** 验证码通过,执行登录 */
async function handleVerifySuccess({ captchaVerification }: any) {
try {
await authStore.authLogin('username', {
...(await loginRef.value.getFormApi().getValues()),
captchaVerification,
});
} catch (error) {
console.error('Error in handleLogin:', error);
}
}
/** 处理第三方登录 */
const redirect = query?.redirect;
async function handleThirdLogin(type: number) {
if (type <= 0) {
return;
}
try {
// 计算 redirectUri
// tricky: type、redirect 需要先 encode 一次,否则钉钉回调会丢失。配合 social-login.vue#getUrlValue() 使用
const redirectUri = `${
location.origin
}/auth/social-login?${encodeURIComponent(
`type=${type}&redirect=${redirect || '/'}`,
)}`;
// 进行跳转
window.location.href = await socialAuthRedirect(type, redirectUri);
} catch (error) {
console.error('第三方登录处理失败:', error);
}
}
/** 组件挂载时获取租户信息 */
onMounted(() => {
fetchTenantList();
});
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenSelect',
componentProps: {
options: tenantList.value.map((item) => ({
label: item.name,
value: item.id.toString(),
})),
placeholder: $t('authentication.tenantTip'),
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z.string().min(1, { message: $t('authentication.tenantTip') }),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,
trigger(values) {
if (values.tenantId) {
accessStore.setTenantId(Number(values.tenantId));
}
},
},
},
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.usernameTip'),
},
fieldName: 'username',
label: $t('authentication.username'),
rules: z
.string()
.min(1, { message: $t('authentication.usernameTip') })
.default(import.meta.env.VITE_APP_DEFAULT_USERNAME),
},
{
component: 'VbenInputPassword',
componentProps: {
placeholder: $t('authentication.passwordTip'),
},
fieldName: 'password',
label: $t('authentication.password'),
rules: z
.string()
.min(1, { message: $t('authentication.passwordTip') })
.default(import.meta.env.VITE_APP_DEFAULT_PASSWORD),
},
];
});
</script>
<template>
<div>
<AuthenticationLogin
ref="loginRef"
:form-schema="formSchema"
:loading="authStore.loginLoading"
@submit="handleLogin"
@third-login="handleThirdLogin"
/>
<Verification
ref="verifyRef"
v-if="captchaEnable"
:captcha-type="captchaType"
:check-captcha-api="checkCaptcha"
:get-captcha-api="getCaptcha"
:img-size="{ width: '400px', height: '200px' }"
mode="pop"
@on-success="handleVerifySuccess"
/>
</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,221 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { AuthApi } from '#/api/core/auth';
import { computed, h, onMounted, ref } from 'vue';
import { AuthenticationRegister, Verification, z } from '@vben/common-ui';
import { isCaptchaEnable, isTenantEnable } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
import {
checkCaptcha,
getCaptcha,
getTenantByWebsite,
getTenantSimpleList,
} from '#/api/core/auth';
import { useAuthStore } from '#/store';
defineOptions({ name: 'Register' });
const loading = ref(false);
const accessStore = useAccessStore();
const authStore = useAuthStore();
const tenantEnable = isTenantEnable();
const captchaEnable = isCaptchaEnable();
const registerRef = ref();
const verifyRef = ref();
const captchaType = 'blockPuzzle'; // 验证码类型:'blockPuzzle' | 'clickWord'
/** 获取租户列表,并默认选中 */
const tenantList = ref<AuthApi.TenantResult[]>([]); // 租户列表
async function fetchTenantList() {
if (!tenantEnable) {
return;
}
try {
// 获取租户列表、域名对应租户
const websiteTenantPromise = getTenantByWebsite(window.location.hostname);
tenantList.value = await getTenantSimpleList();
// 选中租户:域名 > store 中的租户 > 首个租户
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
}
// 如果没有从域名获取到租户,尝试从 store 中获取
if (!tenantId && accessStore.tenantId) {
tenantId = accessStore.tenantId;
}
// 如果还是没有租户,使用列表中的第一个
if (!tenantId && tenantList.value?.[0]?.id) {
tenantId = tenantList.value[0].id;
}
// 设置选中的租户编号
accessStore.setTenantId(tenantId);
registerRef.value
.getFormApi()
.setFieldValue('tenantId', tenantId?.toString());
} catch (error) {
console.error('获取租户列表失败:', error);
}
}
/** 执行注册 */
async function handleRegister(values: any) {
// 如果开启验证码,则先验证验证码
if (captchaEnable) {
verifyRef.value.show();
return;
}
// 无验证码,直接登录
await authStore.authLogin('register', values);
}
/** 验证码通过,执行注册 */
const handleVerifySuccess = async ({ captchaVerification }: any) => {
try {
await authStore.authLogin('register', {
...(await registerRef.value.getFormApi().getValues()),
captchaVerification,
});
} catch (error) {
console.error('Error in handleRegister:', error);
}
};
/** 组件挂载时获取租户信息 */
onMounted(() => {
fetchTenantList();
});
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenSelect',
componentProps: {
options: tenantList.value.map((item) => ({
label: item.name,
value: item.id.toString(),
})),
placeholder: $t('authentication.tenantTip'),
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z.string().min(1, { message: $t('authentication.tenantTip') }),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,
trigger(values) {
if (values.tenantId) {
accessStore.setTenantId(Number(values.tenantId));
}
},
},
},
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.usernameTip'),
},
fieldName: 'username',
label: $t('authentication.username'),
rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
},
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.nicknameTip'),
},
fieldName: 'nickname',
label: $t('authentication.nickname'),
rules: z.string().min(1, { message: $t('authentication.nicknameTip') }),
},
{
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'),
}),
},
];
});
</script>
<template>
<div>
<AuthenticationRegister
ref="registerRef"
:form-schema="formSchema"
:loading="loading"
@submit="handleRegister"
/>
<Verification
ref="verifyRef"
v-if="captchaEnable"
:captcha-type="captchaType"
:check-captcha-api="checkCaptcha"
:get-captcha-api="getCaptcha"
:img-size="{ width: '400px', height: '200px' }"
mode="pop"
@on-success="handleVerifySuccess"
/>
</div>
</template>

View File

@@ -0,0 +1,210 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { AuthApi } from '#/api/core/auth';
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { AuthenticationLogin, Verification, z } from '@vben/common-ui';
import { isCaptchaEnable, isTenantEnable } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';
import { getUrlValue } from '@vben/utils';
import {
checkCaptcha,
getCaptcha,
getTenantByWebsite,
getTenantSimpleList,
} from '#/api/core/auth';
import { useAuthStore } from '#/store';
defineOptions({ name: 'SocialLogin' });
const authStore = useAuthStore();
const accessStore = useAccessStore();
const { query } = useRoute();
const router = useRouter();
const tenantEnable = isTenantEnable();
const captchaEnable = isCaptchaEnable();
const loginRef = ref();
const verifyRef = ref();
const captchaType = 'blockPuzzle'; // 验证码类型:'blockPuzzle' | 'clickWord'
/** 获取租户列表,并默认选中 */
const tenantList = ref<AuthApi.TenantResult[]>([]); // 租户列表
async function fetchTenantList() {
if (!tenantEnable) {
return;
}
try {
// 获取租户列表、域名对应租户
const websiteTenantPromise = getTenantByWebsite(window.location.hostname);
tenantList.value = await getTenantSimpleList();
// 选中租户:域名 > store 中的租户 > 首个租户
let tenantId: null | number = null;
const websiteTenant = await websiteTenantPromise;
if (websiteTenant?.id) {
tenantId = websiteTenant.id;
}
// 如果没有从域名获取到租户,尝试从 store 中获取
if (!tenantId && accessStore.tenantId) {
tenantId = accessStore.tenantId;
}
// 如果还是没有租户,使用列表中的第一个
if (!tenantId && tenantList.value?.[0]?.id) {
tenantId = tenantList.value[0].id;
}
// 设置选中的租户编号
accessStore.setTenantId(tenantId);
loginRef.value.getFormApi().setFieldValue('tenantId', tenantId);
} catch (error) {
console.error('获取租户列表失败:', error);
}
}
/** 尝试登录当账号已经绑定socialLogin 会直接获得 token */
const socialType = Number(getUrlValue('type'));
const redirect = getUrlValue('redirect');
const socialCode = query?.code as string;
const socialState = query?.state as string;
async function tryLogin() {
// 用于登录后,基于 redirect 的重定向
if (redirect) {
await router.replace({
query: {
...query,
redirect: encodeURIComponent(redirect),
},
});
}
// 尝试登录
await authStore.authLogin('social', {
type: socialType,
code: socialCode,
state: socialState,
});
}
/** 处理登录 */
async function handleLogin(values: any) {
// 如果开启验证码,则先验证验证码
if (captchaEnable) {
verifyRef.value.show();
return;
}
// 无验证码,直接登录
await authStore.authLogin('username', {
...values,
socialType,
socialCode,
socialState,
});
}
/** 验证码通过,执行登录 */
async function handleVerifySuccess({ captchaVerification }: any) {
try {
await authStore.authLogin('username', {
...(await loginRef.value.getFormApi().getValues()),
captchaVerification,
socialType,
socialCode,
socialState,
});
} catch (error) {
console.error('Error in handleLogin:', error);
}
}
/** 组件挂载时获取租户信息 */
onMounted(async () => {
await fetchTenantList();
await tryLogin();
});
const formSchema = computed((): VbenFormSchema[] => {
return [
{
component: 'VbenSelect',
componentProps: {
options: tenantList.value.map((item) => ({
label: item.name,
value: item.id.toString(),
})),
placeholder: $t('authentication.tenantTip'),
},
fieldName: 'tenantId',
label: $t('authentication.tenant'),
rules: z.string().min(1, { message: $t('authentication.tenantTip') }),
dependencies: {
triggerFields: ['tenantId'],
if: tenantEnable,
trigger(values) {
if (values.tenantId) {
accessStore.setTenantId(Number(values.tenantId));
}
},
},
},
{
component: 'VbenInput',
componentProps: {
placeholder: $t('authentication.usernameTip'),
},
fieldName: 'username',
label: $t('authentication.username'),
rules: z
.string()
.min(1, { message: $t('authentication.usernameTip') })
.default(import.meta.env.VITE_APP_DEFAULT_USERNAME),
},
{
component: 'VbenInputPassword',
componentProps: {
placeholder: $t('authentication.passwordTip'),
},
fieldName: 'password',
label: $t('authentication.password'),
rules: z
.string()
.min(1, { message: $t('authentication.passwordTip') })
.default(import.meta.env.VITE_APP_DEFAULT_PASSWORD),
},
];
});
</script>
<template>
<div>
<AuthenticationLogin
ref="loginRef"
:form-schema="formSchema"
:loading="authStore.loginLoading"
:show-code-login="false"
:show-qrcode-login="false"
:show-third-party-login="false"
:show-register="false"
@submit="handleLogin"
/>
<Verification
ref="verifyRef"
v-if="captchaEnable"
:captcha-type="captchaType"
:check-captcha-api="checkCaptcha"
:get-captcha-api="getCaptcha"
:img-size="{ width: '400px', height: '200px' }"
mode="pop"
@on-success="handleVerifySuccess"
/>
</div>
</template>

View File

@@ -0,0 +1,221 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import { computed, onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { AuthenticationAuthTitle, VbenButton } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { authorize, getAuthorize } from '#/api/system/oauth2/open';
defineOptions({ name: 'SSOLogin' });
const { query } = useRoute();
const client = ref({
name: '',
logo: '',
}); // 客户端信息
const queryParams = reactive({
responseType: '',
clientId: '',
redirectUri: '',
state: '',
scopes: [] as string[], // 优先从 query 参数获取;如果未传递,从后端获取
}); // URL 上的 client_id、scope 等参数
const loading = ref(false); // 表单是否提交中
/** 初始化授权信息 */
async function init() {
// 防止在没有登录的情况下循环弹窗
if (query.client_id === undefined) {
return;
}
// 解析参数
// 例如说【自动授权不通过】client_id=default&redirect_uri=https%3A%2F%2Fwww.iocoder.cn&response_type=code&scope=user.read%20user.write
// 例如说【自动授权通过】client_id=default&redirect_uri=https%3A%2F%2Fwww.iocoder.cn&response_type=code&scope=user.read
queryParams.responseType = query.response_type as string;
queryParams.clientId = query.client_id as string;
queryParams.redirectUri = query.redirect_uri as string;
queryParams.state = query.state as string;
if (query.scope) {
queryParams.scopes = (query.scope as string).split(' ');
}
// 如果有 scope 参数,先执行一次自动授权,看看是否之前都授权过了。
if (queryParams.scopes.length > 0) {
const data = await doAuthorize(true, queryParams.scopes, []);
if (data) {
location.href = data;
return;
}
}
// 1.1 获取授权页的基本信息
const data = await getAuthorize(queryParams.clientId);
client.value = data.client;
// 1.2 解析 scope
let scopes;
// 如果 params.scope 非空,则过滤下返回的 scopes
if (queryParams.scopes.length > 0) {
scopes = data.scopes.filter((scope) =>
queryParams.scopes.includes(scope.key),
);
// 如果 params.scope 为空,则使用返回的 scopes 设置它
} else {
scopes = data.scopes;
queryParams.scopes = scopes.map((scope) => scope.key);
}
// 2.设置表单的初始值
formApi.setFieldValue(
'scopes',
scopes.filter((scope) => scope.value).map((scope) => scope.key),
);
}
/** 处理授权的提交 */
async function handleSubmit(approved: boolean) {
// 计算 checkedScopes + uncheckedScopes
let checkedScopes: string[];
let uncheckedScopes: string[];
if (approved) {
// 同意授权,按照用户的选择
const res = await formApi.getValues();
checkedScopes = res.scopes;
uncheckedScopes = queryParams.scopes.filter(
(item) => !checkedScopes.includes(item),
);
} else {
// 拒绝,则都是取消
checkedScopes = [];
uncheckedScopes = queryParams.scopes;
}
// 提交授权的请求
loading.value = true;
try {
const data = await doAuthorize(false, checkedScopes, uncheckedScopes);
if (!data) {
return;
}
// 跳转授权成功后的回调地址
location.href = data;
} finally {
loading.value = false;
}
}
/** 调用授权 API 接口 */
const doAuthorize = (
autoApprove: boolean,
checkedScopes: string[],
uncheckedScopes: string[],
) => {
return authorize(
queryParams.responseType,
queryParams.clientId,
queryParams.redirectUri,
queryParams.state,
autoApprove,
checkedScopes,
uncheckedScopes,
);
};
/** 格式化 scope 文本 */
function formatScope(scope: string) {
// 格式化 scope 授权范围,方便用户理解。
// 这里仅仅是一个 demo可以考虑录入到字典数据中例如说字典类型 "system_oauth2_scope",它的每个 scope 都是一条字典数据。
switch (scope) {
case 'user.read': {
return '访问你的个人信息';
}
case 'user.write': {
return '修改你的个人信息';
}
default: {
return scope;
}
}
}
const formSchema = computed((): VbenFormSchema[] => {
return [
{
fieldName: 'scopes',
label: '授权范围',
component: 'CheckboxGroup',
componentProps: {
options: queryParams.scopes.map((scope) => ({
label: formatScope(scope),
value: scope,
})),
class: 'flex flex-col gap-2',
},
},
];
});
const [Form, formApi] = useVbenForm(
reactive({
commonConfig: {
hideLabel: true,
hideRequiredMark: true,
},
schema: formSchema,
showDefaultActions: false,
}),
);
/** 初始化 */
onMounted(() => {
init();
});
</script>
<template>
<div @keydown.enter.prevent="handleSubmit(true)">
<AuthenticationAuthTitle>
<slot name="title">
{{ `${client.name} 👋🏻` }}
</slot>
<template #desc>
<span class="text-muted-foreground">
此第三方应用请求获得以下权限
</span>
</template>
</AuthenticationAuthTitle>
<Form />
<div class="flex gap-2">
<VbenButton
:class="{
'cursor-wait': loading,
}"
:loading="loading"
aria-label="login"
class="w-2/3"
@click="handleSubmit(true)"
>
同意授权
</VbenButton>
<VbenButton
:class="{
'cursor-wait': loading,
}"
:loading="loading"
aria-label="login"
class="w-1/3"
variant="outline"
@click="handleSubmit(false)"
>
拒绝
</VbenButton>
</div>
</div>
</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 @@
<script setup lang="ts">
import type { Recordable } from '@vben/types';
import type { VbenFormSchema } from '#/adapter/form';
import type { SystemUserProfileApi } from '#/api/system/user/profile';
import { computed, ref, watch } from 'vue';
import { ProfileBaseSetting, z } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { ElMessage } from 'element-plus';
import { updateUserProfile } from '#/api/system/user/profile';
import { $t } from '#/locales';
const props = defineProps<{
profile?: SystemUserProfileApi.UserProfileRespVO;
}>();
const emit = defineEmits<{
(e: 'success'): void;
}>();
const profileBaseSettingRef = ref();
const formSchema = computed((): VbenFormSchema[] => {
return [
{
label: '用户昵称',
fieldName: 'nickname',
component: 'Input',
componentProps: {
placeholder: '请输入用户昵称',
},
rules: 'required',
},
{
label: '用户手机',
fieldName: 'mobile',
component: 'Input',
componentProps: {
placeholder: '请输入用户手机',
},
rules: z.string(),
},
{
label: '用户邮箱',
fieldName: 'email',
component: 'Input',
componentProps: {
placeholder: '请输入用户邮箱',
},
rules: z.string().email('请输入正确的邮箱'),
},
{
label: '用户性别',
fieldName: 'sex',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.SYSTEM_USER_SEX, 'number'),
buttonStyle: 'solid',
optionType: 'button',
},
rules: z.number(),
},
];
});
async function handleSubmit(values: Recordable<any>) {
try {
profileBaseSettingRef.value.getFormApi().setLoading(true);
// 提交表单
await updateUserProfile(values as SystemUserProfileApi.UpdateProfileReqVO);
// 关闭并提示
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} catch (error) {
console.error(error);
} finally {
profileBaseSettingRef.value.getFormApi().setLoading(false);
}
}
/** 监听 profile 变化 */
watch(
() => props.profile,
(newProfile) => {
if (newProfile) {
profileBaseSettingRef.value.getFormApi().setValues(newProfile);
}
},
{ immediate: true },
);
</script>
<template>
<ProfileBaseSetting
ref="profileBaseSettingRef"
:form-schema="formSchema"
@submit="handleSubmit"
/>
</template>

View File

@@ -0,0 +1,67 @@
<script setup lang="ts">
import type { SystemUserProfileApi } from '#/api/system/user/profile';
import { onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';
import { ElCard, ElTabPane, ElTabs } from 'element-plus';
import { getAuthPermissionInfoApi } from '#/api';
import { getUserProfile } from '#/api/system/user/profile';
import BaseInfo from './modules/base-info.vue';
import ProfileUser from './modules/profile-user.vue';
import ResetPwd from './modules/reset-pwd.vue';
import UserSocial from './modules/user-social.vue';
const userStore = useUserStore();
const activeName = ref('basicInfo');
/** 加载个人信息 */
const profile = ref<SystemUserProfileApi.UserProfileRespVO>();
async function loadProfile() {
profile.value = await getUserProfile();
}
/** 刷新个人信息 */
async function refreshProfile() {
// 加载个人信息
await loadProfile();
// 更新 store
const authPermissionInfo = await getAuthPermissionInfoApi();
userStore.setUserInfo(authPermissionInfo.user);
}
/** 初始化 */
onMounted(loadProfile);
</script>
<template>
<Page auto-content-height>
<div class="flex">
<!-- 左侧 个人信息 -->
<ElCard class="w-2/5" title="个人信息">
<ProfileUser :profile="profile" @success="refreshProfile" />
</ElCard>
<!-- 右侧 标签页 -->
<ElCard class="ml-3 w-3/5">
<ElTabs v-model="activeName" class="-mt-4">
<ElTabPane name="basicInfo" label="基本设置">
<BaseInfo :profile="profile" @success="refreshProfile" />
</ElTabPane>
<ElTabPane name="resetPwd" label="密码设置">
<ResetPwd />
</ElTabPane>
<ElTabPane name="userSocial" label="社交绑定" force-render>
<UserSocial @update:active-name="activeName = $event" />
</ElTabPane>
<!-- TODO @芋艿在线设备 -->
</ElTabs>
</ElCard>
</div>
</Page>
</template>

View File

@@ -0,0 +1,106 @@
<script setup lang="ts">
import type { Recordable } from '@vben/types';
import type { SystemUserProfileApi } from '#/api/system/user/profile';
import { watch } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { $t } from '@vben/locales';
import { ElMessage } from 'element-plus';
import { useVbenForm, z } from '#/adapter/form';
import { updateUserProfile } from '#/api/system/user/profile';
const props = defineProps<{
profile?: SystemUserProfileApi.UserProfileRespVO;
}>();
const emit = defineEmits<{
(e: 'success'): void;
}>();
const [Form, formApi] = useVbenForm({
commonConfig: {
labelWidth: 70,
},
schema: [
{
label: '用户昵称',
fieldName: 'nickname',
component: 'Input',
componentProps: {
placeholder: '请输入用户昵称',
},
rules: 'required',
},
{
label: '用户手机',
fieldName: 'mobile',
component: 'Input',
componentProps: {
placeholder: '请输入用户手机',
},
rules: z.string(),
},
{
label: '用户邮箱',
fieldName: 'email',
component: 'Input',
componentProps: {
placeholder: '请输入用户邮箱',
},
rules: z.string().email('请输入正确的邮箱'),
},
{
label: '用户性别',
fieldName: 'sex',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.SYSTEM_USER_SEX, 'number'),
},
rules: z.number(),
},
],
resetButtonOptions: {
show: false,
},
submitButtonOptions: {
content: '更新信息',
},
handleSubmit,
});
async function handleSubmit(values: Recordable<any>) {
try {
formApi.setLoading(true);
// 提交表单
await updateUserProfile(values as SystemUserProfileApi.UpdateProfileReqVO);
// 关闭并提示
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} catch (error) {
console.error(error);
} finally {
formApi.setLoading(false);
}
}
/** 监听 profile 变化 */
watch(
() => props.profile,
(newProfile) => {
if (newProfile) {
formApi.setValues(newProfile);
}
},
{ immediate: true },
);
</script>
<template>
<div class="mt-4 md:w-full lg:w-1/2 2xl:w-2/5">
<Form />
</div>
</template>

View File

@@ -0,0 +1,148 @@
<script setup lang="ts">
import type { SystemUserProfileApi } from '#/api/system/user/profile';
import { computed } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { preferences } from '@vben/preferences';
import { formatDateTime } from '@vben/utils';
import { ElDescriptions, ElDescriptionsItem, ElTooltip } from 'element-plus';
import { updateUserProfile } from '#/api/system/user/profile';
import { CropperAvatar } from '#/components/cropper';
import { useUpload } from '#/components/upload/use-upload';
const props = defineProps<{
profile?: SystemUserProfileApi.UserProfileRespVO;
}>();
const emit = defineEmits<{
(e: 'success'): void;
}>();
const avatar = computed(
() => props.profile?.avatar || preferences.app.defaultAvatar,
);
async function handelUpload({
file,
filename,
}: {
file: Blob;
filename: string;
}) {
// 1. 上传头像,获取 URL
const { httpRequest } = useUpload();
// 将 Blob 转换为 File
const fileObj = new File([file], filename, { type: file.type });
const avatar = await httpRequest(fileObj);
// 2. 更新用户头像
await updateUserProfile({ avatar });
}
</script>
<template>
<div v-if="profile">
<div class="flex flex-col items-center">
<ElTooltip content="点击上传头像">
<CropperAvatar
:show-btn="false"
:upload-api="handelUpload"
:value="avatar"
:width="120"
@change="emit('success')"
/>
</ElTooltip>
</div>
<div class="mt-8">
<ElDescriptions :column="2" border>
<ElDescriptionsItem label="用户账号">
<template #label>
<div class="flex items-center">
<IconifyIcon icon="ant-design:user-outlined" class="mr-1" />
用户账号
</div>
</template>
{{ profile.username }}
</ElDescriptionsItem>
<ElDescriptionsItem>
<template #label>
<div class="flex items-center">
<IconifyIcon
icon="ant-design:user-switch-outlined"
class="mr-1"
/>
所属角色
</div>
</template>
{{ profile.roles.map((role) => role.name).join(',') }}
</ElDescriptionsItem>
<ElDescriptionsItem>
<template #label>
<div class="flex items-center">
<IconifyIcon icon="ant-design:phone-outlined" class="mr-1" />
手机号码
</div>
</template>
{{ profile.mobile }}
</ElDescriptionsItem>
<ElDescriptionsItem>
<template #label>
<div class="flex items-center">
<IconifyIcon icon="ant-design:mail-outlined" class="mr-1" />
用户邮箱
</div>
</template>
{{ profile.email }}
</ElDescriptionsItem>
<ElDescriptionsItem>
<template #label>
<div class="flex items-center">
<IconifyIcon icon="ant-design:team-outlined" class="mr-1" />
所属部门
</div>
</template>
{{ profile.dept?.name }}
</ElDescriptionsItem>
<ElDescriptionsItem>
<template #label>
<div class="flex items-center">
<IconifyIcon
icon="ant-design:usergroup-add-outlined"
class="mr-1"
/>
所属岗位
</div>
</template>
{{
profile.posts && profile.posts.length > 0
? profile.posts.map((post) => post.name).join(',')
: '-'
}}
</ElDescriptionsItem>
<ElDescriptionsItem>
<template #label>
<div class="flex items-center">
<IconifyIcon
icon="ant-design:clock-circle-outlined"
class="mr-1"
/>
创建时间
</div>
</template>
{{ formatDateTime(profile.createTime) }}
</ElDescriptionsItem>
<ElDescriptionsItem>
<template #label>
<div class="flex items-center">
<IconifyIcon icon="ant-design:login-outlined" class="mr-1" />
登录时间
</div>
</template>
{{ formatDateTime(profile.loginDate) }}
</ElDescriptionsItem>
</ElDescriptions>
</div>
</div>
</template>

View File

@@ -0,0 +1,106 @@
<script setup lang="ts">
import type { Recordable } from '@vben/types';
import { $t } from '@vben/locales';
import { ElMessage } from 'element-plus';
import { useVbenForm, z } from '#/adapter/form';
import { updateUserPassword } from '#/api/system/user/profile';
const [Form, formApi] = useVbenForm({
commonConfig: {
labelWidth: 70,
},
schema: [
{
component: 'VbenInputPassword',
componentProps: {
passwordStrength: true,
placeholder: $t('authentication.password'),
},
fieldName: 'oldPassword',
label: '旧密码',
rules: z
.string({ message: '请输入密码' })
.min(5, '密码长度不能少于 5 个字符')
.max(20, '密码长度不能超过 20 个字符'),
},
{
component: 'VbenInputPassword',
componentProps: {
passwordStrength: true,
placeholder: '请输入新密码',
},
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: 'VbenInputPassword',
componentProps: {
passwordStrength: true,
placeholder: $t('authentication.confirmPassword'),
},
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',
},
],
resetButtonOptions: {
show: false,
},
submitButtonOptions: {
content: '修改密码',
},
handleSubmit,
});
async function handleSubmit(values: Recordable<any>) {
try {
formApi.setLoading(true);
// 提交表单
await updateUserPassword({
oldPassword: values.oldPassword,
newPassword: values.newPassword,
});
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} catch (error) {
console.error(error);
} finally {
formApi.setLoading(false);
}
}
</script>
<template>
<div class="mt-4 md:w-full lg:w-1/2 2xl:w-2/5">
<Form />
</div>
</template>

View File

@@ -0,0 +1,207 @@
<script setup lang="tsx">
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemSocialUserApi } from '#/api/system/social/user';
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { confirm } from '@vben/common-ui';
import { DICT_TYPE, SystemUserSocialTypeEnum } from '@vben/constants';
import { getDictLabel } from '@vben/hooks';
import { getUrlValue } from '@vben/utils';
import { ElButton, ElCard, ElImage, ElMessage } from 'element-plus';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { socialAuthRedirect } from '#/api/core/auth';
import {
getBindSocialUserList,
socialBind,
socialUnbind,
} from '#/api/system/social/user';
import { $t } from '#/locales';
const emit = defineEmits<{
(e: 'update:activeName', v: string): void;
}>();
const route = useRoute();
/** 已经绑定的平台 */
const bindList = ref<SystemSocialUserApi.SocialUser[]>([]);
const allBindList = computed<any[]>(() => {
return Object.values(SystemUserSocialTypeEnum).map((social) => {
const socialUser = bindList.value.find((item) => item.type === social.type);
return {
...social,
socialUser,
};
});
});
function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'type',
title: '绑定平台',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.SYSTEM_SOCIAL_TYPE },
},
},
{
field: 'openid',
title: '标识',
minWidth: 180,
},
{
field: 'nickname',
title: '昵称',
minWidth: 180,
},
{
field: 'operation',
title: '操作',
minWidth: 80,
align: 'center',
fixed: 'right',
slots: {
default: ({ row }: { row: SystemSocialUserApi.SocialUser }) => {
return (
<ElButton onClick={() => onUnbind(row)} type="text">
解绑
</ElButton>
);
},
},
},
];
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
columns: useGridColumns(),
minHeight: 0,
keepSource: true,
proxyConfig: {
ajax: {
query: async () => {
bindList.value = await getBindSocialUserList();
return bindList.value;
},
},
},
rowConfig: {
keyField: 'id',
},
pagerConfig: {
enabled: false,
},
toolbarConfig: {
enabled: false,
},
},
});
/** 解绑账号 */
function onUnbind(row: SystemSocialUserApi.SocialUser) {
confirm({
content: `确定解绑[${getDictLabel(DICT_TYPE.SYSTEM_SOCIAL_TYPE, row.type)}]平台的[${row.openid}]账号吗?`,
}).then(async () => {
await socialUnbind({ type: row.type, openid: row.openid });
// 提示成功
ElMessage.success($t('ui.actionMessage.operationSuccess'));
await gridApi.reload();
});
}
/** 绑定账号(跳转授权页面) */
async function onBind(bind: any) {
const type = bind.type;
if (type <= 0) {
return;
}
try {
// 计算 redirectUri
// tricky: type 需要先 encode 一次,否则钉钉回调会丢失。配合 getUrlValue() 使用
const redirectUri = `${location.origin}/profile?${encodeURIComponent(`type=${type}`)}`;
// 进行跳转
window.location.href = await socialAuthRedirect(type, redirectUri);
} catch (error) {
console.error('社交绑定处理失败:', error);
}
}
/** 监听路由变化,处理社交绑定回调 */
async function bindSocial() {
// 社交绑定
const type = Number(getUrlValue('type'));
const code = route.query.code as string;
const state = route.query.state as string;
if (!code) {
return;
}
await socialBind({ type, code, state });
// 提示成功
ElMessage.success('绑定成功');
emit('update:activeName', 'userSocial');
await gridApi.reload();
// 清理 URL 参数,避免刷新重复触发
window.history.replaceState({}, '', location.pathname);
}
/** 初始化 */
onMounted(() => {
bindSocial();
});
</script>
<template>
<div class="flex flex-col">
<Grid />
<div class="pb-3">
<div
class="grid grid-cols-1 gap-2 px-2 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3"
>
<ElCard v-for="item in allBindList" :key="item.type" class="!mb-2">
<div class="flex w-full items-center gap-4">
<ElImage
:src="item.img"
style="width: 40px; height: 40px"
:alt="item.title"
:preview-disabled="true"
fit="contain"
/>
<div class="flex flex-1 items-center justify-between">
<div class="flex flex-col">
<h4 class="mb-1 text-sm text-black/85 dark:text-white/85">
{{ getDictLabel(DICT_TYPE.SYSTEM_SOCIAL_TYPE, item.type) }}
</h4>
<span class="text-black/45 dark:text-white/45">
<template v-if="item.socialUser">
{{ item.socialUser?.nickname || item.socialUser?.openid }}
</template>
<template v-else>
绑定
{{ getDictLabel(DICT_TYPE.SYSTEM_SOCIAL_TYPE, item.type) }}
账号
</template>
</span>
</div>
<ElButton
:disabled="!!item.socialUser"
size="small"
type="text"
@click="onBind(item)"
>
{{ item.socialUser ? '已绑定' : '绑定' }}
</ElButton>
</div>
</div>
</ElCard>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,31 @@
<script setup lang="ts">
import { computed } from 'vue';
import { ProfileNotificationSetting } from '@vben/common-ui';
const formSchema = computed(() => {
return [
{
value: true,
fieldName: 'accountPassword',
label: '账户密码',
description: '其他用户的消息将以站内信的形式通知',
},
{
value: true,
fieldName: 'systemMessage',
label: '系统消息',
description: '系统消息将以站内信的形式通知',
},
{
value: true,
fieldName: 'todoTask',
label: '待办任务',
description: '待办任务将以站内信的形式通知',
},
];
});
</script>
<template>
<ProfileNotificationSetting :form-schema="formSchema" />
</template>

View File

@@ -0,0 +1,63 @@
<script setup lang="ts">
import type { VbenFormSchema } from '#/adapter/form';
import { computed } from 'vue';
import { ProfilePasswordSetting, z } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
const formSchema = computed((): VbenFormSchema[] => {
return [
{
fieldName: 'oldPassword',
label: '旧密码',
component: 'VbenInputPassword',
componentProps: {
placeholder: '请输入旧密码',
},
},
{
fieldName: 'newPassword',
label: '新密码',
component: 'VbenInputPassword',
componentProps: {
passwordStrength: true,
placeholder: '请输入新密码',
},
},
{
fieldName: 'confirmPassword',
label: '确认密码',
component: 'VbenInputPassword',
componentProps: {
passwordStrength: true,
placeholder: '请再次输入新密码',
},
dependencies: {
rules(values) {
const { newPassword } = values;
return z
.string({ required_error: '请再次输入新密码' })
.min(1, { message: '请再次输入新密码' })
.refine((value) => value === newPassword, {
message: '两次输入的密码不一致',
});
},
triggerFields: ['newPassword'],
},
},
];
});
function handleSubmit() {
ElMessage.success('密码修改成功');
}
</script>
<template>
<ProfilePasswordSetting
class="w-1/3"
:form-schema="formSchema"
@submit="handleSubmit"
/>
</template>

View File

@@ -0,0 +1,43 @@
<script setup lang="ts">
import { computed } from 'vue';
import { ProfileSecuritySetting } from '@vben/common-ui';
const formSchema = computed(() => {
return [
{
value: true,
fieldName: 'accountPassword',
label: '账户密码',
description: '当前密码强度:强',
},
{
value: true,
fieldName: 'securityPhone',
label: '密保手机',
description: '已绑定手机138****8293',
},
{
value: true,
fieldName: 'securityQuestion',
label: '密保问题',
description: '未设置密保问题,密保问题可有效保护账户安全',
},
{
value: true,
fieldName: 'securityEmail',
label: '备用邮箱',
description: '已绑定邮箱ant***sign.com',
},
{
value: false,
fieldName: 'securityMfa',
label: 'MFA 设备',
description: '未绑定 MFA 设备,绑定后,可以进行二次确认',
},
];
});
</script>
<template>
<ProfileSecuritySetting :form-schema="formSchema" />
</template>

View File

@@ -0,0 +1,80 @@
import type { VbenFormSchema } from '#/adapter/form';
import { AiModelTypeEnum } from '@vben/constants';
import { getModelSimpleList } from '#/api/ai/model/model';
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'systemMessage',
label: '角色设定',
component: 'Textarea',
componentProps: {
rows: 4,
placeholder: '请输入角色设定',
},
},
{
component: 'ApiSelect',
fieldName: 'modelId',
label: '模型',
componentProps: {
api: () => getModelSimpleList(AiModelTypeEnum.CHAT),
labelField: 'name',
valueField: 'id',
allowClear: true,
placeholder: '请选择模型',
},
rules: 'required',
},
{
fieldName: 'temperature',
label: '温度参数',
component: 'InputNumber',
componentProps: {
placeholder: '请输入温度参数',
precision: 2,
min: 0,
max: 2,
controlsPosition: 'right',
class: '!w-full',
},
rules: 'required',
},
{
fieldName: 'maxTokens',
label: '回复数 Token 数',
component: 'InputNumber',
componentProps: {
placeholder: '请输入回复数 Token 数',
min: 0,
max: 8192,
controlsPosition: 'right',
class: '!w-full',
},
rules: 'required',
},
{
fieldName: 'maxContexts',
label: '上下文数量',
component: 'InputNumber',
componentProps: {
placeholder: '请输入上下文数量',
min: 0,
max: 20,
controlsPosition: 'right',
class: '!w-full',
},
rules: 'required',
},
];
}

View File

@@ -0,0 +1,694 @@
<script lang="ts" setup>
import type { AiChatConversationApi } from '#/api/ai/chat/conversation';
import type { AiChatMessageApi } from '#/api/ai/chat/message';
import { computed, nextTick, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { alert, confirm, Page, useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import {
ElButton,
ElContainer,
ElFooter,
ElHeader,
ElMain,
ElMessage,
ElSwitch,
} from 'element-plus';
import { getChatConversationMy } from '#/api/ai/chat/conversation';
import {
deleteByConversationId,
getChatMessageListByConversationId,
sendChatMessageStream,
} from '#/api/ai/chat/message';
import ConversationList from './modules/conversation/list.vue';
import ConversationUpdateForm from './modules/conversation/update-form.vue';
import MessageFileUpload from './modules/message/file-upload.vue';
import MessageListEmpty from './modules/message/list-empty.vue';
import MessageList from './modules/message/list.vue';
import MessageLoading from './modules/message/loading.vue';
import MessageNewConversation from './modules/message/new-conversation.vue';
/** AI 聊天对话 列表 */
defineOptions({ name: 'AiChat' });
const route = useRoute();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: ConversationUpdateForm,
destroyOnClose: true,
});
// 聊天对话
const conversationListRef = ref();
const activeConversationId = ref<null | number>(null); // 选中的对话编号
const activeConversation = ref<AiChatConversationApi.ChatConversation | null>(
null,
); // 选中的 Conversation
const conversationInProgress = ref(false); // 对话是否正在进行中。目前只有【发送】消息时,会更新为 true避免切换对话、删除对话等操作
// 消息列表
const messageRef = ref();
const activeMessageList = ref<AiChatMessageApi.ChatMessage[]>([]); // 选中对话的消息列表
const activeMessageListLoading = ref<boolean>(false); // activeMessageList 是否正在加载中
const activeMessageListLoadingTimer = ref<any>(); // activeMessageListLoading Timer 定时器。如果加载速度很快,就不进入加载中
// 消息滚动
const textSpeed = ref<number>(50); // Typing speed in milliseconds
const textRoleRunning = ref<boolean>(false); // Typing speed in milliseconds
// 发送消息输入框
const isComposing = ref(false); // 判断用户是否在输入
const conversationInAbortController = ref<any>(); // 对话进行中 abort 控制器(控制 stream 对话)
const inputTimeout = ref<any>(); // 处理输入中回车的定时器
const prompt = ref<string>(); // prompt
const enableContext = ref<boolean>(true); // 是否开启上下文
const enableWebSearch = ref<boolean>(false); // 是否开启联网搜索
const uploadFiles = ref<string[]>([]); // 上传的文件 URL 列表
// 接收 Stream 消息
const receiveMessageFullText = ref('');
const receiveMessageDisplayedText = ref('');
// =========== 【聊天对话】相关 ===========
/** 获取对话信息 */
async function getConversation(id: null | number) {
if (!id) {
return;
}
const conversation: AiChatConversationApi.ChatConversation =
await getChatConversationMy(id);
if (!conversation) {
return;
}
activeConversation.value = conversation;
activeConversationId.value = conversation.id;
}
/**
* 点击某个对话
*
* @param conversation 选中的对话
* @return 是否切换成功
*/
async function handleConversationClick(
conversation: AiChatConversationApi.ChatConversation,
) {
// 对话进行中,不允许切换
if (conversationInProgress.value) {
await alert('对话中,不允许切换!');
return false;
}
// 更新选中的对话 id
activeConversationId.value = conversation.id;
activeConversation.value = conversation;
// 刷新 message 列表
await getMessageList();
// 滚动底部
await scrollToBottom(true);
prompt.value = '';
// 清空输入框
prompt.value = '';
// 清空文件列表
uploadFiles.value = [];
return true;
}
/** 删除某个对话*/
async function handlerConversationDelete(
delConversation: AiChatConversationApi.ChatConversation,
) {
// 删除的对话如果是当前选中的,那么就重置
if (activeConversationId.value === delConversation.id) {
await handleConversationClear();
}
}
/** 清空选中的对话 */
async function handleConversationClear() {
// 对话进行中,不允许切换
if (conversationInProgress.value) {
await alert('对话中,不允许切换!');
return false;
}
activeConversationId.value = null;
activeConversation.value = null;
activeMessageList.value = [];
// 清空输入框和文件列表
prompt.value = '';
uploadFiles.value = [];
}
async function openChatConversationUpdateForm() {
formModalApi.setData({ id: activeConversationId.value }).open();
}
/** 对话更新成功,刷新最新信息 */
async function handleConversationUpdateSuccess() {
await getConversation(activeConversationId.value);
}
/** 处理聊天对话的创建成功 */
async function handleConversationCreate() {
// 创建对话
await conversationListRef.value.createConversation();
}
/** 处理聊天对话的创建成功 */
async function handleConversationCreateSuccess() {
// 创建新的对话,清空输入框
prompt.value = '';
// 清空文件列表
uploadFiles.value = [];
}
// =========== 【消息列表】相关 ===========
/** 获取消息 message 列表 */
async function getMessageList() {
try {
if (activeConversationId.value === null) {
return;
}
// Timer 定时器,如果加载速度很快,就不进入加载中
activeMessageListLoadingTimer.value = setTimeout(() => {
activeMessageListLoading.value = true;
}, 60);
// 获取消息列表
activeMessageList.value = await getChatMessageListByConversationId(
activeConversationId.value,
);
// 滚动到最下面
await nextTick();
await scrollToBottom();
} finally {
// time 定时器,如果加载速度很快,就不进入加载中
if (activeMessageListLoadingTimer.value) {
clearTimeout(activeMessageListLoadingTimer.value);
}
// 加载结束
activeMessageListLoading.value = false;
}
}
/**
* 消息列表
*
* 和 {@link #getMessageList()} 的差异是,把 systemMessage 考虑进去
*/
const messageList = computed(() => {
if (activeMessageList.value.length > 0) {
return activeMessageList.value;
}
// 没有消息时,如果有 systemMessage 则展示它
if (activeConversation.value?.systemMessage) {
return [
{
id: 0,
type: 'system',
content: activeConversation.value.systemMessage,
},
];
}
return [];
});
/** 处理删除 message 消息 */
function handleMessageDelete() {
if (conversationInProgress.value) {
alert('回答中,不能删除!');
return;
}
// 刷新 message 列表
getMessageList();
}
/** 处理 message 清空 */
async function handlerMessageClear() {
if (!activeConversationId.value) {
return;
}
try {
// 确认提示
await confirm('确认清空对话消息?');
// 清空对话
await deleteByConversationId(activeConversationId.value);
// 刷新 message 列表
activeMessageList.value = [];
} catch {}
}
/** 回到 message 列表的顶部 */
function handleGoTopMessage() {
messageRef.value.handlerGoTop();
}
// =========== 【发送消息】相关 ===========
/** 处理来自 keydown 的发送消息 */
async function handleSendByKeydown(event: any) {
// 判断用户是否在输入
if (isComposing.value) {
return;
}
// 进行中不允许发送
if (conversationInProgress.value) {
return;
}
const content = prompt.value?.trim() as string;
if (event.key === 'Enter') {
if (event.shiftKey) {
// 插入换行
prompt.value += '\r\n';
event.preventDefault(); // 防止默认的换行行为
} else {
// 发送消息
await doSendMessage(content);
event.preventDefault(); // 防止默认的提交行为
}
}
}
/** 处理来自【发送】按钮的发送消息 */
function handleSendByButton() {
doSendMessage(prompt.value?.trim() as string);
}
/** 处理 prompt 输入变化 */
function handlePromptInput(event: any) {
// 非输入法 输入设置为 true
if (!isComposing.value) {
// 回车 event data 是 null
if (event.data === null || event.data === 'null') {
return;
}
isComposing.value = true;
}
// 清理定时器
if (inputTimeout.value) {
clearTimeout(inputTimeout.value);
}
// 重置定时器
inputTimeout.value = setTimeout(() => {
isComposing.value = false;
}, 400);
}
function onCompositionstart() {
isComposing.value = true;
}
function onCompositionend() {
setTimeout(() => {
isComposing.value = false;
}, 200);
}
/** 真正执行【发送】消息操作 */
async function doSendMessage(content: string) {
// 校验
if (content.length === 0) {
ElMessage.error('发送失败,原因:内容为空!');
return;
}
if (activeConversationId.value === null) {
ElMessage.error('还没创建对话,不能发送!');
return;
}
// 准备附件 URL 数组
const attachmentUrls = [...uploadFiles.value];
// 清空输入框和文件列表
prompt.value = '';
uploadFiles.value = [];
// 执行发送
await doSendMessageStream({
conversationId: activeConversationId.value,
content,
attachmentUrls,
} as AiChatMessageApi.ChatMessage);
}
/** 真正执行【发送】消息操作 */
async function doSendMessageStream(userMessage: AiChatMessageApi.ChatMessage) {
// 创建 AbortController 实例,以便中止请求
conversationInAbortController.value = new AbortController();
// 标记对话进行中
conversationInProgress.value = true;
// 设置为空
receiveMessageFullText.value = '';
try {
// 1.1 先添加两个假数据,等 stream 返回再替换
activeMessageList.value.push(
{
id: -1,
conversationId: activeConversationId.value,
type: 'user',
content: userMessage.content,
attachmentUrls: userMessage.attachmentUrls || [],
createTime: new Date(),
} as AiChatMessageApi.ChatMessage,
{
id: -2,
conversationId: activeConversationId.value,
type: 'assistant',
content: '思考中...',
reasoningContent: '',
createTime: new Date(),
} as AiChatMessageApi.ChatMessage,
);
// 1.2 滚动到最下面
await nextTick();
await scrollToBottom(); // 底部
// 1.3 开始滚动
textRoll().then();
// 2. 发送 event stream
let isFirstChunk = true; // 是否是第一个 chunk 消息段
await sendChatMessageStream(
userMessage.conversationId,
userMessage.content,
conversationInAbortController.value,
enableContext.value,
enableWebSearch.value,
async (res: any) => {
const { code, data, msg } = JSON.parse(res.data);
if (code !== 0) {
await alert(`对话异常! ${msg}`);
// 如果未接收到消息,则进行删除
if (receiveMessageFullText.value === '') {
activeMessageList.value.pop();
}
return;
}
// 如果内容和推理内容都为空,就不处理
if (data.receive.content === '' && !data.receive.reasoningContent) {
return;
}
// 首次返回需要添加一个 message 到页面,后面的都是更新
if (isFirstChunk) {
isFirstChunk = false;
// 弹出两个假数据
activeMessageList.value.pop();
activeMessageList.value.pop();
// 更新返回的数据
activeMessageList.value.push(data.send, data.receive);
data.send.attachmentUrls = userMessage.attachmentUrls;
}
// 处理 reasoningContent
if (data.receive.reasoningContent) {
const lastMessage =
activeMessageList.value[activeMessageList.value.length - 1];
// 累加推理内容
lastMessage!.reasoningContent =
(lastMessage!.reasoningContent || '') +
data.receive.reasoningContent;
}
// 处理正常内容
if (data.receive.content !== '') {
receiveMessageFullText.value =
receiveMessageFullText.value + data.receive.content;
}
// 滚动到最下面
await scrollToBottom();
},
(error: any) => {
// 异常提示,并停止流
alert(`对话异常!`);
stopStream();
// 需要抛出异常,禁止重试
throw error;
},
() => {
stopStream();
},
userMessage.attachmentUrls,
);
} catch {}
}
/** 停止 stream 流式调用 */
async function stopStream() {
// tip如果 stream 进行中的 message就需要调用 controller 结束
if (conversationInAbortController.value) {
conversationInAbortController.value.abort();
}
// 设置为 false
conversationInProgress.value = false;
}
/** 编辑 message设置为 prompt可以再次编辑 */
function handleMessageEdit(message: AiChatMessageApi.ChatMessage) {
prompt.value = message.content;
}
/** 刷新 message基于指定消息再次发起对话 */
function handleMessageRefresh(message: AiChatMessageApi.ChatMessage) {
doSendMessage(message.content);
}
// ============== 【消息滚动】相关 =============
/** 滚动到 message 底部 */
async function scrollToBottom(isIgnore?: boolean) {
await nextTick();
if (messageRef.value) {
messageRef.value.scrollToBottom(isIgnore);
}
}
/** 自提滚动效果 */
async function textRoll() {
let index = 0;
try {
// 只能执行一次
if (textRoleRunning.value) {
return;
}
// 设置状态
textRoleRunning.value = true;
receiveMessageDisplayedText.value = '';
async function task() {
// 调整速度
const diff =
(receiveMessageFullText.value.length -
receiveMessageDisplayedText.value.length) /
10;
if (diff > 5) {
textSpeed.value = 10;
} else if (diff > 2) {
textSpeed.value = 30;
} else if (diff > 1.5) {
textSpeed.value = 50;
} else {
textSpeed.value = 100;
}
// 对话结束,就按 30 的速度
if (!conversationInProgress.value) {
textSpeed.value = 10;
}
if (index < receiveMessageFullText.value.length) {
receiveMessageDisplayedText.value +=
receiveMessageFullText.value[index];
index++;
// 更新 message
const lastMessage =
activeMessageList.value[activeMessageList.value.length - 1];
if (lastMessage)
lastMessage.content = receiveMessageDisplayedText.value;
// 滚动到住下面
await scrollToBottom();
// 重新设置任务
timer = setTimeout(task, textSpeed.value);
} else {
// 不是对话中可以结束
if (conversationInProgress.value) {
// 重新设置任务
timer = setTimeout(task, textSpeed.value);
} else {
textRoleRunning.value = false;
clearTimeout(timer);
}
}
}
let timer = setTimeout(task, textSpeed.value);
} catch {}
}
/** 初始化 */
onMounted(async () => {
// 如果有 conversationId 参数,则默认选中
if (route.query.conversationId) {
const id = route.query.conversationId as unknown as number;
activeConversationId.value = id;
await getConversation(id);
}
// 获取列表数据
activeMessageListLoading.value = true;
await getMessageList();
});
</script>
<template>
<Page auto-content-height>
<ElContainer
direction="horizontal"
class="absolute left-0 top-0 m-4 h-full w-full flex-1"
>
<!-- 左侧对话列表 -->
<ConversationList
class="!bg-card"
:active-id="activeConversationId"
ref="conversationListRef"
@on-conversation-create="handleConversationCreateSuccess"
@on-conversation-click="handleConversationClick"
@on-conversation-clear="handleConversationClear"
@on-conversation-delete="handlerConversationDelete"
/>
<!-- 右侧详情部分 -->
<ElContainer direction="vertical" class="mx-4 flex-1 bg-card">
<ElHeader
class="flex !h-12 items-center justify-between border-b border-border !bg-card !px-4"
>
<div class="text-lg font-bold">
{{ activeConversation?.title ? activeConversation?.title : '对话' }}
<span v-if="activeMessageList.length > 0">
({{ activeMessageList.length }})
</span>
</div>
<div class="flex w-72 justify-end gap-2" v-if="activeConversation">
<ElButton
type="primary"
plain
class="!px-2"
size="small"
@click="openChatConversationUpdateForm"
>
<span v-html="activeConversation?.modelName"></span>
<IconifyIcon icon="lucide:settings" class="!ml-2 size-4" />
</ElButton>
<ElButton
size="small"
class="!ml-0 !px-2"
@click="handlerMessageClear"
>
<IconifyIcon icon="lucide:trash-2" color="#787878" />
</ElButton>
<ElButton size="small" class="!ml-0 !px-2">
<IconifyIcon icon="lucide:download" color="#787878" />
</ElButton>
<ElButton
size="small"
class="!ml-0 !px-2"
@click="handleGoTopMessage"
>
<IconifyIcon icon="lucide:arrow-up" color="#787878" />
</ElButton>
</div>
</ElHeader>
<ElMain class="relative m-0 h-full w-full p-0">
<div class="absolute inset-0 m-0 overflow-y-hidden p-0">
<MessageLoading v-if="activeMessageListLoading" />
<MessageNewConversation
v-if="!activeConversation"
@on-new-conversation="handleConversationCreate"
/>
<MessageListEmpty
v-if="
!activeMessageListLoading &&
messageList.length === 0 &&
activeConversation
"
@on-prompt="doSendMessage"
/>
<MessageList
v-if="!activeMessageListLoading && messageList.length > 0"
ref="messageRef"
:conversation="activeConversation as any"
:list="messageList as any"
@on-delete-success="handleMessageDelete"
@on-edit="handleMessageEdit"
@on-refresh="handleMessageRefresh"
/>
</div>
</ElMain>
<ElFooter height="auto" class="flex flex-col !bg-card !p-0">
<form
class="mx-4 mb-8 mt-2 flex flex-col rounded-xl border border-border p-2"
>
<textarea
class="box-border h-24 resize-none overflow-auto rounded-md p-2 focus:outline-none"
v-model="prompt"
@keydown="handleSendByKeydown"
@input="handlePromptInput"
@compositionstart="onCompositionstart"
@compositionend="onCompositionend"
placeholder="问我任何问题...Shift+Enter 换行,按下 Enter 发送)"
></textarea>
<div class="flex justify-between pb-0 pt-1">
<div class="flex items-center gap-3">
<MessageFileUpload
v-model="uploadFiles"
:disabled="conversationInProgress"
/>
<div class="flex items-center">
<ElSwitch v-model="enableContext" size="small" />
<span class="ml-1 text-sm text-gray-400">上下文</span>
</div>
<div class="flex items-center">
<ElSwitch v-model="enableWebSearch" size="small" />
<span class="ml-1 text-sm text-gray-400">联网搜索</span>
</div>
</div>
<ElButton
type="primary"
@click="handleSendByButton"
:loading="conversationInProgress"
v-if="conversationInProgress === false"
>
<IconifyIcon
:icon="
conversationInProgress
? 'lucide:loader'
: 'lucide:send-horizontal'
"
/>
{{ conversationInProgress ? '进行中' : '发送' }}
</ElButton>
<ElButton
type="primary"
:danger="true"
@click="stopStream()"
v-if="conversationInProgress === true"
>
<IconifyIcon icon="lucide:circle-stop" />
停止
</ElButton>
</div>
</form>
</ElFooter>
</ElContainer>
</ElContainer>
<FormModal @success="handleConversationUpdateSuccess" />
</Page>
</template>

View File

@@ -0,0 +1,442 @@
<script setup lang="ts">
import type { PropType } from 'vue';
import type { AiChatConversationApi } from '#/api/ai/chat/conversation';
import { h, onMounted, ref, toRefs, watch } from 'vue';
import { confirm, prompt, useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon, SvgGptIcon } from '@vben/icons';
import {
ElAside,
ElAvatar,
ElButton,
ElEmpty,
ElInput,
ElMessage,
} from 'element-plus';
import {
createChatConversationMy,
deleteChatConversationMy,
deleteChatConversationMyByUnpinned,
getChatConversationMyList,
updateChatConversationMy,
} from '#/api/ai/chat/conversation';
import { $t } from '#/locales';
import RoleRepository from '../role/repository.vue';
const props = defineProps({
activeId: {
type: [Number, null] as PropType<null | number>,
default: null,
},
});
const emits = defineEmits([
'onConversationCreate',
'onConversationClick',
'onConversationClear',
'onConversationDelete',
]);
const [Drawer, drawerApi] = useVbenDrawer({
connectedComponent: RoleRepository,
});
const searchName = ref<string>(''); // 对话搜索
const activeConversationId = ref<null | number>(null); // 选中的对话,默认为 null
const hoverConversationId = ref<null | number>(null); // 悬浮上去的对话
const conversationList = ref([] as AiChatConversationApi.ChatConversation[]); // 对话列表
const conversationMap = ref<any>({}); // 对话分组 (置顶、今天、三天前、一星期前、一个月前)
const loading = ref<boolean>(false); // 加载中
const loadingTime = ref<any>();
/** 搜索对话 */
async function searchConversation() {
// 恢复数据
if (searchName.value.trim().length === 0) {
conversationMap.value = await getConversationGroupByCreateTime(
conversationList.value,
);
} else {
// 过滤
const filterValues = conversationList.value.filter((item) => {
return item.title.includes(searchName.value.trim());
});
conversationMap.value =
await getConversationGroupByCreateTime(filterValues);
}
}
/** 点击对话 */
async function handleConversationClick(id: number) {
// 过滤出选中的对话
const filterConversation = conversationList.value.find((item) => {
return item.id === id;
});
// 回调 onConversationClick
// noinspection JSVoidFunctionReturnValueUsed
const success = emits('onConversationClick', filterConversation) as any;
// 切换对话
if (success) {
activeConversationId.value = id;
}
}
/** 获取对话列表 */
async function getChatConversationList() {
try {
// 加载中
loadingTime.value = setTimeout(() => {
loading.value = true;
}, 50);
// 1.1 获取 对话数据
conversationList.value = await getChatConversationMyList();
// 1.2 排序
conversationList.value.toSorted((a, b) => {
return Number(b.createTime) - Number(a.createTime);
});
// 1.3 没有任何对话情况
if (conversationList.value.length === 0) {
activeConversationId.value = null;
conversationMap.value = {};
return;
}
// 2. 对话根据时间分组(置顶、今天、一天前、三天前、七天前、30 天前)
conversationMap.value = await getConversationGroupByCreateTime(
conversationList.value,
);
} finally {
// 清理定时器
if (loadingTime.value) {
clearTimeout(loadingTime.value);
}
// 加载完成
loading.value = false;
}
}
/** 按照 creteTime 创建时间,进行分组 */
async function getConversationGroupByCreateTime(
list: AiChatConversationApi.ChatConversation[],
) {
// 排序、指定、时间分组(今天、一天前、三天前、七天前、30天前)
// noinspection NonAsciiCharacters
const groupMap: any = {
置顶: [],
今天: [],
一天前: [],
三天前: [],
七天前: [],
三十天前: [],
};
// 当前时间的时间戳
const now = Date.now();
// 定义时间间隔常量(单位:毫秒)
const oneDay = 24 * 60 * 60 * 1000;
const threeDays = 3 * oneDay;
const sevenDays = 7 * oneDay;
const thirtyDays = 30 * oneDay;
for (const conversation of list) {
// 置顶
if (conversation.pinned) {
groupMap['置顶'].push(conversation);
continue;
}
// 计算时间差(单位:毫秒)
const diff = now - Number(conversation.createTime);
// 根据时间间隔判断
if (diff < oneDay) {
groupMap['今天'].push(conversation);
} else if (diff < threeDays) {
groupMap['一天前'].push(conversation);
} else if (diff < sevenDays) {
groupMap['三天前'].push(conversation);
} else if (diff < thirtyDays) {
groupMap['七天前'].push(conversation);
} else {
groupMap['三十天前'].push(conversation);
}
}
return groupMap;
}
async function createConversation() {
// 1. 新建对话
const conversationId = await createChatConversationMy(
{} as unknown as AiChatConversationApi.ChatConversation,
);
// 2. 获取对话内容
await getChatConversationList();
// 3. 选中对话
await handleConversationClick(conversationId);
// 4. 回调
emits('onConversationCreate');
}
/** 修改对话的标题 */
async function updateConversationTitle(
conversation: AiChatConversationApi.ChatConversation,
) {
// 1. 二次确认
await prompt({
async beforeClose(scope) {
if (scope.isConfirm) {
if (scope.value) {
try {
// 2. 发起修改
await updateChatConversationMy({
id: conversation.id,
title: scope.value,
} as AiChatConversationApi.ChatConversation);
ElMessage.success('重命名成功');
// 3. 刷新列表
await getChatConversationList();
// 4. 过滤当前切换的
const filterConversationList = conversationList.value.filter(
(item) => {
return item.id === conversation.id;
},
);
if (
filterConversationList.length > 0 &&
filterConversationList[0] && // tip避免切换对话
activeConversationId.value === filterConversationList[0].id!
) {
emits('onConversationClick', filterConversationList[0]);
}
} catch {
return false;
}
} else {
ElMessage.error('请输入标题');
return false;
}
}
},
component: () => {
return h(ElInput, {
placeholder: '请输入标题',
clearable: true,
modelValue: conversation.title,
});
},
content: '请输入标题',
title: '修改标题',
modelPropName: 'modelValue',
});
}
/** 删除聊天对话 */
async function deleteChatConversation(
conversation: AiChatConversationApi.ChatConversation,
) {
// 删除的二次确认
await confirm(`是否确认删除对话 - ${conversation.title}?`);
// 发起删除
await deleteChatConversationMy(conversation.id);
ElMessage.success('对话已删除');
// 刷新列表
await getChatConversationList();
// 回调
emits('onConversationDelete', conversation);
}
/** 清空未置顶的对话 */
async function handleClearConversation() {
await confirm('确认后对话会全部清空,置顶的对话除外。');
await deleteChatConversationMyByUnpinned();
ElMessage.success($t('ui.actionMessage.operationSuccess'));
// 清空对话、对话内容
activeConversationId.value = null;
// 获取对话列表
await getChatConversationList();
// 回调 方法
emits('onConversationClear');
}
/** 对话置顶 */
async function handleTop(conversation: AiChatConversationApi.ChatConversation) {
// 更新对话置顶
conversation.pinned = !conversation.pinned;
await updateChatConversationMy(conversation);
// 刷新对话
await getChatConversationList();
}
// ============ 角色仓库 ============
/** 角色仓库抽屉 */
const handleRoleRepository = async () => {
drawerApi.open();
};
/** 监听选中的对话 */
const { activeId } = toRefs(props);
watch(activeId, async (newValue) => {
activeConversationId.value = newValue;
});
defineExpose({ createConversation });
/** 初始化 */
onMounted(async () => {
// 获取 对话列表
await getChatConversationList();
// 默认选中
if (props.activeId) {
activeConversationId.value = props.activeId;
} else {
// 首次默认选中第一个
if (conversationList.value.length > 0 && conversationList.value[0]) {
activeConversationId.value = conversationList.value[0].id;
// 回调 onConversationClick
emits('onConversationClick', conversationList.value[0]);
}
}
});
</script>
<template>
<ElAside
width="280px"
class="relative flex h-full flex-col justify-between overflow-hidden p-4"
>
<Drawer />
<!-- 左顶部对话 -->
<div class="flex h-full flex-col">
<ElButton class="h-9 w-full" type="primary" @click="createConversation">
<IconifyIcon icon="lucide:plus" class="mr-1" />
新建对话
</ElButton>
<ElInput
v-model="searchName"
size="large"
class="search-input mt-4"
placeholder="搜索历史记录"
@keyup="searchConversation"
>
<template #prefix>
<IconifyIcon icon="lucide:search" />
</template>
</ElInput>
<!-- 左中间对话列表 -->
<div class="mt-2 flex-1 overflow-auto">
<!-- 情况一加载中 -->
<ElEmpty v-if="loading" description="." v-loading="loading" />
<!-- 情况二按照 group 分组 -->
<div
v-for="conversationKey in Object.keys(conversationMap)"
:key="conversationKey"
>
<div
v-if="conversationMap[conversationKey].length > 0"
class="classify-title pt-2"
>
<p class="mx-1">
{{ conversationKey }}
</p>
</div>
<div
v-for="conversation in conversationMap[conversationKey]"
:key="conversation.id"
@click="handleConversationClick(conversation.id)"
@mouseover="hoverConversationId = conversation.id"
@mouseout="hoverConversationId = null"
class="mt-1"
>
<div
class="mb-2 flex cursor-pointer flex-row items-center justify-between rounded-lg px-2 leading-10 transition-colors hover:bg-gray-100 dark:hover:bg-gray-800"
:class="[
conversation.id === activeConversationId
? 'bg-primary/10 dark:bg-primary/20'
: '',
]"
>
<div class="flex items-center">
<ElAvatar
v-if="conversation.roleAvatar"
:src="conversation.roleAvatar"
:size="28"
/>
<SvgGptIcon v-else class="size-6" />
<span
class="max-w-32 overflow-hidden text-ellipsis whitespace-nowrap p-2 text-sm font-normal"
>
{{ conversation.title }}
</span>
</div>
<div
v-show="hoverConversationId === conversation.id"
class="relative right-0.5 flex items-center text-gray-400"
>
<!-- TODO @AI三个按钮之间间隙太大了 -->
<ElButton
class="mr-0 px-1"
link
@click.stop="handleTop(conversation)"
>
<IconifyIcon
v-if="!conversation.pinned"
icon="lucide:arrow-up-to-line"
/>
<IconifyIcon
v-if="conversation.pinned"
icon="lucide:arrow-down-from-line"
/>
</ElButton>
<ElButton
class="mr-0 px-1"
link
@click.stop="updateConversationTitle(conversation)"
>
<IconifyIcon icon="lucide:edit" />
</ElButton>
<ElButton
class="mr-0 px-1"
link
@click.stop="deleteChatConversation(conversation)"
>
<IconifyIcon icon="lucide:trash-2" />
</ElButton>
</div>
</div>
</div>
</div>
</div>
<!-- 底部占位 -->
<div class="h-12 w-full"></div>
</div>
<!-- 左底部工具栏 -->
<div
class="absolute bottom-1 left-0 right-0 mb-4 flex items-center justify-between bg-card px-5 leading-9 text-gray-400 shadow-sm"
>
<div
class="flex cursor-pointer items-center text-gray-400"
@click="handleRoleRepository"
>
<IconifyIcon icon="lucide:user" />
<span class="ml-1">角色仓库</span>
</div>
<div
class="flex cursor-pointer items-center text-gray-400"
@click="handleClearConversation"
>
<IconifyIcon icon="lucide:trash" />
<span class="ml-1">清空未置顶对话</span>
</div>
</div>
</ElAside>
</template>

View File

@@ -0,0 +1,82 @@
<script lang="ts" setup>
import type { AiChatConversationApi } from '#/api/ai/chat/conversation';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import {
getChatConversationMy,
updateChatConversationMy,
} from '#/api/ai/chat/conversation';
import { $t } from '#/locales';
import { useFormSchema } from '../../data';
const emit = defineEmits(['success']);
const formData = ref<AiChatConversationApi.ChatConversation>();
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 110,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data =
(await formApi.getValues()) as AiChatConversationApi.ChatConversation;
try {
await updateChatConversationMy(data);
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<AiChatConversationApi.ChatConversation>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getChatConversationMy(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal class="w-2/5" title="设定">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,304 @@
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { formatFileSize, getFileIcon } from '@vben/utils';
import { ElMessage } from 'element-plus';
import { useUpload } from '#/components/upload/use-upload';
export interface FileItem {
name: string;
size: number;
url?: string;
uploading?: boolean;
progress?: number;
raw?: File;
}
const props = withDefaults(
defineProps<{
acceptTypes?: string;
disabled?: boolean;
limit?: number;
maxSize?: number;
modelValue?: string[];
}>(),
{
modelValue: () => [],
limit: 5,
maxSize: 10,
acceptTypes:
'.jpg,.jpeg,.png,.gif,.webp,.pdf,.doc,.docx,.txt,.xls,.xlsx,.ppt,.pptx,.csv,.md',
disabled: false,
},
);
const emit = defineEmits<{
'update:modelValue': [value: string[]];
uploadError: [error: any];
uploadSuccess: [file: FileItem];
}>();
const fileInputRef = ref<HTMLInputElement>();
const fileList = ref<FileItem[]>([]);
const uploadedUrls = ref<string[]>([]);
const showTooltip = ref(false);
const hideTimer = ref<NodeJS.Timeout | null>(null);
const { httpRequest } = useUpload();
/** 监听 v-model 变化 */
watch(
() => props.modelValue,
(newVal) => {
uploadedUrls.value = [...newVal];
if (newVal.length === 0) {
fileList.value = [];
}
},
{ immediate: true, deep: true },
);
/** 是否有文件 */
const hasFiles = computed(() => fileList.value.length > 0);
/** 是否达到上传限制 */
const isLimitReached = computed(() => fileList.value.length >= props.limit);
/** 触发文件选择 */
function triggerFileInput() {
fileInputRef.value?.click();
}
/** 显示 tooltip */
function showTooltipHandler() {
if (hideTimer.value) {
clearTimeout(hideTimer.value);
hideTimer.value = null;
}
showTooltip.value = true;
}
/** 隐藏 tooltip */
function hideTooltipHandler() {
hideTimer.value = setTimeout(() => {
showTooltip.value = false;
hideTimer.value = null;
}, 300);
}
/** 处理文件选择 */
async function handleFileSelect(event: Event) {
const target = event.target as HTMLInputElement;
const files = [...(target.files || [])];
if (files.length === 0) {
return;
}
if (files.length + fileList.value.length > props.limit) {
ElMessage.error(`最多只能上传 ${props.limit} 个文件`);
target.value = '';
return;
}
for (const file of files) {
if (file.size > props.maxSize * 1024 * 1024) {
ElMessage.error(`文件 ${file.name} 大小超过 ${props.maxSize}MB`);
continue;
}
const fileItem: FileItem = {
name: file.name,
size: file.size,
uploading: true,
progress: 0,
raw: file,
};
fileList.value.push(fileItem);
await uploadFile(fileItem);
}
target.value = '';
}
/** 上传文件 */
async function uploadFile(fileItem: FileItem) {
try {
const progressInterval = setInterval(() => {
if (fileItem.progress! < 90) {
fileItem.progress = (fileItem.progress || 0) + Math.random() * 10;
}
}, 100);
const response = await httpRequest(fileItem.raw!);
clearInterval(progressInterval);
fileItem.uploading = false;
fileItem.progress = 100;
// 调试日志
console.warn('上传响应:', response);
// 兼容不同的返回格式:{ url: '...' } 或 { data: '...' } 或直接是字符串
const fileUrl =
(response as any)?.url || (response as any)?.data || response;
fileItem.url = fileUrl;
console.warn('提取的文件 URL:', fileUrl);
// 只有当 URL 有效时才添加到列表
if (fileUrl && typeof fileUrl === 'string') {
uploadedUrls.value.push(fileUrl);
emit('uploadSuccess', fileItem);
updateModelValue();
} else {
throw new Error('上传返回的 URL 无效');
}
} catch (error) {
fileItem.uploading = false;
ElMessage.error(`文件 ${fileItem.name} 上传失败`);
emit('uploadError', error);
const index = fileList.value.indexOf(fileItem);
if (index !== -1) {
removeFile(index);
}
}
}
/** 删除文件 */
function removeFile(index: number) {
const removedFile = fileList.value[index];
fileList.value.splice(index, 1);
if (removedFile?.url) {
const urlIndex = uploadedUrls.value.indexOf(removedFile.url);
if (urlIndex !== -1) {
uploadedUrls.value.splice(urlIndex, 1);
}
}
updateModelValue();
}
/** 更新 v-model */
function updateModelValue() {
emit('update:modelValue', [...uploadedUrls.value]);
}
/** 清空文件 */
function clearFiles() {
fileList.value = [];
uploadedUrls.value = [];
updateModelValue();
}
defineExpose({
triggerFileInput,
clearFiles,
});
onUnmounted(() => {
if (hideTimer.value) {
clearTimeout(hideTimer.value);
}
});
</script>
<template>
<div
v-if="!disabled"
class="relative inline-block"
@mouseenter="showTooltipHandler"
@mouseleave="hideTooltipHandler"
>
<!-- 文件上传按钮 -->
<button
type="button"
class="relative flex h-8 w-8 items-center justify-center rounded-full border-0 bg-transparent text-gray-600 transition-all duration-200 hover:bg-gray-100"
:class="{ 'text-blue-500 hover:bg-blue-50': hasFiles }"
:disabled="isLimitReached"
@click="triggerFileInput"
>
<IconifyIcon icon="lucide:paperclip" :size="16" />
<!-- 文件数量徽章 -->
<span
v-if="hasFiles"
class="absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-medium leading-none text-white"
>
{{ fileList.length }}
</span>
</button>
<!-- 隐藏的文件输入框 -->
<input
ref="fileInputRef"
type="file"
multiple
style="display: none"
:accept="acceptTypes"
@change="handleFileSelect"
/>
<!-- Hover 显示的文件列表 -->
<div
v-if="hasFiles && showTooltip"
class="absolute bottom-[calc(100%+8px)] left-1/2 z-[1000] min-w-[240px] max-w-[320px] -translate-x-1/2 rounded-lg border border-gray-200 bg-white p-2 shadow-lg duration-200 animate-in fade-in slide-in-from-bottom-1"
@mouseenter="showTooltipHandler"
@mouseleave="hideTooltipHandler"
>
<!-- Tooltip 箭头 -->
<div
class="absolute -bottom-[5px] left-1/2 h-0 w-0 -translate-x-1/2 border-l-[5px] border-r-[5px] border-t-[5px] border-l-transparent border-r-transparent border-t-gray-200"
>
<div
class="absolute bottom-[1px] left-1/2 h-0 w-0 -translate-x-1/2 border-l-[4px] border-r-[4px] border-t-[4px] border-l-transparent border-r-transparent border-t-white"
></div>
</div>
<!-- 文件列表 -->
<div
class="scrollbar-thin scrollbar-track-transparent scrollbar-thumb-gray-300 hover:scrollbar-thumb-gray-400 scrollbar-thumb-rounded-sm max-h-[200px] overflow-y-auto"
>
<div
v-for="(file, index) in fileList"
:key="index"
class="mb-1 flex items-center justify-between rounded-md bg-gray-50 p-2 text-xs transition-all duration-200 last:mb-0 hover:bg-gray-100"
:class="{ 'opacity-70': file.uploading }"
>
<div class="flex min-w-0 flex-1 items-center">
<IconifyIcon
:icon="getFileIcon(file.name)"
class="mr-2 flex-shrink-0 text-blue-500"
/>
<span
class="mr-1 flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-medium text-gray-900"
>
{{ file.name }}
</span>
<span class="flex-shrink-0 text-[11px] text-gray-500">
({{ formatFileSize(file.size) }})
</span>
</div>
<div class="ml-2 flex flex-shrink-0 items-center gap-1">
<div
v-if="file.uploading"
class="h-1 w-[60px] overflow-hidden rounded-full bg-gray-200"
>
<div
class="h-full bg-blue-500 transition-all duration-300"
:style="{ width: `${file.progress || 0}%` }"
></div>
</div>
<button
v-else-if="!disabled"
type="button"
class="flex h-5 w-5 items-center justify-center rounded text-red-500 hover:bg-red-50"
@click="removeFile(index)"
>
<IconifyIcon icon="lucide:x" :size="12" />
</button>
</div>
</div>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,53 @@
<script setup lang="ts">
import { computed } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { getFileIcon, getFileNameFromUrl, getFileTypeClass } from '@vben/utils';
const props = defineProps<{
attachmentUrls?: string[];
}>();
/** 过滤掉空值的附件列表 */
const validAttachmentUrls = computed(() => {
return (props.attachmentUrls || []).filter((url) => url && url.trim());
});
/** 点击文件 */
function handleFileClick(url: string) {
window.open(url, '_blank');
}
</script>
<template>
<div v-if="validAttachmentUrls.length > 0" class="mt-2">
<div class="flex flex-wrap gap-2">
<div
v-for="(url, index) in validAttachmentUrls"
:key="index"
class="max-w-70 flex min-w-40 cursor-pointer items-center rounded-lg border border-transparent bg-gray-100 p-3 transition-all duration-200 hover:-translate-y-1 hover:bg-gray-200 hover:shadow-lg"
@click="handleFileClick(url)"
>
<div class="mr-3 flex-shrink-0">
<div
class="flex h-8 w-8 items-center justify-center rounded-md bg-gradient-to-br font-bold text-white"
:class="getFileTypeClass(getFileNameFromUrl(url))"
>
<IconifyIcon
:icon="getFileIcon(getFileNameFromUrl(url))"
:size="20"
/>
</div>
</div>
<div class="min-w-0 flex-1">
<div
class="mb-1 overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium leading-tight text-gray-800"
:title="getFileNameFromUrl(url)"
>
{{ getFileNameFromUrl(url) }}
</div>
</div>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,103 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { ElTooltip } from 'element-plus';
const props = defineProps<{
segments: {
content: string;
documentId: number;
documentName: string;
id: number;
}[];
}>();
const document = ref<null | {
id: number;
segments: {
content: string;
id: number;
}[];
title: string;
}>(null); // 知识库文档列表
const dialogVisible = ref(false); // 知识引用详情弹窗
const documentRef = ref<HTMLElement>(); // 知识引用详情弹窗 Ref
/** 按照 document 聚合 segments */
const documentList = computed(() => {
if (!props.segments) return [];
const docMap = new Map();
props.segments.forEach((segment) => {
if (!docMap.has(segment.documentId)) {
docMap.set(segment.documentId, {
id: segment.documentId,
title: segment.documentName,
segments: [],
});
}
docMap.get(segment.documentId).segments.push({
id: segment.id,
content: segment.content,
});
});
return [...docMap.values()];
});
/** 点击 document 处理 */
function handleClick(doc: any) {
document.value = doc;
dialogVisible.value = true;
}
</script>
<template>
<!-- 知识引用列表 -->
<div
v-if="segments && segments.length > 0"
class="mt-2 rounded-lg bg-gray-50 p-2"
>
<div class="mb-2 flex items-center text-sm text-gray-400">
<IconifyIcon icon="lucide:file-text" class="mr-1" /> 知识引用
</div>
<div class="flex flex-wrap gap-2">
<div
v-for="(doc, index) in documentList"
:key="index"
class="cursor-pointer rounded-lg bg-card p-2 px-3 transition-all hover:bg-blue-50"
@click="handleClick(doc)"
>
<div class="mb-1 text-sm text-gray-600">
{{ doc.title }}
<span class="ml-1 text-xs text-gray-300">
{{ doc.segments.length }}
</span>
</div>
</div>
</div>
</div>
<ElTooltip placement="top-start" trigger="click">
<div ref="documentRef"></div>
<template #content>
<div class="mb-3 text-base font-bold">{{ document?.title }}</div>
<div class="max-h-[60vh] overflow-y-auto">
<div
v-for="(segment, index) in document?.segments"
:key="index"
class="border-b-solid border-b-gray-200 p-3 last:border-b-0"
>
<div
class="mb-2 block w-fit rounded-sm px-2 py-1 text-xs text-gray-400"
>
分段 {{ segment.id }}
</div>
<div class="mt-2 text-sm leading-[1.6] text-gray-600">
{{ segment.content }}
</div>
</div>
</div>
</template>
</ElTooltip>
</template>

View File

@@ -0,0 +1,37 @@
<!-- 消息列表为空时展示 prompt 列表 -->
<script setup lang="ts">
const emits = defineEmits(['onPrompt']);
const promptList = [
{
prompt: '今天气怎么样?',
},
{
prompt: '写一首好听的诗歌?',
},
]; // prompt 列表
/** 选中 prompt 点击 */
async function handlerPromptClick(prompt: any) {
emits('onPrompt', prompt.prompt);
}
</script>
<template>
<div class="relative flex h-full w-full flex-row justify-center">
<div class="flex flex-col justify-center">
<!-- title -->
<div class="text-center text-3xl font-bold">芋道 AI</div>
<!-- role-list -->
<div class="mt-5 flex w-96 flex-wrap items-center justify-center">
<div
v-for="prompt in promptList"
:key="prompt.prompt"
@click="handlerPromptClick(prompt)"
class="m-2.5 flex w-44 cursor-pointer justify-center rounded-lg border border-gray-200 leading-10 hover:bg-gray-100"
>
{{ prompt.prompt }}
</div>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,243 @@
<script setup lang="ts">
import type { PropType } from 'vue';
import type { AiChatConversationApi } from '#/api/ai/chat/conversation';
import type { AiChatMessageApi } from '#/api/ai/chat/message';
import { computed, nextTick, onMounted, ref, toRefs } from 'vue';
import { IconifyIcon, SvgGptIcon } from '@vben/icons';
import { preferences } from '@vben/preferences';
import { useUserStore } from '@vben/stores';
import { formatDateTime } from '@vben/utils';
import { useClipboard } from '@vueuse/core';
import { ElAvatar, ElButton, ElMessage } from 'element-plus';
import { deleteChatMessage } from '#/api/ai/chat/message';
import { MarkdownView } from '#/components/markdown-view';
import MessageFiles from './files.vue';
import MessageKnowledge from './knowledge.vue';
import MessageReasoning from './reasoning.vue';
import MessageWebSearch from './web-search.vue';
const props = defineProps({
conversation: {
type: Object as PropType<AiChatConversationApi.ChatConversation>,
required: true,
},
list: {
type: Array as PropType<AiChatMessageApi.ChatMessage[]>,
required: true,
},
});
const emits = defineEmits(['onDeleteSuccess', 'onRefresh', 'onEdit']);
const { copy } = useClipboard(); // 初始化 copy 到粘贴板
const userStore = useUserStore();
// 判断“消息列表”滚动的位置(用于判断是否需要滚动到消息最下方)
const messageContainer: any = ref(null);
const isScrolling = ref(false); // 用于判断用户是否在滚动
const userAvatar = computed(
() => userStore.userInfo?.avatar || preferences.app.defaultAvatar,
);
const { list } = toRefs(props); // 定义 emits
// ============ 处理对话滚动 ==============
/** 滚动到底部 */
async function scrollToBottom(isIgnore?: boolean) {
// 注意要使用 nextTick 以免获取不到 dom
await nextTick();
if (isIgnore || !isScrolling.value) {
messageContainer.value.scrollTop =
messageContainer.value.scrollHeight - messageContainer.value.offsetHeight;
}
}
function handleScroll() {
const scrollContainer = messageContainer.value;
const scrollTop = scrollContainer.scrollTop;
const scrollHeight = scrollContainer.scrollHeight;
const offsetHeight = scrollContainer.offsetHeight;
isScrolling.value = scrollTop + offsetHeight < scrollHeight - 100;
}
/** 回到底部 */
async function handleGoBottom() {
const scrollContainer = messageContainer.value;
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
/** 回到顶部 */
async function handlerGoTop() {
const scrollContainer = messageContainer.value;
scrollContainer.scrollTop = 0;
}
defineExpose({ scrollToBottom, handlerGoTop }); // 提供方法给 parent 调用
// ============ 处理消息操作 ==============
/** 复制 */
async function copyContent(content: string) {
await copy(content);
ElMessage.success('复制成功!');
}
/** 删除 */
async function handleDelete(id: number) {
// 删除 message
await deleteChatMessage(id);
ElMessage.success('删除成功!');
// 回调
emits('onDeleteSuccess');
}
/** 刷新 */
async function handleRefresh(message: AiChatMessageApi.ChatMessage) {
emits('onRefresh', message);
}
/** 编辑 */
async function handleEdit(message: AiChatMessageApi.ChatMessage) {
emits('onEdit', message);
}
/** 初始化 */
onMounted(async () => {
messageContainer.value.addEventListener('scroll', handleScroll);
});
</script>
<template>
<div ref="messageContainer" class="relative h-full overflow-y-auto">
<div
v-for="(item, index) in list"
:key="index"
class="mt-12 flex flex-col overflow-y-hidden px-5"
>
<!-- 左侧消息systemassistant -->
<div v-if="item.type !== 'user'" class="flex flex-row">
<div class="avatar">
<ElAvatar
v-if="conversation.roleAvatar"
:src="conversation.roleAvatar"
:size="28"
/>
<SvgGptIcon v-else class="size-7" />
</div>
<div class="mx-4 flex flex-col text-left">
<div class="text-left leading-10">
{{ formatDateTime(item.createTime) }}
</div>
<div
class="relative flex flex-col break-words rounded-lg bg-gray-100 p-2.5 pb-1 pt-2.5 shadow-sm"
>
<MessageReasoning
:reasoning-content="item.reasoningContent || ''"
:content="item.content || ''"
/>
<MarkdownView
class="text-sm text-gray-600"
:content="item.content"
/>
<MessageFiles :attachment-urls="item.attachmentUrls" />
<MessageKnowledge v-if="item.segments" :segments="item.segments" />
<MessageWebSearch
v-if="item.webSearchPages"
:web-search-pages="item.webSearchPages"
/>
</div>
<div class="mt-2 flex flex-row">
<ElButton
class="!ml-1 flex items-center bg-transparent !px-1.5 hover:bg-gray-100"
text
@click="copyContent(item.content)"
>
<IconifyIcon icon="lucide:copy" />
</ElButton>
<ElButton
v-if="item.id > 0"
class="!ml-1 flex items-center bg-transparent !px-1.5 hover:bg-gray-100"
text
@click="handleDelete(item.id)"
>
<IconifyIcon icon="lucide:trash" />
</ElButton>
</div>
</div>
</div>
<!-- 右侧消息user -->
<div v-else class="flex flex-row-reverse justify-start">
<div class="avatar">
<ElAvatar :src="userAvatar" :size="28" />
</div>
<div class="mx-4 flex flex-col text-left">
<div class="text-left leading-8">
{{ formatDateTime(item.createTime) }}
</div>
<div
v-if="item.attachmentUrls && item.attachmentUrls.length > 0"
class="mb-2 flex flex-row-reverse"
>
<MessageFiles :attachment-urls="item.attachmentUrls" />
</div>
<div class="flex flex-row-reverse">
<div
v-if="item.content && item.content.trim()"
class="inline w-auto whitespace-pre-wrap break-words rounded-lg bg-blue-500 p-2.5 text-sm text-white shadow-sm"
>
{{ item.content }}
</div>
</div>
<div class="mt-2 flex flex-row-reverse">
<ElButton
class="!ml-1 flex items-center bg-transparent !px-1.5 hover:bg-gray-100"
text
@click="copyContent(item.content)"
>
<IconifyIcon icon="lucide:copy" />
</ElButton>
<ElButton
class="!ml-1 flex items-center bg-transparent !px-1.5 hover:bg-gray-100"
text
@click="handleDelete(item.id)"
>
<IconifyIcon icon="lucide:trash" />
</ElButton>
<ElButton
class="!ml-1 flex items-center bg-transparent !px-1.5 hover:bg-gray-100"
text
@click="handleRefresh(item)"
>
<IconifyIcon icon="lucide:refresh-cw" />
</ElButton>
<ElButton
class="!ml-1 flex items-center bg-transparent !px-1.5 hover:bg-gray-100"
text
@click="handleEdit(item)"
>
<IconifyIcon icon="lucide:edit" />
</ElButton>
</div>
</div>
</div>
</div>
</div>
<!-- 回到底部按钮 -->
<div
v-if="isScrolling"
class="absolute bottom-0 right-1/2 z-1000"
@click="handleGoBottom"
>
<ElButton circle>
<IconifyIcon icon="lucide:chevron-down" />
</ElButton>
</div>
</template>

View File

@@ -0,0 +1,9 @@
<script setup lang="ts">
import { ElSkeleton } from 'element-plus';
</script>
<template>
<div class="p-8">
<ElSkeleton :rows="5" animated />
</div>
</template>

View File

@@ -0,0 +1,25 @@
<script setup lang="ts">
import { ElButton } from 'element-plus';
const emits = defineEmits(['onNewConversation']);
/** 新建 conversation 聊天对话 */
function handlerNewChat() {
emits('onNewConversation');
}
</script>
<template>
<div class="flex h-full w-full flex-row justify-center">
<div class="flex flex-col justify-center">
<div class="text-center text-sm text-gray-400">
点击下方按钮开始你的对话吧
</div>
<div class="mt-5 flex flex-row justify-center">
<ElButton type="primary" round @click="handlerNewChat">
新建对话
</ElButton>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,86 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { MarkdownView } from '#/components/markdown-view';
const props = defineProps<{
content?: string;
reasoningContent?: string;
}>();
const isExpanded = ref(true); // 默认展开
/** 判断是否应该显示组件 */
const shouldShowComponent = computed(() => {
return props.reasoningContent && props.reasoningContent.trim() !== '';
});
/** 标题文本 */
const titleText = computed(() => {
const hasReasoningContent =
props.reasoningContent && props.reasoningContent.trim() !== '';
const hasContent = props.content && props.content.trim() !== '';
if (hasReasoningContent && !hasContent) {
return '深度思考中';
}
return '已深度思考';
});
/** 切换展开/收起 */
function toggleExpanded() {
isExpanded.value = !isExpanded.value;
}
</script>
<template>
<div v-if="shouldShowComponent" class="mt-2.5">
<!-- 标题栏 -->
<div
class="flex cursor-pointer items-center justify-between rounded-t-lg border border-b-0 border-gray-200/60 bg-gradient-to-r from-blue-50 to-purple-50 p-2 transition-all duration-200 hover:from-blue-100 hover:to-purple-100"
@click="toggleExpanded"
>
<div class="flex items-center gap-1.5 text-sm font-medium text-gray-700">
<IconifyIcon icon="lucide:brain" class="text-blue-600" :size="16" />
<span>{{ titleText }}</span>
</div>
<IconifyIcon
icon="lucide:chevron-down"
class="text-gray-500 transition-transform duration-200"
:class="{ 'rotate-180': isExpanded }"
:size="14"
/>
</div>
<!-- 内容区 -->
<div
v-show="isExpanded"
class="scrollbar-thin max-h-[300px] overflow-y-auto rounded-b-lg border border-t-0 border-gray-200/60 bg-white/70 p-3 shadow-sm backdrop-blur-sm"
>
<MarkdownView
v-if="props.reasoningContent"
class="text-sm leading-relaxed text-gray-700"
:content="props.reasoningContent"
/>
</div>
</div>
</template>
<style scoped>
/* 自定义滚动条 */
.scrollbar-thin::-webkit-scrollbar {
width: 4px;
}
.scrollbar-thin::-webkit-scrollbar-track {
background: transparent;
}
.scrollbar-thin::-webkit-scrollbar-thumb {
@apply rounded-sm bg-gray-400/40;
}
.scrollbar-thin::-webkit-scrollbar-thumb:hover {
@apply bg-gray-400/60;
}
</style>

View File

@@ -0,0 +1,173 @@
<script setup lang="ts">
import type { AiChatMessageApi } from '#/api/ai/chat/message';
import { ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
defineProps<{
webSearchPages?: AiChatMessageApi.WebSearchPage[];
}>();
const isExpanded = ref(false); // 默认收起
const selectedResult = ref<AiChatMessageApi.WebSearchPage | null>(null); // 选中的搜索结果
const iconLoadError = ref<Record<number, boolean>>({}); // 记录图标加载失败
const [Drawer, drawerApi] = useVbenDrawer({
title: '联网搜索详情',
closable: true,
footer: true,
onCancel() {
drawerApi.close();
},
onConfirm() {
if (selectedResult.value?.url) {
window.open(selectedResult.value.url, '_blank');
}
drawerApi.close();
},
});
/** 切换展开/收起 */
function toggleExpanded() {
isExpanded.value = !isExpanded.value;
}
/** 点击搜索结果 */
function handleClick(result: AiChatMessageApi.WebSearchPage) {
selectedResult.value = result;
drawerApi.open();
}
/** 图标加载失败处理 */
function handleIconError(index: number) {
iconLoadError.value[index] = true;
}
</script>
<template>
<div v-if="webSearchPages && webSearchPages.length > 0" class="mt-2.5">
<!-- 标题栏可点击展开/收起 -->
<div
class="mb-2 flex cursor-pointer items-center justify-between text-sm text-gray-600 transition-colors hover:text-blue-500"
@click="toggleExpanded"
>
<div class="flex items-center gap-1.5">
<IconifyIcon icon="lucide:search" :size="14" />
<span>联网搜索结果 ({{ webSearchPages.length }} )</span>
</div>
<IconifyIcon
:icon="isExpanded ? 'lucide:chevron-up' : 'lucide:chevron-down'"
class="text-xs transition-transform duration-200"
:size="12"
/>
</div>
<!-- 可展开的搜索结果列表 -->
<div
v-show="isExpanded"
class="flex flex-col gap-2 transition-all duration-200 ease-in-out"
>
<div
v-for="(page, index) in webSearchPages"
:key="index"
class="cursor-pointer rounded-md bg-white p-2.5 transition-all hover:bg-blue-50"
@click="handleClick(page)"
>
<div class="flex items-start gap-2">
<!-- 网站图标 -->
<div class="mt-0.5 h-4 w-4 flex-shrink-0">
<img
v-if="page.icon && !iconLoadError[index]"
:src="page.icon"
:alt="page.name"
class="h-full w-full rounded-sm object-contain"
@error="handleIconError(index)"
/>
<IconifyIcon
v-else
icon="lucide:link"
class="h-full w-full text-gray-600"
/>
</div>
<!-- 内容区域 -->
<div class="min-w-0 flex-1">
<!-- 网站名称 -->
<div class="mb-1 truncate text-xs text-gray-400">
{{ page.name }}
</div>
<!-- 主标题 -->
<div
class="mb-1 line-clamp-2 text-sm font-medium leading-snug text-blue-600"
>
{{ page.title }}
</div>
<!-- 描述 -->
<div class="mb-1 line-clamp-2 text-xs leading-snug text-gray-600">
{{ page.snippet }}
</div>
<!-- URL -->
<div class="truncate text-xs text-green-700">
{{ page.url }}
</div>
</div>
</div>
</div>
</div>
<!-- 联网搜索详情 Drawer -->
<Drawer class="w-[600px]" cancel-text="关闭" confirm-text="访问原文">
<div v-if="selectedResult">
<!-- 标题区域 -->
<div class="mb-4 flex items-start gap-3">
<div class="mt-0.5 h-6 w-6 flex-shrink-0">
<img
v-if="selectedResult.icon"
:src="selectedResult.icon"
:alt="selectedResult.name"
class="h-full w-full rounded-sm object-contain"
/>
<IconifyIcon
v-else
icon="lucide:link"
class="h-full w-full text-gray-600"
/>
</div>
<div class="min-w-0 flex-1">
<div class="mb-2 text-lg font-bold text-gray-900">
{{ selectedResult.title }}
</div>
<div class="mb-1 text-sm text-gray-500">
{{ selectedResult.name }}
</div>
<div class="break-all text-sm text-green-700">
{{ selectedResult.url }}
</div>
</div>
</div>
<!-- 内容区域 -->
<div class="space-y-4">
<!-- 简短描述 -->
<div>
<div class="mb-2 text-sm font-semibold text-gray-900">简短描述</div>
<div
class="rounded-lg bg-gray-50 p-3 text-sm leading-relaxed text-gray-700"
>
{{ selectedResult.snippet }}
</div>
</div>
<!-- 内容摘要 -->
<div v-if="selectedResult.summary">
<div class="mb-2 text-sm font-semibold text-gray-900">内容摘要</div>
<div
class="max-h-[50vh] overflow-y-auto whitespace-pre-wrap rounded-lg bg-gray-50 p-3 text-sm leading-relaxed text-gray-900"
>
{{ selectedResult.summary }}
</div>
</div>
</div>
</div>
</Drawer>
</div>
</template>

View File

@@ -0,0 +1,43 @@
<script setup lang="ts">
import type { PropType } from 'vue';
import { ElButton } from 'element-plus';
defineProps({
categoryList: {
type: Array as PropType<string[]>,
required: true,
},
active: {
type: String,
required: false,
default: '全部',
},
});
const emits = defineEmits(['onCategoryClick']); // 定义回调
/** 处理分类点击事件 */
async function handleCategoryClick(category: string) {
emits('onCategoryClick', category);
}
</script>
<template>
<div class="mx-0 flex flex-wrap items-center">
<div
class="mr-2 flex flex-row"
v-for="category in categoryList"
:key="category"
>
<ElButton
size="small"
round
:type="category === active ? 'primary' : 'default'"
@click="handleCategoryClick(category)"
>
{{ category }}
</ElButton>
</div>
</div>
</template>

View File

@@ -0,0 +1,123 @@
<script setup lang="ts">
import type { PropType } from 'vue';
import type { AiModelChatRoleApi } from '#/api/ai/model/chatRole';
import { ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import {
ElAvatar,
ElButton,
ElCard,
ElDropdown,
ElDropdownItem,
ElDropdownMenu,
} from 'element-plus';
const props = defineProps({
loading: {
type: Boolean,
required: true,
},
roleList: {
type: Array as PropType<AiModelChatRoleApi.ChatRole[]>,
required: true,
},
showMore: {
type: Boolean,
required: false,
default: false,
},
});
const emits = defineEmits(['onDelete', 'onEdit', 'onUse', 'onPage']);
const tabsRef = ref<any>();
/** 操作:编辑、删除 */
async function handleMoreClick(type: string, role: any) {
if (type === 'delete') {
emits('onDelete', role);
} else {
emits('onEdit', role);
}
}
/** 选中 */
function handleUseClick(role: any) {
emits('onUse', role);
}
/** 滚动 */
async function handleTabsScroll() {
if (tabsRef.value) {
const { scrollTop, scrollHeight, clientHeight } = tabsRef.value;
if (scrollTop + clientHeight >= scrollHeight - 20 && !props.loading) {
emits('onPage');
}
}
}
</script>
<template>
<div
class="relative flex h-full flex-wrap content-start items-start overflow-auto pb-36"
ref="tabsRef"
@scroll="handleTabsScroll"
>
<div class="mb-3 mr-3 inline-block" v-for="role in roleList" :key="role.id">
<ElCard
class="relative rounded-lg"
body-style="position: relative; display: flex; flex-direction: column; justify-content: flex-start; width: 240px; max-width: 240px; padding: 15px;"
>
<!-- 头部头像名称 -->
<div class="flex items-center justify-between">
<div class="flex min-w-0 flex-1 items-center">
<ElAvatar
:src="role.avatar"
class="h-8 w-8 flex-shrink-0 overflow-hidden"
/>
<div class="ml-2 truncate text-base font-medium">
{{ role.name }}
</div>
</div>
</div>
<!-- 描述信息 -->
<div
class="mt-2 line-clamp-2 h-10 overflow-hidden text-sm text-gray-600"
>
{{ role.description }}
</div>
<!-- 底部操作按钮 -->
<div class="flex items-center justify-end gap-2">
<ElDropdown v-if="showMore">
<ElButton size="small">
<IconifyIcon icon="lucide:ellipsis" />
</ElButton>
<template #dropdown>
<ElDropdownMenu>
<ElDropdownItem @click="handleMoreClick('delete', role)">
<div class="flex items-center">
<IconifyIcon icon="lucide:trash" color="red" />
<span class="ml-2 text-red-500">删除</span>
</div>
</ElDropdownItem>
<ElDropdownItem @click="handleMoreClick('edit', role)">
<div class="flex items-center">
<IconifyIcon icon="lucide:edit" color="#787878" />
<span class="ml-2 text-primary">编辑</span>
</div>
</ElDropdownItem>
</ElDropdownMenu>
</template>
</ElDropdown>
<ElButton type="primary" size="small" @click="handleUseClick(role)">
使用
</ElButton>
</div>
</ElCard>
</div>
</div>
</template>

View File

@@ -0,0 +1,263 @@
<script setup lang="ts">
import type { AiChatConversationApi } from '#/api/ai/chat/conversation';
import type { AiModelChatRoleApi } from '#/api/ai/model/chatRole';
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import {
ElButton,
ElContainer,
ElInput,
ElMain,
ElTabPane,
ElTabs,
} from 'element-plus';
import { createChatConversationMy } from '#/api/ai/chat/conversation';
import { deleteMy, getCategoryList, getMyPage } from '#/api/ai/model/chatRole';
import Form from '../../../../model/chatRole/modules/form.vue';
import RoleCategoryList from './category-list.vue';
import RoleList from './list.vue';
const router = useRouter();
const [Drawer] = useVbenDrawer({
title: '角色管理',
footer: false,
class: 'w-2/5',
});
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const loading = ref<boolean>(false); // 加载中
const activeTab = ref<string>('my-role'); // 选中的角色 Tab
const search = ref<string>(''); // 加载中
const myRoleParams = reactive({
pageNo: 1,
pageSize: 50,
});
const myRoleList = ref<AiModelChatRoleApi.ChatRole[]>([]); // my 分页大小
const publicRoleParams = reactive({
pageNo: 1,
pageSize: 50,
});
const publicRoleList = ref<AiModelChatRoleApi.ChatRole[]>([]); // public 分页大小
const activeCategory = ref<string>('全部'); // 选择中的分类
const categoryList = ref<string[]>([]); // 角色分类类别
/** tabs 点击 */
async function handleTabsClick(tab: any) {
// 设置切换状态
activeTab.value = tab;
// 切换的时候重新加载数据
await getActiveTabsRole();
}
/** 获取 my role 我的角色 */
async function getMyRole(append?: boolean) {
const params: AiModelChatRoleApi.ChatRolePageReqVO = {
...myRoleParams,
name: search.value,
publicStatus: false,
};
const { list } = await getMyPage(params);
if (append) {
myRoleList.value.push(...list);
} else {
myRoleList.value = list;
}
}
/** 获取 public role 公共角色 */
async function getPublicRole(append?: boolean) {
const params: AiModelChatRoleApi.ChatRolePageReqVO = {
...publicRoleParams,
category: activeCategory.value === '全部' ? '' : activeCategory.value,
name: search.value,
publicStatus: true,
};
const { list } = await getMyPage(params);
if (append) {
publicRoleList.value.push(...list);
} else {
publicRoleList.value = list;
}
}
/** 获取选中的 tabs 角色 */
async function getActiveTabsRole() {
if (activeTab.value === 'my-role') {
myRoleParams.pageNo = 1;
await getMyRole();
} else {
publicRoleParams.pageNo = 1;
await getPublicRole();
}
}
/** 获取角色分类列表 */
async function getRoleCategoryList() {
categoryList.value = ['全部', ...(await getCategoryList())];
}
/** 处理分类点击 */
async function handlerCategoryClick(category: string) {
// 切换选择的分类
activeCategory.value = category;
// 筛选
await getActiveTabsRole();
}
async function handlerAddRole() {
formModalApi.setData({ formType: 'my-create' }).open();
}
/** 编辑角色 */
async function handlerCardEdit(role: any) {
formModalApi.setData({ formType: 'my-update', id: role.id }).open();
}
/** 添加角色成功 */
async function handlerAddRoleSuccess() {
// 刷新数据
await getActiveTabsRole();
}
/** 删除角色 */
async function handlerCardDelete(role: any) {
await deleteMy(role.id);
// 刷新数据
await getActiveTabsRole();
}
/** 角色分页:获取下一页 */
async function handlerCardPage(type: string) {
try {
loading.value = true;
if (type === 'public') {
publicRoleParams.pageNo++;
await getPublicRole(true);
} else {
myRoleParams.pageNo++;
await getMyRole(true);
}
} finally {
loading.value = false;
}
}
/** 选择 card 角色:新建聊天对话 */
async function handlerCardUse(role: any) {
// 1. 创建对话
const data: AiChatConversationApi.ChatConversation = {
roleId: role.id,
} as unknown as AiChatConversationApi.ChatConversation;
const conversationId = await createChatConversationMy(data);
// 2. 跳转页面
await router.push({
path: '/ai/chat',
query: {
conversationId,
},
});
}
/** 初始化 */
onMounted(async () => {
// 获取分类
await getRoleCategoryList();
// 获取 role 数据
await getActiveTabsRole();
});
</script>
<template>
<Drawer>
<ElContainer
class="absolute inset-0 flex h-full w-full flex-col overflow-hidden bg-card"
>
<FormModal @success="handlerAddRoleSuccess" />
<ElMain class="relative m-0 flex-1 overflow-hidden p-0">
<div class="absolute right-5 top-5 z-100 flex items-center">
<!-- 搜索输入框 -->
<ElInput
v-model="search"
class="w-60"
placeholder="请输入搜索的内容"
@keyup.enter="getActiveTabsRole"
>
<template #suffix>
<IconifyIcon
icon="lucide:search"
class="cursor-pointer"
@click="getActiveTabsRole"
/>
</template>
</ElInput>
<ElButton
v-if="activeTab === 'my-role'"
type="primary"
@click="handlerAddRole"
class="ml-5"
>
<IconifyIcon icon="lucide:user" class="mr-1.5" />
添加角色
</ElButton>
</div>
<!-- 标签页内容 -->
<ElTabs
v-model="activeTab"
class="relative h-full pb-4 pr-4"
@tab-click="handleTabsClick"
>
<ElTabPane
name="my-role"
class="flex h-full flex-col overflow-y-auto"
label="我的角色"
>
<RoleList
:loading="loading"
:role-list="myRoleList"
:show-more="true"
@on-delete="handlerCardDelete"
@on-edit="handlerCardEdit"
@on-use="handlerCardUse"
@on-page="handlerCardPage('my')"
/>
</ElTabPane>
<ElTabPane
name="public-role"
class="flex h-full flex-col overflow-y-auto"
label="公共角色"
>
<RoleCategoryList
:category-list="categoryList"
:active="activeCategory"
@on-category-click="handlerCategoryClick"
class="mx-6"
/>
<RoleList
:role-list="publicRoleList"
@on-delete="handlerCardDelete"
@on-edit="handlerCardEdit"
@on-use="handlerCardUse"
@on-page="handlerCardPage('public')"
class="mt-5"
loading
/>
</ElTabPane>
</ElTabs>
</ElMain>
</ElContainer>
</Drawer>
</template>

View File

@@ -0,0 +1,223 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api/system/user';
import { DICT_TYPE } from '@vben/constants';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 关联数据 */
let userList: SystemUserApi.User[] = [];
getSimpleUserList().then((data) => (userList = data));
/** 列表的搜索表单 */
export function useGridFormSchemaConversation(): VbenFormSchema[] {
return [
{
fieldName: 'userId',
label: '用户编号',
component: 'Input',
componentProps: {
placeholder: '请输入用户编号',
clearable: true,
},
},
{
fieldName: 'title',
label: '聊天标题',
component: 'Input',
componentProps: {
placeholder: '请输入聊天标题',
clearable: true,
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumnsConversation(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '对话编号',
fixed: 'left',
minWidth: 180,
},
{
field: 'title',
title: '对话标题',
minWidth: 180,
fixed: 'left',
},
{
title: '用户',
minWidth: 180,
field: 'userId',
formatter: ({ cellValue }) => {
if (cellValue === 0) {
return '系统';
}
return userList.find((user) => user.id === cellValue)?.nickname || '-';
},
},
{
field: 'roleName',
title: '角色',
minWidth: 180,
},
{
field: 'model',
title: '模型标识',
minWidth: 180,
},
{
field: 'messageCount',
title: '消息数',
minWidth: 180,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
field: 'temperature',
title: '温度参数',
minWidth: 80,
},
{
title: '回复数 Token 数',
field: 'maxTokens',
minWidth: 120,
},
{
title: '上下文数量',
field: 'maxContexts',
minWidth: 120,
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchemaMessage(): VbenFormSchema[] {
return [
{
fieldName: 'conversationId',
label: '对话编号',
component: 'Input',
componentProps: {
placeholder: '请输入对话编号',
clearable: true,
},
},
{
fieldName: 'userId',
label: '用户编号',
component: 'ApiSelect',
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
placeholder: '请选择用户编号',
clearable: true,
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumnsMessage(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '消息编号',
fixed: 'left',
minWidth: 180,
},
{
field: 'conversationId',
title: '对话编号',
minWidth: 180,
fixed: 'left',
},
{
title: '用户',
minWidth: 180,
field: 'userId',
formatter: ({ cellValue }) =>
userList.find((user) => user.id === cellValue)?.nickname || '-',
},
{
field: 'roleName',
title: '角色',
minWidth: 180,
},
{
field: 'type',
title: '消息类型',
minWidth: 100,
},
{
field: 'model',
title: '模型标识',
minWidth: 180,
},
{
field: 'content',
title: '消息内容',
minWidth: 300,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
field: 'replyId',
title: '回复消息编号',
minWidth: 180,
},
{
title: '携带上下文',
field: 'useContext',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.INFRA_BOOLEAN_STRING },
},
minWidth: 100,
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,29 @@
<script lang="ts" setup>
import { ref } from 'vue';
import { DocAlert, Page } from '@vben/common-ui';
import { ElTabs } from 'element-plus';
import ChatConversationList from './modules/conversation-list.vue';
import ChatMessageList from './modules/message-list.vue';
const activeTabName = ref('conversation');
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="AI 对话聊天" url="https://doc.iocoder.cn/ai/chat/" />
</template>
<ElTabs v-model:model-value="activeTabName">
<ElTabs.TabPane label="对话列表" name="conversation">
<ChatConversationList />
</ElTabs.TabPane>
<ElTabs.TabPane label="消息列表" name="message">
<ChatMessageList />
</ElTabs.TabPane>
</ElTabs>
</Page>
</template>

View File

@@ -0,0 +1,93 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiChatConversationApi } from '#/api/ai/chat/conversation';
import { Page } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteChatConversationByAdmin,
getChatConversationPage,
} from '#/api/ai/chat/conversation';
import { $t } from '#/locales';
import {
useGridColumnsConversation,
useGridFormSchemaConversation,
} from '../data';
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 删除对话 */
async function handleDelete(row: AiChatConversationApi.ChatConversation) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteChatConversationByAdmin(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchemaConversation(),
},
gridOptions: {
columns: useGridColumnsConversation(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getChatConversationPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiChatConversationApi.ChatConversation>,
});
</script>
<template>
<Page auto-content-height>
<Grid table-title="对话列表">
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:chat-conversation:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.id]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,90 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiChatConversationApi } from '#/api/ai/chat/conversation';
import { Page } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteChatMessageByAdmin,
getChatMessagePage,
} from '#/api/ai/chat/message';
import { $t } from '#/locales';
import { useGridColumnsMessage, useGridFormSchemaMessage } from '../data';
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 删除消息 */
async function handleDelete(row: AiChatConversationApi.ChatConversation) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteChatMessageByAdmin(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchemaMessage(),
},
gridOptions: {
columns: useGridColumnsMessage(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getChatMessagePage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiChatConversationApi.ChatConversation>,
});
</script>
<template>
<Page auto-content-height>
<Grid table-title="消息列表">
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:chat-message:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.id]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,128 @@
<script lang="ts" setup>
import type { AiImageApi } from '#/api/ai/image';
import type { AiModelModelApi } from '#/api/ai/model/model';
import { nextTick, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { AiModelTypeEnum, AiPlatformEnum } from '@vben/constants';
import { ElSegmented } from 'element-plus';
import { getModelSimpleList } from '#/api/ai/model/model';
import Common from './modules/common/index.vue';
import Dall3 from './modules/dall3/index.vue';
import ImageList from './modules/list.vue';
import Midjourney from './modules/midjourney/index.vue';
import StableDiffusion from './modules/stable-diffusion/index.vue';
const imageListRef = ref<any>(); // image 列表 ref
const dall3Ref = ref<any>(); // dall3(openai) ref
const midjourneyRef = ref<any>(); // midjourney ref
const stableDiffusionRef = ref<any>(); // stable diffusion ref
const commonRef = ref<any>(); // stable diffusion ref
const selectPlatform = ref('common'); // 选中的平台
const platformOptions = [
{
label: '通用',
value: 'common',
},
{
label: 'DALL3 绘画',
value: AiPlatformEnum.OPENAI,
},
{
label: 'MJ 绘画',
value: AiPlatformEnum.MIDJOURNEY,
},
{
label: 'SD 绘图',
value: AiPlatformEnum.STABLE_DIFFUSION,
},
];
const models = ref<AiModelModelApi.Model[]>([]); // 模型列表
/** 绘画 start */
async function handleDrawStart() {}
/** 绘画 complete */
async function handleDrawComplete() {
await imageListRef.value.getImageList();
}
/** 重新生成:将画图详情填充到对应平台 */
async function handleRegeneration(image: AiImageApi.Image) {
// 切换平台
selectPlatform.value = image.platform;
// 根据不同平台填充 image
await nextTick();
switch (image.platform) {
case AiPlatformEnum.MIDJOURNEY: {
midjourneyRef.value.settingValues(image);
break;
}
case AiPlatformEnum.OPENAI: {
dall3Ref.value.settingValues(image);
break;
}
case AiPlatformEnum.STABLE_DIFFUSION: {
stableDiffusionRef.value.settingValues(image);
break;
}
// No default
}
// TODO @fan貌似 other 重新设置不行?
}
/** 组件挂载的时候 */
onMounted(async () => {
// 获取模型列表
models.value = await getModelSimpleList(AiModelTypeEnum.IMAGE);
});
</script>
<template>
<Page auto-content-height>
<div class="absolute inset-0 m-4 flex h-full w-full flex-row">
<div class="left-0 mr-4 flex w-96 flex-col rounded-lg bg-card p-4">
<div class="flex justify-center">
<ElSegmented v-model="selectPlatform" :options="platformOptions" />
</div>
<div class="mt-8 h-full overflow-y-auto">
<Common
v-if="selectPlatform === 'common'"
ref="commonRef"
:models="models"
@on-draw-complete="handleDrawComplete"
/>
<Dall3
v-if="selectPlatform === AiPlatformEnum.OPENAI"
ref="dall3Ref"
:models="models"
@on-draw-start="handleDrawStart"
@on-draw-complete="handleDrawComplete"
/>
<Midjourney
v-if="selectPlatform === AiPlatformEnum.MIDJOURNEY"
ref="midjourneyRef"
:models="models"
/>
<StableDiffusion
v-if="selectPlatform === AiPlatformEnum.STABLE_DIFFUSION"
ref="stableDiffusionRef"
:models="models"
@on-draw-complete="handleDrawComplete"
/>
</div>
</div>
<div class="flex-1 bg-card">
<ImageList ref="imageListRef" @on-regeneration="handleRegeneration" />
</div>
</div>
</Page>
</template>

View File

@@ -0,0 +1,136 @@
<script setup lang="ts">
import type { PropType } from 'vue';
import type { AiImageApi } from '#/api/ai/image';
import { onMounted, ref, toRefs, watch } from 'vue';
import { confirm } from '@vben/common-ui';
import { AiImageStatusEnum } from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { ElButton, ElCard, ElImage, ElMessage } from 'element-plus';
const props = defineProps({
detail: {
type: Object as PropType<AiImageApi.Image>,
default: () => ({}),
},
});
const emits = defineEmits(['onBtnClick', 'onMjBtnClick']);
const cardImageRef = ref<any>(); // 卡片 image ref
/** 处理点击事件 */
async function handleButtonClick(type: string, detail: AiImageApi.Image) {
emits('onBtnClick', type, detail);
}
/** 处理 Midjourney 按钮点击事件 */
async function handleMidjourneyBtnClick(
button: AiImageApi.ImageMidjourneyButtons,
) {
await confirm(`确认操作 "${button.label} ${button.emoji}" ?`);
emits('onMjBtnClick', button, props.detail);
}
/** 监听详情 */
const { detail } = toRefs(props);
watch(detail, async (newVal) => {
await handleLoading(newVal.status);
});
const loading = ref();
/** 处理加载状态 */
async function handleLoading(status: number) {
// 情况一:如果是生成中,则设置加载中的 loading
if (status === AiImageStatusEnum.IN_PROGRESS) {
loading.value = ElMessage({
message: `生成中...`,
type: 'info',
});
} else {
// 情况二:如果已经生成结束,则移除 loading
if (loading.value) {
setTimeout(() => loading.value.close(), 100);
}
}
}
/** 初始化 */
onMounted(async () => {
await handleLoading(props.detail.status);
});
</script>
<template>
<ElCard class="relative flex h-auto w-80 flex-col rounded-lg">
<!-- 图片操作区 -->
<div class="flex flex-row justify-between">
<div>
<ElButton v-if="detail?.status === AiImageStatusEnum.IN_PROGRESS">
生成中
</ElButton>
<ElButton v-else-if="detail?.status === AiImageStatusEnum.SUCCESS">
已完成
</ElButton>
<ElButton
type="danger"
v-else-if="detail?.status === AiImageStatusEnum.FAIL"
>
异常
</ElButton>
</div>
<div class="flex">
<ElButton
class="m-0 p-2"
text
@click="handleButtonClick('download', detail)"
>
<IconifyIcon icon="lucide:download" />
</ElButton>
<ElButton
class="m-0 p-2"
text
@click="handleButtonClick('regeneration', detail)"
>
<IconifyIcon icon="lucide:refresh-cw" />
</ElButton>
<ElButton
class="m-0 p-2"
text
@click="handleButtonClick('delete', detail)"
>
<IconifyIcon icon="lucide:trash" />
</ElButton>
<ElButton
class="m-0 p-2"
text
@click="handleButtonClick('more', detail)"
>
<IconifyIcon icon="lucide:ellipsis-vertical" />
</ElButton>
</div>
</div>
<!-- 图片展示区域 -->
<div class="mt-5 h-72 flex-1 overflow-hidden" ref="cardImageRef">
<ElImage class="w-full rounded-lg" :src="detail?.picUrl" />
<div v-if="detail?.status === AiImageStatusEnum.FAIL">
{{ detail?.errorMessage }}
</div>
</div>
<!-- Midjourney 专属操作按钮 -->
<div class="mt-2 flex w-full flex-wrap justify-start">
<ElButton
size="small"
v-for="(button, index) in detail?.buttons"
:key="index"
class="m-2 ml-0 min-w-10"
@click="handleMidjourneyBtnClick(button)"
>
{{ button.label }}{{ button.emoji }}
</ElButton>
</div>
</ElCard>
</template>

View File

@@ -0,0 +1,226 @@
<!-- dall3 -->
<script setup lang="ts">
import type { AiImageApi } from '#/api/ai/image';
import type { AiModelModelApi } from '#/api/ai/model/model';
import { ref, watch } from 'vue';
import { confirm } from '@vben/common-ui';
import {
AiPlatformEnum,
ImageHotWords,
OtherPlatformEnum,
} from '@vben/constants';
import {
ElButton,
ElInputNumber,
ElOption,
ElSelect,
ElSpace,
} from 'element-plus';
import { drawImage } from '#/api/ai/image';
const props = defineProps({
models: {
type: Array<AiModelModelApi.Model>,
default: () => [] as AiModelModelApi.Model[],
},
}); // 接收父组件传入的模型列表
const emits = defineEmits(['onDrawStart', 'onDrawComplete']);
const drawIn = ref<boolean>(false); // 生成中
const selectHotWord = ref<string>(''); // 选中的热词
const prompt = ref<string>(''); // 提示词
const width = ref<number>(512); // 图片宽度
const height = ref<number>(512); // 图片高度
const otherPlatform = ref<string>(AiPlatformEnum.TONG_YI); // 平台
const platformModels = ref<AiModelModelApi.Model[]>([]); // 模型列表
const modelId = ref<number>(); // 选中的模型
/** 选择热词 */
async function handleHotWordClick(hotWord: string) {
// 情况一:取消选中
if (selectHotWord.value === hotWord) {
selectHotWord.value = '';
return;
}
// 情况二:选中
selectHotWord.value = hotWord; // 选中
prompt.value = hotWord; // 替换提示词
}
/** 图片生成 */
async function handleGenerateImage() {
// 二次确认
await confirm(`确认生成内容?`);
try {
// 加载中
drawIn.value = true;
// 回调
emits('onDrawStart', otherPlatform.value);
// 发送请求
const form = {
platform: otherPlatform.value,
modelId: modelId.value, // 模型
prompt: prompt.value, // 提示词
width: width.value, // 图片宽度
height: height.value, // 图片高度
options: {},
} as unknown as AiImageApi.ImageDrawReqVO;
await drawImage(form);
} finally {
// 回调
emits('onDrawComplete', otherPlatform.value);
// 加载结束
drawIn.value = false;
}
}
/** 填充值 */
async function settingValues(detail: AiImageApi.Image) {
prompt.value = detail.prompt;
width.value = detail.width;
height.value = detail.height;
}
/** 平台切换 */
async function handlerPlatformChange(platform: any) {
// 根据选择的平台筛选模型
platformModels.value = props.models.filter(
(item: AiModelModelApi.Model) => item.platform === platform,
);
// 切换平台,默认选择一个模型
modelId.value =
platformModels.value.length > 0 && platformModels.value[0]
? platformModels.value[0].id
: undefined;
}
/** 监听 models 变化 */
watch(
() => props.models,
() => {
handlerPlatformChange(otherPlatform.value);
},
{ immediate: true, deep: true },
);
defineExpose({ settingValues });
</script>
<template>
<div class="prompt">
<b>画面描述</b>
<p>建议使用"形容词 + 动词 + 风格"的格式使用""隔开</p>
<el-input
v-model="prompt"
:maxlength="1024"
:rows="5"
type="textarea"
class="mt-4 w-full"
placeholder="例如:童话里的小屋应该是什么样子?"
show-word-limit
/>
</div>
<div class="mt-8 flex flex-col">
<div>
<b>随机热词</b>
</div>
<ElSpace wrap class="mt-4 flex flex-wrap justify-start">
<ElButton
round
class="m-0"
:type="selectHotWord === hotWord ? 'primary' : 'default'"
v-for="hotWord in ImageHotWords"
:key="hotWord"
@click="handleHotWordClick(hotWord)"
>
{{ hotWord }}
</ElButton>
</ElSpace>
</div>
<div class="mt-8">
<div>
<b>平台</b>
</div>
<ElSpace wrap class="mt-4 w-full">
<ElSelect
v-model="otherPlatform"
placeholder="Select"
size="large"
class="!w-80"
@change="handlerPlatformChange"
>
<ElOption
v-for="item in OtherPlatformEnum"
:key="item.key"
:value="item.key"
:label="item.name"
>
{{ item.name }}
</ElOption>
</ElSelect>
</ElSpace>
</div>
<div class="mt-8">
<div>
<b>模型</b>
</div>
<ElSpace wrap class="mt-4 w-full">
<ElSelect
v-model="modelId"
placeholder="Select"
size="large"
class="!w-80"
>
<ElOption
v-for="item in platformModels"
:key="item.id"
:value="item.id"
:label="item.name"
>
{{ item.name }}
</ElOption>
</ElSelect>
</ElSpace>
</div>
<div class="mt-8">
<div>
<b>图片尺寸</b>
</div>
<div class="mt-4 flex items-center gap-2">
<ElInputNumber
v-model="width"
placeholder="图片宽度"
controls-position="right"
class="!w-32"
/>
<span class="mx-2">×</span>
<ElInputNumber
v-model="height"
placeholder="图片高度"
controls-position="right"
class="!w-32"
/>
</div>
</div>
<div class="mt-12 flex justify-center">
<ElButton
type="primary"
size="large"
round
:loading="drawIn"
:disabled="prompt.length === 0"
@click="handleGenerateImage"
>
{{ drawIn ? '生成中' : '生成内容' }}
</ElButton>
</div>
</template>

View File

@@ -0,0 +1,260 @@
<!-- dall3 -->
<script setup lang="ts">
import type { ImageModel, ImageSize } from '@vben/constants';
import type { AiImageApi } from '#/api/ai/image';
import type { AiModelModelApi } from '#/api/ai/model/model';
import { ref } from 'vue';
import { confirm } from '@vben/common-ui';
import {
AiPlatformEnum,
Dall3Models,
Dall3SizeList,
Dall3StyleList,
ImageHotWords,
} from '@vben/constants';
import { ElButton, ElImage, ElMessage, ElSpace } from 'element-plus';
import { drawImage } from '#/api/ai/image';
const props = defineProps({
models: {
type: Array<AiModelModelApi.Model>,
default: () => [] as AiModelModelApi.Model[],
},
}); // 接收父组件传入的模型列表
const emits = defineEmits(['onDrawStart', 'onDrawComplete']);
const prompt = ref<string>(''); // 提示词
const drawIn = ref<boolean>(false); // 生成中
const selectHotWord = ref<string>(''); // 选中的热词
const selectModel = ref<string>('dall-e-3'); // 模型
const selectSize = ref<string>('1024x1024'); // 选中 size
const style = ref<string>('vivid'); // style 样式
/** 选择热词 */
async function handleHotWordClick(hotWord: string) {
// 情况一:取消选中
if (selectHotWord.value === hotWord) {
selectHotWord.value = '';
return;
}
// 情况二:选中
selectHotWord.value = hotWord;
prompt.value = hotWord;
}
/** 选择 model 模型 */
async function handleModelClick(model: ImageModel) {
selectModel.value = model.key;
// 可以在这里添加模型特定的处理逻辑
// 例如,如果未来需要根据不同模型设置不同参数
if (model.key === 'dall-e-3') {
// DALL-E-3 模型特定的处理
style.value = 'vivid'; // 默认设置vivid风格
} else if (model.key === 'dall-e-2') {
// DALL-E-2 模型特定的处理
style.value = 'natural'; // 如果有其他DALL-E-2适合的默认风格
}
// 更新其他相关参数
// 例如可以默认选择最适合当前模型的尺寸
const recommendedSize = Dall3SizeList.find(
(size) =>
(model.key === 'dall-e-3' && size.key === '1024x1024') ||
(model.key === 'dall-e-2' && size.key === '512x512'),
);
if (recommendedSize) {
selectSize.value = recommendedSize.key;
}
}
/** 选择 style 样式 */
async function handleStyleClick(imageStyle: ImageModel) {
style.value = imageStyle.key;
}
/** 选择 size 大小 */
async function handleSizeClick(imageSize: ImageSize) {
selectSize.value = imageSize.key;
}
/** 图片生产 */
async function handleGenerateImage() {
// 从 models 中查找匹配的模型
const matchedModel = props.models.find(
(item) =>
item.model === selectModel.value &&
item.platform === AiPlatformEnum.OPENAI,
);
if (!matchedModel) {
ElMessage.error('该模型不可用,请选择其它模型');
return;
}
// 二次确认
await confirm(`确认生成内容?`);
try {
// 加载中
drawIn.value = true;
// 回调
emits('onDrawStart', AiPlatformEnum.OPENAI);
const imageSize = Dall3SizeList.find(
(item) => item.key === selectSize.value,
) as ImageSize;
const form = {
platform: AiPlatformEnum.OPENAI,
prompt: prompt.value, // 提示词
modelId: matchedModel.id, // 使用匹配到的模型
style: style.value, // 图像生成的风格
width: imageSize.width, // size 不能为空
height: imageSize.height, // size 不能为空
options: {
style: style.value, // 图像生成的风格
},
} as AiImageApi.ImageDrawReqVO;
// 发送请求
await drawImage(form);
} finally {
// 回调
emits('onDrawComplete', AiPlatformEnum.OPENAI);
// 加载结束
drawIn.value = false;
}
}
/** 填充值 */
async function settingValues(detail: AiImageApi.Image) {
prompt.value = detail.prompt;
selectModel.value = detail.model;
style.value = detail.options?.style;
const imageSize = Dall3SizeList.find(
(item) => item.key === `${detail.width}x${detail.height}`,
) as ImageSize;
await handleSizeClick(imageSize);
}
/** 暴露组件方法 */
defineExpose({ settingValues });
</script>
<template>
<div class="prompt">
<b>画面描述</b>
<p>建议使用"形容词 + 动词 + 风格"的格式使用""隔开</p>
<el-input
v-model="prompt"
:maxlength="1024"
:rows="5"
type="textarea"
class="mt-4 w-full"
placeholder="例如:童话里的小屋应该是什么样子?"
show-word-limit
/>
</div>
<div class="mt-8 flex flex-col">
<div><b>随机热词</b></div>
<ElSpace wrap class="mt-4 flex flex-wrap justify-start">
<ElButton
round
class="m-0"
:type="selectHotWord === hotWord ? 'primary' : 'default'"
v-for="hotWord in ImageHotWords"
:key="hotWord"
@click="handleHotWordClick(hotWord)"
>
{{ hotWord }}
</ElButton>
</ElSpace>
</div>
<div class="mt-8">
<div><b>模型选择</b></div>
<ElSpace wrap class="mt-4 flex flex-wrap gap-2">
<div
class="flex w-28 cursor-pointer flex-col items-center overflow-hidden rounded-lg border-2"
:class="[
selectModel === model.key ? '!border-blue-500' : 'border-transparent',
]"
v-for="model in Dall3Models"
:key="model.key"
@click="handleModelClick(model)"
>
<ElImage
:preview-src-list="[]"
:src="model.image"
fit="contain"
class="w-full"
/>
<div class="text-sm font-bold text-gray-600">
{{ model.name }}
</div>
</div>
</ElSpace>
</div>
<div class="mt-8">
<div><b>风格选择</b></div>
<ElSpace wrap class="mt-4 flex flex-wrap gap-2">
<div
class="flex w-28 cursor-pointer flex-col items-center overflow-hidden rounded-lg border-2"
:class="[
style === imageStyle.key ? 'border-blue-500' : 'border-transparent',
]"
v-for="imageStyle in Dall3StyleList"
:key="imageStyle.key"
>
<ElImage
:preview-src-list="[]"
:src="imageStyle.image"
fit="contain"
@click="handleStyleClick(imageStyle)"
/>
<div class="text-sm font-bold text-gray-600">
{{ imageStyle.name }}
</div>
</div>
</ElSpace>
</div>
<div class="mt-8 w-full">
<div><b>画面比例</b></div>
<ElSpace wrap class="mt-5 flex w-full flex-wrap gap-2">
<div
class="flex cursor-pointer flex-col items-center"
v-for="imageSize in Dall3SizeList"
:key="imageSize.key"
@click="handleSizeClick(imageSize)"
>
<div
class="flex h-12 w-12 flex-col items-center justify-center rounded-lg border bg-card p-0"
:class="[
selectSize === imageSize.key ? 'border-blue-500' : 'border-white',
]"
>
<div :style="imageSize.style"></div>
</div>
<div class="text-sm font-bold text-gray-600">
{{ imageSize.name }}
</div>
</div>
</ElSpace>
</div>
<div class="mt-12 flex justify-center">
<ElButton
type="primary"
size="large"
round
:loading="drawIn"
:disabled="prompt.length === 0"
@click="handleGenerateImage"
>
{{ drawIn ? '生成中' : '生成内容' }}
</ElButton>
</div>
</template>

View File

@@ -0,0 +1,206 @@
<script setup lang="ts">
import type { AiImageApi } from '#/api/ai/image';
import { ref, toRefs, watch } from 'vue';
import {
AiPlatformEnum,
Dall3StyleList,
StableDiffusionClipGuidancePresets,
StableDiffusionSamplers,
StableDiffusionStylePresets,
} from '@vben/constants';
import { formatDateTime } from '@vben/utils';
import { ElImage } from 'element-plus';
import { getImageMy } from '#/api/ai/image';
const props = defineProps({
id: {
type: Number,
required: true,
},
});
const detail = ref<AiImageApi.Image>({} as AiImageApi.Image); // 图片详细信息
/** 获取图片详情 */
async function getImageDetail(id: number) {
detail.value = await getImageMy(id);
}
const { id } = toRefs(props);
watch(
id,
async (newVal) => {
if (newVal) {
await getImageDetail(newVal);
}
},
{ immediate: true },
);
</script>
<template>
<div class="mb-5 w-full overflow-hidden break-words">
<div class="mt-2">
<ElImage class="rounded-lg" :src="detail?.picUrl" />
</div>
</div>
<!-- 时间 -->
<div class="mb-5 w-full overflow-hidden break-words">
<div class="text-lg font-bold">时间</div>
<div class="mt-2">
<div>提交时间{{ formatDateTime(detail.createTime) }}</div>
<div>生成时间{{ formatDateTime(detail.finishTime) }}</div>
</div>
</div>
<!-- 模型 -->
<div class="mb-5 w-full overflow-hidden break-words">
<div class="text-lg font-bold">模型</div>
<div class="mt-2">
{{ detail.model }}({{ detail.height }}x{{ detail.width }})
</div>
</div>
<!-- 提示词 -->
<div class="mb-5 w-full overflow-hidden break-words">
<div class="text-lg font-bold">提示词</div>
<div class="mt-2">
{{ detail.prompt }}
</div>
</div>
<!-- 图片地址 -->
<div class="mb-5 w-full overflow-hidden break-words">
<div class="text-lg font-bold">图片地址</div>
<div class="mt-2">
{{ detail.picUrl }}
</div>
</div>
<!-- StableDiffusion 专属 -->
<div
v-if="
detail.platform === AiPlatformEnum.STABLE_DIFFUSION &&
detail?.options?.sampler
"
class="mb-5 w-full overflow-hidden break-words"
>
<div class="text-lg font-bold">采样方法</div>
<div class="mt-2">
{{
StableDiffusionSamplers.find(
(item) => item.key === detail?.options?.sampler,
)?.name
}}
</div>
</div>
<div
v-if="
detail.platform === AiPlatformEnum.STABLE_DIFFUSION &&
detail?.options?.clipGuidancePreset
"
class="mb-5 w-full overflow-hidden break-words"
>
<div class="text-lg font-bold">CLIP</div>
<div class="mt-2">
{{
StableDiffusionClipGuidancePresets.find(
(item) => item.key === detail?.options?.clipGuidancePreset,
)?.name
}}
</div>
</div>
<div
v-if="
detail.platform === AiPlatformEnum.STABLE_DIFFUSION &&
detail?.options?.stylePreset
"
class="mb-5 w-full overflow-hidden break-words"
>
<div class="text-lg font-bold">风格</div>
<div class="mt-2">
{{
StableDiffusionStylePresets.find(
(item) => item.key === detail?.options?.stylePreset,
)?.name
}}
</div>
</div>
<div
v-if="
detail.platform === AiPlatformEnum.STABLE_DIFFUSION &&
detail?.options?.steps
"
class="mb-5 w-full overflow-hidden break-words"
>
<div class="text-lg font-bold">迭代步数</div>
<div class="mt-2">{{ detail?.options?.steps }}</div>
</div>
<div
v-if="
detail.platform === AiPlatformEnum.STABLE_DIFFUSION &&
detail?.options?.scale
"
class="mb-5 w-full overflow-hidden break-words"
>
<div class="text-lg font-bold">引导系数</div>
<div class="mt-2">{{ detail?.options?.scale }}</div>
</div>
<div
v-if="
detail.platform === AiPlatformEnum.STABLE_DIFFUSION &&
detail?.options?.seed
"
class="mb-5 w-full overflow-hidden break-words"
>
<div class="text-lg font-bold">随机因子</div>
<div class="mt-2">{{ detail?.options?.seed }}</div>
</div>
<!-- Dall3 专属 -->
<div
v-if="detail.platform === AiPlatformEnum.OPENAI && detail?.options?.style"
class="mb-5 w-full overflow-hidden break-words"
>
<div class="text-lg font-bold">风格选择</div>
<div class="mt-2">
{{
Dall3StyleList.find((item) => item.key === detail?.options?.style)?.name
}}
</div>
</div>
<!-- Midjourney 专属 -->
<div
v-if="
detail.platform === AiPlatformEnum.MIDJOURNEY && detail?.options?.version
"
class="mb-5 w-full overflow-hidden break-words"
>
<div class="text-lg font-bold">模型版本</div>
<div class="mt-2">{{ detail?.options?.version }}</div>
</div>
<div
v-if="
detail.platform === AiPlatformEnum.MIDJOURNEY &&
detail?.options?.referImageUrl
"
class="mb-5 w-full overflow-hidden break-words"
>
<div class="text-lg font-bold">参考图</div>
<div class="mt-2">
<ElImage :src="detail.options.referImageUrl" />
</div>
</div>
</template>

View File

@@ -0,0 +1,222 @@
<script setup lang="ts">
import type { AiImageApi } from '#/api/ai/image';
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { confirm, useVbenDrawer } from '@vben/common-ui';
import { AiImageStatusEnum } from '@vben/constants';
import { downloadFileFromImageUrl } from '@vben/utils';
import { useDebounceFn } from '@vueuse/core';
import { ElButton, ElCard, ElMessage, ElPagination } from 'element-plus';
import {
deleteImageMy,
getImageListMyByIds,
getImagePageMy,
midjourneyAction,
} from '#/api/ai/image';
import ImageCard from './card.vue';
import ImageDetail from './detail.vue';
const emits = defineEmits(['onRegeneration']);
const router = useRouter();
const [Drawer, drawerApi] = useVbenDrawer({
title: '图片详情',
footer: false,
});
const queryParams = reactive({
pageNo: 1,
pageSize: 10,
}); // 图片分页相关的参数
const pageTotal = ref<number>(0); // page size
const imageList = ref<AiImageApi.Image[]>([]); // image 列表
const imageListRef = ref<any>(); // ref
const inProgressImageMap = ref<{}>({}); // 监听的 image 映射一般是生成中需要轮询key 为 image 编号value 为 image
const inProgressTimer = ref<any>(); // 生成中的 image 定时器,轮询生成进展
const showImageDetailId = ref<number>(0); // 图片详情的图片编号
/** 处理查看绘图作品 */
function handleViewPublic() {
router.push({
name: 'AiImageSquare',
});
}
/** 查看图片的详情 */
async function handleDetailOpen() {
drawerApi.open();
}
/** 获得 image 图片列表 */
async function getImageList() {
const loading = ElMessage({
message: `加载中...`,
type: 'info',
duration: 0,
});
try {
// 1. 加载图片列表
const { list, total } = await getImagePageMy(queryParams);
imageList.value = list;
pageTotal.value = total;
// 2. 计算需要轮询的图片
const newWatImages: any = {};
imageList.value.forEach((item: any) => {
if (item.status === AiImageStatusEnum.IN_PROGRESS) {
newWatImages[item.id] = item;
}
});
inProgressImageMap.value = newWatImages;
} finally {
// 关闭正在"加载中"的 Loading
loading.close();
}
}
const debounceGetImageList = useDebounceFn(getImageList, 80);
/** 轮询生成中的 image 列表 */
async function refreshWatchImages() {
const imageIds = Object.keys(inProgressImageMap.value).map(Number);
if (imageIds.length === 0) {
return;
}
const list = (await getImageListMyByIds(imageIds)) as AiImageApi.Image[];
const newWatchImages: any = {};
list.forEach((image) => {
if (image.status === AiImageStatusEnum.IN_PROGRESS) {
newWatchImages[image.id] = image;
} else {
const index = imageList.value.findIndex(
(oldImage) => image.id === oldImage.id,
);
if (index !== -1) {
// 更新 imageList
imageList.value[index] = image;
}
}
});
inProgressImageMap.value = newWatchImages;
}
/** 图片的点击事件 */
async function handleImageButtonClick(
type: string,
imageDetail: AiImageApi.Image,
) {
// 详情
if (type === 'more') {
showImageDetailId.value = imageDetail.id;
await handleDetailOpen();
return;
}
// 删除
if (type === 'delete') {
await confirm(`是否删除照片?`);
await deleteImageMy(imageDetail.id);
await getImageList();
ElMessage.success('删除成功!');
return;
}
// 下载
if (type === 'download') {
await downloadFileFromImageUrl({
fileName: imageDetail.model,
source: imageDetail.picUrl,
});
return;
}
// 重新生成
if (type === 'regeneration') {
emits('onRegeneration', imageDetail);
}
}
/** 处理 Midjourney 按钮点击事件 */
async function handleImageMidjourneyButtonClick(
button: AiImageApi.ImageMidjourneyButtons,
imageDetail: AiImageApi.Image,
) {
// 1. 构建 params 参数
const data = {
id: imageDetail.id,
customId: button.customId,
} as AiImageApi.ImageMidjourneyAction;
// 2. 发送 action
await midjourneyAction(data);
// 3. 刷新列表
await getImageList();
}
defineExpose({ getImageList });
/** 组件挂在的时候 */
onMounted(async () => {
// 获取 image 列表
await getImageList();
// 自动刷新 image 列表
inProgressTimer.value = setInterval(async () => {
await refreshWatchImages();
}, 1000 * 3);
});
/** 组件取消挂在的时候 */
onUnmounted(async () => {
if (inProgressTimer.value) {
clearInterval(inProgressTimer.value);
}
});
</script>
<template>
<Drawer class="w-2/5">
<ImageDetail :id="showImageDetailId" />
</Drawer>
<ElCard
class="flex h-full w-full flex-col"
:body-style="{
margin: 0,
padding: 0,
height: '100%',
position: 'relative',
display: 'flex',
flexDirection: 'column',
}"
>
<template #header>
绘画任务
<ElButton @click="handleViewPublic">绘画作品</ElButton>
</template>
<div
class="flex flex-1 flex-wrap content-start overflow-y-auto p-3 pb-28 pt-5"
ref="imageListRef"
>
<ImageCard
v-for="image in imageList"
:key="image.id"
:detail="image"
@on-btn-click="handleImageButtonClick"
@on-mj-btn-click="handleImageMidjourneyButtonClick"
class="mb-3 mr-3"
/>
</div>
<div
class="sticky bottom-0 z-50 flex h-16 items-center justify-center bg-card shadow-sm"
>
<ElPagination
:total="pageTotal"
v-model:current-page="queryParams.pageNo"
v-model:page-size="queryParams.pageSize"
:page-sizes="[10, 20, 30, 40, 50]"
layout="total, sizes, prev, pager, next, jumper"
@size-change="debounceGetImageList"
@current-change="debounceGetImageList"
/>
</div>
</ElCard>
</template>

View File

@@ -0,0 +1,257 @@
<!-- dall3 -->
<script setup lang="ts">
import type { ImageModel, ImageSize } from '@vben/constants';
import type { AiImageApi } from '#/api/ai/image';
import type { AiModelModelApi } from '#/api/ai/model/model';
import { ref } from 'vue';
import { confirm } from '@vben/common-ui';
import {
AiPlatformEnum,
ImageHotWords,
MidjourneyModels,
MidjourneySizeList,
MidjourneyVersions,
NijiVersionList,
} from '@vben/constants';
import {
ElButton,
ElImage,
ElMessage,
ElOption,
ElSelect,
ElSpace,
} from 'element-plus';
import { midjourneyImagine } from '#/api/ai/image';
import { ImageUpload } from '#/components/upload';
const props = defineProps({
models: {
type: Array<AiModelModelApi.Model>,
default: () => [] as AiModelModelApi.Model[],
},
}); // 接收父组件传入的模型列表
const emits = defineEmits(['onDrawStart', 'onDrawComplete']);
const drawIn = ref<boolean>(false); // 生成中
const selectHotWord = ref<string>(''); // 选中的热词
const prompt = ref<string>(''); // 提示词
const referImageUrl = ref<any>(); // 参考图
const selectModel = ref<string>('midjourney'); // 选中的模型
const selectSize = ref<string>('1:1'); // 选中 size
const selectVersion = ref<any>('6.0'); // 选中的 version
const versionList = ref<any>(MidjourneyVersions); // version 列表
/** 选择热词 */
async function handleHotWordClick(hotWord: string) {
// 情况一:取消选中
if (selectHotWord.value === hotWord) {
selectHotWord.value = '';
return;
}
// 情况二:选中
selectHotWord.value = hotWord; // 选中
prompt.value = hotWord; // 设置提示次
}
/** 点击 size 尺寸 */
async function handleSizeClick(imageSize: ImageSize) {
selectSize.value = imageSize.key;
}
/** 点击 model 模型 */
async function handleModelClick(model: ImageModel) {
selectModel.value = model.key;
versionList.value =
model.key === 'niji' ? NijiVersionList : MidjourneyVersions;
selectVersion.value = versionList.value[0].value;
}
/** 图片生成 */
async function handleGenerateImage() {
// 从 models 中查找匹配的模型
const matchedModel = props.models.find(
(item) =>
item.model === selectModel.value &&
item.platform === AiPlatformEnum.MIDJOURNEY,
);
if (!matchedModel) {
ElMessage.error('该模型不可用,请选择其它模型');
return;
}
// 二次确认
await confirm(`确认生成内容?`);
try {
// 加载中
drawIn.value = true;
// 回调
emits('onDrawStart', AiPlatformEnum.MIDJOURNEY);
// 发送请求
const imageSize = MidjourneySizeList.find(
(item) => selectSize.value === item.key,
) as ImageSize;
const req = {
prompt: prompt.value,
modelId: matchedModel.id,
width: imageSize.width,
height: imageSize.height,
version: selectVersion.value,
referImageUrl: referImageUrl.value,
} as AiImageApi.ImageMidjourneyImagineReqVO;
await midjourneyImagine(req);
} finally {
// 回调
emits('onDrawComplete', AiPlatformEnum.MIDJOURNEY);
// 加载结束
drawIn.value = false;
}
}
/** 填充值 */
async function settingValues(detail: AiImageApi.Image) {
// 提示词
prompt.value = detail.prompt;
// image size
const imageSize = MidjourneySizeList.find(
(item) => item.key === `${detail.width}:${detail.height}`,
) as ImageSize;
selectSize.value = imageSize.key;
// 选中模型
const model = MidjourneyModels.find(
(item) => item.key === detail.options?.model,
) as ImageModel;
await handleModelClick(model);
// 版本
selectVersion.value = versionList.value.find(
(item: any) => item.value === detail.options?.version,
).value;
// image
referImageUrl.value = detail.options.referImageUrl;
}
/** 暴露组件方法 */
defineExpose({ settingValues });
</script>
<template>
<div class="prompt">
<b>画面描述</b>
<p>建议使用"形容词+动词+风格"的格式使用""隔开.</p>
<el-input
v-model="prompt"
:maxlength="1024"
:rows="5"
type="textarea"
class="mt-4 w-full"
placeholder="例如:童话里的小屋应该是什么样子?"
show-word-limit
/>
</div>
<div class="mt-8 flex flex-col">
<div><b>随机热词</b></div>
<ElSpace wrap class="mt-4 flex flex-wrap gap-2">
<ElButton
round
class="m-0"
:type="selectHotWord === hotWord ? 'primary' : 'default'"
v-for="hotWord in ImageHotWords"
:key="hotWord"
@click="handleHotWordClick(hotWord)"
>
{{ hotWord }}
</ElButton>
</ElSpace>
</div>
<div class="mt-8">
<div><b>尺寸</b></div>
<ElSpace wrap class="mt-4 flex w-full flex-wrap gap-2">
<div
class="flex cursor-pointer flex-col items-center overflow-hidden"
v-for="imageSize in MidjourneySizeList"
:key="imageSize.key"
@click="handleSizeClick(imageSize)"
>
<div
class="flex h-12 w-12 items-center justify-center rounded-lg border bg-card p-0"
:class="[
selectSize === imageSize.key ? 'border-blue-500' : 'border-white',
]"
>
<div :style="imageSize.style"></div>
</div>
<div class="text-sm font-bold text-gray-600">{{ imageSize.key }}</div>
</div>
</ElSpace>
</div>
<div class="mt-8">
<div><b>模型</b></div>
<ElSpace wrap class="mt-4 flex flex-wrap gap-2">
<div
v-for="model in MidjourneyModels"
:key="model.key"
class="flex max-w-40 cursor-pointer flex-col items-center overflow-hidden"
:class="[
selectModel === model.key
? 'rounded border-blue-500'
: 'border-transparent',
]"
>
<ElImage
:preview-src-list="[]"
:src="model.image"
fit="contain"
@click="handleModelClick(model)"
/>
<div class="text-sm font-bold text-gray-600">{{ model.name }}</div>
</div>
</ElSpace>
</div>
<div class="mt-8">
<div><b>版本</b></div>
<ElSpace wrap class="mt-5 flex w-full flex-wrap gap-2">
<ElSelect
v-model="selectVersion"
class="!w-80"
clearable
placeholder="请选择版本"
>
<ElOption
v-for="item in versionList"
:key="item.value"
:value="item.value"
:label="item.label"
>
{{ item.label }}
</ElOption>
</ElSelect>
</ElSpace>
</div>
<div class="mt-8">
<div><b>参考图</b></div>
<ElSpace wrap class="mt-4">
<ImageUpload v-model:value="referImageUrl" :show-description="false" />
</ElSpace>
</div>
<div class="mt-8 flex justify-center">
<ElButton
type="primary"
size="large"
round
:disabled="prompt.length === 0"
@click="handleGenerateImage"
>
{{ drawIn ? '生成中' : '生成内容' }}
</ElButton>
</div>
</template>

View File

@@ -0,0 +1,309 @@
<!-- dall3 -->
<script setup lang="ts">
import type { AiImageApi } from '#/api/ai/image';
import type { AiModelModelApi } from '#/api/ai/model/model';
import { ref } from 'vue';
import { alert, confirm } from '@vben/common-ui';
import {
AiPlatformEnum,
ImageHotEnglishWords,
StableDiffusionClipGuidancePresets,
StableDiffusionSamplers,
StableDiffusionStylePresets,
} from '@vben/constants';
import {
ElButton,
ElInputNumber,
ElMessage,
ElOption,
ElSelect,
ElSpace,
} from 'element-plus';
import { drawImage } from '#/api/ai/image';
const props = defineProps({
models: {
type: Array<AiModelModelApi.Model>,
default: () => [] as AiModelModelApi.Model[],
},
}); // 接收父组件传入的模型列表
const emits = defineEmits(['onDrawStart', 'onDrawComplete']);
function hasChinese(str: string) {
return /[\u4E00-\u9FA5]/.test(str);
}
// 定义属性
const drawIn = ref<boolean>(false); // 生成中
const selectHotWord = ref<string>(''); // 选中的热词
// 表单
const prompt = ref<string>(''); // 提示词
const width = ref<number>(512); // 图片宽度
const height = ref<number>(512); // 图片高度
const sampler = ref<string>('DDIM'); // 采样方法
const steps = ref<number>(20); // 迭代步数
const seed = ref<number>(42); // 控制生成图像的随机性
const scale = ref<number>(7.5); // 引导系数
const clipGuidancePreset = ref<string>('NONE'); // 文本提示相匹配的图像(clip_guidance_preset) 简称 CLIP
const stylePreset = ref<string>('3d-model'); // 风格
/** 选择热词 */
async function handleHotWordClick(hotWord: string) {
// 情况一:取消选中
if (selectHotWord.value === hotWord) {
selectHotWord.value = '';
return;
}
// 情况二:选中
selectHotWord.value = hotWord; // 选中
prompt.value = hotWord; // 替换提示词
}
/** 图片生成 */
async function handleGenerateImage() {
// 从 models 中查找匹配的模型
const selectModel = 'stable-diffusion-v1-6';
const matchedModel = props.models.find(
(item) =>
item.model === selectModel &&
item.platform === AiPlatformEnum.STABLE_DIFFUSION,
);
if (!matchedModel) {
ElMessage.error('该模型不可用,请选择其它模型');
return;
}
// 二次确认
if (hasChinese(prompt.value)) {
await alert('暂不支持中文!');
return;
}
await confirm(`确认生成内容?`);
try {
// 加载中
drawIn.value = true;
// 回调
emits('onDrawStart', AiPlatformEnum.STABLE_DIFFUSION);
// 发送请求
const form = {
modelId: matchedModel.id,
prompt: prompt.value, // 提示词
width: width.value, // 图片宽度
height: height.value, // 图片高度
options: {
seed: seed.value, // 随机种子
steps: steps.value, // 图片生成步数
scale: scale.value, // 引导系数
sampler: sampler.value, // 采样算法
clipGuidancePreset: clipGuidancePreset.value, // 文本提示相匹配的图像 CLIP
stylePreset: stylePreset.value, // 风格
},
} as unknown as AiImageApi.ImageDrawReqVO;
await drawImage(form);
} finally {
// 回调
emits('onDrawComplete', AiPlatformEnum.STABLE_DIFFUSION);
// 加载结束
drawIn.value = false;
}
}
/** 填充值 */
async function settingValues(detail: AiImageApi.Image) {
prompt.value = detail.prompt;
width.value = detail.width;
height.value = detail.height;
seed.value = detail.options?.seed;
steps.value = detail.options?.steps;
scale.value = detail.options?.scale;
sampler.value = detail.options?.sampler;
clipGuidancePreset.value = detail.options?.clipGuidancePreset;
stylePreset.value = detail.options?.stylePreset;
}
/** 暴露组件方法 */
defineExpose({ settingValues });
</script>
<template>
<div class="prompt">
<b>画面描述</b>
<p>建议使用"形容词 + 动词 + 风格"的格式使用""隔开</p>
<el-input
v-model="prompt"
:maxlength="1024"
:rows="5"
type="textarea"
class="mt-4 w-full"
placeholder="例如:童话里的小屋应该是什么样子?"
show-word-limit
/>
</div>
<!-- 热词区域 -->
<div class="mt-8 flex flex-col">
<div><b>随机热词</b></div>
<ElSpace wrap class="mt-4 flex flex-wrap gap-2">
<ElButton
round
class="m-0"
:type="selectHotWord === hotWord ? 'primary' : 'default'"
v-for="hotWord in ImageHotEnglishWords"
:key="hotWord"
@click="handleHotWordClick(hotWord)"
>
{{ hotWord }}
</ElButton>
</ElSpace>
</div>
<!-- 参数项采样方法 -->
<div class="mt-8">
<div><b>采样方法</b></div>
<ElSpace wrap class="mt-4 w-full">
<ElSelect
v-model="sampler"
placeholder="Select"
size="large"
class="!w-80"
>
<ElOption
v-for="item in StableDiffusionSamplers"
:key="item.key"
:value="item.key"
:label="item.name"
>
{{ item.name }}
</ElOption>
</ElSelect>
</ElSpace>
</div>
<!-- CLIP -->
<div class="mt-8">
<div><b>CLIP</b></div>
<ElSpace wrap class="mt-4 w-full">
<ElSelect
v-model="clipGuidancePreset"
placeholder="Select"
size="large"
class="!w-80"
>
<ElOption
v-for="item in StableDiffusionClipGuidancePresets"
:key="item.key"
:value="item.key"
:label="item.name"
>
{{ item.name }}
</ElOption>
</ElSelect>
</ElSpace>
</div>
<!-- 风格 -->
<div class="mt-8">
<div><b>风格</b></div>
<ElSpace wrap class="mt-4 w-full">
<ElSelect
v-model="stylePreset"
placeholder="Select"
size="large"
class="!w-80"
>
<ElOption
v-for="item in StableDiffusionStylePresets"
:key="item.key"
:label="item.name"
:value="item.key"
>
{{ item.name }}
</ElOption>
</ElSelect>
</ElSpace>
</div>
<!-- 图片尺寸 -->
<div class="mt-8">
<div><b>图片尺寸</b></div>
<ElSpace wrap class="mt-4 w-full">
<div class="flex items-center gap-2">
<ElInputNumber
v-model="width"
placeholder="图片宽度"
controls-position="right"
class="!w-32"
/>
</div>
<span class="mx-2">×</span>
<div class="flex items-center gap-2">
<ElInputNumber
v-model="height"
placeholder="图片高度"
controls-position="right"
class="!w-32"
/>
</div>
</ElSpace>
</div>
<!-- 迭代步数 -->
<div class="mt-8">
<div><b>迭代步数</b></div>
<ElSpace wrap class="mt-4 w-full">
<ElInputNumber
v-model="steps"
size="large"
class="!w-80"
placeholder="Please input"
controls-position="right"
/>
</ElSpace>
</div>
<!-- 引导系数 -->
<div class="mt-8">
<div><b>引导系数</b></div>
<ElSpace wrap class="mt-4 w-full">
<ElInputNumber
v-model="scale"
size="large"
class="!w-80"
placeholder="Please input"
controls-position="right"
/>
</ElSpace>
</div>
<!-- 随机因子 -->
<div class="mt-8">
<div><b>随机因子</b></div>
<ElSpace wrap class="mt-4 w-full">
<ElInputNumber
v-model="seed"
size="large"
class="!w-80"
placeholder="Please input"
controls-position="right"
/>
</ElSpace>
</div>
<!-- 生成按钮 -->
<div class="mt-12 flex justify-center">
<ElButton
type="primary"
size="large"
round
:loading="drawIn"
:disabled="prompt.length === 0"
@click="handleGenerateImage"
>
{{ drawIn ? '生成中' : '生成内容' }}
</ElButton>
</div>
</template>

View File

@@ -0,0 +1,180 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api/system/user';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
let userList: SystemUserApi.User[] = [];
async function getUserData() {
userList = await getSimpleUserList();
}
getUserData();
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'userId',
label: '用户编号',
component: 'ApiSelect',
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
placeholder: '请选择用户编号',
clearable: true,
},
},
{
fieldName: 'platform',
label: '平台',
component: 'Select',
componentProps: {
placeholder: '请选择平台',
clearable: true,
options: getDictOptions(DICT_TYPE.AI_PLATFORM, 'string'),
},
},
{
fieldName: 'status',
label: '绘画状态',
component: 'Select',
componentProps: {
placeholder: '请选择绘画状态',
clearable: true,
options: getDictOptions(DICT_TYPE.AI_IMAGE_STATUS, 'number'),
},
},
{
fieldName: 'publicStatus',
label: '是否发布',
component: 'Select',
componentProps: {
placeholder: '请选择是否发布',
clearable: true,
options: getDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING, 'boolean'),
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(
onPublicStatusChange?: (
newStatus: boolean,
row: any,
) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '编号',
minWidth: 180,
fixed: 'left',
},
{
field: 'picUrl',
title: '图片',
minWidth: 110,
fixed: 'left',
cellRender: {
name: 'CellImage',
},
},
{
field: 'userId',
title: '用户',
minWidth: 180,
formatter: ({ cellValue }) =>
userList.find((user) => user.id === cellValue)?.nickname || '-',
},
{
field: 'platform',
title: '平台',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_PLATFORM },
},
},
{
field: 'model',
title: '模型',
minWidth: 180,
},
{
field: 'status',
title: '绘画状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_IMAGE_STATUS },
},
},
{
minWidth: 100,
title: '是否发布',
field: 'publicStatus',
align: 'center',
cellRender: {
attrs: { beforeChange: onPublicStatusChange },
name: 'CellSwitch',
props: {
activeValue: true,
inactiveValue: false,
},
},
},
{
field: 'prompt',
title: '提示词',
minWidth: 180,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
field: 'width',
title: '宽度',
minWidth: 180,
},
{
field: 'height',
title: '高度',
minWidth: 180,
},
{
field: 'errorMessage',
title: '错误信息',
minWidth: 180,
},
{
field: 'taskId',
title: '任务编号',
minWidth: 180,
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,116 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiImageApi } from '#/api/ai/image';
import { confirm, DocAlert, Page } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteImage, getImagePage, updateImage } from '#/api/ai/image';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 删除图片 */
async function handleDelete(row: AiImageApi.Image) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteImage(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 修改是否发布 */
async function handleUpdatePublicStatusChange(
newStatus: boolean,
row: AiImageApi.Image,
): Promise<boolean | undefined> {
const text = newStatus ? '公开' : '私有';
return new Promise((resolve, reject) => {
confirm({
content: `确认要将该图片切换为【${text}】吗?`,
})
.then(async () => {
// 更新图片状态
await updateImage({
id: row.id,
publicStatus: newStatus,
});
// 提示并返回成功
ElMessage.success($t('ui.actionMessage.operationSuccess'));
resolve(true);
})
.catch(() => {
reject(new Error('取消操作'));
});
});
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(handleUpdatePublicStatusChange),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getImagePage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiImageApi.Image>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="AI 绘图创作" url="https://doc.iocoder.cn/ai/image/" />
</template>
<Grid table-title="绘画管理列表">
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:image:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.id]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,90 @@
<script setup lang="ts">
import type { AiImageApi } from '#/api/ai/image';
import { onMounted, reactive, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { useDebounceFn } from '@vueuse/core';
import { ElImage, ElInput, ElPagination } from 'element-plus';
import { getImagePageMy } from '#/api/ai/image';
const loading = ref(true); // 列表的加载中
const list = ref<AiImageApi.Image[]>([]); // 列表的数据
const total = ref(0); // 列表的总页数
const queryParams = reactive({
pageNo: 1,
pageSize: 10,
publicStatus: true,
prompt: undefined,
});
/** 查询列表 */
async function getList() {
loading.value = true;
try {
const data = await getImagePageMy(queryParams);
list.value = data.list;
total.value = data.total;
} finally {
loading.value = false;
}
}
const debounceGetList = useDebounceFn(getList, 80);
/** 搜索按钮操作 */
function handleQuery() {
queryParams.pageNo = 1;
getList();
}
/** 初始化 */
onMounted(async () => {
await getList();
});
</script>
<template>
<Page auto-content-height>
<div class="bg-card p-5">
<ElInput
v-model="queryParams.prompt"
class="mb-5 w-full"
size="large"
placeholder="请输入要搜索的内容"
@keyup.enter="handleQuery"
>
<template #suffix>
<IconifyIcon icon="lucide:search" class="cursor-pointer" />
</template>
</ElInput>
<div
class="grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-2.5 bg-card shadow-sm"
>
<div
v-for="item in list"
:key="item.id"
class="relative cursor-pointer overflow-hidden bg-card transition-transform duration-300 hover:scale-105"
>
<ElImage
:src="item.picUrl"
class="block h-auto w-full transition-transform duration-300 hover:scale-110"
/>
</div>
</div>
<!-- 分页 -->
<ElPagination
:total="total"
v-model:current-page="queryParams.pageNo"
v-model:page-size="queryParams.pageSize"
:page-sizes="[10, 20, 30, 40, 50]"
layout="total, sizes, prev, pager, next, jumper"
@size-change="debounceGetList"
@current-change="debounceGetList"
class="mt-5"
/>
</div>
</Page>
</template>

View File

@@ -0,0 +1,180 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiKnowledgeDocumentApi } from '#/api/ai/knowledge/document';
import { AiModelTypeEnum, CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { z } from '#/adapter/form';
import { getModelSimpleList } from '#/api/ai/model/model';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'name',
label: '知识库名称',
rules: 'required',
},
{
fieldName: 'description',
label: '知识库描述',
component: 'Textarea',
componentProps: {
rows: 3,
placeholder: '请输入知识库描述',
},
},
{
component: 'ApiSelect',
fieldName: 'embeddingModelId',
label: '向量模型',
componentProps: {
api: () => getModelSimpleList(AiModelTypeEnum.EMBEDDING),
labelField: 'name',
valueField: 'id',
allowClear: true,
placeholder: '请选择向量模型',
},
rules: 'required',
},
{
fieldName: 'topK',
label: '检索 topK',
component: 'InputNumber',
componentProps: {
placeholder: '请输入检索 topK',
min: 0,
max: 10,
controlsPosition: 'right',
class: '!w-full',
},
rules: 'required',
},
{
fieldName: 'similarityThreshold',
label: '检索相似度阈值',
component: 'InputNumber',
componentProps: {
placeholder: '请输入检索相似度阈值',
min: 0,
max: 1,
step: 0.01,
precision: 2,
controlsPosition: 'right',
class: '!w-full',
},
rules: 'required',
},
{
fieldName: 'status',
label: '是否启用',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '文件名称',
component: 'Input',
componentProps: {
placeholder: '请输入文件名称',
allowClear: true,
},
},
{
fieldName: 'status',
label: '是否启用',
component: 'Select',
componentProps: {
placeholder: '请选择是否启用',
allowClear: true,
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
},
];
}
/** 列表的字段 */
export function useGridColumns(
onStatusChange?: (
newStatus: number,
row: AiKnowledgeDocumentApi.KnowledgeDocument,
) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '文档编号',
minWidth: 100,
},
{
field: 'name',
title: '文件名称',
minWidth: 200,
},
{
field: 'contentLength',
title: '字符数',
minWidth: 100,
},
{
field: 'tokens',
title: 'Token 数',
minWidth: 100,
},
{
field: 'segmentMaxTokens',
title: '分片最大 Token 数',
minWidth: 150,
},
{
field: 'retrievalCount',
title: '召回次数',
minWidth: 100,
},
{
field: 'status',
title: '是否启用',
minWidth: 100,
align: 'center',
cellRender: {
attrs: { beforeChange: onStatusChange },
name: 'CellSwitch',
props: {
activeValue: CommonStatusEnum.ENABLE,
inactiveValue: CommonStatusEnum.DISABLE,
},
},
},
{
field: 'createTime',
title: '上传时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
minWidth: 150,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,200 @@
<script setup lang="ts">
import {
getCurrentInstance,
onBeforeUnmount,
onMounted,
provide,
ref,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { IconifyIcon } from '@vben/icons';
import { ElCard } from 'element-plus';
import { getKnowledgeDocument } from '#/api/ai/knowledge/document';
import ProcessStep from './modules/process-step.vue';
import SplitStep from './modules/split-step.vue';
import UploadStep from './modules/upload-step.vue';
const route = useRoute();
const router = useRouter();
const uploadDocumentRef = ref();
const documentSegmentRef = ref();
const processCompleteRef = ref();
const currentStep = ref(0); // 步骤控制
const steps = [
{ title: '上传文档' },
{ title: '文档分段' },
{ title: '处理并完成' },
];
const formData = ref({
knowledgeId: undefined, // 知识库编号
id: undefined, // 编辑的文档编号(documentId)
segmentMaxTokens: 500, // 分段最大 token 数
list: [] as Array<{
count?: number; // 段落数量
id: number; // 文档编号
name: string; // 文档名称
process?: number; // 处理进度
segments: Array<{
content?: string;
contentLength?: number;
tokens?: number;
}>;
url: string; // 文档 URL
}>, // 用于存储上传的文件列表
}); // 表单数据
provide('parent', getCurrentInstance()); // 提供 parent 给子组件使用
const tabs = useTabs();
/** 返回列表页 */
function handleBack() {
// 关闭当前页签
tabs.closeCurrentTab();
// 跳转到列表页
router.push({
name: 'AiKnowledgeDocument',
query: {
knowledgeId: route.query.knowledgeId,
},
});
}
/** 初始化数据 */
async function initData() {
if (route.query.knowledgeId) {
formData.value.knowledgeId = route.query.knowledgeId as any;
}
// 【修改场景】从路由参数中获取文档 ID
const documentId = route.query.id;
if (documentId) {
// 获取文档信息
formData.value.id = documentId as any;
const document = await getKnowledgeDocument(documentId as any);
formData.value.segmentMaxTokens = document.segmentMaxTokens;
formData.value.list = [
{
id: document.id,
name: document.name,
url: document.url,
segments: [],
},
];
// 进入下一步
goToNextStep();
}
}
/** 切换到下一步 */
function goToNextStep() {
if (currentStep.value < steps.length - 1) {
currentStep.value++;
}
}
/** 切换到上一步 */
function goToPrevStep() {
if (currentStep.value > 0) {
currentStep.value--;
}
}
/** 添加组件卸载前的清理代码 */
onBeforeUnmount(() => {
// 清理所有的引用
uploadDocumentRef.value = null;
documentSegmentRef.value = null;
processCompleteRef.value = null;
});
/** 暴露方法给子组件使用 */
defineExpose({
goToNextStep,
goToPrevStep,
handleBack,
});
/** 初始化 */
onMounted(async () => {
await initData();
});
</script>
<template>
<Page auto-content-height>
<div class="mx-auto">
<!-- 头部导航栏 -->
<div
class="absolute left-0 right-0 top-0 z-10 flex h-12 items-center border-b bg-card px-4"
>
<!-- 左侧标题 -->
<div class="flex w-48 items-center overflow-hidden">
<IconifyIcon
icon="lucide:arrow-left"
class="size-5 flex-shrink-0 cursor-pointer"
@click="handleBack"
/>
<span class="ml-2.5 truncate text-base">
{{ formData.id ? '编辑知识库文档' : '创建知识库文档' }}
</span>
</div>
<!-- 步骤条 -->
<div class="flex h-full flex-1 items-center justify-center">
<div class="flex h-full w-96 items-center justify-between">
<div
v-for="(step, index) in steps"
:key="index"
class="relative mx-4 flex h-full cursor-pointer items-center"
:class="[
currentStep === index
? 'border-b-2 border-solid border-blue-500 text-blue-500'
: 'text-gray-500',
]"
>
<div
class="mr-2 flex h-7 w-7 items-center justify-center rounded-full border-2 border-solid text-base"
:class="[
currentStep === index
? 'border-blue-500 bg-blue-500 text-white'
: 'border-gray-300 bg-white text-gray-500',
]"
>
{{ index + 1 }}
</div>
<span class="whitespace-nowrap text-base font-bold">
{{ step.title }}
</span>
</div>
</div>
</div>
</div>
<!-- 主体内容 -->
<ElCard :body-style="{ padding: '10px' }" class="mb-4">
<div class="mt-12">
<!-- 第一步上传文档 -->
<div v-if="currentStep === 0" class="mx-auto w-[560px]">
<UploadStep v-model="formData" ref="uploadDocumentRef" />
</div>
<!-- 第二步文档分段 -->
<div v-if="currentStep === 1" class="mx-auto w-[560px]">
<SplitStep v-model="formData" ref="documentSegmentRef" />
</div>
<!-- 第三步处理并完成 -->
<div v-if="currentStep === 2" class="mx-auto w-[560px]">
<ProcessStep v-model="formData" ref="processCompleteRef" />
</div>
</div>
</ElCard>
</div>
</Page>
</template>

View File

@@ -0,0 +1,158 @@
<script setup lang="ts">
import { computed, inject, onBeforeUnmount, onMounted, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { ElButton, ElProgress } from 'element-plus';
import { getKnowledgeSegmentProcessList } from '#/api/ai/knowledge/segment';
const props = defineProps({
modelValue: {
type: Object,
required: true,
},
});
const emit = defineEmits(['update:modelValue']);
const parent = inject('parent') as any;
const pollingTimer = ref<null | number>(null); // 轮询定时器 ID用于跟踪和清除轮询进程
/** 判断文件处理是否完成 */
function isProcessComplete(file: any) {
return file.progress === 100;
}
/** 判断所有文件是否都处理完成 */
const allProcessComplete = computed(() => {
return props.modelValue.list.every((file: any) => isProcessComplete(file));
});
/** 完成按钮点击事件处理 */
function handleComplete() {
if (parent?.exposed?.handleBack) {
parent.exposed.handleBack();
}
}
/** 获取文件处理进度 */
async function getProcessList() {
try {
// 1. 调用 API 获取处理进度
const documentIds = props.modelValue.list
.filter((item: any) => item.id)
.map((item: any) => item.id);
if (documentIds.length === 0) {
return;
}
const result = await getKnowledgeSegmentProcessList(documentIds);
// 2.1更新进度
const updatedList = props.modelValue.list.map((file: any) => {
const processInfo = result.find(
(item: any) => item.documentId === file.id,
);
if (processInfo) {
// 计算进度百分比:已嵌入数量 / 总数量 * 100
const progress =
processInfo.embeddingCount && processInfo.count
? Math.floor((processInfo.embeddingCount / processInfo.count) * 100)
: 0;
return {
...file,
progress,
count: processInfo.count || 0,
};
}
return file;
});
// 2.2 更新数据
emit('update:modelValue', {
...props.modelValue,
list: updatedList,
});
// 3. 如果未完成,继续轮询
if (!updatedList.every((file: any) => isProcessComplete(file))) {
pollingTimer.value = window.setTimeout(getProcessList, 3000);
}
} catch (error) {
// 出错后也继续轮询
console.error('获取处理进度失败:', error);
pollingTimer.value = window.setTimeout(getProcessList, 5000);
}
}
/** 组件挂载时开始轮询 */
onMounted(() => {
// 1. 初始化进度为 0
const initialList = props.modelValue.list.map((file: any) => ({
...file,
progress: 0,
}));
emit('update:modelValue', {
...props.modelValue,
list: initialList,
});
// 2. 开始轮询获取进度
getProcessList();
});
/** 组件卸载前清除轮询 */
onBeforeUnmount(() => {
// 1. 清除定时器
if (pollingTimer.value) {
clearTimeout(pollingTimer.value);
pollingTimer.value = null;
}
});
</script>
<template>
<div>
<!-- 文件处理列表 -->
<div class="mt-4 grid grid-cols-1 gap-2">
<div
v-for="(file, index) in modelValue.list"
:key="index"
class="flex items-center rounded-sm border-l-4 border-l-blue-500 px-3 py-1 shadow-sm transition-all duration-300 hover:bg-blue-50"
>
<!-- 文件图标和名称 -->
<div class="mr-2 flex min-w-48 items-center">
<IconifyIcon icon="lucide:file-text" class="mr-2 text-blue-500" />
<span class="break-all text-sm text-gray-600">
{{ file.name }}
</span>
</div>
<!-- 处理进度 -->
<div class="flex-1">
<ElProgress
:percentage="file.progress || 0"
:stroke-width="10"
:status="isProcessComplete(file) ? 'success' : undefined"
/>
</div>
<!-- 分段数量 -->
<div class="ml-2 text-sm text-gray-400">
分段数量{{ file.count ? file.count : '-' }}
</div>
</div>
</div>
<!-- 底部完成按钮 -->
<div class="mt-5 flex justify-end">
<ElButton
:type="allProcessComplete ? 'primary' : 'default'"
:disabled="!allProcessComplete"
@click="handleComplete"
>
完成
</ElButton>
</div>
</div>
</template>

View File

@@ -0,0 +1,286 @@
<script setup lang="ts">
import type { PropType } from 'vue';
import { computed, getCurrentInstance, inject, onMounted, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import {
ElButton,
ElDropdown,
ElDropdownItem,
ElDropdownMenu,
ElEmpty,
ElForm,
ElFormItem,
ElInputNumber,
ElMessage,
ElTooltip,
} from 'element-plus';
import {
createKnowledgeDocumentList,
updateKnowledgeDocument,
} from '#/api/ai/knowledge/document';
import { splitContent } from '#/api/ai/knowledge/segment';
const props = defineProps({
modelValue: {
type: Object as PropType<any>,
required: true,
},
});
const emit = defineEmits(['update:modelValue']);
const parent = inject('parent', null); // 获取父组件实例
const modelData = computed({
get: () => props.modelValue,
set: (val) => emit('update:modelValue', val),
}); // 表单数据
const splitLoading = ref(false); // 分段加载状态
const currentFile = ref<any>(null); // 当前选中的文件
const submitLoading = ref(false); // 提交按钮加载状态
/** 选择文件 */
async function selectFile(index: number) {
currentFile.value = modelData.value.list[index];
await splitContentFile(currentFile.value);
}
/** 获取文件分段内容 */
async function splitContentFile(file: any) {
if (!file || !file.url) {
ElMessage.warning('文件 URL 不存在');
return;
}
splitLoading.value = true;
try {
// 调用后端分段接口,获取文档的分段内容、字符数和 Token 数
file.segments = await splitContent(
file.url,
modelData.value.segmentMaxTokens,
);
} catch (error) {
console.error('获取分段内容失败:', file, error);
} finally {
splitLoading.value = false;
}
}
/** 处理预览分段 */
async function handleAutoSegment() {
// 如果没有选中文件,默认选中第一个
if (
!currentFile.value &&
modelData.value.list &&
modelData.value.list.length > 0
) {
currentFile.value = modelData.value.list[0];
}
// 如果没有选中文件,提示请先选择文件
if (!currentFile.value) {
ElMessage.warning('请先选择文件');
return;
}
// 获取分段内容
await splitContentFile(currentFile.value);
}
/** 上一步按钮处理 */
function handlePrevStep() {
const parentEl = parent || getCurrentInstance()?.parent;
if (parentEl && typeof parentEl.exposed?.goToPrevStep === 'function') {
parentEl.exposed.goToPrevStep();
}
}
/** 保存操作 */
async function handleSave() {
// 保存前验证
if (
!currentFile?.value?.segments ||
currentFile.value.segments.length === 0
) {
ElMessage.warning('请先预览分段内容');
return;
}
// 设置按钮加载状态
submitLoading.value = true;
try {
if (modelData.value.id) {
// 修改场景
await updateKnowledgeDocument({
id: modelData.value.id,
segmentMaxTokens: modelData.value.segmentMaxTokens,
});
} else {
// 新增场景
const data = await createKnowledgeDocumentList({
knowledgeId: modelData.value.knowledgeId,
segmentMaxTokens: modelData.value.segmentMaxTokens,
list: modelData.value.list.map((item: any) => ({
name: item.name,
url: item.url,
})),
});
modelData.value.list.forEach((document: any, index: number) => {
document.id = data[index];
});
}
// 进入下一步
const parentEl = parent || getCurrentInstance()?.parent;
if (parentEl && typeof parentEl.exposed?.goToNextStep === 'function') {
parentEl.exposed.goToNextStep();
}
} catch (error: any) {
console.error('保存失败:', modelData.value, error);
} finally {
// 关闭按钮加载状态
submitLoading.value = false;
}
}
/** 初始化 */
onMounted(async () => {
// 确保 segmentMaxTokens 存在
if (!modelData.value.segmentMaxTokens) {
modelData.value.segmentMaxTokens = 500;
}
// 如果没有选中文件,默认选中第一个
if (
!currentFile.value &&
modelData.value.list &&
modelData.value.list.length > 0
) {
currentFile.value = modelData.value.list[0];
}
// 如果有选中的文件,获取分段内容
if (currentFile.value) {
await splitContentFile(currentFile.value);
}
});
</script>
<template>
<div>
<!-- 上部分段设置部分 -->
<div class="mb-5">
<div class="mb-5 flex items-center justify-between">
<div class="flex items-center text-base font-bold">
分段设置
<ElTooltip placement="top">
<template #content>
系统会自动将文档内容分割成多个段落您可以根据需要调整分段方式和内容
</template>
<IconifyIcon
icon="lucide:circle-alert"
class="ml-1 text-gray-400"
/>
</ElTooltip>
</div>
<div>
<ElButton type="primary" size="small" @click="handleAutoSegment">
预览分段
</ElButton>
</div>
</div>
<div class="mb-5">
<ElForm :label-col="{ span: 5 }">
<ElFormItem label="最大 Token 数">
<ElInputNumber
v-model="modelData.segmentMaxTokens"
:min="1"
:max="2048"
controls-position="right"
class="!w-full"
/>
</ElFormItem>
</ElForm>
</div>
</div>
<div class="mb-2.5">
<div class="mb-2.5 text-base font-bold">分段预览</div>
<!-- 文件选择器 -->
<div class="mb-2.5">
<ElDropdown
v-if="modelData.list && modelData.list.length > 0"
trigger="click"
>
<div class="flex cursor-pointer items-center">
<IconifyIcon icon="lucide:file-text" class="mr-1" />
<span>{{ currentFile?.name || '请选择文件' }}</span>
<span
v-if="currentFile?.segments"
class="ml-1 text-sm text-gray-500"
>
({{ currentFile.segments.length }}个分片)
</span>
<IconifyIcon icon="lucide:chevron-down" class="ml-1" />
</div>
<template #dropdown>
<ElDropdownMenu>
<ElDropdownItem
v-for="(file, index) in modelData.list"
:key="index"
@click="selectFile(index)"
>
{{ file.name }}
<span v-if="file.segments" class="ml-1 text-sm text-gray-500">
({{ file.segments.length }} 个分片)
</span>
</ElDropdownItem>
</ElDropdownMenu>
</template>
</ElDropdown>
<div v-else class="text-gray-400">暂无上传文件</div>
</div>
<!-- 文件内容预览 -->
<div class="max-h-[600px] overflow-y-auto rounded-md p-4">
<div v-if="splitLoading" class="flex items-center justify-center py-5">
<IconifyIcon icon="lucide:loader" class="is-loading" />
<span class="ml-2.5">正在加载分段内容...</span>
</div>
<template
v-else-if="
currentFile &&
currentFile.segments &&
currentFile.segments.length > 0
"
>
<div
v-for="(segment, index) in currentFile.segments"
:key="index"
class="mb-2.5"
>
<div class="mb-1 text-sm text-gray-500">
分片-{{ index + 1 }} · {{ segment.contentLength || 0 }} 字符数 ·
{{ segment.tokens || 0 }} Token
</div>
<div class="rounded-md bg-card p-2">
{{ segment.content }}
</div>
</div>
</template>
<ElEmpty v-else description="暂无预览内容" />
</div>
</div>
<!-- 添加底部按钮 -->
<div class="mt-5 flex justify-between">
<div>
<ElButton v-if="!modelData.id" @click="handlePrevStep">上一步</ElButton>
</div>
<div>
<ElButton type="primary" :loading="submitLoading" @click="handleSave">
保存并处理
</ElButton>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,270 @@
<script setup lang="ts">
import type { UploadProps, UploadRequestOptions } from 'element-plus';
import type { PropType } from 'vue';
import type { AxiosProgressEvent } from '#/api/infra/file';
import { computed, getCurrentInstance, inject, onMounted, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { generateAcceptedFileTypes } from '@vben/utils';
import {
ElButton,
ElForm,
ElFormItem,
ElMessage,
ElUpload,
} from 'element-plus';
import { useUpload } from '#/components/upload/use-upload';
const props = defineProps({
modelValue: {
type: Object as PropType<any>,
required: true,
},
});
const emit = defineEmits(['update:modelValue']);
const formRef = ref(); // 表单引用
const uploadRef = ref(); // 上传组件引用
const parent = inject('parent', null); // 获取父组件实例
const { uploadUrl, httpRequest } = useUpload(); // 使用上传组件的钩子
const fileList = ref<UploadProps['fileList']>([]); // 文件列表
const uploadingCount = ref(0); // 上传中的文件数量
const supportedFileTypes = [
'TXT',
'MARKDOWN',
'MDX',
'PDF',
'HTML',
'XLSX',
'XLS',
'DOC',
'DOCX',
'CSV',
'EML',
'MSG',
'PPTX',
'XML',
'EPUB',
'PPT',
'MD',
'HTM',
]; // 支持的文件类型和大小限制
const allowedExtensions = new Set(
supportedFileTypes.map((ext) => ext.toLowerCase()),
); // 小写的扩展名列表
const maxFileSize = 15; // 最大文件大小(MB)
const acceptedFileTypes = computed(() =>
generateAcceptedFileTypes(supportedFileTypes),
); // 构建 accept 属性值,用于限制文件选择对话框中可见的文件类型
/** 表单数据 */
const modelData = computed({
get: () => {
return props.modelValue;
},
set: (val) => emit('update:modelValue', val),
});
/** 确保 list 属性存在 */
function ensureListExists() {
if (!props.modelValue.list) {
emit('update:modelValue', {
...props.modelValue,
list: [],
});
}
}
/** 是否所有文件都已上传完成 */
const isAllUploaded = computed(() => {
return (
modelData.value.list &&
modelData.value.list.length > 0 &&
uploadingCount.value === 0
);
});
/**
* 上传前检查文件类型和大小
*
* @param file 待上传的文件
* @returns 是否允许上传
*/
function beforeUpload(file: any) {
// 1.1 检查文件扩展名
const fileName = file.name.toLowerCase();
const fileExtension = fileName.slice(
Math.max(0, fileName.lastIndexOf('.') + 1),
);
if (!allowedExtensions.has(fileExtension)) {
ElMessage.error('不支持的文件类型!');
return false;
}
// 1.2 检查文件大小
if (!(file.size / 1024 / 1024 < maxFileSize)) {
ElMessage.error(`文件大小不能超过 ${maxFileSize} MB`);
return false;
}
// 2. 增加上传中的文件计数
uploadingCount.value++;
return true;
}
async function customRequest(info: UploadRequestOptions) {
const file = info.file as File;
const name = file?.name;
try {
// 上传文件
const progressEvent: AxiosProgressEvent = (e) => {
const percent = Math.trunc((e.loaded / e.total!) * 100);
info.onProgress!({ percent });
};
const res = await httpRequest(info.file as File, progressEvent);
info.onSuccess!(res);
ElMessage.success('上传成功');
ensureListExists();
emit('update:modelValue', {
...props.modelValue,
list: [
...props.modelValue.list,
{
name,
url: res,
},
],
});
} catch (error: any) {
console.error(error);
info.onError!(error);
} finally {
uploadingCount.value = Math.max(0, uploadingCount.value - 1);
}
}
/**
* 从列表中移除文件
*
* @param index 要移除的文件索引
*/
function removeFile(index: number) {
// 从列表中移除文件
const newList = [...props.modelValue.list];
newList.splice(index, 1);
// 更新表单数据
emit('update:modelValue', {
...props.modelValue,
list: newList,
});
}
/** 下一步按钮处理 */
function handleNextStep() {
// 1.1 检查是否有文件上传
if (!modelData.value.list || modelData.value.list.length === 0) {
ElMessage.warning('请上传至少一个文件');
return;
}
// 1.2 检查是否有文件正在上传
if (uploadingCount.value > 0) {
ElMessage.warning('请等待所有文件上传完成');
return;
}
// 2. 获取父组件的goToNextStep方法
const parentEl = parent || getCurrentInstance()?.parent;
if (parentEl && typeof parentEl.exposed?.goToNextStep === 'function') {
parentEl.exposed.goToNextStep();
}
}
/** 初始化 */
onMounted(() => {
ensureListExists();
});
</script>
<template>
<ElForm ref="formRef" :model="modelData" label-width="0" class="mt-5">
<ElFormItem class="mb-5">
<div class="w-full">
<div
class="w-full rounded-md border-2 border-dashed border-gray-200 p-5 text-center hover:border-blue-500"
>
<ElUpload
ref="uploadRef"
class="upload-demo"
:action="uploadUrl"
v-model:file-list="fileList"
:accept="acceptedFileTypes"
:show-file-list="false"
:before-upload="beforeUpload"
:http-request="customRequest"
:multiple="true"
drag
>
<div class="flex flex-col items-center justify-center py-5">
<IconifyIcon
icon="ep:upload-filled"
class="mb-2.5 text-xs text-gray-400"
/>
<div class="ant-upload-text text-base text-gray-400">
拖拽文件至此或者
<em class="cursor-pointer not-italic text-blue-500">
选择文件
</em>
</div>
<div class="mt-2.5 text-sm text-gray-400">
已支持 {{ supportedFileTypes.join('、') }}每个文件不超过
{{ maxFileSize }} MB
</div>
</div>
</ElUpload>
</div>
<div
v-if="modelData.list && modelData.list.length > 0"
class="mt-4 grid grid-cols-1 gap-2"
>
<div
v-for="(file, index) in modelData.list"
:key="index"
class="flex items-center justify-between rounded-sm border-l-4 border-l-blue-500 px-3 py-1 shadow-sm transition-all duration-300 hover:bg-blue-50"
>
<div class="flex items-center">
<IconifyIcon icon="lucide:file-text" class="mr-2 text-blue-500" />
<span class="break-all text-sm text-gray-600">
{{ file.name }}
</span>
</div>
<ElButton
type="danger"
text
link
@click="removeFile(index)"
class="ml-2"
>
<IconifyIcon icon="lucide:trash-2" />
</ElButton>
</div>
</div>
</div>
</ElFormItem>
<ElFormItem>
<div class="flex w-full justify-end">
<ElButton
type="primary"
@click="handleNextStep"
:disabled="!isAllUploaded"
>
下一步
</ElButton>
</div>
</ElFormItem>
</ElForm>
</template>

View File

@@ -0,0 +1,191 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiKnowledgeDocumentApi } from '#/api/ai/knowledge/document';
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { confirm, Page } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictLabel } from '@vben/hooks';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteKnowledgeDocument,
getKnowledgeDocumentPage,
updateKnowledgeDocumentStatus,
} from '#/api/ai/knowledge/document';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
/** AI 知识库文档列表 */
defineOptions({ name: 'AiKnowledgeDocument' });
const route = useRoute();
const router = useRouter();
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建知识库文档 */
function handleCreate() {
router.push({
name: 'AiKnowledgeDocumentCreate',
query: { knowledgeId: route.query.knowledgeId },
});
}
/** 编辑知识库文档 */
function handleEdit(id: number) {
router.push({
name: 'AiKnowledgeDocumentUpdate',
query: { id, knowledgeId: route.query.knowledgeId },
});
}
/** 删除知识库文档 */
async function handleDelete(row: AiKnowledgeDocumentApi.KnowledgeDocument) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteKnowledgeDocument(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 跳转到知识库分段页面 */
function handleSegment(id: number) {
router.push({
name: 'AiKnowledgeSegment',
query: { documentId: id },
});
}
/** 更新文档状态 */
async function handleStatusChange(
newStatus: number,
row: AiKnowledgeDocumentApi.KnowledgeDocument,
): Promise<boolean | undefined> {
return new Promise((resolve, reject) => {
confirm({
content: `你要将${row.name}的状态切换为【${getDictLabel(DICT_TYPE.COMMON_STATUS, newStatus)}】吗?`,
})
.then(async () => {
// 更新文档状态
await updateKnowledgeDocumentStatus({
id: row.id,
status: newStatus,
});
// 提示并返回成功
ElMessage.success($t('ui.actionMessage.operationSuccess'));
resolve(true);
})
.catch(() => {
reject(new Error('取消操作'));
});
});
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(handleStatusChange),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getKnowledgeDocumentPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
knowledgeId: route.query.knowledgeId,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiKnowledgeDocumentApi.KnowledgeDocument>,
});
/** 初始化 */
onMounted(() => {
// 如果知识库 ID 不存在,显示错误提示并关闭页面
if (!route.query.knowledgeId) {
ElMessage.error('知识库 ID 不存在,无法查看文档列表');
// 关闭当前路由,返回到知识库列表页面
router.back();
}
});
</script>
<template>
<Page auto-content-height>
<Grid table-title="知识库文档列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['知识库文档']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['ai:knowledge:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['ai:knowledge:update'],
onClick: handleEdit.bind(null, row.id),
},
{
label: '分段',
type: 'primary',
link: true,
icon: ACTION_ICON.BOOK,
auth: ['ai:knowledge:query'],
onClick: handleSegment.bind(null, row.id),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:knowledge:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,172 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { AiModelTypeEnum, CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { z } from '#/adapter/form';
import { getModelSimpleList } from '#/api/ai/model/model';
import { getRangePickerDefaultProps } from '#/utils';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'name',
label: '知识库名称',
componentProps: {
placeholder: '请输入知识库名称',
},
rules: 'required',
},
{
fieldName: 'description',
label: '知识库描述',
component: 'Textarea',
componentProps: {
rows: 3,
placeholder: '请输入知识库描述',
},
},
{
component: 'ApiSelect',
fieldName: 'embeddingModelId',
label: '向量模型',
componentProps: {
api: () => getModelSimpleList(AiModelTypeEnum.EMBEDDING),
labelField: 'name',
valueField: 'id',
allowClear: true,
placeholder: '请选择向量模型',
},
rules: 'required',
},
{
fieldName: 'topK',
label: '检索 topK',
component: 'InputNumber',
componentProps: {
placeholder: '请输入检索 topK',
min: 0,
max: 10,
controlsPosition: 'right',
class: '!w-full',
},
rules: 'required',
},
{
fieldName: 'similarityThreshold',
label: '检索相似度阈值',
component: 'InputNumber',
componentProps: {
placeholder: '请输入检索相似度阈值',
min: 0,
max: 1,
step: 0.01,
precision: 2,
controlsPosition: 'right',
class: '!w-full',
},
rules: 'required',
},
{
fieldName: 'status',
label: '是否启用',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '知识库名称',
component: 'Input',
componentProps: {
placeholder: '请输入知识库名称',
allowClear: true,
},
},
{
fieldName: 'status',
label: '是否启用',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择是否启用',
allowClear: true,
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '编号',
minWidth: 100,
},
{
field: 'name',
title: '知识库名称',
minWidth: 150,
},
{
field: 'description',
title: '知识库描述',
minWidth: 200,
},
{
field: 'embeddingModel',
title: '向量化模型',
minWidth: 150,
},
{
field: 'status',
title: '是否启用',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 280,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,166 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiKnowledgeKnowledgeApi } from '#/api/ai/knowledge/knowledge';
import { useRouter } from 'vue-router';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteKnowledge,
getKnowledgePage,
} from '#/api/ai/knowledge/knowledge';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建知识库 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑知识库 */
function handleEdit(row: AiKnowledgeKnowledgeApi.Knowledge) {
formModalApi.setData(row).open();
}
/** 删除知识库 */
async function handleDelete(row: AiKnowledgeKnowledgeApi.Knowledge) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteKnowledge(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 跳转到知识库文档页面 */
const router = useRouter();
function handleDocument(id: number) {
router.push({
name: 'AiKnowledgeDocument',
query: { knowledgeId: id },
});
}
/** 跳转到文档召回测试页面 */
function handleRetrieval(id: number) {
router.push({
name: 'AiKnowledgeRetrieval',
query: { id },
});
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getKnowledgePage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiKnowledgeKnowledgeApi.Knowledge>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="AI 手册" url="https://doc.iocoder.cn/ai/build/" />
</template>
<FormModal @success="handleRefresh" />
<Grid table-title="AI 知识库列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['AI 知识库']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['ai:knowledge:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['ai:knowledge:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('ui.widgets.document'),
type: 'primary',
link: true,
icon: ACTION_ICON.BOOK,
auth: ['ai:knowledge:query'],
onClick: handleDocument.bind(null, row.id),
},
{
label: '召回测试',
type: 'primary',
link: true,
icon: ACTION_ICON.SEARCH,
auth: ['ai:knowledge:query'],
onClick: handleRetrieval.bind(null, row.id),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:knowledge:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,89 @@
<script lang="ts" setup>
import type { AiKnowledgeKnowledgeApi } from '#/api/ai/knowledge/knowledge';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import {
createKnowledge,
getKnowledge,
updateKnowledge,
} from '#/api/ai/knowledge/knowledge';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<AiKnowledgeKnowledgeApi.Knowledge>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['AI 知识库'])
: $t('ui.actionTitle.create', ['AI 知识库']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 140,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data =
(await formApi.getValues()) as AiKnowledgeKnowledgeApi.Knowledge;
try {
await (formData.value?.id
? updateKnowledge(data)
: createKnowledge(data));
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<AiKnowledgeKnowledgeApi.Knowledge>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getKnowledge(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-2/5">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,214 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import {
ElButton,
ElCard,
ElEmpty,
ElInput,
ElInputNumber,
ElMessage,
} from 'element-plus';
import { getKnowledge } from '#/api/ai/knowledge/knowledge';
import { searchKnowledgeSegment } from '#/api/ai/knowledge/segment';
/** 知识库文档召回测试 */
defineOptions({ name: 'KnowledgeDocumentRetrieval' });
const route = useRoute();
const router = useRouter();
const loading = ref(false); // 加载状态
const segments = ref<any[]>([]); // 召回结果
const queryParams = reactive({
id: undefined,
content: '',
topK: 10,
similarityThreshold: 0.5,
});
/** 执行召回测试 */
async function getRetrievalResult() {
if (!queryParams.content) {
ElMessage.warning('请输入查询文本');
return;
}
loading.value = true;
segments.value = [];
try {
const data = await searchKnowledgeSegment({
knowledgeId: queryParams.id,
content: queryParams.content,
topK: queryParams.topK,
similarityThreshold: queryParams.similarityThreshold,
});
segments.value = data || [];
} finally {
loading.value = false;
}
}
/** 切换段落展开状态 */
function toggleExpand(segment: any) {
segment.expanded = !segment.expanded;
}
/** 获取知识库配置信息 */
async function getKnowledgeInfo(id: number) {
try {
const knowledge = await getKnowledge(id);
if (knowledge) {
queryParams.topK = knowledge.topK || queryParams.topK;
queryParams.similarityThreshold =
knowledge.similarityThreshold || queryParams.similarityThreshold;
}
} catch {}
}
/** 初始化 */
onMounted(() => {
// 如果知识库 ID 不存在,显示错误提示并关闭页面
if (!route.query.id) {
ElMessage.error('知识库 ID 不存在,无法进行召回测试');
router.back();
return;
}
queryParams.id = route.query.id as any;
// 获取知识库信息并设置默认值
getKnowledgeInfo(queryParams.id as any);
});
</script>
<template>
<Page auto-content-height>
<div class="flex w-full gap-4">
<ElCard class="w-3/4 flex-1">
<div class="mb-15">
<h3 class="m-2 text-lg font-semibold leading-none tracking-tight">
召回测试
</h3>
<div class="m-2 text-sm text-gray-500">
根据给定的查询文本测试召回效果
</div>
</div>
<div>
<div class="relative m-2">
<ElInput
v-model="queryParams.content"
:rows="8"
type="textarea"
placeholder="请输入文本"
/>
<div class="absolute bottom-2 right-2 text-sm text-gray-400">
{{ queryParams.content?.length }} / 200
</div>
</div>
<div class="m-2 flex items-center">
<span class="w-16 text-gray-500">topK:</span>
<ElInputNumber
v-model="queryParams.topK"
:min="1"
:max="20"
controls-position="right"
class="!w-full"
/>
</div>
<div class="m-2 flex items-center">
<span class="w-16 text-gray-500">相似度:</span>
<ElInputNumber
v-model="queryParams.similarityThreshold"
class="!w-full"
controls-position="right"
:min="0"
:max="1"
:precision="2"
:step="0.01"
/>
</div>
<div class="flex justify-end">
<ElButton
type="primary"
@click="getRetrievalResult"
:loading="loading"
>
测试
</ElButton>
</div>
</div>
</ElCard>
<ElCard class="min-w-300 flex-1">
<!-- 加载中状态 -->
<template v-if="loading">
<div class="flex h-72 items-center justify-center">
<ElEmpty description="正在检索中..." />
</div>
</template>
<!-- 有段落 -->
<template v-else-if="segments.length > 0">
<div class="mb-15 font-bold">{{ segments.length }} 个召回段落</div>
<div>
<div
v-for="(segment, index) in segments"
:key="index"
class="mt-2 rounded border border-solid border-gray-200 px-2 py-2"
>
<div
class="mb-2 flex items-center justify-between gap-8 text-sm text-gray-500"
>
<span>
分段({{ segment.id }}) · {{ segment.contentLength }} 字符数 ·
{{ segment.tokens }} Token
</span>
<span
class="whitespace-nowrap rounded-full bg-blue-50 px-2 py-1 text-sm text-blue-500"
>
score: {{ segment.score }}
</span>
</div>
<div
class="mb-2 overflow-hidden whitespace-pre-wrap rounded bg-gray-50 text-sm transition-all duration-100"
:class="{
'line-clamp-2 max-h-40': !segment.expanded,
'max-h-[1500px]': segment.expanded,
}"
>
{{ segment.content }}
</div>
<div class="flex items-center justify-between gap-8">
<div class="flex items-center gap-1 text-sm text-gray-500">
<IconifyIcon icon="lucide:file-text" />
<span>{{ segment.documentName || '未知文档' }}</span>
</div>
<ElButton size="small" @click="toggleExpand(segment)">
{{ segment.expanded ? '收起' : '展开' }}
<IconifyIcon
:icon="
segment.expanded
? 'lucide:chevron-up'
: 'lucide:chevron-down'
"
/>
</ElButton>
</div>
</div>
</div>
</template>
<!-- 无召回结果 -->
<template v-else>
<div class="flex h-72 items-center justify-center">
<ElEmpty description="暂无召回结果" />
</div>
</template>
</ElCard>
</div>
</Page>
</template>

View File

@@ -0,0 +1,130 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiKnowledgeSegmentApi } from '#/api/ai/knowledge/segment';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'documentId',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'content',
label: '切片内容',
component: 'Textarea',
componentProps: {
placeholder: '请输入切片内容',
rows: 6,
showCount: true,
},
rules: 'required',
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'documentId',
label: '文档编号',
component: 'Input',
componentProps: {
placeholder: '请输入文档编号',
allowClear: true,
},
},
{
fieldName: 'status',
label: '是否启用',
component: 'Select',
componentProps: {
placeholder: '请选择是否启用',
allowClear: true,
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
},
];
}
/** 列表的字段 */
export function useGridColumns(
onStatusChange?: (
newStatus: number,
row: AiKnowledgeSegmentApi.KnowledgeSegment,
) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '分段编号',
minWidth: 100,
},
{
type: 'expand',
width: 40,
slots: { content: 'expand_content' },
},
{
field: 'content',
title: '切片内容',
minWidth: 250,
},
{
field: 'contentLength',
title: '字符数',
minWidth: 100,
},
{
field: 'tokens',
title: 'token 数量',
minWidth: 120,
},
{
field: 'retrievalCount',
title: '召回次数',
minWidth: 100,
},
{
field: 'status',
title: '状态',
minWidth: 100,
align: 'center',
cellRender: {
attrs: { beforeChange: onStatusChange },
name: 'CellSwitch',
props: {
activeValue: CommonStatusEnum.ENABLE,
inactiveValue: CommonStatusEnum.DISABLE,
},
},
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 150,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,171 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiKnowledgeSegmentApi } from '#/api/ai/knowledge/segment';
import { onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictLabel } from '@vben/hooks';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteKnowledgeSegment,
getKnowledgeSegmentPage,
updateKnowledgeSegmentStatus,
} from '#/api/ai/knowledge/segment';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const route = useRoute();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建知识库片段 */
function handleCreate() {
formModalApi.setData({ documentId: route.query.documentId }).open();
}
/** 编辑知识库片段 */
function handleEdit(row: AiKnowledgeSegmentApi.KnowledgeSegment) {
formModalApi.setData(row).open();
}
/** 删除知识库片段 */
async function handleDelete(row: AiKnowledgeSegmentApi.KnowledgeSegment) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteKnowledgeSegment(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 更新知识库片段状态 */
async function handleStatusChange(
newStatus: number,
row: AiKnowledgeSegmentApi.KnowledgeSegment,
): Promise<boolean | undefined> {
return new Promise((resolve, reject) => {
confirm({
content: `你要将片段 ${row.id} 的状态切换为【${getDictLabel(DICT_TYPE.COMMON_STATUS, newStatus)}】吗?`,
})
.then(async () => {
// 更新片段状态
await updateKnowledgeSegmentStatus(row.id!, newStatus);
// 提示并返回成功
ElMessage.success($t('ui.actionMessage.operationSuccess'));
resolve(true);
})
.catch(() => {
reject(new Error('取消操作'));
});
});
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(handleStatusChange),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getKnowledgeSegmentPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiKnowledgeSegmentApi.KnowledgeSegment>,
});
/** 初始化 */
onMounted(() => {
gridApi.formApi.setFieldValue('documentId', route.query.documentId);
});
</script>
<template>
<Page auto-content-height>
<FormModal @success="handleRefresh" />
<Grid table-title="分段列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['分段']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['ai:knowledge:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #expand_content="{ row }">
<div
class="whitespace-pre-wrap border-l-4 border-blue-500 px-2.5 py-5 leading-5"
>
<div class="mb-2 text-sm font-bold text-gray-600">完整内容</div>
{{ row.content }}
</div>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['ai:knowledge:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:knowledge:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.id]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,89 @@
<script lang="ts" setup>
import type { AiKnowledgeSegmentApi } from '#/api/ai/knowledge/segment';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import {
createKnowledgeSegment,
getKnowledgeSegment,
updateKnowledgeSegment,
} from '#/api/ai/knowledge/segment';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<AiKnowledgeSegmentApi.KnowledgeSegment>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['分段'])
: $t('ui.actionTitle.create', ['分段']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 140,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data =
(await formApi.getValues()) as AiKnowledgeSegmentApi.KnowledgeSegment;
try {
await (formData.value?.id
? updateKnowledgeSegment(data)
: createKnowledgeSegment(data));
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<AiKnowledgeSegmentApi.KnowledgeSegment>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getKnowledgeSegment(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal class="w-2/5" :title="getTitle">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,99 @@
<script lang="ts" setup>
import type { AiMindmapApi } from '#/api/ai/mindmap';
import { nextTick, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { MindMapContentExample } from '@vben/constants';
import { ElMessage } from 'element-plus';
import { generateMindMap } from '#/api/ai/mindmap';
import Left from './modules/left.vue';
import Right from './modules/right.vue';
const ctrl = ref<AbortController>(); // 请求控制
const isGenerating = ref(false); // 是否正在生成思维导图
const isStart = ref(false); // 开始生成,用来清空思维导图
const isEnd = ref(true); // 用来判断结束的时候渲染思维导图
const generatedContent = ref(''); // 生成思维导图结果
const leftRef = ref<InstanceType<typeof Left>>(); // 左边组件
const rightRef = ref(); // 右边组件
/** 使用已有内容直接生成 */
function directGenerate(existPrompt: string) {
isEnd.value = false; // 先设置为 false 再设置为 true让子组建的 watch 能够监听到
generatedContent.value = existPrompt;
isEnd.value = true;
}
/** 提交生成 */
function handleSubmit(data: AiMindmapApi.AiMindMapGenerateReqVO) {
isGenerating.value = true;
isStart.value = true;
isEnd.value = false;
ctrl.value = new AbortController(); // 请求控制赋值
generatedContent.value = ''; // 清空生成数据
generateMindMap({
data,
onMessage: async (res: any) => {
const { code, data, msg } = JSON.parse(res.data);
if (code !== 0) {
ElMessage.error(`生成思维导图异常! ${msg}`);
handleStopStream();
return;
}
generatedContent.value = generatedContent.value + data;
await nextTick();
rightRef.value?.scrollBottom();
},
onClose() {
isEnd.value = true;
leftRef.value?.setGeneratedContent(generatedContent.value);
handleStopStream();
},
onError(err) {
console.error('生成思维导图失败', err);
handleStopStream();
// 需要抛出异常,禁止重试
throw err;
},
ctrl: ctrl.value,
});
}
/** 停止 stream 生成 */
function handleStopStream() {
isGenerating.value = false;
isStart.value = false;
ctrl.value?.abort();
}
/** 初始化 */
onMounted(() => {
generatedContent.value = MindMapContentExample;
});
</script>
<template>
<Page auto-content-height>
<div class="absolute bottom-0 left-0 right-0 top-0 m-4 flex">
<Left
ref="leftRef"
class="mr-4"
:is-generating="isGenerating"
@submit="handleSubmit"
@direct-generate="directGenerate"
/>
<Right
ref="rightRef"
:generated-content="generatedContent"
:is-end="isEnd"
:is-generating="isGenerating"
:is-start="isStart"
/>
</div>
</Page>
</template>

View File

@@ -0,0 +1,75 @@
<script setup lang="ts">
import { reactive, ref } from 'vue';
import { MindMapContentExample } from '@vben/constants';
import { ElButton, ElInput } from 'element-plus';
defineProps<{
isGenerating: boolean;
}>();
const emits = defineEmits(['submit', 'directGenerate']);
const formData = reactive({
prompt: '',
});
const generatedContent = ref(MindMapContentExample); // 已有的内容
defineExpose({
setGeneratedContent(newContent: string) {
// 设置已有的内容,在生成结束的时候将结果赋值给该值
generatedContent.value = newContent;
},
});
</script>
<template>
<div class="flex w-80 flex-col rounded-lg bg-card p-5">
<h3 class="h-7 w-full text-center text-xl leading-7 text-primary">
思维导图创作中心
</h3>
<div class="mt-4 flex-grow overflow-y-auto">
<div>
<b>您的需求</b>
<ElInput
v-model="formData.prompt"
type="textarea"
:maxlength="1024"
:rows="8"
class="mt-4 w-full"
placeholder="请输入提示词让AI帮你完善"
show-word-limit
/>
<ElButton
class="mt-4 !w-full"
type="primary"
:loading="isGenerating"
@click="emits('submit', formData)"
>
智能生成思维导图
</ElButton>
</div>
<div class="mt-7">
<b>使用已有内容生成</b>
<ElInput
v-model="generatedContent"
type="textarea"
:maxlength="1024"
:rows="8"
class="mt-4 w-full"
placeholder="例如:童话里的小屋应该是什么样子?"
show-word-limit
/>
<ElButton
class="mt-4 !w-full"
type="primary"
@click="emits('directGenerate', generatedContent)"
:disabled="isGenerating"
>
直接生成
</ElButton>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,215 @@
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { IconifyIcon } from '@vben/icons';
import {
MarkdownIt,
Markmap,
Toolbar,
Transformer,
} from '@vben/plugins/markmap';
import { downloadImageByCanvas } from '@vben/utils';
import { ElButton, ElCard, ElMessage } from 'element-plus';
const props = defineProps<{
generatedContent: string; // 生成结果
isEnd: boolean; // 是否结束
isGenerating: boolean; // 是否正在生成
isStart: boolean; // 开始状态,开始时需要清除 html
}>();
const md = MarkdownIt();
const contentRef = ref<HTMLDivElement>(); // 右侧出来 header 以下的区域
const mdContainerRef = ref<HTMLDivElement>(); // markdown 的容器,用来滚动到底下的
const mindMapRef = ref<HTMLDivElement>(); // 思维导图的容器
const svgRef = ref<SVGElement>(); // 思维导图的渲染 svg
const toolBarRef = ref<HTMLDivElement>(); // 思维导图右下角的工具栏,缩放等
const html = ref(''); // 生成过程中的文本
const contentAreaHeight = ref(0); // 生成区域的高度,出去 header 部分
let markMap: Markmap | null = null;
const transformer = new Transformer();
let resizeObserver: null | ResizeObserver = null;
const initialized = false;
/** 初始化 */
onMounted(() => {
resizeObserver = new ResizeObserver(() => {
contentAreaHeight.value = contentRef.value?.clientHeight || 0;
// 先更新高度,再更新思维导图
if (contentAreaHeight.value && !initialized) {
// 初始化思维导图
try {
if (!markMap) {
markMap = Markmap.create(svgRef.value!);
const { el } = Toolbar.create(markMap);
toolBarRef.value?.append(el);
}
nextTick(update);
} catch {
ElMessage.error('思维导图初始化失败');
}
}
});
if (contentRef.value) {
resizeObserver.observe(contentRef.value);
}
});
/** 卸载 */
onBeforeUnmount(() => {
if (resizeObserver && contentRef.value) {
resizeObserver.unobserve(contentRef.value);
}
});
/** 监听 props 变化 */
watch(props, ({ generatedContent, isGenerating, isEnd, isStart }) => {
// 开始生成的时候清空一下 markdown 的内容
if (isStart) {
html.value = '';
}
// 生成内容的时候使用 markdown 来渲染
if (isGenerating) {
html.value = md.render(generatedContent);
}
// 生成结束时更新思维导图
if (isEnd) {
update();
}
});
/** 更新思维导图的展示 */
function update() {
try {
const { root } = transformer.transform(
processContent(props.generatedContent),
);
markMap?.setData(root);
markMap?.fit();
} catch (error: any) {
console.error(error);
}
}
/** 处理内容 */
function processContent(text: string) {
const arr: string[] = [];
const lines = text.split('\n');
for (let line of lines) {
if (line.includes('```')) {
continue;
}
// eslint-disable-next-line unicorn/prefer-string-replace-all
line = line.replace(/([*_~`>])|(\d+\.)\s/g, '');
arr.push(line);
}
return arr.join('\n');
}
/** 下载图片download SVG to png file */
function downloadImage() {
const svgElement = mindMapRef.value;
// 将 SVG 渲染到图片对象
const serializer = new XMLSerializer();
const source = `<?xml version="1.0" standalone="no"?>\r\n${serializer.serializeToString(svgRef.value!)}`;
const base64Url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(source)}`;
downloadImageByCanvas({
url: base64Url,
canvasWidth: svgElement?.offsetWidth,
canvasHeight: svgElement?.offsetHeight,
drawWithImageSize: false,
});
}
defineExpose({
scrollBottom() {
mdContainerRef.value?.scrollTo(0, mdContainerRef.value?.scrollHeight);
},
});
</script>
<template>
<ElCard class="my-card flex h-full flex-grow flex-col">
<template #header>
<div class="m-0 flex shrink-0 items-center justify-between px-7">
<h3>思维导图预览</h3>
<ElButton
type="primary"
size="small"
class="flex"
@click="downloadImage"
>
<template #icon>
<div class="flex items-center justify-center">
<IconifyIcon icon="lucide:copy" />
</div>
</template>
下载图片
</ElButton>
</div>
</template>
<div ref="contentRef" class="hide-scroll-bar box-border h-full">
<div
v-if="isGenerating"
ref="mdContainerRef"
class="wh-full overflow-y-auto"
>
<div
class="flex flex-col items-center justify-center"
v-html="html"
></div>
</div>
<div ref="mindMapRef" class="wh-full">
<svg
ref="svgRef"
:style="{ height: `${contentAreaHeight}px` }"
class="w-full"
/>
<div ref="toolBarRef" class="absolute bottom-2.5 right-5"></div>
</div>
</div>
</ElCard>
</template>
<style lang="scss" scoped>
// 定义一个 mixin 替代 extend
@mixin hide-scroll-bar {
-ms-overflow-style: none;
scrollbar-width: none;
&::-webkit-scrollbar {
width: 0;
height: 0;
}
}
.hide-scroll-bar {
@include hide-scroll-bar;
}
.my-card {
:deep(.el-card__body) {
box-sizing: border-box;
flex-grow: 1;
padding: 0;
overflow-y: auto;
@include hide-scroll-bar;
}
}
// markmap的tool样式覆盖
:deep(.markmap) {
width: 100%;
}
:deep(.mm-toolbar-brand) {
display: none;
}
:deep(.mm-toolbar) {
display: flex;
flex-direction: row;
}
</style>

View File

@@ -0,0 +1,97 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api/system/user';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 关联数据 */
let userList: SystemUserApi.User[] = [];
getSimpleUserList().then((data) => (userList = data));
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'userId',
label: '用户编号',
component: 'ApiSelect',
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
placeholder: '请选择用户',
allowClear: true,
},
},
{
fieldName: 'prompt',
label: '提示词',
component: 'Input',
componentProps: {
placeholder: '请输入提示词',
clearable: true,
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '编号',
minWidth: 180,
fixed: 'left',
},
{
field: 'userId',
title: '用户',
minWidth: 180,
formatter: ({ cellValue }) =>
userList.find((user) => user.id === cellValue)?.nickname || '-',
},
{
field: 'prompt',
title: '提示词',
minWidth: 180,
},
{
field: 'generatedContent',
title: '思维导图',
minWidth: 300,
},
{
field: 'model',
title: '模型',
minWidth: 180,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
field: 'errorMessage',
title: '错误信息',
minWidth: 180,
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,120 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiMindmapApi } from '#/api/ai/mindmap';
import { DocAlert, Page, useVbenDrawer } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteMindMap, getMindMapPage } from '#/api/ai/mindmap';
import { $t } from '#/locales';
import Right from '../index/modules/right.vue';
import { useGridColumns, useGridFormSchema } from './data';
const [Drawer, drawerApi] = useVbenDrawer({
header: false,
footer: false,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 删除思维导图记录 */
async function handleDelete(row: AiMindmapApi.MindMap) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteMindMap(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 预览思维导图 */
async function openPreview(row: AiMindmapApi.MindMap) {
drawerApi.setData(row.generatedContent).open();
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getMindMapPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiMindmapApi.MindMap>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="AI 思维导图" url="https://doc.iocoder.cn/ai/mindmap/" />
</template>
<Drawer class="w-3/5">
<Right
:generated-content="drawerApi.getData() as any"
:is-end="true"
:is-generating="false"
:is-start="false"
/>
</Drawer>
<Grid table-title="思维导图管理列表">
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('ui.cropper.preview'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['ai:api-key:update'],
disabled: !row.generatedContent,
onClick: openPreview.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:mind-map:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.id]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,147 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { z } from '#/adapter/form';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'platform',
label: '所属平台',
component: 'Select',
componentProps: {
placeholder: '请选择所属平台',
options: getDictOptions(DICT_TYPE.AI_PLATFORM, 'string'),
allowClear: true,
},
rules: 'required',
},
{
component: 'Input',
fieldName: 'name',
label: '名称',
rules: 'required',
componentProps: {
placeholder: '请输入名称',
},
},
{
component: 'Input',
fieldName: 'apiKey',
label: '密钥',
rules: 'required',
componentProps: {
placeholder: '请输入密钥',
},
},
{
component: 'Input',
fieldName: 'url',
label: '自定义 API URL',
componentProps: {
placeholder: '请输入自定义 API URL',
},
},
{
fieldName: 'status',
label: '状态',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '名称',
component: 'Input',
componentProps: {
placeholder: '请输入名称',
allowClear: true,
},
},
{
fieldName: 'platform',
label: '平台',
component: 'Select',
componentProps: {
allowClear: true,
placeholder: '请选择平台',
options: getDictOptions(DICT_TYPE.AI_PLATFORM, 'string'),
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
allowClear: true,
placeholder: '请选择状态',
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'platform',
title: '所属平台',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_PLATFORM },
},
minWidth: 100,
},
{
field: 'name',
title: '名称',
minWidth: 120,
},
{
field: 'apiKey',
title: '密钥',
minWidth: 140,
},
{
field: 'url',
title: '自定义 API URL',
minWidth: 180,
},
{
field: 'status',
title: '状态',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
minWidth: 80,
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,128 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiModelApiKeyApi } from '#/api/ai/model/apiKey';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteApiKey, getApiKeyPage } from '#/api/ai/model/apiKey';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建 API 密钥 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑 API 密钥 */
function handleEdit(row: AiModelApiKeyApi.ApiKey) {
formModalApi.setData(row).open();
}
/** 删除 API 密钥 */
async function handleDelete(row: AiModelApiKeyApi.ApiKey) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteApiKey(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getApiKeyPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiModelApiKeyApi.ApiKey>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="AI 手册" url="https://doc.iocoder.cn/ai/build/" />
</template>
<FormModal @success="handleRefresh" />
<Grid table-title="API 密钥列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['API 密钥']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['ai:api-key:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['ai:api-key:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:api-key:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,82 @@
<script lang="ts" setup>
import type { AiModelApiKeyApi } from '#/api/ai/model/apiKey';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { createApiKey, getApiKey, updateApiKey } from '#/api/ai/model/apiKey';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<AiModelApiKeyApi.ApiKey>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['API 密钥'])
: $t('ui.actionTitle.create', ['API 密钥']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data = (await formApi.getValues()) as AiModelApiKeyApi.ApiKey;
try {
await (formData.value?.id ? updateApiKey(data) : createApiKey(data));
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<AiModelApiKeyApi.ApiKey>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getApiKey(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-2/5">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,318 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { AiModelTypeEnum, CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { z } from '#/adapter/form';
import { getSimpleKnowledgeList } from '#/api/ai/knowledge/knowledge';
import { getModelSimpleList } from '#/api/ai/model/model';
import { getToolSimpleList } from '#/api/ai/model/tool';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'formType',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'name',
label: '角色名称',
rules: 'required',
componentProps: {
placeholder: '请输入角色名称',
},
},
{
component: 'ImageUpload',
fieldName: 'avatar',
label: '角色头像',
rules: 'required',
},
{
fieldName: 'modelId',
label: '绑定模型',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择绑定模型',
api: () => getModelSimpleList(AiModelTypeEnum.CHAT),
labelField: 'name',
valueField: 'id',
allowClear: true,
},
dependencies: {
triggerFields: ['formType'],
show: (values) => {
return values.formType === 'create' || values.formType === 'update';
},
},
},
{
component: 'Input',
fieldName: 'category',
label: '角色类别',
rules: 'required',
componentProps: {
placeholder: '请输入角色类别',
},
dependencies: {
triggerFields: ['formType'],
show: (values) => {
return values.formType === 'create' || values.formType === 'update';
},
},
},
{
component: 'Textarea',
fieldName: 'description',
label: '角色描述',
componentProps: {
placeholder: '请输入角色描述',
},
rules: 'required',
},
{
fieldName: 'systemMessage',
label: '角色设定',
component: 'Textarea',
componentProps: {
placeholder: '请输入角色设定',
},
rules: 'required',
},
{
fieldName: 'knowledgeIds',
label: '引用知识库',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择引用知识库',
api: getSimpleKnowledgeList,
labelField: 'name',
mode: 'multiple',
valueField: 'id',
allowClear: true,
},
},
{
fieldName: 'toolIds',
label: '引用工具',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择引用工具',
api: getToolSimpleList,
mode: 'multiple',
labelField: 'name',
valueField: 'id',
allowClear: true,
},
},
{
fieldName: 'mcpClientNames',
label: '引用 MCP',
component: 'Select',
componentProps: {
placeholder: '请选择 MCP',
options: getDictOptions(DICT_TYPE.AI_MCP_CLIENT_NAME, 'string'),
mode: 'multiple',
allowClear: true,
},
},
{
fieldName: 'publicStatus',
label: '是否公开',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING, 'boolean'),
},
defaultValue: true,
dependencies: {
triggerFields: ['formType'],
show: (values) => {
return values.formType === 'create' || values.formType === 'update';
},
},
rules: 'required',
},
{
fieldName: 'sort',
label: '角色排序',
component: 'InputNumber',
componentProps: {
placeholder: '请输入角色排序',
controlsPosition: 'right',
class: '!w-full',
},
dependencies: {
triggerFields: ['formType'],
show: (values) => {
return values.formType === 'create' || values.formType === 'update';
},
},
rules: 'required',
},
{
fieldName: 'status',
label: '开启状态',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
dependencies: {
triggerFields: ['formType'],
show: (values) => {
return values.formType === 'create' || values.formType === 'update';
},
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '角色名称',
component: 'Input',
componentProps: {
placeholder: '请输入角色名称',
},
},
{
fieldName: 'category',
label: '角色类别',
component: 'Input',
componentProps: {
placeholder: '请输入角色类别',
},
},
{
fieldName: 'publicStatus',
label: '是否公开',
component: 'Select',
componentProps: {
placeholder: '请选择是否公开',
options: getDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING, 'boolean'),
allowClear: true,
},
defaultValue: true,
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'name',
title: '角色名称',
minWidth: 100,
},
{
title: '绑定模型',
field: 'modelName',
minWidth: 100,
},
{
title: '角色头像',
field: 'avatar',
minWidth: 140,
cellRender: {
name: 'CellImage',
props: {
width: 40,
height: 40,
},
},
},
{
title: '角色类别',
field: 'category',
minWidth: 100,
},
{
title: '角色描述',
field: 'description',
minWidth: 100,
},
{
title: '角色设定',
field: 'systemMessage',
minWidth: 100,
},
{
title: '知识库',
field: 'knowledgeIds',
minWidth: 100,
formatter: ({ cellValue }) => {
return !cellValue || cellValue.length === 0
? '-'
: `引用${cellValue.length}`;
},
},
{
title: '工具',
field: 'toolIds',
minWidth: 100,
formatter: ({ cellValue }) => {
return !cellValue || cellValue.length === 0
? '-'
: `引用${cellValue.length}`;
},
},
{
title: 'MCP',
field: 'mcpClientNames',
minWidth: 100,
formatter: ({ cellValue }) => {
return !cellValue || cellValue.length === 0
? '-'
: `引用${cellValue.length}`;
},
},
{
field: 'publicStatus',
title: '是否公开',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.INFRA_BOOLEAN_STRING },
},
minWidth: 80,
},
{
field: 'status',
title: '状态',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
minWidth: 80,
},
{
title: '角色排序',
field: 'sort',
minWidth: 80,
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,128 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiModelChatRoleApi } from '#/api/ai/model/chatRole';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteChatRole, getChatRolePage } from '#/api/ai/model/chatRole';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建聊天角色 */
function handleCreate() {
formModalApi.setData({ formType: 'create' }).open();
}
/** 编辑聊天角色 */
function handleEdit(row: AiModelChatRoleApi.ChatRole) {
formModalApi.setData({ formType: 'update', ...row }).open();
}
/** 删除聊天角色 */
async function handleDelete(row: AiModelChatRoleApi.ChatRole) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteChatRole(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getChatRolePage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiModelChatRoleApi.ChatRole>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="AI 对话聊天" url="https://doc.iocoder.cn/ai/chat/" />
</template>
<FormModal @success="handleRefresh" />
<Grid table-title="聊天角色列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['聊天角色']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['ai:chat-role:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['ai:chat-role:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:chat-role:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,87 @@
<script lang="ts" setup>
import type { AiModelChatRoleApi } from '#/api/ai/model/chatRole';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import {
createChatRole,
getChatRole,
updateChatRole,
} from '#/api/ai/model/chatRole';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<AiModelChatRoleApi.ChatRole>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['聊天角色'])
: $t('ui.actionTitle.create', ['聊天角色']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data = (await formApi.getValues()) as AiModelChatRoleApi.ChatRole;
try {
await (formData.value?.id ? updateChatRole(data) : createChatRole(data));
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<AiModelChatRoleApi.ChatRole>();
if (!data || !data.id) {
await formApi.setValues(data);
return;
}
modalApi.lock();
try {
formData.value = await getChatRole(data.id);
// 设置到 values
await formApi.setValues({ ...data, ...formData.value });
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-2/5">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,272 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiModelApiKeyApi } from '#/api/ai/model/apiKey';
import { AiModelTypeEnum, CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { z } from '#/adapter/form';
import { getApiKeySimpleList } from '#/api/ai/model/apiKey';
/** 关联数据 */
let apiKeyList: AiModelApiKeyApi.ApiKey[] = [];
getApiKeySimpleList().then((data) => (apiKeyList = data));
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'platform',
label: '所属平台',
component: 'Select',
componentProps: {
placeholder: '请选择所属平台',
options: getDictOptions(DICT_TYPE.AI_PLATFORM, 'string'),
allowClear: true,
},
rules: 'required',
},
{
fieldName: 'type',
label: '模型类型',
component: 'Select',
componentProps: (values) => {
return {
placeholder: '请输入模型类型',
disabled: !!values.id,
options: getDictOptions(DICT_TYPE.AI_MODEL_TYPE, 'number'),
allowClear: true,
};
},
rules: 'required',
},
{
fieldName: 'keyId',
label: 'API 秘钥',
component: 'ApiSelect',
componentProps: {
placeholder: '请选择 API 秘钥',
api: getApiKeySimpleList,
labelField: 'name',
valueField: 'id',
allowClear: true,
},
rules: 'required',
},
{
component: 'Input',
fieldName: 'name',
label: '模型名字',
rules: 'required',
componentProps: {
placeholder: '请输入模型名字',
},
},
{
component: 'Input',
fieldName: 'model',
label: '模型标识',
rules: 'required',
componentProps: {
placeholder: '请输入模型标识',
},
},
{
fieldName: 'sort',
label: '模型排序',
component: 'InputNumber',
componentProps: {
placeholder: '请输入模型排序',
controlsPosition: 'right',
class: '!w-full',
},
rules: 'required',
},
{
fieldName: 'status',
label: '开启状态',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
{
fieldName: 'temperature',
label: '温度参数',
component: 'InputNumber',
componentProps: {
placeholder: '请输入温度参数',
min: 0,
max: 2,
controlsPosition: 'right',
class: '!w-full',
},
dependencies: {
triggerFields: ['type'],
show: (values) => {
return [AiModelTypeEnum.CHAT].includes(values.type);
},
},
rules: 'required',
},
{
fieldName: 'maxTokens',
label: '回复数 Token 数',
component: 'InputNumber',
componentProps: {
min: 0,
max: 8192,
placeholder: '请输入回复数 Token 数',
controlsPosition: 'right',
class: '!w-full',
},
dependencies: {
triggerFields: ['type'],
show: (values) => {
return [AiModelTypeEnum.CHAT].includes(values.type);
},
},
rules: 'required',
},
{
fieldName: 'maxContexts',
label: '上下文数量',
component: 'InputNumber',
componentProps: {
min: 0,
max: 20,
placeholder: '请输入上下文数量',
controlsPosition: 'right',
class: '!w-full',
},
dependencies: {
triggerFields: ['type'],
show: (values) => {
return [AiModelTypeEnum.CHAT].includes(values.type);
},
},
rules: 'required',
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '模型名字',
component: 'Input',
componentProps: {
placeholder: '请输入模型名字',
allowClear: true,
},
},
{
fieldName: 'model',
label: '模型标识',
component: 'Input',
componentProps: {
placeholder: '请输入模型标识',
allowClear: true,
},
},
{
fieldName: 'platform',
label: '模型平台',
component: 'Input',
componentProps: {
placeholder: '请输入模型平台',
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'platform',
title: '所属平台',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_PLATFORM },
},
minWidth: 100,
},
{
field: 'type',
title: '模型类型',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_MODEL_TYPE },
},
minWidth: 100,
},
{
field: 'name',
title: '模型名字',
minWidth: 180,
},
{
title: '模型标识',
field: 'model',
minWidth: 180,
},
{
title: 'API 秘钥',
field: 'keyId',
formatter: ({ cellValue }) => {
return (
apiKeyList.find((apiKey) => apiKey.id === cellValue)?.name || '-'
);
},
minWidth: 140,
},
{
title: '排序',
field: 'sort',
minWidth: 80,
},
{
field: 'status',
title: '状态',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
minWidth: 80,
},
{
field: 'temperature',
title: '温度参数',
minWidth: 100,
},
{
title: '回复数 Token 数',
field: 'maxTokens',
minWidth: 140,
},
{
title: '上下文数量',
field: 'maxContexts',
minWidth: 120,
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,128 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiModelModelApi } from '#/api/ai/model/model';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteModel, getModelPage } from '#/api/ai/model/model';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建模型配置 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑模型配置 */
function handleEdit(row: AiModelModelApi.Model) {
formModalApi.setData(row).open();
}
/** 删除模型配置 */
async function handleDelete(row: AiModelModelApi.Model) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteModel(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getModelPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiModelModelApi.Model>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="AI 手册" url="https://doc.iocoder.cn/ai/build/" />
</template>
<FormModal @success="handleRefresh" />
<Grid table-title="模型配置列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['模型配置']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['ai:model:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['ai:model:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:model:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,82 @@
<script lang="ts" setup>
import type { AiModelModelApi } from '#/api/ai/model/model';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { createModel, getModel, updateModel } from '#/api/ai/model/model';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<AiModelModelApi.Model>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['模型配置'])
: $t('ui.actionTitle.create', ['模型配置']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data = (await formApi.getValues()) as AiModelModelApi.Model;
try {
await (formData.value?.id ? updateModel(data) : createModel(data));
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<AiModelModelApi.Model>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getModel(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-2/5">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,123 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { getRangePickerDefaultProps } from '#/utils';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'name',
label: '工具名称',
rules: 'required',
componentProps: {
placeholder: '请输入工具名称',
},
},
{
component: 'Textarea',
fieldName: 'description',
label: '工具描述',
componentProps: {
placeholder: '请输入工具描述',
},
},
{
fieldName: 'status',
label: '状态',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
defaultValue: CommonStatusEnum.ENABLE,
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '工具名称',
component: 'Input',
componentProps: {
placeholder: '请输入工具名称',
allowClear: true,
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
allowClear: true,
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择状态',
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '工具编号',
minWidth: 100,
},
{
field: 'name',
title: '工具名称',
minWidth: 120,
},
{
field: 'description',
title: '工具描述',
minWidth: 140,
},
{
field: 'status',
title: '状态',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
minWidth: 80,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,131 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiModelToolApi } from '#/api/ai/model/tool';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteTool, getToolPage } from '#/api/ai/model/tool';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建工具 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑工具 */
function handleEdit(row: AiModelToolApi.Tool) {
formModalApi.setData(row).open();
}
/** 删除工具 */
async function handleDelete(row: AiModelToolApi.Tool) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteTool(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getToolPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiModelToolApi.Tool>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert
title="AI 工具调用function calling"
url="https://doc.iocoder.cn/ai/tool/"
/>
</template>
<FormModal @success="handleRefresh" />
<Grid table-title="工具列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['工具']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['ai:tool:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['ai:tool:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:tool:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,82 @@
<script lang="ts" setup>
import type { AiModelToolApi } from '#/api/ai/model/tool';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { createTool, getTool, updateTool } from '#/api/ai/model/tool';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<AiModelToolApi.Tool>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['工具'])
: $t('ui.actionTitle.create', ['工具']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 100,
},
layout: 'horizontal',
schema: useFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data = (await formApi.getValues()) as AiModelToolApi.Tool;
try {
await (formData.value?.id ? updateTool(data) : createTool(data));
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
// 加载数据
const data = modalApi.getData<AiModelToolApi.Tool>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getTool(data.id);
// 设置到 values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-2/5">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,29 @@
<script lang="ts" setup>
import type { Nullable, Recordable } from '@vben/types';
import { ref, unref } from 'vue';
import { Page } from '@vben/common-ui';
import List from './list/index.vue';
import Mode from './mode/index.vue';
defineOptions({ name: 'AiMusicIndex' });
const listRef = ref<Nullable<{ generateMusic: (...args: any) => void }>>(null);
function generateMusic(args: { formData: Recordable<any> }) {
unref(listRef)?.generateMusic(args.formData);
}
</script>
<template>
<Page auto-content-height>
<div class="flex h-full items-stretch">
<!-- 模式 -->
<Mode class="flex-none" @generate-music="generateMusic" />
<!-- 音频列表 -->
<List ref="listRef" class="flex-auto" />
</div>
</Page>
</template>

View File

@@ -0,0 +1,99 @@
<script lang="ts" setup>
import { inject, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { formatPast } from '@vben/utils';
import { ElImage, ElSlider } from 'element-plus';
defineOptions({ name: 'AiMusicAudioBarIndex' });
const currentSong = inject<any>('currentSong', {});
const audioRef = ref<HTMLAudioElement | null>(null);
const audioProps = reactive<any>({
autoplay: true,
paused: false,
currentTime: '00:00',
duration: '00:00',
muted: false,
volume: 50,
}); // 音频相关属性https://www.runoob.com/tags/ref-av-dom.html
function toggleStatus(type: string) {
audioProps[type] = !audioProps[type];
if (type === 'paused' && audioRef.value) {
if (audioProps[type]) {
audioRef.value.pause();
} else {
audioRef.value.play();
}
}
}
/** 更新播放位置 */
function audioTimeUpdate(args: any) {
audioProps.currentTime = formatPast(new Date(args.timeStamp), 'mm:ss');
}
</script>
<template>
<div
class="b-1 b-l-none h-18 flex items-center justify-between border border-solid border-rose-100 bg-card px-2"
>
<!-- 歌曲信息 -->
<div class="flex gap-2.5">
<ElImage
src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
class="!w-[45px]"
/>
<div>
<div>{{ currentSong.name }}</div>
<div class="text-xs text-gray-400">{{ currentSong.singer }}</div>
</div>
</div>
<!-- 音频controls -->
<div class="flex items-center gap-3">
<IconifyIcon
icon="majesticons:back-circle"
class="size-5 cursor-pointer text-gray-300"
/>
<IconifyIcon
:icon="
audioProps.paused
? 'mdi:arrow-right-drop-circle'
: 'solar:pause-circle-bold'
"
class="size-7 cursor-pointer"
@click="toggleStatus('paused')"
/>
<IconifyIcon
icon="majesticons:next-circle"
class="size-5 cursor-pointer text-gray-300"
/>
<div class="flex items-center gap-4">
<span>{{ audioProps.currentTime }}</span>
<ElSlider v-model="audioProps.duration" color="#409eff" class="!w-40" />
<span>{{ audioProps.duration }}</span>
</div>
<!-- 音频 -->
<audio
v-bind="audioProps"
ref="audioRef"
controls
v-show="!audioProps"
@timeupdate="audioTimeUpdate"
>
<!-- <source :src="audioUrl" /> -->
</audio>
</div>
<div class="flex items-center gap-4">
<IconifyIcon
:icon="audioProps.muted ? 'tabler:volume-off' : 'tabler:volume'"
class="size-5 cursor-pointer"
@click="toggleStatus('muted')"
/>
<ElSlider v-model="audioProps.volume" color="#409eff" class="!w-40" />
</div>
</div>
</template>

View File

@@ -0,0 +1,100 @@
<script setup lang="ts">
import type { Recordable } from '@vben/types';
import { provide, ref } from 'vue';
import { ElCol, ElEmpty, ElRow, ElTabPane, ElTabs } from 'element-plus';
import audioBar from './audioBar/index.vue';
import songCard from './songCard/index.vue';
import songInfo from './songInfo/index.vue';
defineOptions({ name: 'AiMusicListIndex' });
const currentType = ref('mine');
const loading = ref(false); // loading 状态
const currentSong = ref({}); // 当前音乐
const mySongList = ref<Recordable<any>[]>([]);
const squareSongList = ref<Recordable<any>[]>([]);
function generateMusic(_formData: Recordable<any>) {
loading.value = true;
setTimeout(() => {
mySongList.value = Array.from({ length: 20 }, (_, index) => {
return {
id: index,
audioUrl: '',
videoUrl: '',
title: `我走后${index}`,
imageUrl:
'https://www.carsmp3.com/data/attachment/forum/201909/19/091020q5kgre20fidreqyt.jpg',
desc: 'Metal, symphony, film soundtrack, grand, majesticMetal, dtrack, grand, majestic',
date: '2024年04月30日 14:02:57',
lyric: `<div class="_words_17xen_66"><div>大江东去,浪淘尽,千古风流人物。
</div><div>故垒西边,人道是,三国周郎赤壁。
</div><div>乱石穿空,惊涛拍岸,卷起千堆雪。
</div><div>江山如画,一时多少豪杰。
</div><div>
</div><div>遥想公瑾当年,小乔初嫁了,雄姿英发。
</div><div>羽扇纶巾,谈笑间,樯橹灰飞烟灭。
</div><div>故国神游,多情应笑我,早生华发。
</div><div>人生如梦,一尊还酹江月。</div></div>`,
};
});
loading.value = false;
}, 3000);
}
function setCurrentSong(music: Recordable<any>) {
currentSong.value = music;
}
defineExpose({
generateMusic,
});
provide('currentSong', currentSong);
</script>
<template>
<div class="flex flex-col">
<div class="flex flex-auto overflow-hidden">
<ElTabs
v-model="currentType"
class="flex-auto px-5"
tab-position="bottom"
>
<!-- 我的创作 -->
<ElTabPane name="mine" label="我的创作" v-loading="loading">
<ElRow v-if="mySongList.length > 0" :gutter="12">
<ElCol v-for="song in mySongList" :key="song.id" :span="24">
<songCard :song-info="song" @play="setCurrentSong(song)" />
</ElCol>
</ElRow>
<ElEmpty v-else description="暂无音乐" />
</ElTabPane>
<!-- 试听广场 -->
<ElTabPane name="square" label="试听广场" v-loading="loading">
<ElRow v-if="squareSongList.length > 0" :gutter="12">
<ElCol v-for="song in squareSongList" :key="song.id" :span="24">
<songCard :song-info="song" @play="setCurrentSong(song)" />
</ElCol>
</ElRow>
<ElEmpty v-else description="暂无音乐" />
</ElTabPane>
</ElTabs>
<!-- songInfo -->
<songInfo class="flex-none" />
</div>
<audioBar class="flex-none" />
</div>
</template>
<style lang="scss" scoped>
:deep(.el-tabs) {
.el-tabs__content {
padding: 0 7px;
overflow: auto;
}
}
</style>

View File

@@ -0,0 +1,50 @@
<script lang="ts" setup>
import { inject } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { ElImage } from 'element-plus';
defineOptions({ name: 'AiMusicSongCardIndex' });
defineProps({
songInfo: {
type: Object,
default: () => ({}),
},
});
const emits = defineEmits(['play']);
const currentSong = inject<any>('currentSong', {});
function playSong() {
emits('play');
}
</script>
<template>
<div class="mb-3 flex rounded p-3">
<div class="relative" @click="playSong">
<ElImage :src="songInfo.imageUrl" class="w-20 flex-none" />
<div
class="absolute left-0 top-0 flex h-full w-full cursor-pointer items-center justify-center bg-black bg-opacity-40"
>
<IconifyIcon
:icon="
currentSong.id === songInfo.id
? 'solar:pause-circle-bold'
: 'mdi:arrow-right-drop-circle'
"
:size="30"
/>
</div>
</div>
<div class="ml-2">
<div>{{ songInfo.title }}</div>
<div class="mt-2 line-clamp-2 text-xs">
{{ songInfo.desc }}
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,25 @@
<script lang="ts" setup>
import { inject } from 'vue';
import { ElButton, ElCard, ElImage } from 'element-plus';
defineOptions({ name: 'AiMusicSongInfoIndex' });
const currentSong = inject<any>('currentSong', {});
</script>
<template>
<ElCard class="!mb-0 w-40 leading-6">
<ElImage :src="currentSong.imageUrl" class="h-full w-full" />
<div class="">{{ currentSong.title }}</div>
<div class="line-clamp-1 text-xs">
{{ currentSong.desc }}
</div>
<div class="text-xs">
{{ currentSong.date }}
</div>
<ElButton size="small" round class="my-2">信息复用</ElButton>
<div class="text-xs" v-html="currentSong.lyric"></div>
</ElCard>
</template>

View File

@@ -0,0 +1,66 @@
<script lang="ts" setup>
import { reactive } from 'vue';
import { ElInput, ElOption, ElSelect, ElSwitch } from 'element-plus';
import Title from '../title/index.vue';
defineOptions({ name: 'AiMusicModeDesc' });
const formData = reactive({
desc: '',
pure: false,
version: '3',
});
defineExpose({
formData,
});
</script>
<template>
<div>
<Title
title="音乐/歌词说明"
desc="描述您想要的音乐风格和主题,使用流派和氛围而不是特定的艺术家和歌曲"
>
<ElInput
v-model="formData.desc"
type="textarea"
:autosize="{ minRows: 6, maxRows: 6 }"
:maxlength="1200"
:show-word-limit="true"
placeholder="一首关于糟糕分手的欢快歌曲"
/>
</Title>
<Title title="纯音乐" class="mt-5" desc="创建一首没有歌词的歌曲">
<template #extra>
<ElSwitch v-model="formData.pure" size="small" />
</template>
</Title>
<Title
title="版本"
desc="描述您想要的音乐风格和主题,使用流派和氛围而不是特定的艺术家和歌曲"
>
<ElSelect v-model="formData.version" class="w-full" placeholder="请选择">
<ElOption
v-for="item in [
{
value: '3',
label: 'V3',
},
{
value: '2',
label: 'V2',
},
]"
:key="item.value"
:value="item.value"
:label="item.label"
/>
</ElSelect>
</Title>
</div>
</template>

View File

@@ -0,0 +1,38 @@
<script lang="ts" setup>
import type { Nullable, Recordable } from '@vben/types';
import { ref, unref } from 'vue';
import { ElButton, ElCard, ElRadioButton, ElRadioGroup } from 'element-plus';
import desc from './desc.vue';
import lyric from './lyric.vue';
defineOptions({ name: 'AiMusicModeIndex' });
const emits = defineEmits(['generateMusic']);
const generateMode = ref('lyric');
const modeRef = ref<Nullable<{ formData: Recordable<any> }>>(null);
function generateMusic() {
emits('generateMusic', { formData: unref(modeRef)?.formData });
}
</script>
<template>
<ElCard class="!mb-0 h-full w-80">
<ElRadioGroup v-model="generateMode" class="mb-4">
<ElRadioButton value="desc"> 描述模式 </ElRadioButton>
<ElRadioButton value="lyric"> 歌词模式 </ElRadioButton>
</ElRadioGroup>
<!-- 描述模式/歌词模式 切换 -->
<component :is="generateMode === 'desc' ? desc : lyric" ref="modeRef" />
<ElButton type="primary" round class="w-full" @click="generateMusic">
创作音乐
</ElButton>
</ElCard>
</template>

View File

@@ -0,0 +1,107 @@
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import {
ElButton,
ElInput,
ElOption,
ElSelect,
ElSpace,
ElTag,
} from 'element-plus';
import Title from '../title/index.vue';
defineOptions({ name: 'AiMusicModeLyric' });
const tags = ['rock', 'punk', 'jazz', 'soul', 'country', 'kidsmusic', 'pop'];
const showCustom = ref(false);
const formData = reactive({
lyric: '',
style: '',
name: '',
version: '',
});
defineExpose({
formData,
});
</script>
<template>
<div class="">
<Title title="歌词" desc="自己编写歌词或使用Ai生成歌词两节/8行效果最佳">
<ElInput
v-model="formData.lyric"
type="textarea"
:autosize="{ minRows: 6, maxRows: 6 }"
:maxlength="1200"
:show-word-limit="true"
placeholder="请输入您自己的歌词"
/>
</Title>
<Title title="音乐风格">
<ElSpace class="flex-wrap">
<ElTag v-for="tag in tags" :key="tag" class="mb-2">
{{ tag }}
</ElTag>
</ElSpace>
<ElButton
:type="showCustom ? 'primary' : 'default'"
round
size="small"
class="mb-2"
@click="showCustom = !showCustom"
>
自定义风格
</ElButton>
</Title>
<Title
v-show="showCustom"
desc="描述您想要的音乐风格Suno无法识别艺术家的名字但可以理解流派和氛围"
class="mt-3"
>
<ElInput
v-model="formData.style"
type="textarea"
:autosize="{ minRows: 4, maxRows: 4 }"
:maxlength="256"
show-word-limit
placeholder="输入音乐风格(英文)"
/>
</Title>
<Title title="音乐/歌曲名称">
<ElInput
class="w-full"
v-model="formData.name"
placeholder="请输入音乐/歌曲名称"
/>
</Title>
<Title title="版本">
<ElSelect v-model="formData.version" class="w-full" placeholder="请选择">
<ElOption
v-for="item in [
{
value: '3',
label: 'V3',
},
{
value: '2',
label: 'V2',
},
]"
:key="item.value"
:value="item.value"
:label="item.label"
/>
</ElSelect>
</Title>
</div>
</template>

View File

@@ -0,0 +1,27 @@
<script lang="ts" setup>
defineOptions({ name: 'AiMusicTitleIndex' });
defineProps({
title: {
type: String,
default: '',
},
desc: {
type: String,
default: '',
},
});
</script>
<template>
<div class="mb-3">
<div class="flex items-center justify-between text-gray-600">
<span>{{ title }}</span>
<slot name="extra"></slot>
</div>
<div class="my-2 text-xs text-gray-400">
{{ desc }}
</div>
<slot></slot>
</div>
</template>

View File

@@ -0,0 +1,202 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api/system/user';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 关联数据 */
let userList: SystemUserApi.User[] = [];
getSimpleUserList().then((data) => (userList = data));
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'userId',
label: '用户编号',
component: 'ApiSelect',
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
placeholder: '请选择用户编号',
clearable: true,
},
},
{
fieldName: 'title',
label: '音乐名称',
component: 'Input',
componentProps: {
placeholder: '请输入音乐名称',
clearable: true,
},
},
{
fieldName: 'status',
label: '绘画状态',
component: 'Select',
componentProps: {
placeholder: '请选择绘画状态',
clearable: true,
options: getDictOptions(DICT_TYPE.AI_MUSIC_STATUS, 'number'),
},
},
{
fieldName: 'generateMode',
label: '生成模式',
component: 'Select',
componentProps: {
placeholder: '请选择生成模式',
clearable: true,
options: getDictOptions(DICT_TYPE.AI_GENERATE_MODE, 'number'),
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
{
fieldName: 'publicStatus',
label: '是否发布',
component: 'Select',
componentProps: {
placeholder: '请选择是否发布',
clearable: true,
options: getDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING, 'boolean'),
},
},
];
}
/** 列表的字段 */
export function useGridColumns(
onPublicStatusChange?: (
newStatus: boolean,
row: any,
) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '编号',
minWidth: 180,
fixed: 'left',
},
{
title: '音乐名称',
minWidth: 180,
fixed: 'left',
field: 'title',
},
{
minWidth: 180,
title: '用户',
field: 'userId',
formatter: ({ cellValue }) => {
return userList.find((user) => user.id === cellValue)?.nickname || '-';
},
},
{
field: 'status',
title: '音乐状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_MUSIC_STATUS },
},
},
{
field: 'model',
title: '模型',
minWidth: 180,
},
{
title: '内容',
minWidth: 180,
slots: { default: 'content' },
},
{
field: 'duration',
title: '时长(秒)',
minWidth: 100,
},
{
field: 'prompt',
title: '提示词',
minWidth: 180,
},
{
field: 'lyric',
title: '歌词',
minWidth: 180,
},
{
field: 'gptDescriptionPrompt',
title: '描述',
minWidth: 180,
},
{
field: 'generateMode',
title: '生成模式',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_GENERATE_MODE },
},
},
{
field: 'tags',
title: '风格标签',
minWidth: 180,
cellRender: {
name: 'CellTags',
},
},
{
minWidth: 100,
title: '是否发布',
field: 'publicStatus',
align: 'center',
cellRender: {
attrs: { beforeChange: onPublicStatusChange },
name: 'CellSwitch',
props: {
activeValue: true,
inactiveValue: false,
},
},
},
{
field: 'taskId',
title: '任务编号',
minWidth: 180,
},
{
field: 'errorMessage',
title: '错误信息',
minWidth: 180,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,152 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiMusicApi } from '#/api/ai/music';
import { confirm, DocAlert, Page } from '@vben/common-ui';
import { ElButton, ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteMusic, getMusicPage, updateMusic } from '#/api/ai/music';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 删除音乐记录 */
async function handleDelete(row: AiMusicApi.Music) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteMusic(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 修改是否发布 */
async function handleUpdatePublicStatusChange(
newStatus: boolean,
row: AiMusicApi.Music,
): Promise<boolean | undefined> {
const text = newStatus ? '公开' : '私有';
return new Promise((resolve, reject) => {
confirm({
content: `确认要将该音乐切换为【${text}】吗?`,
})
.then(async () => {
// 更新音乐状态
await updateMusic({
id: row.id,
publicStatus: newStatus,
});
// 提示并返回成功
ElMessage.success($t('ui.actionMessage.operationSuccess'));
resolve(true);
})
.catch(() => {
reject(new Error('取消操作'));
});
});
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(handleUpdatePublicStatusChange),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getMusicPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiMusicApi.Music>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="AI 音乐创作" url="https://doc.iocoder.cn/ai/music/" />
</template>
<Grid table-title="音乐管理列表">
<template #toolbar-tools>
<TableAction :actions="[]" />
</template>
<template #content="{ row }">
<ElButton
type="primary"
link
v-if="row.audioUrl?.length > 0"
:href="row.audioUrl"
target="_blank"
class="p-0"
>
音乐
</ElButton>
<ElButton
type="primary"
link
v-if="row.videoUrl?.length > 0"
:href="row.videoUrl"
target="_blank"
class="p-0 !pl-1"
>
视频
</ElButton>
<ElButton
type="primary"
link
v-if="row.imageUrl?.length > 0"
:href="row.imageUrl"
target="_blank"
class="p-0 !pl-1"
>
封面
</ElButton>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:music:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.id]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,97 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { getRangePickerDefaultProps } from '#/utils';
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'code',
label: '流程标识',
component: 'Input',
componentProps: {
placeholder: '请输入流程标识',
allowClear: true,
},
},
{
fieldName: 'name',
label: '流程名称',
component: 'Input',
componentProps: {
placeholder: '请输入流程名称',
allowClear: true,
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择状态',
allowClear: true,
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '编号',
minWidth: 100,
},
{
field: 'code',
title: '流程标识',
minWidth: 150,
},
{
field: 'name',
title: '流程名称',
minWidth: 200,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
field: 'remark',
title: '备注',
minWidth: 200,
},
{
field: 'status',
title: '状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,288 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, provide, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { confirm, Page } from '@vben/common-ui';
import { AiModelTypeEnum, CommonStatusEnum } from '@vben/constants';
import { useTabs } from '@vben/hooks';
import { IconifyIcon } from '@vben/icons';
import { ElButton, ElCard, ElMessage } from 'element-plus';
import { getModelSimpleList } from '#/api/ai/model/model';
import { createWorkflow, getWorkflow, updateWorkflow } from '#/api/ai/workflow';
import { createModel, deployModel, updateModel } from '#/api/bpm/model';
import BasicInfo from './modules/basic-info.vue';
import WorkflowDesign from './modules/workflow-design.vue';
defineOptions({ name: 'AiWorkflowCreate' });
const router = useRouter();
const route = useRoute();
const workflowId = ref<string>('');
const actionType = ref<string>('');
const basicInfoRef = ref<InstanceType<typeof BasicInfo>>(); // 基础信息组件引用
const workflowDesignRef = ref<InstanceType<typeof WorkflowDesign>>(); // 工作流设计组件引用
const currentStep = ref(-1); // 步骤控制。-1 用于,一开始全部不展示等当前页面数据初始化完成
const steps = [
{ title: '基本信息', validator: validateBasic },
{ title: '工作流设计', validator: validateWorkflow },
];
const formData: any = ref({
id: undefined,
name: '',
code: '',
remark: '',
graph: '',
status: CommonStatusEnum.ENABLE,
}); // 表单数据
const llmProvider = ref<any>([]);
const workflowData = ref<any>({});
provide('workflowData', workflowData);
/** 步骤校验函数 */
async function validateBasic() {
await basicInfoRef.value?.validate();
}
/** 工作流设计校验 */
async function validateWorkflow() {
await workflowDesignRef.value?.validate();
}
async function initData() {
if (actionType.value === 'update' && workflowId.value) {
formData.value = await getWorkflow(workflowId.value as any);
workflowData.value = JSON.parse(formData.value.graph);
}
const models = await getModelSimpleList(AiModelTypeEnum.CHAT);
llmProvider.value = {
llm: () =>
models.map(({ id, name }) => ({
value: id,
label: name,
})),
knowledge: () => [],
internal: () => [],
};
// 设置当前步骤
currentStep.value = 0;
}
/** 校验所有步骤数据是否完整 */
async function validateAllSteps() {
// 基本信息校验
try {
await validateBasic();
} catch {
currentStep.value = 0;
throw new Error('请完善基本信息');
}
// 表单设计校验
try {
await validateWorkflow();
} catch {
currentStep.value = 1;
throw new Error('请完善工作流信息');
}
return true;
}
/** 保存操作 */
async function handleSave() {
try {
// 保存前校验所有步骤的数据
await validateAllSteps();
// 更新表单数据
const data = {
...formData.value,
graph: JSON.stringify(workflowData.value),
};
await (actionType.value === 'update'
? updateWorkflow(data)
: createWorkflow(data));
// 保存成功,提示并跳转到列表页
ElMessage.success('保存成功');
await tabs.closeCurrentTab();
await router.push({ name: 'AiWorkflow' });
} catch (error: any) {
console.error('保存失败:', error);
ElMessage.warning(error.message || '请完善所有步骤的必填信息');
}
}
/** 发布操作 */
async function handleDeploy() {
try {
// 修改场景下直接发布,新增场景下需要先确认
if (!formData.value.id) {
await confirm('是否确认发布该流程?');
}
// 校验所有步骤
await validateAllSteps();
// 更新表单数据
const modelData = {
...formData.value,
};
// 先保存所有数据
if (formData.value.id) {
await updateModel(modelData);
} else {
const result = await createModel(modelData);
formData.value.id = result.id;
}
// 发布
await deployModel(formData.value.id);
ElMessage.success('发布成功');
// 返回列表页
await router.push({ name: 'AiWorkflow' });
} catch (error: any) {
console.error('发布失败:', error);
ElMessage.warning(error.message || '发布失败');
}
}
/** 步骤切换处理 */
async function handleStepClick(index: number) {
try {
if (index !== 0) {
await validateBasic();
}
if (index !== 1) {
await validateWorkflow();
}
// 切换步骤
currentStep.value = index;
} catch (error) {
console.error('步骤切换失败:', error);
ElMessage.warning('请先完善当前步骤必填信息');
}
}
const tabs = useTabs();
/** 返回列表页 */
function handleBack() {
// 关闭当前页签
tabs.closeCurrentTab();
// 跳转到列表页,使用路径, 目前后端的路由 name 'name'+ menuId
router.push({ path: '/ai/workflow' });
}
/** 初始化 */
onMounted(async () => {
workflowId.value = route.params.id as string;
actionType.value = route.params.type as string;
await initData();
});
/** 添加组件卸载前的清理 */
onBeforeUnmount(() => {
// 清理所有的引用
basicInfoRef.value = undefined;
workflowDesignRef.value = undefined;
});
</script>
<template>
<Page auto-content-height>
<div class="mx-auto">
<!-- 头部导航栏 -->
<div
class="absolute inset-x-0 top-0 z-10 flex h-12 items-center border-b bg-card px-5"
>
<!-- 左侧标题 -->
<div class="flex w-48 items-center overflow-hidden">
<IconifyIcon
icon="lucide:arrow-left"
class="size-5 flex-shrink-0 cursor-pointer"
@click="handleBack"
/>
<span
class="ml-2.5 truncate text-base"
:title="formData.name || '创建AI 工作流'"
>
{{ formData.name || '创建AI 工作流' }}
</span>
</div>
<!-- 步骤条 -->
<div class="flex h-full flex-1 items-center justify-center">
<div class="flex h-full w-96 items-center justify-between">
<div
v-for="(step, index) in steps"
:key="index"
class="relative mx-4 flex h-full cursor-pointer items-center"
:class="[
currentStep === index
? 'border-b-2 border-solid border-blue-500 text-blue-500'
: 'text-gray-500',
]"
@click="handleStepClick(index)"
>
<div
class="mr-2 flex h-7 w-7 items-center justify-center rounded-full border-2 border-solid text-base"
:class="[
currentStep === index
? 'border-blue-500 bg-blue-500 text-white'
: 'border-gray-300 bg-white text-gray-500',
]"
>
{{ index + 1 }}
</div>
<span class="whitespace-nowrap text-base font-bold">
{{ step.title }}
</span>
</div>
</div>
</div>
<!-- 右侧按钮 -->
<div class="flex w-48 items-center justify-end gap-2">
<ElButton
v-if="actionType === 'update'"
type="primary"
@click="handleDeploy"
>
</ElButton>
<ElButton type="primary" @click="handleSave">
<span v-if="actionType === 'definition'"> </span>
<span v-else> </span>
</ElButton>
</div>
</div>
<!-- 主体内容 -->
<ElCard class="mb-4 p-4">
<div class="mt-12">
<!-- 第一步基本信息 -->
<div v-if="currentStep === 0" class="mx-auto w-4/6">
<BasicInfo v-model="formData" ref="basicInfoRef" />
</div>
<!-- 第二步表单设计 -->
<WorkflowDesign
v-if="currentStep === 1"
v-model="formData"
:provider="llmProvider"
ref="workflowDesignRef"
/>
</div>
</ElCard>
</div>
</Page>
</template>

View File

@@ -0,0 +1,70 @@
<script lang="ts" setup>
import type { FormRules } from 'element-plus';
import { ref } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { ElForm, ElFormItem, ElInput, ElOption, ElSelect } from 'element-plus';
const modelData = defineModel<any>(); // 创建本地数据副本
const formRef = ref(); // 表单引用
const rules: FormRules = {
code: [{ required: true, message: '流程标识不能为空', trigger: 'blur' }],
name: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }],
status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
};
/** 表单校验 */
async function validate() {
await formRef.value?.validate();
}
defineExpose({ validate });
</script>
<template>
<ElForm
ref="formRef"
:model="modelData"
:rules="rules"
label-width="120px"
label-position="right"
class="mt-5"
>
<ElFormItem label="流程标识" prop="code" class="mb-5">
<ElInput
class="w-full"
v-model="modelData.code"
clearable
placeholder="请输入流程标识"
/>
</ElFormItem>
<ElFormItem label="流程名称" prop="name" class="mb-5">
<ElInput
v-model="modelData.name"
clearable
placeholder="请输入流程名称"
/>
</ElFormItem>
<ElFormItem label="状态" prop="status" class="mb-5">
<ElSelect
class="w-full"
v-model="modelData.status"
clearable
placeholder="请选择状态"
>
<ElOption
v-for="dict in getDictOptions(DICT_TYPE.COMMON_STATUS, 'number')"
:key="dict.value"
:value="dict.value"
:label="dict.label"
/>
</ElSelect>
</ElFormItem>
<ElFormItem label="流程描述" prop="description" class="mb-5">
<ElInput v-model="modelData.description" type="textarea" clearable />
</ElFormItem>
</ElForm>
</template>

View File

@@ -0,0 +1,286 @@
<script lang="ts" setup>
import type { Ref } from 'vue';
import { inject, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { Tinyflow } from '@vben/plugins/tinyflow';
import { isNumber } from '@vben/utils';
import { ElButton, ElInput, ElOption, ElSelect } from 'element-plus';
import { testWorkflow } from '#/api/ai/workflow';
defineProps<{
provider: any;
}>();
const tinyflowRef = ref<InstanceType<typeof Tinyflow> | null>(null);
const workflowData = inject('workflowData') as Ref;
const params4Test = ref<any[]>([]);
const paramsOfStartNode = ref<any>({});
const testResult = ref(null);
const loading = ref(false);
const error = ref(null);
const [Drawer, drawerApi] = useVbenDrawer({
footer: false,
closeOnClickModal: false,
modal: false,
onOpenChange(isOpen: boolean) {
if (!isOpen) {
return;
}
try {
// 查找 start 节点
const startNode = getStartNode();
// 获取参数定义
const parameters: any[] = (startNode.data?.parameters as any[]) || [];
const paramDefinitions: Record<string, any> = {};
// 加入参数选项方便用户添加非必须参数
parameters.forEach((param: any) => {
paramDefinitions[param.name] = param;
});
// 自动装载需必填的参数
function mergeIfRequiredButNotSet(target: any[]) {
const needPushList = [];
for (const key in paramDefinitions) {
const param = paramDefinitions[key];
if (param.required) {
const item = target.find((item: any) => item.key === key);
if (!item) {
needPushList.push({
key: param.name,
value: param.defaultValue || '',
});
}
}
}
target.push(...needPushList);
}
mergeIfRequiredButNotSet(params4Test.value);
// 设置参数
paramsOfStartNode.value = paramDefinitions;
} catch (error) {
console.error('加载参数失败:', error);
}
},
});
/** 展示工作流测试抽屉 */
function testWorkflowModel() {
drawerApi.open();
}
/** 运行流程 */
async function goRun() {
try {
const val = tinyflowRef.value?.getData();
loading.value = true;
error.value = null;
testResult.value = null;
// 查找start节点
const startNode = getStartNode();
// 获取参数定义
const parameters: any[] = (startNode.data?.parameters as any[]) || [];
const paramDefinitions: Record<string, any> = {};
parameters.forEach((param: any) => {
paramDefinitions[param.name] = param.dataType;
});
// 参数类型转换
const convertedParams: Record<string, any> = {};
for (const { key, value } of params4Test.value) {
const paramKey = key.trim();
if (!paramKey) {
continue;
}
let dataType = paramDefinitions[paramKey];
if (!dataType) {
dataType = 'String';
}
try {
convertedParams[paramKey] = convertParamValue(value, dataType);
} catch (error: any) {
throw new Error(`参数 ${paramKey} 转换失败: ${error.message}`);
}
}
// 执行测试请求
testResult.value = await testWorkflow({
graph: JSON.stringify(val),
params: convertedParams,
});
} catch (error: any) {
error.value =
error.response?.data?.message || '运行失败,请检查参数和网络连接';
} finally {
loading.value = false;
}
}
/** 获取开始节点 */
function getStartNode() {
if (tinyflowRef.value) {
// TODO @xingyu不确定是不是这里封装了 Tinyflow现在 .getData() 会报错;
const val = tinyflowRef.value.getData();
const startNode = val!.nodes.find((node: any) => node.type === 'startNode');
if (!startNode) {
throw new Error('流程缺少开始节点');
}
return startNode;
}
throw new Error('请设计流程');
}
/** 添加参数项 */
function addParam() {
params4Test.value.push({ key: '', value: '' });
}
/** 删除参数项 */
function removeParam(index: number) {
params4Test.value.splice(index, 1);
}
/** 类型转换函数 */
function convertParamValue(value: string, dataType: string) {
if (value === '') {
return null;
}
switch (dataType) {
case 'Number': {
const num = Number(value);
if (!isNumber(num)) throw new Error('非数字格式');
return num;
}
case 'String': {
return String(value);
}
case 'Boolean': {
if (value.toLowerCase() === 'true') {
return true;
}
if (value.toLowerCase() === 'false') {
return false;
}
throw new Error('必须为 true/false');
}
case 'Array':
case 'Object': {
try {
return JSON.parse(value);
} catch (error: any) {
throw new Error(`JSON格式错误: ${error.message}`);
}
}
default: {
throw new Error(`不支持的类型: ${dataType}`);
}
}
}
/** 表单校验 */
async function validate() {
if (!workflowData.value || !tinyflowRef.value) {
throw new Error('请设计流程');
}
workflowData.value = tinyflowRef.value.getData();
return true;
}
defineExpose({ validate });
</script>
<template>
<div class="relative h-[800px] w-full">
<Tinyflow
v-if="workflowData"
ref="tinyflowRef"
class-name="custom-class"
class="h-full w-full"
:data="workflowData"
:provider="provider"
/>
<div class="absolute right-8 top-8">
<ElButton
@click="testWorkflowModel"
type="primary"
v-access:code="['ai:workflow:test']"
>
测试
</ElButton>
</div>
<Drawer title="工作流测试">
<fieldset
class="min-inline-size-auto m-0 rounded-lg border border-gray-200 px-3 py-4"
>
<legend class="ml-2 px-2.5 text-base font-semibold text-gray-600">
<h3>运行参数配置</h3>
</legend>
<div class="p-2">
<div
class="mb-1 flex items-center justify-around"
v-for="(param, index) in params4Test"
:key="index"
>
<ElSelect class="w-48" v-model="param.key" placeholder="参数名">
<ElOption
v-for="(value, key) in paramsOfStartNode"
:key="key"
:value="key"
:disabled="!!value?.disabled"
:label="value?.description || key"
/>
</ElSelect>
<ElInput
class="mx-2 w-48"
v-model="param.value"
placeholder="参数值"
/>
<ElButton type="danger" circle @click="removeParam(index)">
<template #icon>
<IconifyIcon icon="lucide:trash" />
</template>
</ElButton>
</div>
<ElButton type="primary" plain class="mt-2" @click="addParam">
添加参数
</ElButton>
</div>
</fieldset>
<fieldset
class="m-0 mt-10 rounded-lg border border-gray-200 bg-card px-3 py-4"
>
<legend class="ml-2 px-2.5 text-base font-semibold text-gray-600">
<h3>运行结果</h3>
</legend>
<div class="p-2">
<div v-if="loading" class="text-primary">执行中...</div>
<div v-else-if="error" class="text-danger">{{ error }}</div>
<pre
v-else-if="testResult"
class="max-h-80 overflow-auto whitespace-pre-wrap rounded-lg bg-white p-3 font-mono text-sm leading-5"
>
{{ JSON.stringify(testResult, null, 2) }}
</pre>
<div v-else class="text-gray-400">点击运行查看结果</div>
</div>
</fieldset>
<ElButton
size="large"
class="mt-2 w-full bg-green-500 text-white"
@click="goRun"
>
运行流程
</ElButton>
</Drawer>
</div>
</template>

View File

@@ -0,0 +1,124 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiWorkflowApi } from '#/api/ai/workflow';
import { Page } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteWorkflow, getWorkflowPage } from '#/api/ai/workflow';
import { $t } from '#/locales';
import { router } from '#/router';
import { useGridColumns, useGridFormSchema } from './data';
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建工作流 */
function handleCreate() {
router.push({
name: 'AiWorkflowCreate',
});
}
/** 编辑工作流 */
function handleEdit(row: any) {
router.push({
name: 'AiWorkflowCreate',
params: { id: row.id, type: 'update' },
});
}
/** 删除工作流 */
async function handleDelete(row: any) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteWorkflow(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getWorkflowPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiWorkflowApi.Workflow>,
});
</script>
<template>
<Page auto-content-height>
<Grid table-title="AI 工作流列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['AI 工作流']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['ai:workflow:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['ai:workflow:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:workflow:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.id]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

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