feat: 新增代码生成页面

This commit is contained in:
xlsea 2024-09-04 15:50:09 +08:00
parent c4d959d133
commit 824974e904
22 changed files with 1272 additions and 76 deletions

View File

@ -129,6 +129,7 @@ export default function useHookTable<A extends ApiFn, T, C>(config: TableConfig<
/** reset search params */
function resetSearchParams() {
Object.assign(searchParams, jsonClone(apiParams));
getData();
}
if (immediate) {

View File

@ -0,0 +1,25 @@
<script setup lang="ts">
defineOptions({
name: 'TableColumnCheckAlert'
});
const checkedRowKeys = defineModel<CommonType.IdType[]>('columns', { required: true });
</script>
<template>
<NAlert type="info">
<span v-if="checkedRowKeys.length">
已选择{{ checkedRowKeys.length }}条记录
<NButton class="pl-6px" text type="primary" @click="() => (checkedRowKeys = [])">清空</NButton>
</span>
<span v-else>未选中任何记录</span>
</NAlert>
</template>
<style scoped lang="scss">
.n-alert {
--n-padding: 5px 13px !important;
--n-icon-margin: 6px 8px 0 12px !important;
--n-icon-size: 20px !important;
}
</style>

View File

@ -9,9 +9,15 @@ interface Props {
itemAlign?: NaiveUI.Align;
disabledDelete?: boolean;
loading?: boolean;
showAdd?: boolean;
showDelete?: boolean;
}
defineProps<Props>();
withDefaults(defineProps<Props>(), {
itemAlign: undefined,
showAdd: true,
showDelete: true
});
interface Emits {
(e: 'add'): void;
@ -42,13 +48,13 @@ function refresh() {
<NSpace :align="itemAlign" wrap justify="end" class="lt-sm:w-200px">
<slot name="prefix"></slot>
<slot name="default">
<NButton size="small" ghost type="primary" @click="add">
<NButton v-if="showAdd" size="small" ghost type="primary" @click="add">
<template #icon>
<icon-ic-round-plus class="text-icon" />
</template>
{{ $t('common.add') }}
</NButton>
<NPopconfirm @positive-click="batchDelete">
<NPopconfirm v-if="showDelete" @positive-click="batchDelete">
<template #trigger>
<NButton size="small" ghost type="error" :disabled="disabledDelete">
<template #icon>

View File

@ -1,39 +1,50 @@
<script setup lang="tsx">
import { ref, useAttrs, watch } from 'vue';
import { ref, useAttrs } from 'vue';
import { useLoading } from '@sa/hooks';
import type { SelectProps } from 'naive-ui';
import { useDict } from '@/hooks/business/dict';
import type { SelectOption, SelectProps } from 'naive-ui';
import { fetchGetDictTypeOption } from '@/service/api';
defineOptions({ name: 'DictSelect' });
const dictType = defineModel<string>('value', { required: true });
interface Props {
[key: string]: any;
}
defineProps<Props>();
const value = defineModel<string>('value', { required: true });
const attrs: SelectProps = useAttrs();
const { getDictOptions } = useDict();
const options = ref<Array<CommonType.Option>>([]);
const options = ref<SelectOption[]>([]);
const { loading, startLoading, endLoading } = useLoading();
async function getDeptOptions() {
if (!dictType.value) {
return;
}
startLoading();
const dictData = await getDictOptions(dictType.value);
options.value = dictData[dictType.value];
const { error, data } = await fetchGetDictTypeOption();
if (error) return;
options.value = data.map(dict => ({
value: dict.dictType!,
label: () => (
<div class="w-520px flex justify-between">
<span>{dict.dictType}</span>
<span>{dict.dictName}</span>
</div>
)
}));
endLoading();
}
watch(
() => dictType.value,
() => {
getDeptOptions();
},
{ immediate: true }
);
getDeptOptions();
</script>
<template>
<NSelect :loading="loading" :options="options" :clear-filter-after-select="false" v-bind="attrs" />
<NSelect
v-model:value="value"
:loading="loading"
:options="options"
:clear-filter-after-select="false"
v-bind="attrs"
/>
</template>
<style scoped></style>

View File

@ -0,0 +1,63 @@
<script setup lang="tsx">
import { ref, useAttrs } from 'vue';
import { useLoading } from '@sa/hooks';
import type { TreeOption, TreeSelectProps } from 'naive-ui';
import { fetchGetMenuList } from '@/service/api';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { handleMenuTree } from '@/utils/ruoyi';
defineOptions({ name: 'MenuTreeSelect' });
interface Props {
[key: string]: any;
}
defineProps<Props>();
const value = defineModel<CommonType.IdType | null>('value', { required: true });
const attrs: TreeSelectProps = useAttrs();
const options = ref<Api.System.MenuList>([]);
const { loading, startLoading, endLoading } = useLoading();
async function getMenuList() {
startLoading();
const { error, data } = await fetchGetMenuList();
if (error) return;
options.value = [
{
menuId: 0,
menuName: '根目录',
icon: 'material-symbols:home-outline-rounded',
children: handleMenuTree(data, 'menuId')
}
] as Api.System.Menu[];
endLoading();
}
getMenuList();
function renderPrefix({ option }: { option: TreeOption }) {
const renderLocalIcon = String(option.icon).startsWith('icon-');
const icon = renderLocalIcon ? undefined : String(option.icon);
const localIcon = renderLocalIcon ? String(option.icon).replace('icon-', 'menu-') : undefined;
return <SvgIcon icon={icon} localIcon={localIcon} />;
}
</script>
<template>
<NTreeSelect
v-model:value="value"
filterable
class="h-full"
:loading="loading"
key-field="menuId"
label-field="menuName"
:options="options"
:default-expanded-keys="[0]"
:render-prefix="renderPrefix"
v-bind="attrs"
/>
</template>
<style scoped></style>

View File

@ -1,5 +1,6 @@
import { transformRecordToOption } from '@/utils/common';
/** enable status */
export const enableStatusRecord: Record<Api.Common.EnableStatus, string> = {
'0': '启用',
'1': '禁用'
@ -7,6 +8,7 @@ export const enableStatusRecord: Record<Api.Common.EnableStatus, string> = {
export const enableStatusOptions = transformRecordToOption(enableStatusRecord);
/** menu type */
export const menuTypeRecord: Record<Api.System.MenuType, string> = {
M: '目录',
C: '菜单',
@ -22,3 +24,61 @@ export const menuIconTypeRecord: Record<Api.System.IconType, string> = {
};
export const menuIconTypeOptions = transformRecordToOption(menuIconTypeRecord);
/** gen java type */
export const genJavaTypeRecord: Record<Api.Tool.JavaType, string> = {
Long: 'Long',
String: 'String',
Integer: 'Integer',
Double: 'Double',
BigDecimal: 'BigDecimal',
Date: 'Date',
Boolean: 'Boolean'
};
export const genJavaTypeOptions = transformRecordToOption(genJavaTypeRecord);
/** gen query type */
export const genQueryTypeRecord: Record<Api.Tool.QueryType, string> = {
EQ: '=',
NE: '!=',
GT: '>',
GE: '>=',
LT: '<',
LE: '<=',
LIKE: 'LIKE',
BETWEEN: 'BETWEEN'
};
export const genQueryTypeOptions = transformRecordToOption(genQueryTypeRecord);
/** gen html type */
export const genHtmlTypeRecord: Record<Api.Tool.HtmlType, string> = {
input: '文本框',
textarea: '文本域',
select: '下拉框',
radio: '单选框',
checkbox: '复选框',
datetime: '日期控件',
imageUpload: '图片上传',
fileUpload: '文件上传',
editor: '富文本控件'
};
export const genHtmlTypeOptions = transformRecordToOption(genHtmlTypeRecord);
/** gen type */
export const genTypeRecord: Record<Api.Tool.GenType, string> = {
'0': 'ZIP 压缩包',
'1': '自定义路径'
};
export const genTypeOptions = transformRecordToOption(genTypeRecord);
/** gen type */
export const genTplCategoryRecord: Record<Api.Tool.TplCategory, string> = {
crud: '单表(增删改查)',
tree: '树表(增删改查)'
};
export const genTplCategoryOptions = transformRecordToOption(genTplCategoryRecord);

View File

@ -4,8 +4,8 @@ import { useDictStore } from '@/store/modules/dict';
export function useDict() {
const dictStore = useDictStore();
async function getDictData(...args: Array<string>) {
const dictData: { [key: string]: Array<Api.System.DictData> } = {};
async function getDictData(...args: string[]) {
const dictData: { [key: string]: Api.System.DictData[] } = {};
const promises = args.map(async dictType => {
dictData[dictType] = [];
const dicts = dictStore.getDict(dictType);
@ -22,7 +22,7 @@ export function useDict() {
return dictData;
}
async function getDictRecord(...args: Array<string>) {
async function getDictRecord(...args: string[]) {
const dictRecord: { [key: string]: { [key: string]: string } } = {};
const dictData = await getDictData(...args);
Object.keys(dictData).forEach(dictType => {
@ -36,8 +36,8 @@ export function useDict() {
return dictRecord;
}
async function getDictOptions(...args: Array<string>) {
const dictOptions: { [key: string]: Array<CommonType.Option> } = {};
async function getDictOptions(...args: string[]) {
const dictOptions: { [key: string]: CommonType.Option[] } = {};
const dictData = await getDictData(...args);
Object.keys(dictData).forEach(dictType => {
dictOptions[dictType] = dictData[dictType].map(dict => ({ label: dict.dictLabel!, value: dict.dictValue! }));
@ -50,7 +50,7 @@ export function useDict() {
return transformDictByOptions(code, dictData[type]);
}
function transformDictByOptions(code: string, options: Array<Api.System.DictData>) {
function transformDictByOptions(code: string, options: Api.System.DictData[]) {
return options.find(item => item.dictValue === code)?.dictLabel;
}

View File

@ -228,7 +228,7 @@ export function useTableOperate<T extends TableData = TableData>(data: Ref<T[]>,
/** the editing row data */
const editingData: Ref<T | null> = ref(null);
function handleEdit(field: keyof T, id: string) {
function handleEdit(field: keyof T, id: CommonType.IdType) {
operateType.value = 'edit';
const findItem = data.value.find(item => item[field] === id) || null;
editingData.value = jsonClone(findItem);
@ -237,7 +237,7 @@ export function useTableOperate<T extends TableData = TableData>(data: Ref<T[]>,
}
/** the checked row keys of table */
const checkedRowKeys = ref<string[]>([]);
const checkedRowKeys = ref<CommonType.IdType[]>([]);
/** the hook after the batch delete operation is completed */
async function onBatchDeleted() {

View File

@ -137,7 +137,7 @@ export function useTreeTableOperate<T extends TableData = TableData>(_: Ref<T[]>
}
/** the checked row keys of table */
const checkedRowKeys = ref<string[]>([]);
const checkedRowKeys = ref<CommonType.IdType[]>([]);
function clearCheckedRowKeys() {
checkedRowKeys.value = [];

View File

@ -2,8 +2,16 @@ import { request } from '@/service/request';
/** 根据字典类型查询字典数据信息 */
export function fetchGetDictDataByType(dictType: string) {
return request<Array<Api.System.DictData>>({
return request<Api.System.DictData[]>({
url: `/system/dict/data/type/${dictType}`,
method: 'get'
});
}
/** 获取字典选择框列表 */
export function fetchGetDictTypeOption() {
return request<Api.System.DictType[]>({
url: '/system/dict/type/optionselect',
method: 'get'
});
}

View File

@ -15,16 +15,16 @@ export function fetchGetGenTableList(params?: Api.Tool.GenTableSearchParams) {
* @param tables
* @param dataName
*/
export function fetchImportGenTable(tables: Array<string>, dataName: string) {
export function fetchImportGenTable(tables: string[], dataName: string) {
return request<boolean>({
url: '/tool/gen/importTable',
method: 'post',
data: { tables, dataName }
params: { tables: tables.join(','), dataName }
});
}
/** 修改代码生成 */
export function fetchUpdateGenTable(data: Api.System.MenuOperateParams) {
export function fetchUpdateGenTable(data: Api.Tool.GenTable) {
return request<boolean>({
url: '/tool/gen',
method: 'put',
@ -32,11 +32,36 @@ export function fetchUpdateGenTable(data: Api.System.MenuOperateParams) {
});
}
/** 获取代码生成信息 */
export function fetchGetGenTableInfo(tableId: CommonType.IdType) {
return request<Api.Tool.GenTableInfo>({
url: `/tool/gen/${tableId}`,
method: 'get'
});
}
/** 批量删除代码生成 */
export function fetchBatchDeleteGenTable(tableIds: Array<CommonType.IdType>) {
export function fetchBatchDeleteGenTable(tableIds: CommonType.IdType[]) {
const ids = tableIds.join(',');
return request<boolean>({
url: `/system/menu/${ids}`,
url: `/tool/gen/${ids}`,
method: 'delete'
});
}
/** 查询数据源名称列表 */
export function fetchGetGenDataNames() {
return request<string[]>({
url: '/tool/gen/getDataNames',
method: 'get'
});
}
/** 查询数据库列表 */
export function fetchGetGenDbList(params?: Api.Tool.GenTableDbSearchParams) {
return request<Api.Tool.GenTableDbList>({
url: '/tool/gen/db/list',
method: 'get',
params
});
}

View File

@ -2,13 +2,13 @@ import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useDictStore = defineStore('dict', () => {
const dictData = ref<{ [key: string]: Array<Api.System.DictData> }>({});
const dictData = ref<{ [key: string]: Api.System.DictData[] }>({});
const getDict = (key: string) => {
return dictData.value[key];
};
const setDict = (key: string, dict: Array<Api.System.DictData>) => {
const setDict = (key: string, dict: Api.System.DictData[]) => {
dictData.value[key] = dict;
};

View File

@ -188,7 +188,7 @@ declare namespace Api {
}>;
/** menu list */
type MenuList = Array<Menu>;
type MenuList = Menu[];
/** menu search params */
type MenuSearchParams = CommonType.RecordNullable<Pick<Menu, 'menuName' | 'status' | 'menuType' | 'parentId'>>;
@ -213,8 +213,20 @@ declare namespace Api {
| 'remark'
>;
/** 字典类型 */
type DictType = Common.CommonRecord<{
/** 字典主键 */
dictId?: number;
/** 字典名称 */
dictName?: string;
/** 字典类型 */
dictType?: string;
/** 备注 */
remark?: string;
}>;
/** 字典数据 */
export type DictData = Common.CommonRecord<{
type DictData = Common.CommonRecord<{
/** 样式属性(其他样式扩展) */
cssClass?: string;
/** 字典编码 */

View File

@ -10,8 +10,37 @@ declare namespace Api {
* backend api module: "tool"
*/
namespace Tool {
/** 生成模板 */
type TplCategory = 'crud' | 'tree';
/** Java类型 */
type JavaType = 'Long' | 'String' | 'Integer' | 'Double' | 'BigDecimal' | 'Date' | 'Boolean';
/** 查询方式 */
type QueryType = 'EQ' | 'NE' | 'GT' | 'GE' | 'LT' | 'LE' | 'LIKE' | 'BETWEEN';
/** 显示类型 */
type HtmlType =
| 'input'
| 'textarea'
| 'select'
| 'radio'
| 'checkbox'
| 'datetime'
| 'imageUpload'
| 'fileUpload'
| 'editor';
/**
*
*
* - 0: zip压缩包
* - 1: 自定义路径
*/
type GenType = '0' | '1';
/** 代码生成业务表 */
export type GenTable = {
export type GenTable = Common.CommonRecord<{
/** 生成业务名 */
businessName: string;
/** 实体类名称(首字母大写) */
@ -29,7 +58,7 @@ declare namespace Api {
/** 生成路径(不填默认项目路径) */
genPath?: string;
/** 生成代码方式0zip压缩包 1自定义路径 */
genType?: string;
genType?: GenType;
/** 菜单 id 列表 */
menuIds?: CommonType.IdType[];
/** 生成模块名 */
@ -39,7 +68,7 @@ declare namespace Api {
/** 生成包路径 */
packageName: string;
/** 上级菜单ID字段 */
parentMenuId?: string;
parentMenuId?: CommonType.IdType;
/** 上级菜单名称字段 */
parentMenuName?: string;
/** 主键信息 */
@ -53,11 +82,11 @@ declare namespace Api {
/** 表描述 */
tableComment: string;
/** 编号 */
tableId?: number;
tableId?: CommonType.IdType;
/** 表名称 */
tableName: string;
/** 使用的模板crud单表操作 tree树表操作 sub主子表操作 */
tplCategory?: string;
tplCategory?: TplCategory;
/** 是否tree树表操作 */
tree?: boolean;
/** 树编码字段 */
@ -66,14 +95,15 @@ declare namespace Api {
treeName?: string;
/** 树父编码字段 */
treeParentCode?: string;
};
params: { [key: string]: any };
}>;
/** 代码生成业务字段 */
export type GenTableColumn = {
export type GenTableColumn = Common.CommonRecord<{
/** 列描述 */
columnComment?: string;
/** 编号 */
columnId?: number;
columnId?: CommonType.IdType;
/** 列名称 */
columnName?: string;
/** 列类型 */
@ -83,7 +113,7 @@ declare namespace Api {
/** 是否编辑字段1是 */
edit?: boolean;
/** 显示类型input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、image图片上传控件、upload文件上传控件、editor富文本控件 */
htmlType?: string;
htmlType?: HtmlType;
/** 是否自增1是 */
increment?: boolean;
/** 是否为插入字段1是 */
@ -105,7 +135,7 @@ declare namespace Api {
/** JAVA字段名 */
javaField: string;
/** JAVA类型 */
javaType?: string;
javaType?: JavaType;
/** 是否列表字段1是 */
list?: boolean;
/** 是否主键1是 */
@ -113,7 +143,7 @@ declare namespace Api {
/** 是否查询字段1是 */
query?: boolean;
/** 查询方式EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围 */
queryType?: string;
queryType?: QueryType;
/** 是否必填1是 */
required?: boolean;
/** 排序 */
@ -121,25 +151,43 @@ declare namespace Api {
/** 是否基类字段 */
superColumn?: boolean;
/** 归属表编号 */
tableId?: number;
tableId?: CommonType.IdType;
/** 可用字段 */
usableColumn?: boolean;
};
}>;
/** gen table search params */
type GenTableSearchParams = CommonType.RecordNullable<
Pick<GenTable, 'dataName' | 'tableName' | 'tableComment'> &
CommonType.RecordNullable<
Common.CommonSearchParams & {
params: {
beginTime: string;
endTime: string;
};
}
>
Common.CommonSearchParams & {
params: {
beginTime?: string;
endTime?: string;
};
}
>;
/** gen table list */
type GenTableList = Common.PaginatingQueryRecord<GenTable>;
/** gen table search params */
type GenTableDbSearchParams = CommonType.RecordNullable<
Pick<GenTable, 'dataName' | 'tableName' | 'tableComment'> & Common.CommonSearchParams
>;
/** gen table db list */
type GenTableDbList = Common.PaginatingQueryRecord<
Common.CommonRecord<Pick<GenTable, 'tableName' | 'tableComment'>>
>;
/** gen table info */
type GenTableInfo = {
/** 字段信息 */
rows: GenTableColumn[];
/** 生成信息 */
tables: GenTable[];
/** 基本信息 */
info: GenTable;
};
}
}

View File

@ -23,12 +23,15 @@ declare module 'vue' {
IconGridiconsFullscreenExit: typeof import('~icons/gridicons/fullscreen-exit')['default']
'IconIc:roundPlus': typeof import('~icons/ic/round-plus')['default']
IconIcRoundDelete: typeof import('~icons/ic/round-delete')['default']
IconIcRoundDownload: typeof import('~icons/ic/round-download')['default']
IconIcRoundEdit: typeof import('~icons/ic/round-edit')['default']
IconIcRoundPlus: typeof import('~icons/ic/round-plus')['default']
IconIcRoundRefresh: typeof import('~icons/ic/round-refresh')['default']
IconIcRoundRemove: typeof import('~icons/ic/round-remove')['default']
IconIcRoundRoundDownload: typeof import('~icons/ic/round-round-download')['default']
IconIcRoundSave: typeof import('~icons/ic/round-save')['default']
IconIcRoundSearch: typeof import('~icons/ic/round-search')['default']
IconIcRoundUpload: typeof import('~icons/ic/round-upload')['default']
IconLocalBanner: typeof import('~icons/local/banner')['default']
IconLocalLogo: typeof import('~icons/local/logo')['default']
IconMdiArrowDownThin: typeof import('~icons/mdi/arrow-down-thin')['default']
@ -41,6 +44,7 @@ declare module 'vue' {
LangSwitch: typeof import('./../components/common/lang-switch.vue')['default']
LookForward: typeof import('./../components/custom/look-forward.vue')['default']
MenuToggler: typeof import('./../components/common/menu-toggler.vue')['default']
MenuTreeSelect: typeof import('./../components/custom/menu-tree-select.vue')['default']
NAlert: typeof import('naive-ui')['NAlert']
NBreadcrumb: typeof import('naive-ui')['NBreadcrumb']
NBreadcrumbItem: typeof import('naive-ui')['NBreadcrumbItem']
@ -51,6 +55,7 @@ declare module 'vue' {
NCollapseItem: typeof import('naive-ui')['NCollapseItem']
NColorPicker: typeof import('naive-ui')['NColorPicker']
NDataTable: typeof import('naive-ui')['NDataTable']
NDatePicker: typeof import('naive-ui')['NDatePicker']
NDescriptions: typeof import('naive-ui')['NDescriptions']
NDescriptionsItem: typeof import('naive-ui')['NDescriptionsItem']
NDialogProvider: typeof import('naive-ui')['NDialogProvider']
@ -92,6 +97,7 @@ declare module 'vue' {
NStatistic: typeof import('naive-ui')['NStatistic']
NSwitch: typeof import('naive-ui')['NSwitch']
NTab: typeof import('naive-ui')['NTab']
NTabPane: typeof import('naive-ui')['NTabPane']
NTabs: typeof import('naive-ui')['NTabs']
NTag: typeof import('naive-ui')['NTag']
NThing: typeof import('naive-ui')['NThing']
@ -107,6 +113,7 @@ declare module 'vue' {
StatusTag: typeof import('./../components/custom/status-tag.vue')['default']
SvgIcon: typeof import('./../components/custom/svg-icon.vue')['default']
SystemLogo: typeof import('./../components/common/system-logo.vue')['default']
TableColumnCheckAlert: typeof import('./../components/advanced/table-column-check-alert.vue')['default']
TableColumnSetting: typeof import('./../components/advanced/table-column-setting.vue')['default']
TableHeaderOperation: typeof import('./../components/advanced/table-header-operation.vue')['default']
TableSiderLayout: typeof import('./../components/advanced/table-sider-layout.vue')['default']

View File

@ -35,16 +35,15 @@ const btnData = ref<Api.System.MenuList>([]);
const getMeunTree = async () => {
startLoading();
const { data, error } = await fetchGetMenuList();
if (!error) {
treeData.value = [
{
menuId: 0,
menuName: '根目录',
icon: 'material-symbols:home-outline-rounded',
children: handleMenuTree(data, 'menuId')
}
] as Api.System.Menu[];
}
if (error) return;
treeData.value = [
{
menuId: 0,
menuName: '根目录',
icon: 'material-symbols:home-outline-rounded',
children: handleMenuTree(data, 'menuId')
}
] as Api.System.Menu[];
endLoading();
};

View File

@ -252,8 +252,8 @@ const FormTipComponent = defineComponent({
}
});
const enableStatusOptions = ref<Array<CommonType.Option>>([]);
const showHideOptions = ref<Array<CommonType.Option>>([]);
const enableStatusOptions = ref<CommonType.Option[]>([]);
const showHideOptions = ref<CommonType.Option[]>([]);
async function initDictData() {
const { getDictOptions } = useDict();

View File

@ -1,7 +1,244 @@
<script setup lang="ts"></script>
<script setup lang="tsx">
import { NButton, NPopconfirm, NTooltip } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { ref } from 'vue';
import { fetchBatchDeleteGenTable, fetchGetGenDataNames, fetchGetGenTableList } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import ButtonIcon from '@/components/custom/button-icon.vue';
import SvgIcon from '@/components/custom/svg-icon.vue';
import GenTableSearch from './modules/gen-table-search.vue';
import TableImportDrawer from './modules/table-import-drawer.vue';
import GenTableOperateDrawer from './modules/gen-table-operate-drawer.vue';
const appStore = useAppStore();
const { bool: importVisible, setTrue: openImportVisible } = useBoolean();
const {
columns,
columnChecks,
data,
getData,
getDataByPage,
loading,
mobilePagination,
searchParams,
resetSearchParams
} = useTable({
apiFn: fetchGetGenTableList,
showTotal: true,
apiParams: {
pageNum: 1,
pageSize: 10,
// if you want to use the searchParams in Form, you need to define the following properties, and the value is null
// the value can not be undefined, otherwise the property in Form will not be reactive
dataName: null,
tableName: null,
tableComment: null,
params: {}
},
columns: () => [
{
type: 'selection',
align: 'center',
width: 48
},
{
key: 'index',
title: $t('common.index'),
align: 'center',
width: 64
},
{
key: 'dataName',
title: '数据源',
align: 'center',
minWidth: 120
},
{
key: 'tableName',
title: '表名称',
align: 'center',
minWidth: 120
},
{
key: 'tableComment',
title: '表描述',
align: 'center',
minWidth: 120
},
{
key: 'className',
title: '实体',
align: 'center',
minWidth: 120
},
{
key: 'createTime',
title: '创建时间',
align: 'center',
minWidth: 150
},
{
key: 'updateTime',
title: '更新时间',
align: 'center',
minWidth: 150
},
{
key: 'operate',
title: $t('common.operate'),
align: 'center',
width: 180,
render: row => (
<div class="flex-center gap-16px">
<ButtonIcon type="primary" text icon="ep:view" tooltipContent="预览" onClick={() => edit(row.tableId!)} />
<ButtonIcon
type="primary"
text
icon="ep:edit"
tooltipContent={$t('common.edit')}
onClick={() => edit(row.tableId!)}
/>
<ButtonIcon type="primary" text icon="ep:refresh" tooltipContent="同步" onClick={() => edit(row.tableId!)} />
<ButtonIcon
type="primary"
text
icon="ep:download"
tooltipContent="生成代码"
onClick={() => edit(row.tableId!)}
/>
<NTooltip placement="bottom">
{{
trigger: () => (
<NPopconfirm onPositiveClick={() => handleDelete(row.tableId!)}>
{{
default: () => $t('common.confirmDelete'),
trigger: () => (
<NButton class="h-36px text-icon" type="error" text>
{{
default: () => (
<div class="flex-center gap-8px">
<SvgIcon icon="ep:delete" />
</div>
)
}}
</NButton>
)
}}
</NPopconfirm>
),
default: () => <>{$t('common.delete')}</>
}}
</NTooltip>
</div>
)
}
]
});
const {
drawerVisible,
editingData,
handleEdit,
checkedRowKeys,
onBatchDeleted,
onDeleted
// closeDrawer
} = useTableOperate(data, getData);
async function handleBatchDelete() {
// request
const { error } = await fetchBatchDeleteGenTable(checkedRowKeys.value);
if (error) return;
window.$message?.success('删除成功');
onBatchDeleted();
}
async function handleDelete(id: CommonType.IdType) {
// request
const { error } = await fetchBatchDeleteGenTable([id]);
if (error) return;
window.$message?.success('删除成功');
onDeleted();
}
function edit(id: CommonType.IdType) {
handleEdit('tableId', id);
}
function handleImport() {
openImportVisible();
}
function handleGenCode() {}
const dataNameOptions = ref<CommonType.Option[]>([]);
async function getDataNames() {
const { error, data: dataNames } = await fetchGetGenDataNames();
if (error) return;
dataNameOptions.value = dataNames.map(item => ({ label: item, value: item }));
}
getDataNames();
</script>
<template>
<div></div>
<div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
<GenTableSearch
v-model:model="searchParams"
:options="dataNameOptions"
@reset="resetSearchParams"
@search="getDataByPage"
/>
<TableColumnCheckAlert v-model:columns="checkedRowKeys" />
<NCard title="代码生成" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
<template #header-extra>
<TableHeaderOperation
v-model:columns="columnChecks"
:disabled-delete="checkedRowKeys.length === 0"
:loading="loading"
:show-add="false"
@delete="handleBatchDelete"
@refresh="getData"
>
<template #prefix>
<NButton :disabled="checkedRowKeys.length === 0" size="small" ghost type="primary" @click="handleGenCode">
<template #icon>
<icon-ic-round-download class="text-icon" />
</template>
生成代码
</NButton>
<NButton size="small" ghost type="primary" @click="handleImport">
<template #icon>
<icon-ic-round-upload class="text-icon" />
</template>
导入
</NButton>
</template>
</TableHeaderOperation>
</template>
<NDataTable
v-model:checked-row-keys="checkedRowKeys"
:columns="columns"
:data="data"
size="small"
:flex-height="!appStore.isMobile"
:scroll-x="962"
:loading="loading"
remote
:row-key="row => row.tableId"
:pagination="mobilePagination"
class="sm:h-full"
/>
<TableImportDrawer v-model:visible="importVisible" :options="dataNameOptions" @submitted="getDataByPage" />
<GenTableOperateDrawer v-model:visible="drawerVisible" :row-data="editingData" @submitted="getDataByPage" />
</NCard>
</div>
</template>
<style scoped></style>

View File

@ -0,0 +1,69 @@
<script setup lang="ts">
import { $t } from '@/locales';
import { useNaiveForm } from '@/hooks/common/form';
defineOptions({
name: 'GenTableDbSearch'
});
interface Props {
options: CommonType.Option[];
}
defineProps<Props>();
interface Emits {
(e: 'reset'): void;
(e: 'search'): void;
}
const emit = defineEmits<Emits>();
const { formRef, validate, restoreValidation } = useNaiveForm();
const model = defineModel<Api.Tool.GenTableDbSearchParams>('model', { required: true });
async function reset() {
await restoreValidation();
emit('reset');
}
async function search() {
await validate();
emit('search');
}
</script>
<template>
<NForm ref="formRef" :model="model" label-placement="left" :label-width="80">
<NGrid responsive="screen" item-responsive>
<NFormItemGi span="24 s:12" label="数据源" path="dataName" class="pr-24px">
<NSelect v-model:value="model.dataName" :options="options" placeholder="请选择数据源" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="表名称" path="tableName" class="pr-24px">
<NInput v-model:value="model.tableName" placeholder="请输入表名称" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="表描述" path="tableComment" class="pr-24px">
<NInput v-model:value="model.tableComment" placeholder="请输入表描述" />
</NFormItemGi>
<NFormItemGi :show-feedback="false" span="24 s:12" class="pb-6px pr-24px">
<NSpace class="w-full" justify="end">
<NButton @click="reset">
<template #icon>
<icon-ic-round-refresh class="text-icon" />
</template>
{{ $t('common.reset') }}
</NButton>
<NButton type="primary" ghost @click="search">
<template #icon>
<icon-ic-round-search class="text-icon" />
</template>
{{ $t('common.search') }}
</NButton>
</NSpace>
</NFormItemGi>
</NGrid>
</NForm>
</template>
<style scoped></style>

View File

@ -0,0 +1,401 @@
<script setup lang="tsx">
import { ref, watch } from 'vue';
import type { FormInst, SelectOption } from 'naive-ui';
import { NCheckbox, NInput, NSelect, NTabs } from 'naive-ui';
import { useLoading } from '@sa/hooks';
import { jsonClone } from '@sa/utils';
import { fetchGetDictTypeOption, fetchGetGenTableInfo, fetchUpdateGenTable } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import {
genHtmlTypeOptions,
genJavaTypeOptions,
genQueryTypeOptions,
genTplCategoryOptions,
genTypeOptions
} from '@/constants/business';
import { useFormRules } from '@/hooks/common/form';
defineOptions({
name: 'GenTableOperateDrawer'
});
interface Props {
/** the edit row data */
rowData?: Api.Tool.GenTable | null;
}
const props = defineProps<Props>();
const visible = defineModel<boolean>('visible', {
default: false
});
interface Emits {
(e: 'submitted'): void;
}
const emit = defineEmits<Emits>();
const appStore = useAppStore();
const { defaultRequiredRule } = useFormRules();
const { loading, startLoading, endLoading } = useLoading();
const genTableInfo = ref<Api.Tool.GenTableInfo>();
const tab = ref<'basic' | 'dragTable' | 'genInfo'>('dragTable');
const basicFormRef = ref<FormInst | null>(null);
type BasicRuleKey = Extract<keyof Api.Tool.GenTable, 'tableName' | 'tableComment' | 'className' | 'functionAuthor'>;
const basicRules: Record<BasicRuleKey, App.Global.FormRule> = {
tableName: defaultRequiredRule,
tableComment: defaultRequiredRule,
className: defaultRequiredRule,
functionAuthor: defaultRequiredRule
};
const infoFormRef = ref<FormInst | null>(null);
type InfoRuleKey = Extract<
keyof Api.Tool.GenTable,
| 'tplCategory'
| 'packageName'
| 'moduleName'
| 'businessName'
| 'functionName'
| 'parentMenuId'
| 'genType'
| 'genPath'
>;
const infoRules: Record<InfoRuleKey, App.Global.FormRule> = {
tplCategory: defaultRequiredRule,
packageName: defaultRequiredRule,
moduleName: defaultRequiredRule,
businessName: defaultRequiredRule,
functionName: defaultRequiredRule,
parentMenuId: defaultRequiredRule,
genType: defaultRequiredRule,
genPath: defaultRequiredRule
};
async function getGenTableInfo() {
if (!props.rowData?.tableId) return;
startLoading();
// request
const { error, data } = await fetchGetGenTableInfo(props.rowData.tableId);
if (error) return;
genTableInfo.value = data;
endLoading();
}
function closeDrawer() {
visible.value = false;
}
async function handleSubmit() {
try {
await basicFormRef.value?.validate();
} catch {
tab.value = 'basic';
window.$message?.error('表单校验未通过,请重新检查提交内容');
return;
}
try {
await infoFormRef.value?.validate();
} catch {
tab.value = 'genInfo';
window.$message?.error('表单校验未通过,请重新检查提交内容');
return;
}
const info = genTableInfo.value!.info;
const genTable: Api.Tool.GenTable = jsonClone(info);
genTable.params = {
treeCode: info?.treeCode,
treeName: info?.treeName,
treeParentCode: info?.treeParentCode,
parentMenuId: info?.parentMenuId
};
genTable.columns = genTableInfo.value?.rows;
// request
const { error } = await fetchUpdateGenTable(genTable);
if (error) return;
window.$message?.success('修改成功');
closeDrawer();
emit('submitted');
}
watch(visible, () => {
if (visible.value) {
tab.value = 'dragTable';
getDeptOptions();
getGenTableInfo();
}
});
const dictOptions = ref<SelectOption[]>([]);
const { loading: dictLoading, startLoading: startDictLoading, endLoading: endDictLoading } = useLoading();
async function getDeptOptions() {
startDictLoading();
const { error, data } = await fetchGetDictTypeOption();
if (error) return;
dictOptions.value = data.map(dict => ({
value: dict.dictType!,
class: 'gen-dict-select',
label: dict.dictName
}));
endDictLoading();
}
const columns: NaiveUI.TableColumn<Api.Tool.GenTableColumn>[] = [
{
key: 'sort',
title: $t('common.index'),
align: 'left',
width: 64
},
{
key: 'columnName',
title: '字段列名',
align: 'left',
minWidth: 120
},
{
key: 'columnComment',
title: '字段描述',
align: 'left',
minWidth: 120,
render: row => <NInput v-model:value={row.columnComment} placeholder="请输入字段描述" />
},
{
key: 'columnType',
title: '物理类型',
align: 'left',
width: 120
},
{
key: 'javaType',
title: 'Java 类型',
align: 'left',
width: 136,
render: row => <NSelect v-model:value={row.javaType} placeholder="请选择 Java 类型" options={genJavaTypeOptions} />
},
{
key: 'javaField',
title: 'Java 属性',
align: 'left',
minWidth: 120,
render: row => <NInput v-model:value={row.javaField} placeholder="请输入 Java 属性" />
},
{
key: 'isInsert',
title: '插入',
align: 'center',
width: 64,
render: row => <NCheckbox checked-value="1" unchecked-value="0" v-model:checked={row.isInsert} />
},
{
key: 'isEdit',
title: '编辑',
align: 'center',
width: 64,
render: row => <NCheckbox checked-value="1" unchecked-value="0" v-model:checked={row.isEdit} />
},
{
key: 'isList',
title: '列表',
align: 'center',
width: 64,
render: row => <NCheckbox checked-value="1" unchecked-value="0" v-model:checked={row.isList} />
},
{
key: 'isQuery',
title: '查询',
align: 'center',
width: 64,
render: row => <NCheckbox checked-value="1" unchecked-value="0" v-model:checked={row.isQuery} />
},
{
key: 'queryType',
title: '查询方式',
align: 'left',
width: 130,
render: row => <NSelect v-model:value={row.queryType} placeholder="请选择查询方式" options={genQueryTypeOptions} />
},
{
key: 'isRequired',
title: '必填',
align: 'center',
width: 64,
render: row => <NCheckbox checked-value="1" unchecked-value="0" v-model:checked={row.isRequired} />
},
{
key: 'htmlType',
title: '显示类型',
align: 'left',
width: 130,
render: row => <NSelect v-model:value={row.htmlType} placeholder="请选择显示类型" options={genHtmlTypeOptions} />
},
{
key: 'dictType',
title: '字典类型',
align: 'left',
width: 150,
render: row => {
if (row.dictType === '') {
row.dictType = undefined;
}
const renderLabel = (option: CommonType.Option) => (
<div class="w-full flex justify-between gap-12px">
<span>{option.label}</span>
<span class="flex-1 text-end text-13px text-#8492a6">{option.value}</span>
</div>
);
const renderTag = ({ option }: { option: CommonType.Option }) => <>{option.label}</>;
return (
<NSelect
v-model:value={row.dictType}
loading={dictLoading.value}
options={dictOptions.value}
clear-filter-after-select={false}
consistent-menu-width={false}
render-label={renderLabel}
render-tag={renderTag}
/>
);
}
}
];
</script>
<template>
<NDrawer v-model:show="visible" display-directive="show" width="100%">
<NDrawerContent title="导入表" :native-scrollbar="false" closable>
<NSpin :show="loading" class="h-full" content-class="h-full">
<NTabs v-model:value="tab" type="segment" animated class="h-full" pane-class="h-full">
<NTabPane name="basic" tab="基本信息" display-directive="show">
<NForm
v-if="genTableInfo?.info"
ref="basicFormRef"
class="mx-auto max-w-800px"
:model="genTableInfo.info"
:rules="basicRules"
>
<NGrid :x-gap="16" responsive="screen" item-responsive>
<NFormItemGi span="24 s:12" label="表名称" path="tableName">
<NInput v-model:value="genTableInfo.info.tableName" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="表描述" path="tableComment">
<NInput v-model:value="genTableInfo.info.tableComment" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="实体类名称" path="className">
<NInput v-model:value="genTableInfo.info.className" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="作者" path="functionAuthor">
<NInput v-model:value="genTableInfo.info.functionAuthor" />
</NFormItemGi>
<NFormItemGi span="24" label="备注" path="remark">
<NInput v-model:value="genTableInfo.info.remark" type="textarea" />
</NFormItemGi>
</NGrid>
</NForm>
</NTabPane>
<NTabPane name="dragTable" tab="字段信息" display-directive="show">
<div class="h-full flex-col">
<NDataTable
:columns="columns"
:data="genTableInfo?.rows"
size="small"
:flex-height="!appStore.isMobile"
:scroll-x="750"
remote
class="flex-1"
/>
</div>
</NTabPane>
<NTabPane name="genInfo" tab="生成信息" display-directive="show">
<NForm
v-if="genTableInfo?.info"
ref="infoFormRef"
class="mx-auto max-w-800px"
:model="genTableInfo.info"
:rules="infoRules"
>
<NGrid :x-gap="16" responsive="screen" item-responsive>
<NFormItemGi span="24 s:12" label="生成模板" path="tplCategory">
<NSelect
v-model:value="genTableInfo.info.tplCategory"
:options="genTplCategoryOptions"
placeholder="请选择生成模板"
/>
</NFormItemGi>
<NFormItemGi span="24 s:12" label="生成包路径" path="packageName">
<NInput v-model:value="genTableInfo.info.packageName" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="生成模块名" path="moduleName">
<NInput v-model:value="genTableInfo.info.moduleName" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="生成业务名" path="businessName">
<NInput v-model:value="genTableInfo.info.businessName" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="生成功能名" path="functionName">
<NInput v-model:value="genTableInfo.info.functionName" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="上级菜单" path="parentMenuId">
<MenuTreeSelect v-model:value="genTableInfo.info.parentMenuId" />
</NFormItemGi>
<NFormItemGi span="24 s:12" label="生成代码方式" path="genType">
<NRadioGroup v-model:value="genTableInfo.info.genType">
<NSpace :span="16">
<NRadio
v-for="option in genTypeOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</NSpace>
</NRadioGroup>
</NFormItemGi>
<NFormItemGi v-if="genTableInfo.info.genType === '1'" span="24 s:12" label="自定义路径" path="genPath">
<NInput v-model:value="genTableInfo.info.genPath" />
</NFormItemGi>
</NGrid>
</NForm>
</NTabPane>
</NTabs>
</NSpin>
<template #footer>
<NSpace :size="16">
<NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
<NButton :disabled="loading" type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
</NSpace>
</template>
</NDrawerContent>
</NDrawer>
</template>
<style scoped lang="scss">
:deep(.n-drawer-body-content-wrapper) {
height: 100%;
}
:deep(.n-tabs-pane-wrapper) {
height: 100%;
}
</style>
<style>
.gen-dict-select {
width: 100%;
.n-base-select-option__content {
width: 100%;
}
}
</style>

View File

@ -0,0 +1,90 @@
<script setup lang="ts">
import { ref } from 'vue';
import { $t } from '@/locales';
import { useNaiveForm } from '@/hooks/common/form';
defineOptions({
name: 'GenTableSearch'
});
interface Props {
options: CommonType.Option[];
}
defineProps<Props>();
interface Emits {
(e: 'reset'): void;
(e: 'search'): void;
}
const emit = defineEmits<Emits>();
const { formRef, validate, restoreValidation } = useNaiveForm();
const model = defineModel<Api.Tool.GenTableSearchParams>('model', { required: true });
const dateRange = ref<[string, string]>();
async function reset() {
await restoreValidation();
emit('reset');
}
async function search() {
await validate();
if (dateRange.value?.length) {
model.value.params!.beginTime = dateRange.value[0];
model.value.params!.endTime = dateRange.value[0];
}
emit('search');
}
</script>
<template>
<NCard :bordered="false" size="small" class="card-wrapper">
<NCollapse>
<NCollapseItem :title="$t('common.search')" name="user-search">
<NForm ref="formRef" :model="model" label-placement="left" :label-width="80">
<NGrid responsive="screen" item-responsive>
<NFormItemGi span="24 s:12 m:6" label="数据源" path="dataName" class="pr-24px">
<NSelect v-model:value="model.dataName" :options="options" placeholder="请选择数据源" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="表名称" path="tableName" class="pr-24px">
<NInput v-model:value="model.tableName" placeholder="请输入表名称" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="表描述" path="tableComment" class="pr-24px">
<NInput v-model:value="model.tableComment" placeholder="请输入表描述" />
</NFormItemGi>
<NFormItemGi span="24 s:12 m:6" label="创建时间" class="pr-24px">
<NDatePicker
v-model:formatted-value="dateRange"
value-format="yyyy-MM-dd HH:mm:ss"
type="daterange"
clearable
/>
</NFormItemGi>
<NFormItemGi :show-feedback="false" span="24" class="pb-6px pr-24px">
<NSpace class="w-full" justify="end">
<NButton @click="reset">
<template #icon>
<icon-ic-round-refresh class="text-icon" />
</template>
{{ $t('common.reset') }}
</NButton>
<NButton type="primary" ghost @click="search">
<template #icon>
<icon-ic-round-search class="text-icon" />
</template>
{{ $t('common.search') }}
</NButton>
</NSpace>
</NFormItemGi>
</NGrid>
</NForm>
</NCollapseItem>
</NCollapse>
</NCard>
</template>
<style scoped></style>

View File

@ -0,0 +1,134 @@
<script setup lang="tsx">
import { watch } from 'vue';
import { fetchGetGenDbList, fetchImportGenTable } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import GenTableDbSearch from './gen-table-db-search.vue';
defineOptions({
name: 'TableImportDrawer'
});
interface Props {
options: CommonType.Option[];
}
const props = defineProps<Props>();
const visible = defineModel<boolean>('visible', {
default: false
});
interface Emits {
(e: 'submitted'): void;
}
const emit = defineEmits<Emits>();
const appStore = useAppStore();
const { columns, data, getData, getDataByPage, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
apiFn: fetchGetGenDbList,
immediate: false,
showTotal: true,
apiParams: {
pageNum: 1,
pageSize: 15,
// if you want to use the searchParams in Form, you need to define the following properties, and the value is null
// the value can not be undefined, otherwise the property in Form will not be reactive
dataName: null,
tableName: null,
tableComment: null
},
columns: () => [
{
type: 'selection',
align: 'center',
width: 52
},
{
key: 'index',
title: $t('common.index'),
align: 'center',
width: 64
},
{
key: 'tableName',
title: '表名称',
align: 'center',
minWidth: 120
},
{
key: 'tableComment',
title: '表描述',
align: 'center',
minWidth: 120
}
]
});
const { checkedRowKeys } = useTableOperate(data, getData);
function closeDrawer() {
visible.value = false;
}
async function handleSubmit() {
// request
const { error } = await fetchImportGenTable(checkedRowKeys.value as string[], searchParams.dataName!);
if (error) return;
window.$message?.success('导入成功');
closeDrawer();
emit('submitted');
}
watch(visible, () => {
if (visible.value) {
searchParams.dataName = props.options.length ? props.options[0].value : null;
getData();
}
});
</script>
<template>
<NDrawer v-model:show="visible" display-directive="show" :width="800" class="max-w-90%">
<NDrawerContent title="导入表" :native-scrollbar="false" closable>
<div class="h-full flex-col">
<GenTableDbSearch
v-model:model="searchParams"
:options="options"
@reset="resetSearchParams"
@search="getDataByPage"
/>
<TableColumnCheckAlert v-model:columns="checkedRowKeys" class="mb-16px" />
<NDataTable
v-model:checked-row-keys="checkedRowKeys"
:columns="columns"
:data="data"
size="small"
:flex-height="!appStore.isMobile"
:scroll-x="750"
:loading="loading"
remote
:row-key="row => row.tableName"
:pagination="mobilePagination"
class="flex-1"
/>
</div>
<template #footer>
<NSpace :size="16">
<NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
<NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
</NSpace>
</template>
</NDrawerContent>
</NDrawer>
</template>
<style scoped>
:deep(.n-drawer-body-content-wrapper) {
height: 100%;
}
</style>