This commit is contained in:
hw
2025-11-18 13:45:13 +08:00
424 changed files with 37728 additions and 1604 deletions

View File

@@ -0,0 +1,77 @@
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: '请输入温度参数',
class: 'w-full',
precision: 2,
min: 0,
max: 2,
},
rules: 'required',
},
{
fieldName: 'maxTokens',
label: '回复数 Token 数',
component: 'InputNumber',
componentProps: {
placeholder: '请输入回复数 Token 数',
class: 'w-full',
min: 0,
max: 8192,
},
rules: 'required',
},
{
fieldName: 'maxContexts',
label: '上下文数量',
component: 'InputNumber',
componentProps: {
placeholder: '请输入上下文数量',
class: 'w-full',
min: 0,
max: 20,
},
rules: 'required',
},
];
}

View File

@@ -0,0 +1,690 @@
<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 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 class="bg-card mx-4">
<ElHeader
class="!bg-card border-border flex !h-12 items-center justify-between border-b !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" v-if="activeConversation">
<ElButton
type="primary"
plain
class="mr-2 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="mr-2 px-2"
@click="handlerMessageClear"
>
<IconifyIcon icon="lucide:trash-2" color="#787878" />
</ElButton>
<ElButton size="small" class="mr-2 px-2">
<IconifyIcon icon="lucide:download" color="#787878" />
</ElButton>
<ElButton
size="small"
class="mr-2 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 class="!bg-card flex flex-col !p-0">
<form
class="border-border mx-4 mb-8 mt-2 flex flex-col rounded-xl 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="danger"
@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,397 @@
<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.sort((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 handleConversationCreate() {
// 1. 创建对话
const conversationId = await createChatConversationMy({
roleId: undefined,
} as unknown as AiChatConversationApi.ChatConversation);
// 2. 刷新列表
await getChatConversationList();
// 3. 回调
emits('onConversationCreate', conversationId);
}
/** 清空未置顶的对话 */
async function handleConversationClear() {
await confirm({
title: '清空未置顶的对话',
content: h('div', {}, [
h('p', '确认清空未置顶的对话吗?'),
h('p', '清空后,未置顶的对话将被删除,无法恢复!'),
]),
});
// 清空
await deleteChatConversationMyByUnpinned();
// 刷新列表
await getChatConversationList();
// 回调
emits('onConversationClear');
}
/** 删除对话 */
async function handleConversationDelete(id: number) {
await confirm({
title: '删除对话',
content: h('div', {}, [
h('p', '确认删除该对话吗?'),
h('p', '删除后,该对话将被删除,无法恢复!'),
]),
});
// 删除
await deleteChatConversationMy(id);
// 刷新列表
await getChatConversationList();
// 回调
emits('onConversationDelete', id);
}
/** 置顶对话 */
async function handleConversationPin(conversation: any) {
// 更新
await updateChatConversationMy({
id: conversation.id,
pinned: !conversation.pinned,
} as AiChatConversationApi.ChatConversation);
// 刷新列表
await getChatConversationList();
}
/** 编辑对话 */
async function handleConversationEdit(conversation: any) {
const title = await prompt({
title: '编辑对话',
content: '请输入对话标题',
defaultValue: conversation.title,
});
// 更新
await updateChatConversationMy({
id: conversation.id,
title,
} as AiChatConversationApi.ChatConversation);
// 刷新列表
await getChatConversationList();
// 提示
ElMessage.success($t('ui.actionMessage.operationSuccess'));
}
/** 打开角色仓库 */
async function handleRoleRepositoryOpen() {
drawerApi.open();
}
/** 监听 activeId 变化 */
watch(
() => props.activeId,
(newValue) => {
activeConversationId.value = newValue;
},
);
const { activeId } = toRefs(props);
/** 初始化 */
onMounted(async () => {
// 获取对话列表
await getChatConversationList();
// 设置选中的对话
if (activeId.value) {
activeConversationId.value = activeId.value;
}
});
defineExpose({ getChatConversationList });
</script>
<template>
<ElAside
class="bg-card relative flex h-full flex-col overflow-hidden border-r border-gray-200"
width="280px"
>
<Drawer />
<!-- 头部 -->
<div class="flex flex-col p-4">
<div class="mb-4 flex flex-row items-center justify-between">
<div class="text-lg font-bold">对话</div>
<div class="flex flex-row">
<ElButton
class="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
text
@click="handleConversationCreate"
>
<IconifyIcon icon="lucide:plus" />
</ElButton>
<ElButton
class="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
text
@click="handleConversationClear"
>
<IconifyIcon icon="lucide:trash" />
</ElButton>
<ElButton
class="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
text
@click="handleRoleRepositoryOpen"
>
<IconifyIcon icon="lucide:user" />
</ElButton>
</div>
</div>
<ElInput
v-model="searchName"
placeholder="搜索对话"
@keyup.enter="searchConversation"
>
<template #suffix>
<IconifyIcon icon="lucide:search" />
</template>
</ElInput>
</div>
<!-- 对话列表 -->
<div class="flex-1 overflow-y-auto px-4">
<div v-if="loading" class="flex h-full items-center justify-center">
<div class="text-sm text-gray-400">加载中...</div>
</div>
<div v-else-if="Object.keys(conversationMap).length === 0">
<ElEmpty description="暂无对话" />
</div>
<div v-else>
<div
v-for="(conversations, groupName) in conversationMap"
:key="groupName"
>
<div
v-if="conversations.length > 0"
class="mb-2 mt-4 text-xs text-gray-400"
>
{{ groupName }}
</div>
<div
v-for="conversation in conversations"
:key="conversation.id"
class="group relative mb-2 cursor-pointer rounded-lg p-2 transition-all hover:bg-gray-100"
:class="{
'bg-gray-100': activeConversationId === conversation.id,
}"
@click="handleConversationClick(conversation.id)"
@mouseenter="hoverConversationId = conversation.id"
@mouseleave="hoverConversationId = null"
>
<div class="flex items-center">
<ElAvatar
v-if="conversation.roleAvatar"
:src="conversation.roleAvatar"
:size="28"
/>
<SvgGptIcon v-else class="size-7" />
<div class="ml-2 flex-1 overflow-hidden">
<div class="truncate text-sm font-medium">
{{ conversation.title }}
</div>
</div>
<div
v-if="hoverConversationId === conversation.id"
class="flex flex-row"
>
<ElButton
class="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
text
@click.stop="handleConversationPin(conversation)"
>
<IconifyIcon
:icon="
conversation.pinned ? 'lucide:pin-off' : 'lucide:pin'
"
/>
</ElButton>
<ElButton
class="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
text
@click.stop="handleConversationEdit(conversation)"
>
<IconifyIcon icon="lucide:edit" />
</ElButton>
<ElButton
class="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
text
@click.stop="handleConversationDelete(conversation.id)"
>
<IconifyIcon icon="lucide:trash" />
</ElButton>
</div>
</div>
</div>
</div>
</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.log('上传响应:', response);
// 兼容不同的返回格式:{ url: '...' } 或 { data: '...' } 或直接是字符串
const fileUrl =
(response as any)?.url || (response as any)?.data || response;
fileItem.url = fileUrl;
console.log('提取的文件 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="animate-in fade-in slide-in-from-bottom-1 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"
@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="bg-card cursor-pointer rounded-lg 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,39 @@
<!-- 消息列表为空时展示 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">
<!-- center-container -->
<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,242 @@
<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="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="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="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
text
@click="copyContent(item.content)"
>
<IconifyIcon icon="lucide:copy" />
</ElButton>
<ElButton
class="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
text
@click="handleDelete(item.id)"
>
<IconifyIcon icon="lucide:trash" />
</ElButton>
<ElButton
class="flex items-center bg-transparent px-1.5 hover:bg-gray-100"
text
@click="handleRefresh(item)"
>
<IconifyIcon icon="lucide:refresh-cw" />
</ElButton>
<ElButton
class="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="z-1000 absolute bottom-0 right-1/2"
@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,83 @@
<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="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 px-6 pb-36"
ref="tabsRef"
@scroll="handleTabsScroll"
>
<div class="mb-5 mr-5 inline-block" v-for="role in roleList" :key="role.id">
<ElCard
class="relative rounded-lg"
body-style="position: relative; display: flex; flex-direction: row; justify-content: flex-start; width: 240px; max-width: 240px; padding: 15px 15px 10px;"
>
<!-- 更多操作 -->
<div v-if="showMore" class="absolute right-2 top-0">
<ElDropdown>
<ElButton link>
<IconifyIcon icon="lucide:ellipsis-vertical" />
</ElButton>
<template #dropdown>
<ElDropdownMenu>
<ElDropdownItem @click="handleMoreClick('edit', role)">
<div class="flex items-center">
<IconifyIcon icon="lucide:edit" color="#787878" />
<span class="text-primary">编辑</span>
</div>
</ElDropdownItem>
<ElDropdownItem @click="handleMoreClick('delete', role)">
<div class="flex items-center">
<IconifyIcon icon="lucide:trash" color="red" />
<span class="text-red-500">删除</span>
</div>
</ElDropdownItem>
</ElDropdownMenu>
</template>
</ElDropdown>
</div>
<!-- 角色信息 -->
<div>
<ElAvatar :src="role.avatar" class="h-10 w-10 overflow-hidden" />
</div>
<div class="ml-2 w-4/5">
<div class="h-20">
<div class="max-w-32 text-lg font-bold">
{{ role.name }}
</div>
<div class="mt-2 text-sm">
{{ role.description }}
</div>
</div>
<div class="mt-1 flex flex-row-reverse">
<ElButton type="primary" size="small" @click="handleUseClick(role)">
使用
</ElButton>
</div>
</div>
</ElCard>
</div>
</div>
</template>

View File

@@ -0,0 +1,261 @@
<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="bg-card absolute inset-0 flex h-full w-full flex-col overflow-hidden"
>
<FormModal @success="handlerAddRoleSuccess" />
<ElMain class="relative m-0 flex-1 overflow-hidden p-0">
<div class="z-100 absolute right-0 top--1 mr-5 mt-5">
<!-- 搜索输入框 -->
<ElInput
v-model="search"
class="w-60"
placeholder="请输入搜索的内容"
@keyup.enter="getActiveTabsRole"
>
<template #suffix>
<IconifyIcon icon="lucide:search" />
</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 p-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')"
class="mt-5"
/>
</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,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="bg-card left-0 mr-4 flex w-96 flex-col rounded-lg 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="bg-card flex-1">
<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.ImageDrawReq;
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.ImageDrawReq;
// 发送请求
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="bg-card flex h-12 w-12 flex-col items-center justify-center rounded-lg border 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="bg-card sticky bottom-0 z-50 flex h-16 items-center justify-center 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.ImageMidjourneyImagineReq;
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="bg-card flex h-12 w-12 items-center justify-center rounded-lg border 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.ImageDrawReq;
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

@@ -23,7 +23,7 @@ async function handleDelete(row: AiImageApi.Image) {
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteImage(row.id as number);
await deleteImage(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {

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="bg-card grid grid-cols-[repeat(auto-fill,minmax(200px,1fr))] gap-2.5 shadow-sm"
>
<div
v-for="item in list"
:key="item.id"
class="bg-card relative cursor-pointer overflow-hidden 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="bg-card absolute left-0 right-0 top-0 z-10 flex h-12 items-center border-b 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="bg-card rounded-md 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

@@ -30,7 +30,7 @@ async function handleDelete(row: AiMindmapApi.MindMap) {
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteMindMap(row.id as number);
await deleteMindMap(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {

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 bg-card flex items-center justify-between border border-solid border-rose-100 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

@@ -23,7 +23,7 @@ async function handleDelete(row: AiMusicApi.Music) {
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteMusic(row.id as number);
await deleteMusic(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {

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="bg-card absolute inset-x-0 top-0 z-10 flex h-12 items-center border-b 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="bg-card m-0 mt-10 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 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>

View File

@@ -0,0 +1,326 @@
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 { useUserStore } from '@vben/stores';
import { getAreaTree } from '#/api/system/area';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
const userStore = useUserStore();
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'name',
label: '线索名称',
component: 'Input',
rules: 'required',
componentProps: {
placeholder: '请输入线索名称',
},
},
{
fieldName: 'source',
label: '客户来源',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE, 'number'),
placeholder: '请选择客户来源',
},
rules: 'required',
},
{
fieldName: 'mobile',
label: '手机',
component: 'Input',
componentProps: {
placeholder: '请输入手机号',
},
},
{
fieldName: 'ownerUserId',
label: '负责人',
component: 'ApiSelect',
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
clearable: true,
placeholder: '请选择负责人',
},
defaultValue: userStore.userInfo?.id,
rules: 'required',
dependencies: {
triggerFields: ['id'],
disabled: (values) => values.id,
},
},
{
fieldName: 'telephone',
label: '电话',
component: 'Input',
componentProps: {
placeholder: '请输入电话',
},
},
{
fieldName: 'email',
label: '邮箱',
component: 'Input',
componentProps: {
placeholder: '请输入邮箱',
},
},
{
fieldName: 'wechat',
label: '微信',
component: 'Input',
componentProps: {
placeholder: '请输入微信',
},
},
{
fieldName: 'qq',
label: 'QQ',
component: 'Input',
componentProps: {
placeholder: '请输入 QQ',
},
},
{
fieldName: 'industryId',
label: '客户行业',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.CRM_CUSTOMER_INDUSTRY, 'number'),
placeholder: '请选择客户行业',
},
},
{
fieldName: 'level',
label: '客户级别',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.CRM_CUSTOMER_LEVEL, 'number'),
placeholder: '请选择客户级别',
},
},
{
fieldName: 'areaId',
label: '地址',
component: 'ApiTreeSelect',
componentProps: {
api: getAreaTree,
fieldNames: { label: 'name', value: 'id', children: 'children' },
placeholder: '请选择地址',
},
},
{
fieldName: 'detailAddress',
label: '详细地址',
component: 'Input',
componentProps: {
placeholder: '请输入详细地址',
},
},
{
fieldName: 'contactNextTime',
label: '下次联系时间',
component: 'DatePicker',
componentProps: {
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
placeholder: '请选择下次联系时间',
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
},
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '线索名称',
component: 'Input',
componentProps: {
placeholder: '请输入线索名称',
clearable: true,
},
},
{
fieldName: 'transformStatus',
label: '转化状态',
component: 'RadioGroup',
componentProps: {
options: [
{ label: '未转化', value: false },
{ label: '已转化', value: true },
],
placeholder: '请选择转化状态',
clearable: true,
},
defaultValue: false,
},
{
fieldName: 'mobile',
label: '手机号',
component: 'Input',
componentProps: {
placeholder: '请输入手机号',
clearable: true,
},
},
{
fieldName: 'telephone',
label: '电话',
component: 'Input',
componentProps: {
placeholder: '请输入电话',
clearable: true,
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
clearable: true,
placeholder: ['开始日期', '结束日期'],
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'name',
title: '线索名称',
fixed: 'left',
minWidth: 160,
slots: {
default: 'name',
},
},
{
field: 'source',
title: '线索来源',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_CUSTOMER_SOURCE },
},
},
{
field: 'mobile',
title: '手机',
minWidth: 120,
},
{
field: 'telephone',
title: '电话',
minWidth: 130,
},
{
field: 'email',
title: '邮箱',
minWidth: 180,
},
{
field: 'detailAddress',
title: '地址',
minWidth: 180,
},
{
field: 'industryId',
title: '客户行业',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_CUSTOMER_INDUSTRY },
},
},
{
field: 'level',
title: '客户级别',
minWidth: 135,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_CUSTOMER_LEVEL },
},
},
{
field: 'contactNextTime',
title: '下次联系时间',
formatter: 'formatDateTime',
minWidth: 180,
},
{
field: 'remark',
title: '备注',
minWidth: 200,
},
{
field: 'contactLastTime',
title: '最后跟进时间',
formatter: 'formatDateTime',
minWidth: 180,
},
{
field: 'contactLastContent',
title: '最后跟进记录',
minWidth: 200,
},
{
field: 'ownerUserName',
title: '负责人',
minWidth: 100,
},
{
field: 'ownerUserDeptName',
title: '所属部门',
minWidth: 100,
},
{
field: 'updateTime',
title: '更新时间',
formatter: 'formatDateTime',
minWidth: 180,
},
{
field: 'createTime',
title: '创建时间',
formatter: 'formatDateTime',
minWidth: 180,
},
{
title: '操作',
width: 140,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,111 @@
import type { DescriptionItemSchema } from '#/components/description';
import { h } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { formatDateTime } from '@vben/utils';
import { DictTag } from '#/components/dict-tag';
/** 详情头部的配置 */
export function useDetailSchema(): DescriptionItemSchema[] {
return [
{
field: 'source',
label: '线索来源',
render: (val) =>
h(DictTag, {
type: DICT_TYPE.CRM_CUSTOMER_SOURCE,
value: val,
}),
},
{
field: 'mobile',
label: '手机',
},
{
field: 'ownerUserName',
label: '负责人',
},
{
field: 'createTime',
label: '创建时间',
render: (val) => formatDateTime(val) as string,
},
];
}
/** 详情基本信息的配置 */
export function useDetailBaseSchema(): DescriptionItemSchema[] {
return [
{
field: 'name',
label: '线索名称',
},
{
field: 'source',
label: '客户来源',
render: (val) =>
h(DictTag, {
type: DICT_TYPE.CRM_CUSTOMER_SOURCE,
value: val,
}),
},
{
field: 'mobile',
label: '手机',
},
{
field: 'telephone',
label: '电话',
},
{
field: 'email',
label: '邮箱',
},
{
field: 'areaName',
label: '地址',
render: (val, data) => {
const areaName = val ?? '';
const detailAddress = data?.detailAddress ?? '';
return [areaName, detailAddress].filter((item) => !!item).join(' ');
},
},
{
field: 'qq',
label: 'QQ',
},
{
field: 'wechat',
label: '微信',
},
{
field: 'industryId',
label: '客户行业',
render: (val) =>
h(DictTag, {
type: DICT_TYPE.CRM_CUSTOMER_INDUSTRY,
value: val,
}),
},
{
field: 'level',
label: '客户级别',
render: (val) =>
h(DictTag, {
type: DICT_TYPE.CRM_CUSTOMER_LEVEL,
value: val,
}),
},
{
field: 'contactNextTime',
label: '下次联系时间',
render: (val) => formatDateTime(val) as string,
},
{
field: 'remark',
label: '备注',
},
];
}

View File

@@ -0,0 +1,174 @@
<script setup lang="ts">
import type { CrmClueApi } from '#/api/crm/clue';
import type { SystemOperateLogApi } from '#/api/system/operate-log';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { ElCard, ElMessage, ElTabPane, ElTabs } from 'element-plus';
import { getClue, transformClue } from '#/api/crm/clue';
import { getOperateLogPage } from '#/api/crm/operateLog';
import { BizTypeEnum } from '#/api/crm/permission';
import { useDescription } from '#/components/description';
import { OperateLog } from '#/components/operate-log';
import { ACTION_ICON, TableAction } from '#/components/table-action';
import { FollowUp } from '#/views/crm/followup';
import { PermissionList, TransferForm } from '#/views/crm/permission';
import Form from '../modules/form.vue';
import { useDetailSchema } from './data';
import Info from './modules/info.vue';
const route = useRoute();
const router = useRouter();
const tabs = useTabs();
const loading = ref(false); // 加载中
const clueId = ref(0); // 线索编号
const clue = ref<CrmClueApi.Clue>({} as CrmClueApi.Clue); // 线索详情
const logList = ref<SystemOperateLogApi.OperateLog[]>([]); // 操作日志
const permissionListRef = ref<InstanceType<typeof PermissionList>>(); // 团队成员列表 Ref
const activeTabName = ref('1'); // 选中 Tab 名
const [Descriptions] = useDescription({
border: false,
column: 4,
schema: useDetailSchema(),
});
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const [TransferModal, transferModalApi] = useVbenModal({
connectedComponent: TransferForm,
destroyOnClose: true,
});
/** 加载线索详情 */
async function getClueDetail() {
loading.value = true;
try {
clue.value = await getClue(clueId.value);
// 操作日志
const res = await getOperateLogPage({
bizType: BizTypeEnum.CRM_CLUE,
bizId: clueId.value,
});
logList.value = res.list;
} finally {
loading.value = false;
}
}
/** 返回列表页 */
function handleBack() {
tabs.closeCurrentTab();
router.push({ name: 'CrmClue' });
}
/** 编辑线索 */
function handleEdit() {
formModalApi.setData({ id: clueId.value }).open();
}
/** 转移线索 */
function handleTransfer() {
transferModalApi.setData({ bizType: BizTypeEnum.CRM_CLUE }).open();
}
/** 转化为客户 */
async function handleTransform(): Promise<boolean | undefined> {
return new Promise((resolve, reject) => {
confirm({
content: '确定将该线索转化为客户吗?',
})
.then(async () => {
// 转化为客户
await transformClue(clueId.value);
// 提示并返回成功
ElMessage.success('转化客户成功');
resolve(true);
})
.catch(() => {
reject(new Error('取消操作'));
});
});
}
/** 加载数据 */
onMounted(() => {
clueId.value = Number(route.params.id);
getClueDetail();
});
</script>
<template>
<Page auto-content-height :title="clue?.name" :loading="loading">
<FormModal @success="getClueDetail" />
<TransferModal @success="getClueDetail" />
<template #extra>
<TableAction
:actions="[
{
label: '返回',
type: 'default',
icon: 'lucide:arrow-left',
onClick: handleBack,
},
{
label: $t('ui.actionTitle.edit'),
type: 'primary',
icon: ACTION_ICON.EDIT,
auth: ['crm:clue:update'],
ifShow: permissionListRef?.validateWrite,
onClick: handleEdit,
},
{
label: '转移',
type: 'primary',
ifShow: permissionListRef?.validateOwnerUser,
onClick: handleTransfer,
},
{
label: '转化为客户',
type: 'primary',
ifShow:
permissionListRef?.validateOwnerUser && !clue?.transformStatus,
onClick: handleTransform,
},
]"
/>
</template>
<ElCard class="min-h-[10%]">
<Descriptions :data="clue" />
</ElCard>
<ElCard class="mt-4 min-h-[60%]">
<ElTabs v-model:model-value="activeTabName">
<ElTabPane label="跟进记录" name="1">
<FollowUp :biz-id="clueId" :biz-type="BizTypeEnum.CRM_CLUE" />
</ElTabPane>
<ElTabPane label="基本信息" name="2">
<Info :clue="clue" />
</ElTabPane>
<ElTabPane label="团队成员" name="3">
<PermissionList
ref="permissionListRef"
:biz-id="clueId"
:biz-type="BizTypeEnum.CRM_CLUE"
:show-action="true"
@quit-team="handleBack"
/>
</ElTabPane>
<ElTabPane label="操作日志" name="4">
<OperateLog :log-list="logList" />
</ElTabPane>
</ElTabs>
</ElCard>
</Page>
</template>

View File

@@ -0,0 +1,36 @@
<script lang="ts" setup>
import type { CrmClueApi } from '#/api/crm/clue';
import { ElDivider } from 'element-plus';
import { useDescription } from '#/components/description';
import { useFollowUpDetailSchema } from '#/views/crm/followup/data';
import { useDetailBaseSchema } from '../data';
defineProps<{
clue: CrmClueApi.Clue;
}>();
const [BaseDescriptions] = useDescription({
title: '基本信息',
border: false,
column: 4,
schema: useDetailBaseSchema(),
});
const [SystemDescriptions] = useDescription({
title: '系统信息',
border: false,
column: 3,
schema: useFollowUpDetailSchema(),
});
</script>
<template>
<div>
<BaseDescriptions :data="clue" />
<ElDivider />
<SystemDescriptions :data="clue" />
</div>
</template>

View File

@@ -0,0 +1,193 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmClueApi } from '#/api/crm/clue';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import {
ElButton,
ElLoading,
ElMessage,
ElTabPane,
ElTabs,
} from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteClue, exportClue, getCluePage } from '#/api/crm/clue';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const { push } = useRouter();
const sceneType = ref('1');
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 导出表格 */
async function handleExport() {
const data = await exportClue({
sceneType: sceneType.value,
...(await gridApi.formApi.getValues()),
});
downloadFileFromBlobPart({ fileName: '线索.xls', source: data });
}
/** 创建线索 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑线索 */
function handleEdit(row: CrmClueApi.Clue) {
formModalApi.setData(row).open();
}
/** 删除线索 */
async function handleDelete(row: CrmClueApi.Clue) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteClue(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 查看线索详情 */
function handleDetail(row: CrmClueApi.Clue) {
push({ name: 'CrmClueDetail', params: { id: row.id } });
}
/** 处理场景类型的切换 */
function handleChangeSceneType(key: number | string) {
sceneType.value = key.toString();
gridApi.query();
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getCluePage({
pageNo: page.currentPage,
pageSize: page.pageSize,
sceneType: sceneType.value,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<CrmClueApi.Clue>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert
title="【线索】线索管理"
url="https://doc.iocoder.cn/crm/clue/"
/>
<DocAlert
title="【通用】数据权限"
url="https://doc.iocoder.cn/crm/permission/"
/>
</template>
<FormModal @success="handleRefresh" />
<Grid>
<template #toolbar-actions>
<ElTabs
class="w-full"
@tab-change="handleChangeSceneType"
v-model:model-value="sceneType"
>
<ElTabPane label="我负责的" name="1" />
<ElTabPane label="我参与的" name="2" />
<ElTabPane label="下属负责的" name="3" />
</ElTabs>
</template>
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['线索']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['crm:clue:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['crm:clue:export'],
onClick: handleExport,
},
]"
/>
</template>
<template #name="{ row }">
<ElButton type="primary" link @click="handleDetail(row)">
{{ row.name }}
</ElButton>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['crm:clue:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['crm:clue: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 { CrmClueApi } from '#/api/crm/clue';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { createClue, getClue, updateClue } from '#/api/crm/clue';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<CrmClueApi.Clue>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['线索'])
: $t('ui.actionTitle.create', ['线索']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
labelWidth: 100,
},
wrapperClass: 'grid-cols-2',
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 CrmClueApi.Clue;
try {
await (formData.value?.id ? updateClue(data) : createClue(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<CrmClueApi.Clue>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getClue(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,194 @@
import type { Ref } from 'vue';
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { DescriptionItemSchema } from '#/components/description';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { formatDateTime } from '@vben/utils';
import { getBusinessPageByCustomer } from '#/api/crm/business';
import { getContactPageByCustomer } from '#/api/crm/contact';
import { BizTypeEnum } from '#/api/crm/permission';
/** 新增/修改的表单 */
export function useFormSchema(
bizId: Ref<number | undefined>,
): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'bizId',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'bizType',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'type',
label: '跟进类型',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.CRM_FOLLOW_UP_TYPE, 'number'),
},
rules: 'required',
},
{
fieldName: 'nextTime',
label: '下次联系时间',
component: 'DatePicker',
componentProps: {
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
class: '!w-full',
},
rules: 'required',
},
{
fieldName: 'content',
label: '跟进内容',
component: 'Textarea',
rules: 'required',
},
{
fieldName: 'picUrls',
label: '图片',
component: 'ImageUpload',
},
{
fieldName: 'fileUrls',
label: '附件',
component: 'FileUpload',
},
{
fieldName: 'contactIds',
label: '关联联系人',
component: 'ApiSelect',
componentProps: {
api: async () => {
if (!bizId.value) {
return [];
}
const res = await getContactPageByCustomer({
pageNo: 1,
pageSize: 100,
customerId: bizId.value,
});
return res.list;
},
labelField: 'name',
valueField: 'id',
mode: 'multiple',
},
},
{
fieldName: 'businessIds',
label: '关联商机',
component: 'ApiSelect',
componentProps: {
api: async () => {
if (!bizId.value) {
return [];
}
const res = await getBusinessPageByCustomer({
pageNo: 1,
pageSize: 100,
customerId: bizId.value,
});
return res.list;
},
labelField: 'name',
valueField: 'id',
mode: 'multiple',
},
},
];
}
/** 列表的字段 */
export function useGridColumns(
bizType: number,
): VxeTableGridOptions['columns'] {
return [
{
field: 'createTime',
title: '创建时间',
formatter: 'formatDateTime',
},
{ field: 'creatorName', title: '跟进人' },
{
field: 'type',
title: '跟进类型',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_FOLLOW_UP_TYPE },
},
},
{ field: 'content', title: '跟进内容' },
{
field: 'nextTime',
title: '下次联系时间',
formatter: 'formatDateTime',
},
{
field: 'contacts',
title: '关联联系人',
visible: bizType === BizTypeEnum.CRM_CUSTOMER,
slots: { default: 'contacts' },
},
{
field: 'businesses',
title: '关联商机',
visible: bizType === BizTypeEnum.CRM_CUSTOMER,
slots: { default: 'businesses' },
},
{
field: 'actions',
title: '操作',
slots: { default: 'actions' },
},
];
}
/** 详情页的系统字段 */
export function useFollowUpDetailSchema(): DescriptionItemSchema[] {
return [
{
field: 'ownerUserName',
label: '负责人',
},
{
field: 'contactLastContent',
label: '最后跟进记录',
},
{
field: 'contactLastTime',
label: '最后跟进时间',
render: (val) => formatDateTime(val) as string,
},
{
field: 'creatorName',
label: '创建人',
},
{
field: 'createTime',
label: '创建时间',
render: (val) => formatDateTime(val) as string,
},
{
field: 'updateTime',
label: '更新时间',
render: (val) => formatDateTime(val) as string,
},
];
}

View File

@@ -0,0 +1 @@
export { default as FollowUp } from './index.vue';

View File

@@ -0,0 +1,165 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmFollowUpApi } from '#/api/crm/followup';
import { watch } from 'vue';
import { useRouter } from 'vue-router';
import { useVbenModal } from '@vben/common-ui';
import { ElButton, ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteFollowUpRecord,
getFollowUpRecordPage,
} from '#/api/crm/followup';
import { $t } from '#/locales';
import { useGridColumns } from './data';
import FollowUpRecordForm from './modules/form.vue';
/** 跟进记录列表 */
defineOptions({ name: 'FollowUpRecord' });
const props = defineProps<{
bizId: number;
bizType: number;
}>();
const { push } = useRouter();
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 添加跟进记录 */
function handleCreate() {
formModalApi.setData({ bizId: props.bizId, bizType: props.bizType }).open();
}
/** 删除跟进记录 */
async function handleDelete(row: CrmFollowUpApi.FollowUpRecord) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.id]),
});
try {
await deleteFollowUpRecord(row.id);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 打开联系人详情 */
function openContactDetail(id: number) {
push({ name: 'CrmContactDetail', params: { id } });
}
/** 打开商机详情 */
function openBusinessDetail(id: number) {
push({ name: 'CrmBusinessDetail', params: { id } });
}
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: FollowUpRecordForm,
destroyOnClose: true,
});
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
columns: useGridColumns(props.bizType),
height: 600,
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }) => {
return await getFollowUpRecordPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
bizType: props.bizType,
bizId: props.bizId,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
},
} as VxeTableGridOptions<CrmFollowUpApi.FollowUpRecord>,
});
/** 监听业务 ID 变化 */
watch(
() => props.bizId,
() => {
gridApi.query();
},
);
</script>
<template>
<div>
<FormModal @success="handleRefresh" />
<Grid>
<template #toolbar-tools>
<TableAction
:actions="[
{
label: '写跟进',
type: 'primary',
icon: ACTION_ICON.EDIT,
onClick: handleCreate,
},
]"
/>
</template>
<template #contacts="{ row }">
<ElButton
v-for="contact in row.contacts || []"
:key="`contact-${contact.id}`"
type="primary"
link
class="ml-2"
@click="openContactDetail(contact.id)"
>
{{ contact.name }}
</ElButton>
</template>
<template #businesses="{ row }">
<ElButton
v-for="business in row.businesses || []"
:key="`business-${business.id}`"
type="primary"
link
class="ml-2"
@click="openBusinessDetail(business.id)"
>
{{ business.name }}
</ElButton>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.id]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</div>
</template>

View File

@@ -0,0 +1,81 @@
<script lang="ts" setup>
import type { CrmFollowUpApi } from '#/api/crm/followup';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { createFollowUpRecord } from '#/api/crm/followup';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const bizId = ref<number>();
const bizType = ref<number>();
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useFormSchema(bizId),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data = (await formApi.getValues()) as CrmFollowUpApi.FollowUpRecord;
try {
await createFollowUpRecord(data);
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
return;
}
// 加载数据
const data = modalApi.getData<CrmFollowUpApi.FollowUpRecord>();
if (!data) {
return;
}
if (data.bizId && data.bizType) {
bizId.value = data.bizId;
bizType.value = data.bizType;
}
modalApi.lock();
try {
// 设置到 values
await formApi.setValues(data);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal title="添加跟进记录" class="w-2/5">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,2 @@
export { default as PermissionList } from './modules/list.vue';
export { default as TransferForm } from './modules/transfer-form.vue';

View File

@@ -0,0 +1,233 @@
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 { BizTypeEnum, PermissionLevelEnum } from '#/api/crm/permission';
import { getSimpleUserList } from '#/api/system/user';
/** 新增/修改的表单 */
export function useTransferFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'newOwnerUserId',
label: '选择新负责人',
component: 'ApiSelect',
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
},
rules: 'required',
},
{
fieldName: 'oldOwnerHandler',
label: '老负责人',
component: 'RadioGroup',
componentProps: {
options: [
{
label: '加入团队',
value: true,
},
{
label: '移除',
value: false,
},
],
},
rules: 'required',
},
{
fieldName: 'oldOwnerPermissionLevel',
label: '老负责人权限级别',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(
DICT_TYPE.CRM_PERMISSION_LEVEL,
'number',
).filter((dict) => dict.value !== PermissionLevelEnum.OWNER),
},
dependencies: {
triggerFields: ['oldOwnerHandler'],
show: (values) => values.oldOwnerHandler,
trigger(values) {
if (!values.oldOwnerHandler) {
values.oldOwnerPermissionLevel = undefined;
}
},
},
rules: 'required',
},
{
fieldName: 'toBizTypes',
label: '同时转移',
component: 'CheckboxGroup',
componentProps: {
options: [
{
label: '联系人',
value: BizTypeEnum.CRM_CONTACT,
},
{
label: '商机',
value: BizTypeEnum.CRM_BUSINESS,
},
{
label: '合同',
value: BizTypeEnum.CRM_CONTRACT,
},
],
},
},
];
}
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'bizId',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'ids',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'userId',
label: '选择人员',
component: 'ApiSelect',
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
},
dependencies: {
triggerFields: ['ids'],
show: (values) => {
return values.ids === undefined;
},
},
},
{
fieldName: 'level',
label: '权限级别',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(
DICT_TYPE.CRM_PERMISSION_LEVEL,
'number',
).filter((dict) => dict.value !== PermissionLevelEnum.OWNER),
},
rules: 'required',
},
{
fieldName: 'bizType',
label: 'Crm 类型',
component: 'RadioGroup',
componentProps: {
options: [
{
label: '联系人',
value: BizTypeEnum.CRM_CONTACT,
},
{
label: '商机',
value: BizTypeEnum.CRM_BUSINESS,
},
{
label: '合同',
value: BizTypeEnum.CRM_CONTRACT,
},
],
},
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'toBizTypes',
label: '同时添加至',
component: 'CheckboxGroup',
componentProps: {
options: [
{
label: '联系人',
value: BizTypeEnum.CRM_CONTACT,
},
{
label: '商机',
value: BizTypeEnum.CRM_BUSINESS,
},
{
label: '合同',
value: BizTypeEnum.CRM_CONTRACT,
},
],
},
dependencies: {
triggerFields: ['ids', 'bizType'],
show: (values) => {
return (
values.ids === undefined &&
values.bizType === BizTypeEnum.CRM_CUSTOMER
);
},
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
type: 'checkbox',
width: 50,
},
{
field: 'nickname',
title: '姓名',
},
{
field: 'deptName',
title: '部门',
},
{
field: 'postNames',
title: '岗位',
},
{
field: 'level',
title: '权限级别',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_PERMISSION_LEVEL },
},
},
{
field: 'createTime',
title: '加入时间',
formatter: 'formatDateTime',
},
];
}

View File

@@ -0,0 +1,90 @@
<script lang="ts" setup>
import type { CrmPermissionApi } from '#/api/crm/permission';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { createPermission, updatePermission } from '#/api/crm/permission';
import { $t } from '#/locales';
import { useFormSchema } from './data';
const emit = defineEmits(['success']);
const formData = ref<CrmPermissionApi.Permission>();
const getTitle = computed(() => {
return formData.value?.ids
? $t('ui.actionTitle.edit', ['团队成员'])
: $t('ui.actionTitle.create', ['团队成员']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 80,
},
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 CrmPermissionApi.Permission;
try {
await (formData.value?.ids
? updatePermission(data)
: createPermission(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();
if (!data || !data.bizType || !data.bizId) {
return;
}
modalApi.lock();
try {
formData.value = {
ids: data.ids ?? (data.id ? [data.id] : undefined),
userId: undefined,
bizType: data.bizType,
bizId: data.bizId,
level: data.level,
};
// 设置到 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,265 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmPermissionApi } from '#/api/crm/permission';
import { ref, watch } from 'vue';
import { confirm, useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';
import { ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePermissionBatch,
deleteSelfPermission,
getPermissionList,
PermissionLevelEnum,
} from '#/api/crm/permission';
import { $t } from '#/locales';
import { useGridColumns } from './data';
import Form from './form.vue';
const props = defineProps<{
bizId: number; // 模块数据编号
bizType: number; // 模块类型
showAction: boolean; // 是否展示操作按钮
}>();
const emits = defineEmits<{
(e: 'quitTeam'): void;
}>();
const gridData = ref<CrmPermissionApi.Permission[]>([]);
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const userStore = useUserStore();
const validateOwnerUser = ref(false); // 负责人权限
const validateWrite = ref(false); // 编辑权限
const isPool = ref(false); // 是否是公海
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
const checkedRows = ref<CrmPermissionApi.Permission[]>([]);
function setCheckedRows({
records,
}: {
records: CrmPermissionApi.Permission[];
}) {
if (records.some((item) => item.level === PermissionLevelEnum.OWNER)) {
ElMessage.warning('不能选择负责人!');
gridApi.grid.setAllCheckboxRow(false);
return;
}
checkedRows.value = records;
}
/** 新建团队成员 */
function handleCreate() {
formModalApi
.setData({
bizType: props.bizType,
bizId: props.bizId,
})
.open();
}
/** 编辑团队成员 */
function handleEdit() {
if (checkedRows.value.length === 0) {
ElMessage.error('请先选择团队成员后操作!');
return;
}
if (checkedRows.value.length > 1) {
ElMessage.error('只能选择一个团队成员进行编辑!');
return;
}
formModalApi
.setData({
bizType: props.bizType,
bizId: props.bizId,
id: checkedRows.value[0]?.id,
level: checkedRows.value[0]?.level,
})
.open();
}
/** 删除团队成员 */
function handleDelete() {
if (checkedRows.value.length === 0) {
ElMessage.error('请先选择团队成员后操作!');
return;
}
return new Promise((resolve, reject) => {
confirm({
content: `你要将${checkedRows.value.map((item) => item.nickname).join(',')}移出团队吗?`,
})
.then(async () => {
const res = await deletePermissionBatch(
checkedRows.value.map((item) => item.id!),
);
if (res) {
// 提示并返回成功
ElMessage.success($t('ui.actionMessage.operationSuccess'));
handleRefresh();
resolve(true);
} else {
reject(new Error('移出失败'));
}
})
.catch(() => {
reject(new Error('取消操作'));
});
});
}
/** 退出团队 */
async function handleQuit() {
const permission = gridApi.grid
.getData()
.find(
(item) =>
item.id === userStore.userInfo?.id &&
item.level === PermissionLevelEnum.OWNER,
);
if (permission) {
ElMessage.warning('负责人不能退出团队!');
return;
}
const userPermission = gridApi.grid
.getData()
.find((item) => item.id === userStore.userInfo?.id);
if (!userPermission) {
ElMessage.warning('你不是团队成员!');
return;
}
await deleteSelfPermission(userPermission.id!);
ElMessage.success('退出团队成员成功!');
emits('quitTeam');
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
columns: useGridColumns(),
height: 'auto',
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async (_params) => {
const res = await getPermissionList({
bizId: props.bizId,
bizType: props.bizType,
});
gridData.value = res;
return res;
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<CrmPermissionApi.Permission>,
gridEvents: {
checkboxAll: setCheckedRows,
checkboxChange: setCheckedRows,
},
});
defineExpose({
openForm: handleCreate,
validateOwnerUser,
validateWrite,
isPool,
});
watch(
() => gridData.value,
(data) => {
isPool.value = false;
if (data.length > 0) {
isPool.value = data.some(
(item) => item.level === PermissionLevelEnum.OWNER,
);
validateOwnerUser.value = false;
validateWrite.value = false;
const userId = userStore.userInfo?.id;
gridData.value
.filter((item) => item.userId === userId)
.forEach((item) => {
if (item.level === PermissionLevelEnum.OWNER) {
validateOwnerUser.value = true;
validateWrite.value = true;
} else if (item.level === PermissionLevelEnum.WRITE) {
validateWrite.value = true;
}
});
} else {
// 特殊:没有成员的情况下,说明没有负责人,是公海
isPool.value = true;
}
},
{
immediate: true,
},
);
</script>
<template>
<div>
<FormModal @success="handleRefresh" />
<Grid>
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('common.create'),
type: 'primary',
icon: ACTION_ICON.ADD,
ifShow: validateOwnerUser,
onClick: handleCreate,
},
{
label: $t('common.edit'),
type: 'primary',
icon: ACTION_ICON.EDIT,
ifShow: validateOwnerUser,
onClick: handleEdit,
disabled: checkedRows.length === 0,
},
{
label: $t('common.delete'),
type: 'danger',
icon: ACTION_ICON.DELETE,
ifShow: validateOwnerUser,
onClick: handleDelete,
disabled: checkedRows.length === 0,
},
{
label: '退出团队',
type: 'danger',
ifShow: !validateOwnerUser,
onClick: handleQuit,
},
]"
/>
</template>
</Grid>
</div>
</template>

View File

@@ -0,0 +1,120 @@
<script lang="ts" setup>
import type { CrmPermissionApi } from '#/api/crm/permission';
import { computed } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { transferBusiness } from '#/api/crm/business';
import { transferClue } from '#/api/crm/clue';
import { transferContact } from '#/api/crm/contact';
import { transferContract } from '#/api/crm/contract';
import { transferCustomer } from '#/api/crm/customer';
import { BizTypeEnum } from '#/api/crm/permission';
import { $t } from '#/locales';
import { useTransferFormSchema } from './data';
const emit = defineEmits(['success']);
const bizType = defineModel<number>('bizType');
const getTitle = computed(() => {
switch (bizType.value) {
case BizTypeEnum.CRM_BUSINESS: {
return '商机转移';
}
case BizTypeEnum.CRM_CLUE: {
return '线索转移';
}
case BizTypeEnum.CRM_CONTACT: {
return '联系人转移';
}
case BizTypeEnum.CRM_CONTRACT: {
return '合同转移';
}
case BizTypeEnum.CRM_CUSTOMER: {
return '客户转移';
}
default: {
return '转移';
}
}
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useTransferFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
// 提交表单
const data = (await formApi.getValues()) as CrmPermissionApi.TransferReq;
try {
switch (bizType.value) {
case BizTypeEnum.CRM_BUSINESS: {
return await transferBusiness(data);
}
case BizTypeEnum.CRM_CLUE: {
return await transferClue(data);
}
case BizTypeEnum.CRM_CONTACT: {
return await transferContact(data);
}
case BizTypeEnum.CRM_CONTRACT: {
return await transferContract(data);
}
case BizTypeEnum.CRM_CUSTOMER: {
return await transferCustomer(data);
}
default: {
ElMessage.error('【转移失败】没有转移接口');
throw new Error('【转移失败】没有转移接口');
}
}
} finally {
// 关闭并提示
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
await formApi.resetForm();
return;
}
// 加载数据
const data = modalApi.getData<{ bizType: number }>();
if (!data || !data.bizType) {
return;
}
bizType.value = data.bizType;
await formApi.setFieldValue('id', data.bizType);
},
});
</script>
<template>
<Modal :title="getTitle" class="w-2/5">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,97 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmProductCategoryApi } from '#/api/crm/product/category';
import { handleTree } from '@vben/utils';
import { getProductCategoryList } from '#/api/crm/product/category';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'parentId',
label: '上级分类',
component: 'ApiTreeSelect',
componentProps: {
clearable: true,
api: async () => {
const data = await getProductCategoryList();
data.unshift({
id: 0,
name: '顶级分类',
} as CrmProductCategoryApi.ProductCategory);
return handleTree(data);
},
labelField: 'name',
valueField: 'id',
childrenField: 'children',
placeholder: '请选择上级分类',
showSearch: true,
treeDefaultExpandAll: true,
},
rules: 'selectRequired',
},
{
fieldName: 'name',
label: '分类名称',
component: 'Input',
componentProps: {
placeholder: '请输入分类名称',
},
rules: 'required',
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '分类名称',
component: 'Input',
componentProps: {
clearable: true,
placeholder: '请输入分类名称',
},
},
];
}
/** 表格列配置 */
export function useGridColumns(): VxeTableGridOptions<CrmProductCategoryApi.ProductCategory>['columns'] {
return [
{
field: 'name',
title: '分类名称',
treeNode: true,
},
{
field: 'id',
title: '分类编号',
},
{
field: 'createTime',
title: '创建时间',
formatter: 'formatDateTime',
},
{
field: 'actions',
title: '操作',
width: 250,
fixed: 'right',
slots: {
default: 'actions',
},
},
];
}

View File

@@ -0,0 +1,168 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmProductCategoryApi } from '#/api/crm/product/category';
import { ref } from 'vue';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteProductCategory,
getProductCategoryList,
} from '#/api/crm/product/category';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 切换树形展开/收缩状态 */
const isExpanded = ref(false);
function handleExpand() {
isExpanded.value = !isExpanded.value;
gridApi.grid.setAllTreeExpand(isExpanded.value);
}
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建分类 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 添加下级分类 */
function handleAppend(row: CrmProductCategoryApi.ProductCategory) {
formModalApi.setData({ parentId: row.id }).open();
}
/** 编辑分类 */
function handleEdit(row: CrmProductCategoryApi.ProductCategory) {
formModalApi.setData(row).open();
}
/** 删除分类 */
async function handleDelete(row: CrmProductCategoryApi.ProductCategory) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteProductCategory(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,
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async (_, formValues) => {
return await getProductCategoryList(formValues);
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
treeConfig: {
parentField: 'parentId',
rowField: 'id',
transform: true,
expandAll: true,
reserve: true,
},
} as VxeTableGridOptions<CrmProductCategoryApi.ProductCategory>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert
title="【产品】产品管理、产品分类"
url="https://doc.iocoder.cn/crm/product/"
/>
</template>
<FormModal @success="handleRefresh" />
<Grid>
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['分类']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['crm:product-category:create'],
onClick: handleCreate,
},
{
label: isExpanded ? '收缩' : '展开',
type: 'primary',
onClick: handleExpand,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: '新增下级',
type: 'primary',
link: true,
icon: ACTION_ICON.ADD,
auth: ['crm:product-category:create'],
onClick: handleAppend.bind(null, row),
},
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['crm:product-category:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['crm:product-category:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,94 @@
<script lang="ts" setup>
import type { CrmProductCategoryApi } from '#/api/crm/product/category';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import {
createProductCategory,
getProductCategory,
updateProductCategory,
} from '#/api/crm/product/category';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<CrmProductCategoryApi.ProductCategory>();
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: 80,
},
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 CrmProductCategoryApi.ProductCategory;
try {
await (formData.value?.id
? updateProductCategory(data)
: createProductCategory(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;
}
// 加载数据
let data = modalApi.getData<CrmProductCategoryApi.ProductCategory>();
if (!data || !data.id) {
// 设置上级
await formApi.setValues(data);
return;
}
modalApi.lock();
try {
if (data.id) {
data = await getProductCategory(data.id);
}
// 设置到 values
formData.value = data;
await formApi.setValues(data);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal class="w-2/5" :title="getTitle">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,111 @@
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { DICT_TYPE } from '@vben/constants';
/** 产品详情列表的列定义 */
export function useDetailListColumns(
showBusinessPrice: boolean,
): VxeTableGridOptions['columns'] {
return [
{
field: 'productName',
title: '产品名称',
},
{
field: 'productNo',
title: '产品条码',
},
{
field: 'productUnit',
title: '产品单位',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_PRODUCT_UNIT },
},
},
{
field: 'productPrice',
title: '产品价格(元)',
formatter: 'formatAmount2',
},
{
field: 'businessPrice',
title: '商机价格(元)',
formatter: 'formatAmount2',
visible: showBusinessPrice,
},
{
field: 'contractPrice',
title: '合同价格(元)',
formatter: 'formatAmount2',
visible: !showBusinessPrice,
},
{
field: 'count',
title: '数量',
formatter: 'formatAmount3',
},
{
field: 'totalPrice',
title: '合计金额(元)',
formatter: 'formatAmount2',
},
];
}
/** 产品编辑表格的列定义 */
export function useProductEditTableColumns(): VxeTableGridOptions['columns'] {
return [
{ type: 'seq', title: '序号', minWidth: 50 },
{
field: 'productId',
title: '产品名称',
minWidth: 100,
slots: { default: 'productId' },
},
{
field: 'productNo',
title: '条码',
minWidth: 150,
},
{
field: 'productUnit',
title: '单位',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_PRODUCT_UNIT },
},
},
{
field: 'productPrice',
title: '价格(元)',
minWidth: 100,
formatter: 'formatAmount2',
},
{
field: 'sellingPrice',
title: '售价(元)',
minWidth: 100,
slots: { default: 'sellingPrice' },
},
{
field: 'count',
title: '数量',
minWidth: 100,
slots: { default: 'count' },
},
{
field: 'totalPrice',
title: '合计',
minWidth: 100,
formatter: 'formatAmount2',
},
{
title: '操作',
width: 80,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,79 @@
<!-- 产品列表用于商机合同详情中展示它们关联的产品列表 -->
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmProductApi } from '#/api/crm/product';
import { ref } from 'vue';
import { erpPriceInputFormatter } from '@vben/utils';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getBusiness } from '#/api/crm/business';
import { getContract } from '#/api/crm/contract';
import { BizTypeEnum } from '#/api/crm/permission';
import { useDetailListColumns } from './data';
/** 组件入参 */
const props = defineProps<{
bizId: number;
bizType: BizTypeEnum;
}>();
/** 整单折扣 */
const discountPercent = ref(0);
/** 产品总金额 */
const totalProductPrice = ref(0);
/** 构建产品列表表格 */
const [Grid] = useVbenVxeGrid({
gridOptions: {
columns: useDetailListColumns(props.bizType === BizTypeEnum.CRM_BUSINESS),
height: 600,
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async (_params) => {
const data =
props.bizType === BizTypeEnum.CRM_BUSINESS
? await getBusiness(props.bizId)
: await getContract(props.bizId);
discountPercent.value = data.discountPercent;
totalProductPrice.value = data.totalProductPrice;
return data.products;
},
},
},
toolbarConfig: {
refresh: true,
search: true,
},
keepSource: true,
rowConfig: {
keyField: 'id',
isHover: true,
},
} as VxeTableGridOptions<CrmProductApi.Product>,
});
</script>
<template>
<div>
<Grid />
<div class="flex flex-col items-end justify-end">
<span class="ml-4 font-bold text-red-500">
{{ `产品总金额:${erpPriceInputFormatter(totalProductPrice)}` }}
</span>
<span class="font-bold text-red-500">
{{ `整单折扣:${erpPriceInputFormatter(discountPercent)}%` }}
</span>
<span class="font-bold text-red-500">
{{
`实际金额:${erpPriceInputFormatter(totalProductPrice * (1 - discountPercent / 100))}`
}}
</span>
</div>
</div>
</template>

View File

@@ -0,0 +1,203 @@
<script lang="ts" setup>
import type { CrmBusinessApi } from '#/api/crm/business';
import type { CrmContractApi } from '#/api/crm/contract';
import type { CrmProductApi } from '#/api/crm/product';
import { nextTick, onMounted, ref, watch } from 'vue';
import { erpPriceMultiply } from '@vben/utils';
import { ElInputNumber, ElOption, ElSelect } from 'element-plus';
import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { BizTypeEnum } from '#/api/crm/permission';
import { getProductSimpleList } from '#/api/crm/product';
import { $t } from '#/locales';
import { useProductEditTableColumns } from './data';
const props = defineProps<{
bizType: BizTypeEnum;
products?:
| CrmBusinessApi.BusinessProduct[]
| CrmContractApi.ContractProduct[];
}>();
const emit = defineEmits(['update:products']);
/** 表格内部数据 */
const tableData = ref<any[]>([]);
/** 添加产品行 */
function handleAdd() {
gridApi.grid.insertAt(null, -1);
}
/** 删除产品行 */
function handleDelete(row: CrmProductApi.Product) {
gridApi.grid.remove(row);
}
/** 切换产品时同步基础信息 */
function handleProductChange(productId: any, row: any) {
const product = productOptions.value.find((p) => p.id === productId);
if (!product) {
return;
}
row.productUnit = product.unit;
row.productNo = product.no;
row.productPrice = product.price;
row.sellingPrice = product.price;
row.count = 0;
row.totalPrice = 0;
handleUpdateValue(row);
}
/** 金额变动时重新计算合计 */
function handlePriceChange(row: any) {
row.totalPrice = erpPriceMultiply(row.sellingPrice, row.count) ?? 0;
handleUpdateValue(row);
}
/** 将最新数据写回并通知父组件 */
function handleUpdateValue(row: any) {
const index = tableData.value.findIndex((item) => item.id === row.id);
if (props.bizType === BizTypeEnum.CRM_BUSINESS) {
row.businessPrice = row.sellingPrice;
} else if (props.bizType === BizTypeEnum.CRM_CONTRACT) {
row.contractPrice = row.sellingPrice;
}
if (index === -1) {
row.id = tableData.value.length + 1;
tableData.value.push(row);
} else {
tableData.value[index] = row;
}
emit('update:products', [...tableData.value]);
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
editConfig: {
trigger: 'click',
mode: 'cell',
},
columns: useProductEditTableColumns(),
data: tableData.value,
border: true,
showOverflow: true,
autoResize: true,
keepSource: true,
rowConfig: {
keyField: 'id',
isHover: true,
},
pagerConfig: {
enabled: false,
},
toolbarConfig: {
enabled: false,
},
},
});
/** 监听外部传入的列数据 */
watch(
() => props.products,
async (products) => {
if (!products) {
return;
}
await nextTick();
tableData.value = products;
if (props.bizType === BizTypeEnum.CRM_BUSINESS) {
tableData.value.forEach((item) => {
item.sellingPrice = item.businessPrice;
});
} else if (props.bizType === BizTypeEnum.CRM_CONTRACT) {
tableData.value.forEach((item) => {
item.sellingPrice = item.contractPrice;
});
}
await gridApi.grid.reloadData(tableData.value);
},
{
immediate: true,
},
);
/** 产品下拉选项 */
const productOptions = ref<CrmProductApi.Product[]>([]);
/** 初始化 */
onMounted(async () => {
productOptions.value = await getProductSimpleList();
});
</script>
<template>
<Grid class="w-full">
<template #productId="{ row }">
<ElSelect
v-model="row.productId"
:field-names="{ label: 'name', value: 'id' }"
class="w-full"
@change="handleProductChange($event, row)"
>
<ElOption
v-for="option in productOptions"
:key="option.id"
:label="option.name"
:value="option.id"
/>
</ElSelect>
</template>
<template #sellingPrice="{ row }">
<ElInputNumber
v-model="row.sellingPrice"
:min="0.001"
:precision="2"
controls-position="right"
class="!w-full"
@change="handlePriceChange(row)"
/>
</template>
<template #count="{ row }">
<ElInputNumber
v-model="row.count"
:min="0.001"
:precision="3"
controls-position="right"
class="!w-full"
@change="handlePriceChange(row)"
/>
</template>
<template #bottom>
<TableAction
class="mt-4 flex justify-center"
:actions="[
{
label: '添加产品',
type: 'default',
onClick: handleAdd,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.delete'),
type: 'danger',
link: true,
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</template>

View File

@@ -0,0 +1,2 @@
export { default as ProductDetailsList } from './detail-list.vue';
export { default as ProductEditTable } from './edit-table.vue';

View File

@@ -0,0 +1,231 @@
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 { useUserStore } from '@vben/stores';
import { handleTree } from '@vben/utils';
import { z } from '#/adapter/form';
import { getProductCategoryList } from '#/api/crm/product/category';
import { getSimpleUserList } from '#/api/system/user';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
const userStore = useUserStore();
return [
{
component: 'Input',
fieldName: 'id',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
component: 'Input',
fieldName: 'name',
label: '产品名称',
rules: 'required',
componentProps: {
placeholder: '请输入产品名称',
clearable: true,
},
},
{
component: 'ApiSelect',
fieldName: 'ownerUserId',
label: '负责人',
rules: 'required',
dependencies: {
triggerFields: ['id'],
disabled: (values) => values.id,
},
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
placeholder: '请选择负责人',
clearable: true,
},
defaultValue: userStore.userInfo?.id,
},
{
component: 'Input',
fieldName: 'no',
label: '产品编码',
rules: 'required',
componentProps: {
placeholder: '请输入产品编码',
clearable: true,
},
},
{
component: 'ApiTreeSelect',
fieldName: 'categoryId',
label: '产品类型',
rules: 'required',
componentProps: {
api: async () => {
const data = await getProductCategoryList();
return handleTree(data);
},
fieldNames: { label: 'name', value: 'id', children: 'children' },
placeholder: '请选择产品类型',
clearable: true,
},
},
{
fieldName: 'unit',
label: '产品单位',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.CRM_PRODUCT_UNIT, 'number'),
placeholder: '请选择产品单位',
clearable: true,
},
rules: 'required',
},
{
component: 'InputNumber',
fieldName: 'price',
label: '价格(元)',
rules: 'required',
componentProps: {
min: 0,
precision: 2,
step: 0.1,
placeholder: '请输入产品价格',
controlsPosition: 'right',
class: '!w-full',
},
},
{
component: 'Textarea',
fieldName: 'description',
label: '产品描述',
componentProps: {
placeholder: '请输入产品描述',
clearable: true,
},
},
{
fieldName: 'status',
label: '上架状态',
component: 'RadioGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.CRM_PRODUCT_STATUS, 'number'),
},
rules: z.number().default(CommonStatusEnum.ENABLE),
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '产品名称',
component: 'Input',
componentProps: {
placeholder: '请输入产品名称',
clearable: true,
},
},
{
fieldName: 'status',
label: '上架状态',
component: 'Select',
componentProps: {
clearable: true,
placeholder: '请选择上架状态',
options: getDictOptions(DICT_TYPE.CRM_PRODUCT_STATUS, 'number'),
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '产品编号',
visible: false,
},
{
field: 'name',
title: '产品名称',
minWidth: 240,
slots: { default: 'name' },
},
{
field: 'categoryName',
title: '产品类型',
minWidth: 120,
},
{
field: 'unit',
title: '产品单位',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_PRODUCT_UNIT },
},
},
{
field: 'no',
title: '产品编码',
minWidth: 120,
},
{
field: 'price',
title: '价格(元)',
formatter: 'formatAmount2',
minWidth: 120,
},
{
field: 'description',
title: '产品描述',
minWidth: 200,
},
{
field: 'status',
title: '上架状态',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_PRODUCT_STATUS },
},
minWidth: 120,
},
{
field: 'ownerUserName',
title: '负责人',
minWidth: 120,
},
{
field: 'updateTime',
title: '更新时间',
formatter: 'formatDateTime',
minWidth: 180,
},
{
field: 'creatorName',
title: '创建人',
minWidth: 120,
},
{
field: 'createTime',
title: '创建时间',
formatter: 'formatDateTime',
minWidth: 180,
},
{
title: '操作',
width: 160,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,72 @@
import type { DescriptionItemSchema } from '#/components/description';
import { h } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { erpPriceInputFormatter } from '@vben/utils';
import { DictTag } from '#/components/dict-tag';
/** 详情页的字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
return [
{
field: 'categoryName',
label: '产品类别',
},
{
field: 'unit',
label: '产品单位',
render: (val) =>
h(DictTag, { type: DICT_TYPE.CRM_PRODUCT_UNIT, value: val }),
},
{
field: 'price',
label: '产品价格(元)',
render: (val) => erpPriceInputFormatter(val),
},
{
field: 'no',
label: '产品编码',
},
];
}
/** 详情页的基础字段 */
export function useDetailBaseSchema(): DescriptionItemSchema[] {
return [
{
field: 'name',
label: '产品名称',
},
{
field: 'no',
label: '产品编码',
},
{
field: 'price',
label: '价格(元)',
render: (val) => erpPriceInputFormatter(val),
},
{
field: 'description',
label: '产品描述',
},
{
field: 'categoryName',
label: '产品类型',
},
{
field: 'status',
label: '是否上下架',
render: (val) =>
h(DictTag, { type: DICT_TYPE.CRM_PRODUCT_STATUS, value: val }),
},
{
field: 'unit',
label: '产品单位',
render: (val) =>
h(DictTag, { type: DICT_TYPE.CRM_PRODUCT_UNIT, value: val }),
},
];
}

View File

@@ -0,0 +1,89 @@
<script setup lang="ts">
import type { CrmProductApi } from '#/api/crm/product';
import type { SystemOperateLogApi } from '#/api/system/operate-log';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { ElButton, ElCard, ElTabPane, ElTabs } from 'element-plus';
import { getOperateLogPage } from '#/api/crm/operateLog';
import { BizTypeEnum } from '#/api/crm/permission';
import { getProduct } from '#/api/crm/product';
import { useDescription } from '#/components/description';
import { OperateLog } from '#/components/operate-log';
import { useDetailSchema } from './data';
import Info from './modules/info.vue';
const route = useRoute();
const router = useRouter();
const tabs = useTabs();
const loading = ref(false); // 加载中
const productId = ref(0); // 产品编号
const product = ref<CrmProductApi.Product>({} as CrmProductApi.Product); // 产品详情
const logList = ref<SystemOperateLogApi.OperateLog[]>([]); // 操作日志
const activeTabName = ref('1'); // 选中 Tab 名
const [Descriptions] = useDescription({
border: false,
column: 4,
schema: useDetailSchema(),
});
/** 加载详情 */
async function getProductDetail() {
loading.value = true;
try {
product.value = await getProduct(productId.value);
// 操作日志
const res = await getOperateLogPage({
bizType: BizTypeEnum.CRM_PRODUCT,
bizId: productId.value,
});
logList.value = res.list;
} finally {
loading.value = false;
}
loading.value = false;
}
/** 返回列表页 */
function handleBack() {
tabs.closeCurrentTab();
router.push({ name: 'CrmProduct' });
}
/** 加载数据 */
onMounted(() => {
productId.value = Number(route.params.id);
getProductDetail();
});
</script>
<template>
<Page auto-content-height :title="product?.name" :loading="loading">
<template #extra>
<div class="flex items-center gap-2">
<ElButton @click="handleBack"> 返回 </ElButton>
</div>
</template>
<ElCard class="min-h-[10%]">
<Descriptions :data="product" />
</ElCard>
<ElCard class="mt-4 min-h-[60%]">
<ElTabs v-model:model-value="activeTabName">
<ElTabPane label="详细资料" name="1">
<Info :product="product" />
</ElTabPane>
<ElTabPane label="操作日志" name="2">
<OperateLog :log-list="logList" />
</ElTabPane>
</ElTabs>
</ElCard>
</Page>
</template>

View File

@@ -0,0 +1,23 @@
<script lang="ts" setup>
import type { CrmProductApi } from '#/api/crm/product';
import { useDescription } from '#/components/description';
import { useDetailBaseSchema } from '../data';
defineProps<{
product: CrmProductApi.Product;
}>();
const [ProductDescriptions] = useDescription({
border: false,
column: 4,
schema: useDetailBaseSchema(),
});
</script>
<template>
<div>
<ProductDescriptions :data="product" />
</div>
</template>

View File

@@ -0,0 +1,157 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmProductApi } from '#/api/crm/product';
import { useRouter } from 'vue-router';
import { Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import { ElButton, ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteProduct,
exportProduct,
getProductPage,
} from '#/api/crm/product';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const { push } = useRouter();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 导出表格 */
async function handleExport() {
const data = await exportProduct(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '产品.xls', source: data });
}
/** 打开详情 */
function handleDetail(row: CrmProductApi.Product) {
push({ name: 'CrmProductDetail', params: { id: row.id } });
}
/** 创建产品 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑产品 */
function handleEdit(row: CrmProductApi.Product) {
formModalApi.setData(row).open();
}
/** 删除产品 */
async function handleDelete(row: CrmProductApi.Product) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteProduct(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 getProductPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<CrmProductApi.Product>,
});
</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: ['crm:product:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['crm:product:export'],
onClick: handleExport,
},
]"
/>
</template>
<template #name="{ row }">
<ElButton type="primary" link @click="handleDetail(row)">
{{ row.name }}
</ElButton>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['crm:product:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['crm:product: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 { CrmProductApi } from '#/api/crm/product';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { createProduct, getProduct, updateProduct } from '#/api/crm/product';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<CrmProductApi.Product>();
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: 80,
},
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 CrmProductApi.Product;
try {
await (formData.value?.id ? updateProduct(data) : createProduct(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<CrmProductApi.Product>();
if (!data || !data.id) {
return;
}
modalApi.lock();
try {
formData.value = await getProduct(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,73 @@
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { DICT_TYPE } from '@vben/constants';
/** 详情列表的字段 */
export function useDetailListColumns(): VxeTableGridOptions['columns'] {
return [
{
title: '回款编号',
field: 'no',
minWidth: 150,
fixed: 'left',
},
{
title: '客户名称',
field: 'customerName',
minWidth: 150,
},
{
title: '合同编号',
field: 'contract.no',
minWidth: 150,
},
{
title: '回款日期',
field: 'returnTime',
minWidth: 150,
formatter: 'formatDateTime',
},
{
title: '回款金额(元)',
field: 'price',
minWidth: 150,
formatter: 'formatAmount2',
},
{
title: '回款方式',
field: 'returnType',
minWidth: 150,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_RECEIVABLE_RETURN_TYPE },
},
},
{
title: '负责人',
field: 'ownerUserName',
minWidth: 150,
},
{
title: '备注',
field: 'remark',
minWidth: 150,
},
{
title: '回款状态',
field: 'auditStatus',
minWidth: 100,
fixed: 'right',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_AUDIT_STATUS },
},
},
{
title: '操作',
field: 'actions',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,144 @@
<!-- 回款列表用于客户合同详情中展示它们关联的回款列表 -->
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmReceivableApi } from '#/api/crm/receivable';
import { useVbenModal } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteReceivable,
getReceivablePageByCustomer,
} from '#/api/crm/receivable';
import { $t } from '#/locales';
import Form from '../modules/form.vue';
import { useDetailListColumns } from './data';
const props = defineProps<{
contractId?: number; // 合同编号
customerId?: number; // 客户编号
}>();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建回款 */
function handleCreate() {
formModalApi
.setData({
contractId: props.contractId,
customerId: props.customerId,
})
.open();
}
/** 编辑回款 */
function handleEdit(row: CrmReceivableApi.Receivable) {
formModalApi.setData({ receivable: row }).open();
}
/** 删除回款 */
async function handleDelete(row: CrmReceivableApi.Receivable) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.no]),
});
try {
await deleteReceivable(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.no]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
columns: useDetailListColumns(),
height: 500,
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }) => {
const queryParams: CrmReceivableApi.ReceivablePageParam = {
pageNo: page.currentPage,
pageSize: page.pageSize,
};
if (props.customerId && !props.contractId) {
queryParams.customerId = props.customerId;
} else if (props.customerId && props.contractId) {
// 如果是合同的话客户编号也需要带上因为权限基于客户
queryParams.customerId = props.customerId;
queryParams.contractId = props.contractId;
}
return await getReceivablePageByCustomer(queryParams);
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<CrmReceivableApi.Receivable>,
});
</script>
<template>
<div>
<FormModal @success="handleRefresh" />
<Grid>
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['回款']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['crm:receivable:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['crm:receivable:update'],
onClick: handleEdit.bind(null, row),
ifShow: row.auditStatus === 0,
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['crm:receivable:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.no]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</div>
</template>

View File

@@ -0,0 +1 @@
export { default as ReceivableDetailsList } from './detail-list.vue';

View File

@@ -0,0 +1,300 @@
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 { useUserStore } from '@vben/stores';
import { getContractSimpleList } from '#/api/crm/contract';
import { getCustomerSimpleList } from '#/api/crm/customer';
import {
getReceivablePlan,
getReceivablePlanSimpleList,
} from '#/api/crm/receivable/plan';
import { getSimpleUserList } from '#/api/system/user';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
const userStore = useUserStore();
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'no',
label: '回款编号',
component: 'Input',
componentProps: {
placeholder: '保存时自动生成',
disabled: true,
},
},
{
fieldName: 'ownerUserId',
label: '负责人',
component: 'ApiSelect',
rules: 'required',
dependencies: {
triggerFields: ['id'],
disabled: (values) => values.id,
},
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
placeholder: '请选择负责人',
allowClear: true,
},
defaultValue: userStore.userInfo?.id,
},
{
fieldName: 'customerId',
label: '客户名称',
component: 'ApiSelect',
rules: 'required',
componentProps: {
api: getCustomerSimpleList,
labelField: 'name',
valueField: 'id',
placeholder: '请选择客户',
},
dependencies: {
triggerFields: ['id'],
disabled: (values) => values.id,
},
},
{
fieldName: 'contractId',
label: '合同名称',
component: 'Select',
rules: 'required',
dependencies: {
triggerFields: ['customerId'],
disabled: (values) => !values.customerId || values.id,
async componentProps(values) {
if (values.customerId) {
if (!values.id) {
// 特殊:只有在【新增】时,才清空合同编号
values.contractId = undefined;
}
const contracts = await getContractSimpleList(values.customerId);
return {
options: contracts.map((item) => ({
label: item.name,
value: item.id,
})),
placeholder: '请选择合同',
} as any;
}
},
},
},
{
fieldName: 'planId',
label: '回款期数',
component: 'Select',
rules: 'required',
dependencies: {
triggerFields: ['contractId'],
disabled: (values) => !values.contractId,
async componentProps(values) {
if (values.contractId) {
values.planId = undefined;
const plans = await getReceivablePlanSimpleList(
values.customerId,
values.contractId,
);
return {
options: plans.map((item) => ({
label: item.period,
value: item.id,
})),
placeholder: '请选择回款期数',
onChange: async (value: any) => {
const plan = await getReceivablePlan(value);
values.returnTime = plan?.returnTime;
values.price = plan?.price;
values.returnType = plan?.returnType;
},
} as any;
}
},
},
},
{
fieldName: 'returnType',
label: '回款方式',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.CRM_RECEIVABLE_RETURN_TYPE, 'number'),
placeholder: '请选择回款方式',
},
},
{
fieldName: 'price',
label: '回款金额',
component: 'InputNumber',
rules: 'required',
componentProps: {
placeholder: '请输入回款金额',
min: 0,
precision: 2,
controlsPosition: 'right',
class: '!w-full',
},
},
{
fieldName: 'returnTime',
label: '回款日期',
component: 'DatePicker',
rules: 'required',
componentProps: {
placeholder: '请选择回款日期',
valueFormat: 'x',
format: 'YYYY-MM-DD',
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
rows: 4,
},
formItemClass: 'md:col-span-2',
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'no',
label: '回款编号',
component: 'Input',
componentProps: {
placeholder: '请输入回款编号',
allowClear: true,
},
},
{
fieldName: 'customerId',
label: '客户',
component: 'ApiSelect',
componentProps: {
api: getCustomerSimpleList,
labelField: 'name',
valueField: 'id',
placeholder: '请选择客户',
allowClear: true,
},
},
];
}
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
title: '回款编号',
field: 'no',
minWidth: 160,
fixed: 'left',
slots: { default: 'no' },
},
{
title: '客户名称',
field: 'customerName',
minWidth: 150,
slots: { default: 'customerName' },
},
{
title: '合同编号',
field: 'contract',
minWidth: 160,
slots: { default: 'contractNo' },
},
{
title: '回款日期',
field: 'returnTime',
minWidth: 150,
formatter: 'formatDateTime',
},
{
title: '回款金额(元)',
field: 'price',
minWidth: 150,
formatter: 'formatAmount2',
},
{
title: '回款方式',
field: 'returnType',
minWidth: 150,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_RECEIVABLE_RETURN_TYPE },
},
},
{
title: '备注',
field: 'remark',
minWidth: 150,
},
{
title: '合同金额(元)',
field: 'contract.totalPrice',
minWidth: 150,
formatter: 'formatAmount2',
},
{
title: '负责人',
field: 'ownerUserName',
minWidth: 150,
},
{
title: '所属部门',
field: 'ownerUserDeptName',
minWidth: 150,
},
{
title: '更新时间',
field: 'updateTime',
minWidth: 150,
formatter: 'formatDateTime',
},
{
title: '创建时间',
field: 'createTime',
minWidth: 150,
formatter: 'formatDateTime',
},
{
title: '创建人',
field: 'creatorName',
minWidth: 150,
},
{
title: '回款状态',
field: 'auditStatus',
minWidth: 100,
fixed: 'right',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_AUDIT_STATUS },
},
},
{
title: '操作',
field: 'actions',
minWidth: 200,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,105 @@
import type { DescriptionItemSchema } from '#/components/description';
import { h } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { erpPriceInputFormatter, formatDateTime } from '@vben/utils';
import { DictTag } from '#/components/dict-tag';
/** 详情页的字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
return [
{
field: 'customerName',
label: '客户名称',
},
{
field: 'totalPrice',
label: '合同金额(元)',
render: (val, data) =>
erpPriceInputFormatter(val ?? data?.contract?.totalPrice ?? 0),
},
{
field: 'returnTime',
label: '回款日期',
render: (val) => formatDateTime(val) as string,
},
{
field: 'price',
label: '回款金额(元)',
render: (val) => erpPriceInputFormatter(val),
},
{
field: 'ownerUserName',
label: '负责人',
},
];
}
/** 详情页的基础字段 */
export function useDetailBaseSchema(): DescriptionItemSchema[] {
return [
{
field: 'no',
label: '回款编号',
},
{
field: 'customerName',
label: '客户名称',
},
{
field: 'contract',
label: '合同编号',
render: (val, data) =>
val && data?.contract?.no ? data?.contract?.no : '',
},
{
field: 'returnTime',
label: '回款日期',
render: (val) => formatDateTime(val) as string,
},
{
field: 'price',
label: '回款金额',
render: (val) => erpPriceInputFormatter(val),
},
{
field: 'returnType',
label: '回款方式',
render: (val) =>
h(DictTag, {
type: DICT_TYPE.CRM_RECEIVABLE_RETURN_TYPE,
value: val,
}),
},
{
field: 'remark',
label: '备注',
},
];
}
/** 系统信息字段 */
export function useDetailSystemSchema(): DescriptionItemSchema[] {
return [
{
field: 'ownerUserName',
label: '负责人',
},
{
field: 'creatorName',
label: '创建人',
},
{
field: 'createTime',
label: '创建时间',
render: (val) => formatDateTime(val) as string,
},
{
field: 'updateTime',
label: '更新时间',
render: (val) => formatDateTime(val) as string,
},
];
}

View File

@@ -0,0 +1,132 @@
<script setup lang="ts">
import type { CrmReceivableApi } from '#/api/crm/receivable';
import type { SystemOperateLogApi } from '#/api/system/operate-log';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page, useVbenModal } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { ElCard, ElTabPane, ElTabs } from 'element-plus';
import { getOperateLogPage } from '#/api/crm/operateLog';
import { BizTypeEnum } from '#/api/crm/permission';
import { getReceivable } from '#/api/crm/receivable';
import { useDescription } from '#/components/description';
import { OperateLog } from '#/components/operate-log';
import { ACTION_ICON, TableAction } from '#/components/table-action';
import { $t } from '#/locales';
import { PermissionList } from '#/views/crm/permission';
import ReceivableForm from '../modules/form.vue';
import { useDetailSchema } from './data';
import Info from './modules/info.vue';
const props = defineProps<{ id?: number }>();
const route = useRoute();
const router = useRouter();
const tabs = useTabs();
const loading = ref(false); // 加载中
const receivableId = ref(0); // 回款编号
const receivable = ref<CrmReceivableApi.Receivable>(
{} as CrmReceivableApi.Receivable,
); // 回款详情
const logList = ref<SystemOperateLogApi.OperateLog[]>([]); // 操作日志
const permissionListRef = ref<InstanceType<typeof PermissionList>>(); // 团队成员列表 Ref
const activeTabName = ref('1'); // 选中 Tab 名
const [Descriptions] = useDescription({
border: false,
column: 4,
schema: useDetailSchema(),
});
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: ReceivableForm,
destroyOnClose: true,
});
/** 加载回款详情 */
async function loadReceivableDetail() {
loading.value = true;
try {
receivable.value = await getReceivable(receivableId.value);
// 操作日志
const res = await getOperateLogPage({
bizType: BizTypeEnum.CRM_RECEIVABLE,
bizId: receivableId.value,
});
logList.value = res.list;
} finally {
loading.value = false;
}
}
/** 返回列表页 */
function handleBack() {
tabs.closeCurrentTab();
router.push({ name: 'CrmReceivable' });
}
/** 编辑收款 */
function handleEdit() {
formModalApi.setData({ receivable: { id: receivableId.value } }).open();
}
/** 加载数据 */
onMounted(() => {
receivableId.value = Number(props.id || route.params.id);
loadReceivableDetail();
});
</script>
<template>
<Page auto-content-height :title="receivable?.no" :loading="loading">
<FormModal @success="loadReceivableDetail" />
<template #extra>
<TableAction
:actions="[
{
label: '返回',
type: 'default',
icon: 'lucide:arrow-left',
onClick: handleBack,
},
{
label: $t('ui.actionTitle.edit'),
type: 'primary',
icon: ACTION_ICON.EDIT,
auth: ['crm:receivable:update'],
ifShow: permissionListRef?.validateWrite,
onClick: handleEdit,
},
]"
/>
</template>
<ElCard class="min-h-[10%]">
<Descriptions :data="receivable" />
</ElCard>
<ElCard class="mt-4 min-h-[60%]">
<ElTabs v-model:model-value="activeTabName">
<ElTabPane label="详细资料" name="1" :lazy="false">
<Info :receivable="receivable" />
</ElTabPane>
<ElTabPane label="操作日志" name="2" :lazy="false">
<OperateLog :log-list="logList" />
</ElTabPane>
<ElTabPane label="团队成员" name="3" :lazy="false">
<PermissionList
ref="permissionListRef"
:biz-id="receivableId"
:biz-type="BizTypeEnum.CRM_RECEIVABLE"
:show-action="true"
@quit-team="handleBack"
/>
</ElTabPane>
</ElTabs>
</ElCard>
</Page>
</template>

View File

@@ -0,0 +1,35 @@
<script lang="ts" setup>
import type { CrmReceivableApi } from '#/api/crm/receivable';
import { ElDivider } from 'element-plus';
import { useDescription } from '#/components/description';
import { useDetailBaseSchema, useDetailSystemSchema } from '../data';
defineProps<{
receivable: CrmReceivableApi.Receivable; // 收款信息
}>();
const [BaseDescriptions] = useDescription({
title: '基本信息',
border: false,
column: 4,
schema: useDetailBaseSchema(),
});
const [SystemDescriptions] = useDescription({
title: '系统信息',
border: false,
column: 3,
schema: useDetailSystemSchema(),
});
</script>
<template>
<div>
<BaseDescriptions :data="receivable" />
<ElDivider />
<SystemDescriptions :data="receivable" />
</div>
</template>

View File

@@ -0,0 +1,263 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmReceivableApi } from '#/api/crm/receivable';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import {
ElButton,
ElLoading,
ElMessage,
ElTabPane,
ElTabs,
} from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteReceivable,
exportReceivable,
getReceivablePage,
submitReceivable,
} from '#/api/crm/receivable';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const { push } = useRouter();
const sceneType = ref('1');
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 处理场景类型的切换 */
function handleChangeSceneType(key: number | string) {
sceneType.value = key.toString();
gridApi.query();
}
/** 导出表格 */
async function handleExport() {
const formValues = await gridApi.formApi.getValues();
const data = await exportReceivable({
sceneType: sceneType.value,
...formValues,
});
downloadFileFromBlobPart({ fileName: '回款.xls', source: data });
}
/** 创建回款 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑回款 */
function handleEdit(row: CrmReceivableApi.Receivable) {
formModalApi.setData({ receivable: row }).open();
}
/** 删除回款 */
async function handleDelete(row: CrmReceivableApi.Receivable) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.no]),
});
try {
await deleteReceivable(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.no]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 提交审核 */
async function handleSubmit(row: CrmReceivableApi.Receivable) {
const loadingInstance = ElLoading.service({
text: '提交审核中...',
});
try {
await submitReceivable(row.id!);
ElMessage.success('提交审核成功');
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 查看回款详情 */
function handleDetail(row: CrmReceivableApi.Receivable) {
push({ name: 'CrmReceivableDetail', params: { id: row.id } });
}
/** 查看客户详情 */
function handleCustomerDetail(row: CrmReceivableApi.Receivable) {
push({ name: 'CrmCustomerDetail', params: { id: row.customerId } });
}
/** 查看合同详情 */
function handleContractDetail(row: CrmReceivableApi.Receivable) {
push({ name: 'CrmContractDetail', params: { id: row.contractId } });
}
/** 查看审批详情 */
function handleProcessDetail(row: CrmReceivableApi.Receivable) {
push({
name: 'BpmProcessInstanceDetail',
query: { id: row.processInstanceId },
});
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getReceivablePage({
pageNo: page.currentPage,
pageSize: page.pageSize,
sceneType: sceneType.value,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<CrmReceivableApi.Receivable>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert
title="【回款】回款管理、回款计划"
url="https://doc.iocoder.cn/crm/receivable/"
/>
<DocAlert
title="【通用】数据权限"
url="https://doc.iocoder.cn/crm/permission/"
/>
</template>
<FormModal @success="handleRefresh" />
<Grid>
<template #toolbar-actions>
<ElTabs
class="w-full"
@tab-change="handleChangeSceneType"
v-model:model-value="sceneType"
>
<ElTabPane label="我负责的" name="1" />
<ElTabPane label="我参与的" name="2" />
<ElTabPane label="下属负责的" name="3" />
</ElTabs>
</template>
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['回款']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['crm:receivable:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['crm:receivable:export'],
onClick: handleExport,
},
]"
/>
</template>
<template #no="{ row }">
<ElButton type="primary" link @click="handleDetail(row)">
{{ row.no }}
</ElButton>
</template>
<template #customerName="{ row }">
<ElButton type="primary" link @click="handleCustomerDetail(row)">
{{ row.customerName }}
</ElButton>
</template>
<template #contractNo="{ row }">
<ElButton
v-if="row.contract"
type="primary"
link
@click="handleContractDetail(row)"
>
{{ row.contract.no }}
</ElButton>
<span v-else>--</span>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['crm:receivable:update'],
onClick: handleEdit.bind(null, row),
},
{
label: '提交审核',
type: 'primary',
link: true,
auth: ['crm:receivable:update'],
onClick: handleSubmit.bind(null, row),
ifShow: row.auditStatus === 0,
},
{
label: '查看审批',
type: 'primary',
link: true,
auth: ['crm:receivable:update'],
onClick: handleProcessDetail.bind(null, row),
ifShow: row.auditStatus !== 0,
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['crm:receivable:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.no]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,102 @@
<script lang="ts" setup>
import type { CrmReceivableApi } from '#/api/crm/receivable';
import { computed, ref } from 'vue';
import { useVbenForm, useVbenModal } from '@vben/common-ui';
import { ElMessage } from 'element-plus';
import {
createReceivable,
getReceivable,
updateReceivable,
} from '#/api/crm/receivable';
import { $t } from '#/locales';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
const formData = ref<CrmReceivableApi.Receivable>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', ['回款'])
: $t('ui.actionTitle.create', ['回款']);
});
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
},
wrapperClass: 'grid-cols-2',
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 CrmReceivableApi.Receivable;
try {
await (formData.value?.id
? updateReceivable(data)
: createReceivable(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();
if (!data) {
return;
}
const { receivable, plan } = data;
modalApi.lock();
try {
if (receivable) {
formData.value = await getReceivable(receivable.id!);
} else if (plan) {
formData.value = plan.id
? {
planId: plan.id,
price: plan.price,
returnType: plan.returnType,
customerId: plan.customerId,
contractId: plan.contractId,
}
: ({
customerId: plan.customerId,
contractId: plan.contractId,
} as any);
}
// 设置到 values
await formApi.setValues(formData.value as any);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-2/5">
<Form class="mx-4" />
</Modal>
</template>

View File

@@ -0,0 +1,62 @@
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
/** 详情列表的字段 */
export function useDetailListColumns(): VxeTableGridOptions['columns'] {
return [
{
title: '客户名称',
field: 'customerName',
minWidth: 150,
},
{
title: '合同编号',
field: 'contractNo',
minWidth: 150,
},
{
title: '期数',
field: 'period',
minWidth: 150,
},
{
title: '计划回款(元)',
field: 'price',
minWidth: 150,
formatter: 'formatAmount2',
},
{
title: '计划回款日期',
field: 'returnTime',
minWidth: 150,
formatter: 'formatDateTime',
},
{
title: '提前几天提醒',
field: 'remindDays',
minWidth: 150,
},
{
title: '提醒日期',
field: 'remindTime',
minWidth: 150,
formatter: 'formatDateTime',
},
{
title: '负责人',
field: 'ownerUserName',
minWidth: 150,
},
{
title: '备注',
field: 'remark',
minWidth: 150,
},
{
title: '操作',
field: 'actions',
width: 240,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,147 @@
<!-- 回款计划列表用于客户合同详情中展示它们关联的回款计划列表 -->
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmReceivablePlanApi } from '#/api/crm/receivable/plan';
import { useVbenModal } from '@vben/common-ui';
import { ElLoading, ElMessage } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteReceivablePlan,
getReceivablePlanPageByCustomer,
} from '#/api/crm/receivable/plan';
import { $t } from '#/locales';
import Form from '../modules/form.vue';
import { useDetailListColumns } from './data';
const props = defineProps<{
contractId?: number; // 合同编号
customerId?: number; // 客户编号
}>();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建回款计划 */
function handleCreate() {
formModalApi
.setData({
contractId: props.contractId,
customerId: props.customerId,
})
.open();
}
/** 编辑回款计划 */
function handleEdit(row: CrmReceivablePlanApi.Plan) {
formModalApi.setData({ receivablePlan: row }).open();
}
/** 删除回款计划 */
async function handleDelete(row: CrmReceivablePlanApi.Plan) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [`${row.period}`]),
});
try {
await deleteReceivablePlan(row.id!);
ElMessage.success(
$t('ui.actionMessage.deleteSuccess', [`${row.period}`]),
);
handleRefresh();
} finally {
loadingInstance.close();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
columns: useDetailListColumns(),
height: 500,
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }) => {
const queryParams: CrmReceivablePlanApi.PlanPageParam = {
pageNo: page.currentPage,
pageSize: page.pageSize,
};
if (props.customerId && !props.contractId) {
queryParams.customerId = props.customerId;
} else if (props.customerId && props.contractId) {
// 如果是合同的话客户编号也需要带上因为权限基于客户
queryParams.customerId = props.customerId;
queryParams.contractId = props.contractId;
}
return await getReceivablePlanPageByCustomer(queryParams);
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<CrmReceivablePlanApi.Plan>,
});
</script>
<template>
<div>
<FormModal @success="handleRefresh" />
<Grid>
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['回款计划']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['crm:receivable-plan:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['crm:receivable-plan:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['crm:receivable-plan:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [
`第${row.period}期`,
]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</div>
</template>

View File

@@ -0,0 +1,2 @@
export { default as ReceivablePlanDetailsInfo } from '../detail/modules/info.vue';
export { default as ReceivablePlanDetailsList } from './detail-list.vue';

View File

@@ -0,0 +1,288 @@
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 { useUserStore } from '@vben/stores';
import { erpPriceInputFormatter } from '@vben/utils';
import { getContractSimpleList } from '#/api/crm/contract';
import { getCustomerSimpleList } from '#/api/crm/customer';
import { getSimpleUserList } from '#/api/system/user';
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
const userStore = useUserStore();
return [
{
fieldName: 'period',
label: '期数',
component: 'Input',
componentProps: {
placeholder: '保存时自动生成',
disabled: true,
},
},
{
fieldName: 'ownerUserId',
label: '负责人',
component: 'ApiSelect',
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
},
dependencies: {
triggerFields: ['id'],
disabled: (values) => values.id,
},
defaultValue: userStore.userInfo?.id,
rules: 'required',
},
{
fieldName: 'customerId',
label: '客户',
component: 'ApiSelect',
rules: 'required',
componentProps: {
api: getCustomerSimpleList,
labelField: 'name',
valueField: 'id',
placeholder: '请选择客户',
allowClear: true,
},
},
{
fieldName: 'contractId',
label: '合同',
component: 'Select',
rules: 'required',
componentProps: {
options: [],
placeholder: '请选择合同',
allowClear: true,
},
dependencies: {
triggerFields: ['customerId'],
disabled: (values) => !values.customerId,
async componentProps(values) {
if (!values.customerId) {
return {
options: [],
placeholder: '请选择客户',
};
}
const res = await getContractSimpleList(values.customerId);
return {
options: res.map((item) => ({
label: item.name,
value: item.id,
})),
placeholder: '请选择合同',
onChange: (value: number) => {
const contract = res.find((item) => item.id === value);
if (contract) {
values.price =
contract.totalPrice - contract.totalReceivablePrice;
}
},
};
},
},
},
{
fieldName: 'price',
label: '计划回款金额',
component: 'InputNumber',
rules: 'required',
componentProps: {
placeholder: '请输入计划回款金额',
min: 0,
precision: 2,
controlsPosition: 'right',
class: '!w-full',
},
},
{
fieldName: 'returnTime',
label: '计划回款日期',
component: 'DatePicker',
rules: 'required',
componentProps: {
placeholder: '请选择计划回款日期',
valueFormat: 'x',
format: 'YYYY-MM-DD',
},
defaultValue: new Date(),
},
{
fieldName: 'remindDays',
label: '提前几天提醒',
component: 'InputNumber',
componentProps: {
placeholder: '请输入提前几天提醒',
min: 0,
controlsPosition: 'right',
class: '!w-full',
},
},
{
fieldName: 'returnType',
label: '回款方式',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.CRM_RECEIVABLE_RETURN_TYPE, 'number'),
placeholder: '请选择回款方式',
},
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
rows: 4,
},
formItemClass: 'md:col-span-2',
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'customerId',
label: '客户',
component: 'ApiSelect',
componentProps: {
api: getCustomerSimpleList,
labelField: 'name',
valueField: 'id',
placeholder: '请选择客户',
allowClear: true,
},
},
{
fieldName: 'contractNo',
label: '合同编号',
component: 'Input',
componentProps: {
placeholder: '请输入合同编号',
allowClear: true,
},
},
];
}
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
title: '客户名称',
field: 'customerName',
minWidth: 150,
fixed: 'left',
slots: { default: 'customerName' },
},
{
title: '合同编号',
field: 'contractNo',
minWidth: 200,
},
{
title: '期数',
field: 'period',
minWidth: 150,
slots: { default: 'period' },
},
{
title: '计划回款金额(元)',
field: 'price',
minWidth: 160,
formatter: 'formatAmount2',
},
{
title: '计划回款日期',
field: 'returnTime',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '提前几天提醒',
field: 'remindDays',
minWidth: 150,
},
{
title: '提醒日期',
field: 'remindTime',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '回款方式',
field: 'returnType',
minWidth: 130,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.CRM_RECEIVABLE_RETURN_TYPE },
},
},
{
title: '备注',
field: 'remark',
minWidth: 120,
},
{
title: '负责人',
field: 'ownerUserName',
minWidth: 120,
},
{
title: '实际回款金额(元)',
field: 'receivable.price',
minWidth: 160,
formatter: 'formatAmount2',
},
{
title: '实际回款日期',
field: 'receivable.returnTime',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '未回款金额(元)',
field: 'unpaidPrice',
minWidth: 160,
formatter: ({ row }) => {
if (row.receivable) {
return erpPriceInputFormatter(row.price - row.receivable.price);
}
return erpPriceInputFormatter(row.price);
},
},
{
title: '更新时间',
field: 'updateTime',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '创建时间',
field: 'createTime',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '创建人',
field: 'creatorName',
minWidth: 100,
},
{
title: '操作',
field: 'actions',
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,124 @@
import type { DescriptionItemSchema } from '#/components/description';
import { h } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { erpPriceInputFormatter, formatDateTime } from '@vben/utils';
import { DictTag } from '#/components/dict-tag';
/** 详情页的字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
return [
{
field: 'customerName',
label: '客户名称',
},
{
field: 'contractNo',
label: '合同编号',
},
{
field: 'price',
label: '计划回款金额',
render: (val) => erpPriceInputFormatter(val),
},
{
field: 'returnTime',
label: '计划回款日期',
render: (val) => formatDateTime(val) as string,
},
{
field: 'receivable',
label: '实际回款金额',
render: (val) => erpPriceInputFormatter(val?.price ?? 0),
},
];
}
/** 详情页的基础字段 */
export function useDetailBaseSchema(): DescriptionItemSchema[] {
return [
{
field: 'period',
label: '期数',
},
{
field: 'customerName',
label: '客户名称',
},
{
field: 'contractNo',
label: '合同编号',
},
{
field: 'returnTime',
label: '计划回款日期',
render: (val) => formatDateTime(val) as string,
},
{
field: 'price',
label: '计划回款金额',
render: (val) => erpPriceInputFormatter(val),
},
{
field: 'returnType',
label: '计划回款方式',
render: (val) =>
h(DictTag, {
type: DICT_TYPE.CRM_RECEIVABLE_RETURN_TYPE,
value: val,
}),
},
{
field: 'remindDays',
label: '提前几天提醒',
},
{
field: 'receivable',
label: '实际回款金额',
render: (val) => erpPriceInputFormatter(val ?? 0),
},
{
field: 'receivableRemain',
label: '未回款金额',
render: (val, data) => {
const paid = data?.receivable?.price ?? 0;
return erpPriceInputFormatter(Math.max(val - paid, 0));
},
},
{
field: 'receivable.returnTime',
label: '实际回款日期',
render: (val) => formatDateTime(val) as string,
},
{
field: 'remark',
label: '备注',
},
];
}
/** 系统信息字段 */
export function useDetailSystemSchema(): DescriptionItemSchema[] {
return [
{
field: 'ownerUserName',
label: '负责人',
},
{
field: 'creatorName',
label: '创建人',
},
{
field: 'createTime',
label: '创建时间',
render: (val) => formatDateTime(val) as string,
},
{
field: 'updateTime',
label: '更新时间',
render: (val) => formatDateTime(val) as string,
},
];
}

View File

@@ -0,0 +1,135 @@
<script setup lang="ts">
import type { CrmReceivablePlanApi } from '#/api/crm/receivable/plan';
import type { SystemOperateLogApi } from '#/api/system/operate-log';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page, useVbenModal } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { ElCard, ElTabPane, ElTabs } from 'element-plus';
import { ACTION_ICON, TableAction } from '#/adapter/vxe-table';
import { getOperateLogPage } from '#/api/crm/operateLog';
import { BizTypeEnum } from '#/api/crm/permission';
import { getReceivablePlan } from '#/api/crm/receivable/plan';
import { useDescription } from '#/components/description';
import { OperateLog } from '#/components/operate-log';
import { $t } from '#/locales';
import { PermissionList } from '#/views/crm/permission';
import { ReceivablePlanDetailsInfo } from '#/views/crm/receivable/plan/components';
import ReceivablePlanForm from '../modules/form.vue';
import { useDetailSchema } from './data';
const route = useRoute();
const router = useRouter();
const tabs = useTabs();
const loading = ref(false); // 加载中
const receivablePlanId = ref(0); // 回款计划编号
const receivablePlan = ref<CrmReceivablePlanApi.Plan>(
{} as CrmReceivablePlanApi.Plan,
);
const activeTabName = ref('1'); // 选中 Tab 名
const logList = ref<SystemOperateLogApi.OperateLog[]>([]); // 操作日志
const permissionListRef = ref<InstanceType<typeof PermissionList>>(); // 团队成员列表 Ref
const validateWrite = () => permissionListRef.value?.validateWrite; // 校验编辑权限
const [Descriptions] = useDescription({
border: false,
column: 4,
schema: useDetailSchema(),
});
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: ReceivablePlanForm,
destroyOnClose: true,
});
/** 加载回款计划详情 */
async function getReceivablePlanDetail() {
loading.value = true;
try {
receivablePlan.value = await getReceivablePlan(receivablePlanId.value);
// 操作日志
const res = await getOperateLogPage({
bizType: BizTypeEnum.CRM_RECEIVABLE_PLAN,
bizId: receivablePlanId.value,
});
logList.value = res.list;
} finally {
loading.value = false;
}
}
/** 返回列表页 */
function handleBack() {
tabs.closeCurrentTab();
router.push({ name: 'CrmReceivablePlan' });
}
/** 编辑收款 */
function handleEdit() {
formModalApi.setData({ id: receivablePlanId.value }).open();
}
/** 加载数据 */
onMounted(() => {
receivablePlanId.value = Number(route.params.id);
getReceivablePlanDetail();
});
</script>
<template>
<Page
auto-content-height
:title="`第 ${receivablePlan?.period} 期`"
:loading="loading"
>
<FormModal @success="getReceivablePlanDetail" />
<template #extra>
<TableAction
:actions="[
{
label: '返回',
type: 'default',
icon: 'lucide:arrow-left',
onClick: handleBack,
},
{
label: $t('ui.actionTitle.edit'),
type: 'primary',
icon: ACTION_ICON.EDIT,
disabled: !validateWrite(),
onClick: handleEdit,
auth: ['crm:receivable-plan:update'],
},
]"
/>
</template>
<ElCard class="min-h-[10%]">
<Descriptions :data="receivablePlan" />
</ElCard>
<ElCard class="mt-4 min-h-[60%]">
<ElTabs v-model:model-value="activeTabName">
<ElTabPane label="详细资料" name="1" :lazy="false">
<ReceivablePlanDetailsInfo :receivable-plan="receivablePlan" />
</ElTabPane>
<ElTabPane label="操作日志" name="2" :lazy="false">
<OperateLog :log-list="logList" />
</ElTabPane>
<ElTabPane label="团队成员" name="3" :lazy="false">
<PermissionList
ref="permissionListRef"
:biz-id="receivablePlanId"
:biz-type="BizTypeEnum.CRM_RECEIVABLE_PLAN"
:show-action="true"
@quit-team="handleBack"
/>
</ElTabPane>
</ElTabs>
</ElCard>
</Page>
</template>

View File

@@ -0,0 +1,37 @@
<script lang="ts" setup>
import type { CrmReceivablePlanApi } from '#/api/crm/receivable/plan';
import { ElDivider } from 'element-plus';
import { useDescription } from '#/components/description';
import { useDetailBaseSchema, useDetailSystemSchema } from '../data';
defineProps<{
receivablePlan: CrmReceivablePlanApi.Plan; // 收款计划信息
}>();
const [BaseDescriptions] = useDescription({
title: '基本信息',
border: false,
column: 4,
class: 'mx-4',
schema: useDetailBaseSchema(),
});
const [SystemDescriptions] = useDescription({
title: '系统信息',
border: false,
column: 3,
class: 'mx-4',
schema: useDetailSystemSchema(),
});
</script>
<template>
<div class="p-4">
<BaseDescriptions :data="receivablePlan" />
<ElDivider />
<SystemDescriptions :data="receivablePlan" />
</div>
</template>

View File

@@ -0,0 +1,228 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CrmReceivablePlanApi } from '#/api/crm/receivable/plan';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import {
ElButton,
ElLoading,
ElMessage,
ElTabPane,
ElTabs,
} from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteReceivablePlan,
exportReceivablePlan,
getReceivablePlanPage,
} from '#/api/crm/receivable/plan';
import { $t } from '#/locales';
import ReceivableForm from '../modules/form.vue';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const { push } = useRouter();
const sceneType = ref('1');
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const [ReceivableFormModal, receivableFormModalApi] = useVbenModal({
connectedComponent: ReceivableForm,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 处理场景类型的切换 */
function handleChangeSceneType(key: number | string) {
sceneType.value = key.toString();
gridApi.query();
}
/** 导出表格 */
async function handleExport() {
const formValues = await gridApi.formApi.getValues();
const data = await exportReceivablePlan({
sceneType: sceneType.value,
...formValues,
});
downloadFileFromBlobPart({ fileName: '回款计划.xls', source: data });
}
/** 创建回款计划 */
function handleCreate() {
formModalApi.setData(null).open();
}
/** 编辑回款计划 */
function handleEdit(row: CrmReceivablePlanApi.Plan) {
formModalApi.setData(row).open();
}
/** 删除回款计划 */
async function handleDelete(row: CrmReceivablePlanApi.Plan) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.period]),
});
try {
await deleteReceivablePlan(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.period]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 创建回款计划 */
function handleCreateReceivable(row: CrmReceivablePlanApi.Plan) {
receivableFormModalApi.setData({ plan: row }).open();
}
/** 查看回款计划详情 */
function handleDetail(row: CrmReceivablePlanApi.Plan) {
push({ name: 'CrmReceivablePlanDetail', params: { id: row.id } });
}
/** 查看客户详情 */
function handleCustomerDetail(row: CrmReceivablePlanApi.Plan) {
push({ name: 'CrmCustomerDetail', params: { id: row.customerId } });
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getReceivablePlanPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
sceneType: sceneType.value,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<CrmReceivablePlanApi.Plan>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert
title="【回款】回款管理、回款计划"
url="https://doc.iocoder.cn/crm/receivable/"
/>
<DocAlert
title="【通用】数据权限"
url="https://doc.iocoder.cn/crm/permission/"
/>
</template>
<FormModal @success="handleRefresh" />
<ReceivableFormModal @success="handleRefresh" />
<Grid>
<template #toolbar-actions>
<ElTabs
class="w-full"
@tab-change="handleChangeSceneType"
v-model:model-value="sceneType"
>
<ElTabPane label="我负责的" name="1" />
<ElTabPane label="下属负责的" name="3" />
</ElTabs>
</template>
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['回款计划']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['crm:receivable-plan:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['crm:receivable-plan:export'],
onClick: handleExport,
},
]"
/>
</template>
<template #customerName="{ row }">
<ElButton type="primary" link @click="handleCustomerDetail(row)">
{{ row.customerName }}
</ElButton>
</template>
<template #period="{ row }">
<ElButton type="primary" link @click="handleDetail(row)">
{{ row.period }}
</ElButton>
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['回款']),
type: 'primary',
link: true,
icon: ACTION_ICON.ADD,
auth: ['crm:receivable:create'],
onClick: handleCreateReceivable.bind(null, row),
ifShow: !row.receivableId,
},
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['crm:receivable-plan:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['crm:receivable-plan:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.period]),
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