7 Commits

Author SHA1 Message Date
9c510636c5 feat: 完善菜单管理
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-25 17:51:46 +08:00
10f78b7cff feat: 添加信息提示hooks 2025-09-25 17:51:05 +08:00
88097e386b feat: qianpw to wuxichen
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-24 15:58:11 +08:00
82d043a414 feat: 富文本编辑器
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-24 15:47:28 +08:00
34cd919441 feat: 添加字典详情
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-24 15:28:36 +08:00
12495b6d85 feat: tagEditor
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-24 11:09:02 +08:00
9363dc0d6e feat: 系统管理
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-23 16:00:15 +08:00
47 changed files with 5465 additions and 132 deletions

View File

@@ -4,8 +4,8 @@ NODE_ENV=development
VITE_DEV=true
# 请求路径
# VITE_BASE_URL='http://114.132.60.20:48080'
VITE_BASE_URL='http://192.168.1.114:48080' # 理君
VITE_BASE_URL='http://114.132.60.20:48080'
# VITE_BASE_URL='http://192.168.1.114:48080' # 理君
# 文件上传类型server - 后端上传, client - 前端直连上传,仅支持 S3 服务

View File

@@ -15,6 +15,7 @@
"jest": "jest",
"lint": "npm run biome:lint && npm run tsc",
"lint-staged": "lint-staged",
"lint:fix": "eslint --fix --quiet",
"biome:lint": "npx @biomejs/biome lint",
"openapi": "max openapi",
"prepare": "husky",
@@ -38,6 +39,7 @@
"@ant-design/icons": "^5.6.1",
"@ant-design/pro-components": "^2.8.9",
"@ant-design/v5-patch-for-react-19": "^1.0.3",
"@tinymce/tinymce-react": "^6.3.0",
"antd": "^5.26.4",
"antd-style": "^3.7.0",
"classnames": "^2.5.1",
@@ -45,6 +47,7 @@
"jsencrypt": "^3.5.4",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"tinymce": "^8.1.2",
"web-storage-cache": "^1.1.1"
},
"devDependencies": {

29
pnpm-lock.yaml generated
View File

@@ -17,6 +17,9 @@ importers:
'@ant-design/v5-patch-for-react-19':
specifier: ^1.0.3
version: 1.0.3(antd@5.27.3(date-fns@2.30.0)(moment@2.30.1)(react-dom@19.1.1(react@19.1.1))(react@19.1.1))(react-dom@19.1.1(react@19.1.1))(react@19.1.1)
'@tinymce/tinymce-react':
specifier: ^6.3.0
version: 6.3.0(react-dom@19.1.1(react@19.1.1))(react@19.1.1)(tinymce@8.1.2)
antd:
specifier: ^5.26.4
version: 5.27.3(date-fns@2.30.0)(moment@2.30.1)(react-dom@19.1.1(react@19.1.1))(react@19.1.1)
@@ -38,6 +41,9 @@ importers:
react-dom:
specifier: ^19.1.0
version: 19.1.1(react@19.1.1)
tinymce:
specifier: ^8.1.2
version: 8.1.2
web-storage-cache:
specifier: ^1.1.1
version: 1.1.1
@@ -2551,6 +2557,16 @@ packages:
'@types/react-dom':
optional: true
'@tinymce/tinymce-react@6.3.0':
resolution: {integrity: sha512-E++xnn0XzDzpKr40jno2Kj7umfAE6XfINZULEBBeNjTMvbACWzA6CjiR6V8eTDc9yVmdVhIPqVzV4PqD5TZ/4g==}
peerDependencies:
react: ^19.0.0 || ^18.0.0 || ^17.0.1 || ^16.7.0
react-dom: ^19.0.0 || ^18.0.0 || ^17.0.1 || ^16.7.0
tinymce: ^8.0.0 || ^7.0.0 || ^6.0.0 || ^5.5.1
peerDependenciesMeta:
tinymce:
optional: true
'@tootallnate/once@1.1.2':
resolution: {integrity: sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==}
engines: {node: '>= 6'}
@@ -10246,6 +10262,9 @@ packages:
tinyexec@1.0.1:
resolution: {integrity: sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==}
tinymce@8.1.2:
resolution: {integrity: sha512-KITxHEEHRlxC5xOnxA123eAJ67NgsWxNphtItWt9TRu07DiTZrWIqJeIKRX9euE51/l3kJO4WQiqoBXKTJJGsA==}
titleize@3.0.0:
resolution: {integrity: sha512-KxVu8EYHDPBdUYdKZdKtU2aj2XfEx9AfjXxE/Aj0vT06w2icA09Vus1rh6eSu1y01akYg6BjIK/hxyLJINoMLQ==}
engines: {node: '>=12'}
@@ -14715,6 +14734,14 @@ snapshots:
'@types/react': 19.1.12
'@types/react-dom': 19.1.9(@types/react@19.1.12)
'@tinymce/tinymce-react@6.3.0(react-dom@19.1.1(react@19.1.1))(react@19.1.1)(tinymce@8.1.2)':
dependencies:
prop-types: 15.8.1
react: 19.1.1
react-dom: 19.1.1(react@19.1.1)
optionalDependencies:
tinymce: 8.1.2
'@tootallnate/once@1.1.2': {}
'@tootallnate/once@2.0.0': {}
@@ -24850,6 +24877,8 @@ snapshots:
tinyexec@1.0.1: {}
tinymce@8.1.2: {}
titleize@3.0.0: {}
tldts-core@6.1.86: {}

View File

@@ -1,16 +1,14 @@
import { CloseOutlined } from '@ant-design/icons';
import type { ProFormColumnsType } from '@ant-design/pro-components';
import { BetaSchemaForm, DrawerForm } from '@ant-design/pro-components';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Button, type ColProps, Drawer, Space, Typography } from 'antd';
import React, { forwardRef, useImperativeHandle } from 'react';
const { Title } = Typography;
interface ConfigurableDrawerFormProps {
title?: string;
columns: ProFormColumnsType[];
onSubmit?: (values: any) => Promise<boolean>;
initialValues?: Record<string, any>;
width?: number;
width?: number | string;
labelCol?: ColProps;
wrapperCol?: ColProps;
}
@@ -70,31 +68,31 @@ const ConfigurableDrawerForm = forwardRef<
setLoading(false);
}
};
const customHeader = (
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '0 0px 16px 0px',
borderBottom: '1px solid #f0f0f0',
marginBottom: '16px',
}}
>
<Title level={4} style={{ margin: 0 }}>
{title}
</Title>
<Button
type="text"
icon={<CloseOutlined />}
onClick={() => setOpen(false)}
style={{
border: 'none',
boxShadow: 'none',
}}
/>
</div>
);
// const customHeader = (
// <div
// style={{
// display: "flex",
// justifyContent: "space-between",
// alignItems: "center",
// padding: "0 0px 16px 0px",
// borderBottom: "1px solid #f0f0f0",
// marginBottom: "16px",
// }}
// >
// <Title level={4} style={{ margin: 0 }}>
// {title}
// </Title>
// <Button
// type="text"
// icon={<CloseOutlined />}
// onClick={() => setOpen(false)}
// style={{
// border: "none",
// boxShadow: "none",
// }}
// />
// </div>
// );
return (
<Drawer
title={title}

View File

@@ -4,30 +4,12 @@ import { PlusOutlined } from '@ant-design/icons';
import {
type ActionType,
type ParamsType,
ProColumns,
ProTable,
TableDropdown,
} from '@ant-design/pro-components';
import { Button, Space } from 'antd';
import React, {
act,
forwardRef,
useCallback,
useMemo,
useRef,
useState,
} from 'react';
import {
buildTableDropdownMenuItems,
formatPaginationTotal,
handleTableDropdownSelect,
} from '@/utils/antd/tableHelpers';
import {
type BaseRecord,
type EnhancedProTableProps,
TableAction,
ToolbarAction,
} from './types';
import React, { forwardRef, useCallback, useMemo, useState } from 'react';
import { formatPaginationTotal } from '@/utils/antd/tableHelpers';
import type { BaseRecord, EnhancedProTableProps } from './types';
function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
props: EnhancedProTableProps<T, U>,
@@ -36,21 +18,22 @@ function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
const {
columns,
request,
actions = [],
permissions = [],
// actions = [],
// permissions = [],
checkPermission = () => true,
toolbarActions,
showIndex = true,
showSelection = true,
showActions = true,
maxActionCount = 2,
onAdd,
onEdit,
onDelete,
onView,
onExport,
customToolbarRender,
// showActions = true,
// maxActionCount = 2,
// onAdd,
// onEdit,
// onDelete,
// onView,
// onExport,
// customToolbarRender,
customActionRender,
rowKey,
...restProps
} = props;
@@ -91,14 +74,13 @@ function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
[showSelection],
);
const toolBarRender = useCallback(
(
action: ActionType | undefined,
rows: {
selectedRowKeys?: (string | number)[] | undefined;
selectedRows?: T[] | undefined;
},
) => {
const toolBarRender = useCallback(() =>
// action: ActionType | undefined,
// rows: {
// selectedRowKeys?: (string | number)[] | undefined;
// selectedRows?: T[] | undefined;
// }
{
const toolbarElements =
toolbarActions?.map((action) => {
return (
@@ -125,22 +107,19 @@ function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
// </Button>,
// ];
return toolbarElements;
},
[toolbarActions],
);
}, [toolbarActions]);
return (
<ProTable<T, U>
{...restProps}
columns={columns}
actionRef={ref}
request={request}
rowKey="id"
rowKey={rowKey || 'id'}
rowSelection={rowSelection}
toolBarRender={toolBarRender}
manualRequest={false}
showSorterTooltip
tableAlertRender={tableAlertRender}
// tableAlertOptionRender={tableAlertOptionRender}
scroll={{ x: 'max-content' }}
search={{
labelWidth: 'auto',

View File

@@ -1,20 +1,19 @@
// components/EnhancedProTable/types.ts
import {
ProTableProps,
ProColumns,
import type {
ActionType,
} from "@ant-design/pro-components";
import { ButtonProps } from "antd";
import React from "react";
ProColumns,
ProTableProps,
} from '@ant-design/pro-components';
import type { ButtonProps } from 'antd';
import React from 'react';
export interface BaseRecord {
id: number;
[key: string]: any;
}
export interface ApiResponse<T> {
data: T[];
total: number;
total?: number;
success: boolean;
message?: string;
}
@@ -32,7 +31,7 @@ export interface TableAction<T = any> {
key: string;
label: string;
icon?: React.ReactNode;
type?: ButtonProps["type"];
type?: ButtonProps['type'];
danger?: boolean;
disabled?: (record: T) => boolean;
visible?: (record: T) => boolean;
@@ -44,7 +43,7 @@ export interface ToolbarAction {
key: string;
label: string;
icon?: React.ReactNode;
type?: ButtonProps["type"];
type?: ButtonProps['type'];
danger?: boolean;
disabled?: boolean;
onClick: (selectedKeys?: React.Key[], selectedRows?: any[]) => void;
@@ -53,10 +52,10 @@ export interface ToolbarAction {
}
export interface EnhancedProTableProps<T extends BaseRecord, U = any>
extends Omit<ProTableProps<T, U>, "columns" | "request" | "toolBarRender"> {
extends Omit<ProTableProps<T, U>, 'columns' | 'request' | 'toolBarRender'> {
columns: ProColumns<T>[];
request?: (
params: U & { current?: number; pageSize?: number }
params: U & { current?: number; pageSize?: number },
) => Promise<ApiResponse<T>>;
loading?: boolean; // 添加 loading 属性
actions?: TableAction<T>[];
@@ -73,11 +72,11 @@ export interface EnhancedProTableProps<T extends BaseRecord, U = any>
onView?: (record: T) => void;
onExport?: (selectedRows: T[]) => void;
customToolbarRender?: (
defaultActions: React.ReactNode[]
defaultActions: React.ReactNode[],
) => React.ReactNode[];
customActionRender?: (
record: T,
defaultActions: React.ReactNode[]
defaultActions: React.ReactNode[],
) => React.ReactNode[];
}

View File

@@ -0,0 +1,105 @@
// src/components/TagEditor/index.tsx
import { PlusOutlined } from '@ant-design/icons';
import type { TagProps } from 'antd';
import { Input, Space, Tag } from 'antd';
import React, { useMemo, useState } from 'react';
interface TagEditorProps {
value?: string[];
onChange?: (value: string[]) => void;
placeholder?: string;
maxCount?: number;
tagProps?: TagProps;
disabled?: boolean;
}
const TagEditor: React.FC<TagEditorProps> = ({
value = [],
onChange,
placeholder = '请输入标签',
maxCount,
tagProps,
disabled = false,
}) => {
// const [tags, setTags] = useState<string[]>(value);
const [inputVisible, setInputVisible] = useState(false);
const [inputValue, setInputValue] = useState('');
const tags = useMemo(() => {
return value || [];
}, [value]);
const handleClose = (removedTag: string) => {
const newTags = tags.filter((tag) => tag !== removedTag);
onChange?.(newTags);
};
const showInput = () => {
setInputVisible(true);
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};
const handleInputConfirm = () => {
if (inputValue && !tags.includes(inputValue)) {
const newTags = [...tags, inputValue];
onChange?.(newTags);
}
setInputVisible(false);
setInputValue('');
};
const handleInputBlur = () => {
handleInputConfirm();
};
const canAddMore = !maxCount || tags.length < maxCount;
return (
<Space wrap>
{tags.map((tag) => (
<Tag
key={tag}
closable={!disabled}
onClose={() => handleClose(tag)}
{...tagProps}
>
{tag}
</Tag>
))}
{inputVisible ? (
<Input
type="text"
size="small"
style={{ width: 110 }}
value={inputValue}
onChange={handleInputChange}
onBlur={handleInputBlur}
onPressEnter={handleInputConfirm}
placeholder={placeholder}
autoFocus
/>
) : (
canAddMore &&
!disabled && (
<Tag
onClick={showInput}
style={{
background: '#fff',
borderStyle: 'dashed',
cursor: 'pointer',
}}
>
<PlusOutlined />
</Tag>
)
)}
</Space>
);
};
export default TagEditor;

View File

@@ -0,0 +1,691 @@
// components/RichEditor/index.tsx
import { Editor } from '@tinymce/tinymce-react';
import { message } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import type { Editor as TinyMCEEditor } from 'tinymce';
import './index.less';
export interface RichEditorProps {
value?: string;
onChange?: (content: string) => void;
height?: number;
placeholder?: string;
disabled?: boolean;
uploadConfig?: {
action: string;
headers?: Record<string, string>;
maxSize?: number;
acceptTypes?: string[];
data?: Record<string, any>;
};
showWordCount?: boolean;
maxWords?: number;
}
const RichEditor: React.FC<RichEditorProps> = ({
value = '',
onChange,
height = 400,
placeholder = '请输入内容...',
disabled = false,
showWordCount = true,
maxWords,
uploadConfig = {
action: '/api/upload/image',
maxSize: 5,
acceptTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
},
}) => {
const [uploading, setUploading] = useState(false);
const [wordCount, setWordCount] = useState(0);
const [charCount, setCharCount] = useState(0);
// 自定义字数统计函数
const countWords = (text: string) => {
const plainText = text.replace(/<[^>]*>/g, '');
const cleanText = plainText.replace(/\s+/g, ' ').trim();
if (!cleanText) return { words: 0, characters: 0 };
const chineseChars = cleanText.match(/[\u4e00-\u9fa5]/g) || [];
const englishWords = cleanText.match(/[a-zA-Z]+/g) || [];
const numbers = cleanText.match(/\d+/g) || [];
const words = chineseChars.length + englishWords.length + numbers.length;
const characters = cleanText.length;
return { words, characters };
};
const handleEditorChange = (content: string) => {
onChange?.(content);
if (showWordCount) {
const { words, characters } = countWords(content);
setWordCount(words);
setCharCount(characters);
if (maxWords && words > maxWords) {
message.warning(
`内容超出字数限制,当前 ${words} 字,限制 ${maxWords}`,
);
}
}
};
useEffect(() => {
if (showWordCount && value) {
const { words, characters } = countWords(value);
setWordCount(words);
setCharCount(characters);
}
}, [value, showWordCount]);
const uploadFile = useCallback(
async (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const formData = new FormData();
formData.append('file', file);
if (uploadConfig.data) {
Object.keys(uploadConfig.data).forEach((key) => {
if (uploadConfig.data) formData.append(key, uploadConfig.data[key]);
});
}
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const percent = Math.round((e.loaded / e.total) * 100);
console.log(`上传进度: ${percent}%`);
}
});
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
if (response.code === 200 && response.data?.url) {
resolve(response.data.url);
} else {
reject(response.message || '上传失败');
}
} catch (_error) {
reject('响应解析失败');
}
} else {
reject(`上传失败: ${xhr.status}`);
}
});
xhr.addEventListener('error', () => {
reject('网络错误');
});
if (uploadConfig.headers) {
Object.keys(uploadConfig.headers).forEach((key) => {
if (uploadConfig.headers)
xhr.setRequestHeader(key, uploadConfig.headers[key]);
});
}
xhr.open('POST', uploadConfig.action);
xhr.send(formData);
});
},
[uploadConfig],
);
const handleImageUpload = useCallback(
(blobInfo: any, _: (percent: number) => void): Promise<string> => {
return new Promise((resolve, reject) => {
try {
setUploading(true);
const file = blobInfo.blob();
uploadFile(file).then((url) => {
resolve(url);
message.success('图片上传成功');
});
} catch (error) {
reject(error);
message.error(typeof error === 'string' ? error : '上传失败');
} finally {
setUploading(false);
}
});
},
[uploadFile],
);
const handleCustomUpload = useCallback(
(editor: TinyMCEEditor) => {
const input = document.createElement('input');
input.type = 'file';
input.accept = uploadConfig.acceptTypes?.join(',') || 'image/*';
input.multiple = true;
const handleFileChange = async (event: Event) => {
const target = event.target as HTMLInputElement;
const files = Array.from(target.files || []);
if (files.length === 0) return;
setUploading(true);
try {
for (const file of files) {
const isValidType = uploadConfig.acceptTypes?.includes(file.type);
if (!isValidType) {
message.error(`文件 ${file.name} 类型不支持`);
continue;
}
const isValidSize =
file.size / 1024 / 1024 < (uploadConfig.maxSize || 5);
if (!isValidSize) {
message.error(
`文件 ${file.name} 大小超过 ${uploadConfig.maxSize || 5}MB`,
);
continue;
}
try {
const url = await uploadFile(file);
const imgHtml = `<img src="${url}" alt="${file.name}" style="max-width: 100%; height: auto;" />`;
editor.insertContent(imgHtml);
message.success(`${file.name} 上传成功`);
} catch (error) {
message.error(`${file.name} 上传失败: ${error}`);
}
}
} finally {
setUploading(false);
}
};
input.addEventListener('change', handleFileChange);
input.click();
},
[uploadConfig, uploadFile],
);
// 全展开的工具栏配置
const editorConfig = {
height,
menubar: 'file edit view insert format tools table help',
plugins: [
'advlist',
'autolink',
'lists',
'link',
'image',
'charmap',
'preview',
'anchor',
'searchreplace',
'visualblocks',
'code',
'fullscreen',
'insertdatetime',
'media',
'table',
'help',
'wordcount',
'emoticons',
'template',
'codesample',
'hr',
'pagebreak',
'nonbreaking',
'toc',
'imagetools',
'textpattern',
'noneditable',
'quickbars',
'accordion',
],
// 修改为全展开的工具栏配置
toolbar: [
// 第一行:撤销重做 + 格式选择 + 字体
'undo redo | blocks fontfamily fontsize',
// 第二行:文本格式
'bold italic underline strikethrough subscript superscript | forecolor backcolor',
// 第三行:对齐和列表
'alignleft aligncenter alignright alignjustify | bullist numlist outdent indent',
// 第四行:插入功能
'link customupload image media table emoticons charmap insertdatetime hr pagebreak',
// 第五行:高级功能
'codesample accordion blockquote | searchreplace visualblocks code',
// 第六行:其他工具
'removeformat | fullscreen preview help',
].join(' | '),
// 设置工具栏模式为换行显示,而不是滑动
toolbar_mode: 'wrap' as const, // 改为 wrap 模式,全部展开
// 工具栏分组,每组之间有分隔符
toolbar_groups: {
history: { icon: 'undo', tooltip: '历史操作' },
formatting: { icon: 'bold', tooltip: '文本格式' },
alignment: { icon: 'align-left', tooltip: '对齐方式' },
indentation: { icon: 'indent', tooltip: '缩进' },
insert: { icon: 'plus', tooltip: '插入' },
tools: { icon: 'preferences', tooltip: '工具' },
},
font_family_formats: [
'微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif',
'苹方=PingFang SC,Microsoft YaHei,sans-serif',
'宋体=SimSun,serif',
'黑体=SimHei,sans-serif',
'楷体=KaiTi,serif',
'Arial=arial,helvetica,sans-serif',
'Times New Roman=times new roman,times,serif',
'Courier New=courier new,courier,monospace',
].join(';'),
fontsize_formats:
'8px 9px 10px 11px 12px 14px 16px 18px 20px 22px 24px 26px 28px 36px 48px 72px',
block_formats: [
'段落=p',
'标题1=h1',
'标题2=h2',
'标题3=h3',
'标题4=h4',
'标题5=h5',
'标题6=h6',
'预格式化=pre',
'地址=address',
'代码=code',
].join(';'),
// 字数统计配置
wordcount_countregex: /[\w\u2019\u4e00-\u9fa5]+/g,
wordcount_cleanregex: /[0-9.(),;:!?%#$?\x27\x22_+=\\/-]*/g,
// 颜色配置
color_map: [
'000000',
'黑色',
'993300',
'深红色',
'333300',
'深黄色',
'003300',
'深绿色',
'003366',
'深青色',
'000080',
'深蓝色',
'333399',
'蓝色',
'333333',
'深灰色',
'800000',
'栗色',
'FF6600',
'橙色',
'808000',
'橄榄色',
'008000',
'绿色',
'008080',
'青色',
'0000FF',
'蓝色',
'666699',
'灰蓝色',
'808080',
'灰色',
'FF0000',
'红色',
'FF9900',
'琥珀色',
'99CC00',
'黄绿色',
'339966',
'海绿色',
'33CCCC',
'青绿色',
'3366FF',
'蓝色',
'800080',
'紫色',
'999999',
'中灰色',
'FF00FF',
'洋红色',
'FFCC00',
'金色',
'FFFF00',
'黄色',
'00FF00',
'酸橙色',
'00FFFF',
'水蓝色',
'00CCFF',
'天蓝色',
'993366',
'红紫色',
'FFFFFF',
'白色',
],
// 代码高亮配置
codesample_languages: [
{ text: 'HTML/XML', value: 'markup' },
{ text: 'JavaScript', value: 'javascript' },
{ text: 'TypeScript', value: 'typescript' },
{ text: 'CSS', value: 'css' },
{ text: 'SCSS', value: 'scss' },
{ text: 'Python', value: 'python' },
{ text: 'Java', value: 'java' },
{ text: 'C++', value: 'cpp' },
{ text: 'C#', value: 'csharp' },
{ text: 'PHP', value: 'php' },
{ text: 'Ruby', value: 'ruby' },
{ text: 'Go', value: 'go' },
{ text: 'Rust', value: 'rust' },
{ text: 'SQL', value: 'sql' },
{ text: 'JSON', value: 'json' },
{ text: 'Bash', value: 'bash' },
],
// 表格配置
table_default_attributes: {
border: '1',
},
table_default_styles: {
'border-collapse': 'collapse',
width: '100%',
},
table_class_list: [
{ title: '无样式', value: '' },
{ title: '简单表格', value: 'simple-table' },
{ title: '条纹表格', value: 'striped-table' },
{ title: '边框表格', value: 'bordered-table' },
],
// 链接配置
link_default_target: '_blank',
link_assume_external_targets: true,
link_context_toolbar: true,
// 图片配置
image_advtab: true,
image_caption: true,
// 媒体配置
media_live_embeds: true,
media_filter_html: false,
content_style: `
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
font-size: 14px;
line-height: 1.6;
margin: 16px;
color: #333;
}
h1, h2, h3, h4, h5, h6 {
margin-top: 24px;
margin-bottom: 16px;
font-weight: 600;
line-height: 1.25;
}
h1 { font-size: 2em; color: #1a1a1a; }
h2 { font-size: 1.5em; color: #2a2a2a; }
h3 { font-size: 1.25em; color: #3a3a3a; }
p { margin-bottom: 16px; }
img {
max-width: 100%;
height: auto;
border-radius: 6px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
margin: 8px 0;
}
table {
border-collapse: collapse;
width: 100%;
margin: 16px 0;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
table td, table th {
border: 1px solid #e8e8e8;
padding: 12px;
text-align: left;
}
table th {
background-color: #f8f9fa;
font-weight: 600;
color: #495057;
}
blockquote {
border-left: 4px solid #1890ff;
margin: 16px 0;
padding: 8px 16px;
background-color: #f6f8fa;
color: #666;
font-style: italic;
}
code {
background-color: #f1f3f4;
padding: 2px 4px;
border-radius: 3px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
color: #d73a49;
}
pre {
background-color: #f8f8f8;
border: 1px solid #e1e4e8;
border-radius: 6px;
padding: 16px;
overflow-x: auto;
margin: 16px 0;
}
pre code {
background: none;
padding: 0;
color: inherit;
}
`,
placeholder,
branding: false,
elementpath: true,
resize: 'both' as const,
statusbar: showWordCount,
// 图片上传配置
images_upload_handler: handleImageUpload,
automatic_uploads: true,
images_reuse_filename: true,
images_upload_url: uploadConfig.action,
images_upload_base_path: '',
images_upload_credentials: true,
// 粘贴配置
paste_data_images: true,
paste_as_text: false,
paste_webkit_styles: 'none',
paste_merge_formats: true,
paste_remove_styles_if_webkit: true,
// 文件选择器配置
file_picker_types: 'image media',
file_picker_callback: (
callback: (url: string, meta?: any) => void,
// value: string,
meta: any,
) => {
if (meta.filetype === 'image') {
const input = document.createElement('input');
input.type = 'file';
input.accept = uploadConfig.acceptTypes?.join(',') || 'image/*';
const handleChange = async (event: Event) => {
const target = event.target as HTMLInputElement;
const file = target.files?.[0];
if (!file) return;
const isValidType = uploadConfig.acceptTypes?.includes(file.type);
const isValidSize =
file.size / 1024 / 1024 < (uploadConfig.maxSize || 5);
if (!isValidType) {
message.error('文件类型不支持');
return;
}
if (!isValidSize) {
message.error(`文件大小不能超过 ${uploadConfig.maxSize || 5}MB`);
return;
}
try {
setUploading(true);
const url = await uploadFile(file);
callback(url, { alt: file.name });
message.success('图片上传成功');
} catch (error) {
message.error('上传失败');
console.error('Upload error:', error);
} finally {
setUploading(false);
}
};
input.addEventListener('change', handleChange);
input.click();
}
},
// 快速工具栏
quickbars_selection_toolbar:
'bold italic | quicklink h2 h3 blockquote quickimage quicktable',
quickbars_insert_toolbar: 'quickimage quicktable',
// 文本模式
textpattern_patterns: [
{ start: '*', end: '*', format: 'italic' },
{ start: '**', end: '**', format: 'bold' },
{ start: '#', format: 'h1' },
{ start: '##', format: 'h2' },
{ start: '###', format: 'h3' },
{ start: '####', format: 'h4' },
{ start: '#####', format: 'h5' },
{ start: '######', format: 'h6' },
{ start: '1. ', cmd: 'InsertOrderedList' },
{ start: '* ', cmd: 'InsertUnorderedList' },
{ start: '- ', cmd: 'InsertUnorderedList' },
],
// 初始化设置
setup: (editor: TinyMCEEditor) => {
// 注册自定义上传按钮
editor.ui.registry.addButton('customupload', {
text: uploading ? '上传中...' : '上传',
icon: 'upload',
tooltip: '上传图片(支持多选)',
enabled: !disabled && !uploading,
onAction: () => {
handleCustomUpload(editor);
},
});
// 监听内容变化,实时更新字数统计
editor.on('input change undo redo', () => {
if (showWordCount) {
const content = editor.getContent();
const { words, characters } = countWords(content);
setWordCount(words);
setCharCount(characters);
}
});
editor.on('init', () => {
console.log('编辑器初始化完成');
// 初始化字数统计
if (showWordCount && value) {
const { words, characters } = countWords(value);
setWordCount(words);
setCharCount(characters);
}
});
},
// 其他配置
convert_urls: false,
remove_script_host: false,
relative_urls: false,
language: 'zh_CN',
directionality: 'ltr' as const,
// 高级配置
extended_valid_elements: 'script[src|async|defer|type|charset]',
// 性能配置
browser_spellcheck: true,
contextmenu: 'link image table',
};
return (
<div className="rich-editor-wrapper">
<Editor
value={value}
onEditorChange={handleEditorChange}
init={editorConfig}
disabled={disabled}
/>
{/* 自定义字数统计显示 */}
{showWordCount && (
<div className="word-count-display">
<span className="word-count">
: {wordCount}
{maxWords && (
<span className={wordCount > maxWords ? 'over-limit' : ''}>
/{maxWords}
</span>
)}
</span>
<span className="char-count">: {charCount}</span>
</div>
)}
{uploading && (
<div className="upload-overlay">
<div className="upload-spinner">
<div className="spinner"></div>
<span>...</span>
</div>
</div>
)}
</div>
);
};
export default RichEditor;

View File

@@ -0,0 +1,145 @@
/* components/RichEditor/index.css */
.rich-editor-wrapper {
position: relative;
border: 1px solid #d9d9d9;
border-radius: 6px;
overflow: hidden;
transition: all 0.3s;
background: #fff;
}
.rich-editor-wrapper:hover {
border-color: #4096ff;
}
.rich-editor-wrapper:focus-within {
border-color: #4096ff;
box-shadow: 0 0 0 2px rgba(64, 150, 255, 0.2);
}
.rich-editor-wrapper .tox-tinymce {
border: none !important;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
.rich-editor-wrapper .tox-editor-header {
border-bottom: 1px solid #e8e8e8 !important;
background: #fafafa !important;
}
.rich-editor-wrapper .tox-toolbar__primary {
background: #fafafa !important;
}
.rich-editor-wrapper .tox-statusbar {
border-top: 1px solid #e8e8e8 !important;
background: #fafafa !important;
}
/* 自定义按钮样式 */
.rich-editor-wrapper .tox-tbtn--enabled {
background: transparent !important;
}
.rich-editor-wrapper .tox-tbtn--enabled:hover {
background: #e6f7ff !important;
border-color: #91d5ff !important;
}
.rich-editor-wrapper .tox-tbtn--enabled:active {
background: #bae7ff !important;
}
/* 上传状态覆盖层 */
.upload-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
backdrop-filter: blur(2px);
}
.upload-spinner {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 20px;
background: #fff;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.spinner {
width: 32px;
height: 32px;
border: 3px solid #f3f3f3;
border-top: 3px solid #1890ff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.upload-spinner span {
color: #666;
font-size: 14px;
}
/* 响应式设计 */
@media (max-width: 768px) {
.rich-editor-wrapper .tox-toolbar__primary {
flex-wrap: wrap;
}
.rich-editor-wrapper .tox-toolbar__group {
margin: 2px;
}
}
/* 图片样式优化 */
.rich-editor-wrapper .tox-edit-area img {
max-width: 100% !important;
height: auto !important;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
margin: 4px 0;
cursor: pointer;
transition: transform 0.2s;
}
.rich-editor-wrapper .tox-edit-area img:hover {
transform: scale(1.02);
}
/* 表格样式优化 */
.rich-editor-wrapper .tox-edit-area table {
border-collapse: collapse;
width: 100%;
margin: 8px 0;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.rich-editor-wrapper .tox-edit-area table td,
.rich-editor-wrapper .tox-edit-area table th {
border: 1px solid #e8e8e8;
padding: 8px 12px;
}
.rich-editor-wrapper .tox-edit-area table th {
background-color: #fafafa;
font-weight: 600;
}

View File

@@ -0,0 +1,262 @@
import { Editor } from '@tinymce/tinymce-react';
import { message } from 'antd';
import React, { useCallback, useState } from 'react';
import type { Editor as TinyMCEEditor } from 'tinymce';
export interface RichEditorProps {
value?: string;
onChange?: (content: string) => void;
height?: number;
placeholder?: string;
disabled?: boolean;
uploadConfig?: {
action: string;
headers?: Record<string, string>;
maxSize?: number;
acceptTypes?: string[];
data?: Record<string, any>;
};
showWordCount?: boolean;
maxWords?: number;
}
const RichEditor: React.FC<RichEditorProps> = ({
// value = "",
// onChange,
// height = 400,
// placeholder = "请输入内容...",
disabled = false,
// showWordCount = true,
// maxWords,
uploadConfig = {
action: '/api/upload/image',
maxSize: 5,
acceptTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
},
}) => {
const [uploading, setUploading] = useState<boolean>(false);
const uploadFile = useCallback(
async (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const formData = new FormData();
formData.append('file', file);
if (uploadConfig.data) {
Object.keys(uploadConfig.data).forEach((key) => {
formData.append(key, uploadConfig.data?.[key]);
});
}
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const percent = Math.round((e.loaded / e.total) * 100);
console.log(`上传进度: ${percent}%`);
}
});
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
if (response.code === 200 && response.data?.url) {
resolve(response.data.url);
} else {
reject(response.message || '上传失败');
}
} catch (_error) {
reject('响应解析失败');
}
} else {
reject(`上传失败: ${xhr.status}`);
}
});
xhr.addEventListener('error', () => {
reject('网络错误');
});
if (uploadConfig.headers) {
Object.keys(uploadConfig.headers).forEach((key) => {
xhr.setRequestHeader(key, uploadConfig.headers![key]);
});
}
xhr.open('POST', uploadConfig.action);
xhr.send(formData);
});
},
[uploadConfig],
);
const handleImageUpload = useCallback(
(blobInfo: any, _: (percent: number) => void): Promise<string> => {
return new Promise((resolve, reject) => {
try {
setUploading(true);
const file = blobInfo.blob();
uploadFile(file).then((url) => {
resolve(url);
});
message.success('图片上传成功');
} catch (error) {
reject(error);
message.error(typeof error === 'string' ? error : '上传失败');
} finally {
setUploading(false);
}
});
},
[uploadFile],
);
const handleCustomUpload = useCallback(
(editor: TinyMCEEditor) => {
const input = document.createElement('input');
input.type = 'file';
input.accept = uploadConfig.acceptTypes?.join(',') || 'image/*';
input.multiple = true;
const handleFileChange = async (event: Event) => {
const target = event.target as HTMLInputElement;
const files = Array.from(target.files || []);
if (files.length === 0) return;
setUploading(true);
try {
for (const file of files) {
const isValidType = uploadConfig.acceptTypes?.includes(file.type);
if (!isValidType) {
message.error(`文件 ${file.name} 类型不支持`);
continue;
}
const isValidSize =
file.size / 1024 / 1024 < (uploadConfig.maxSize || 5);
if (!isValidSize) {
message.error(
`文件 ${file.name} 大小超过 ${uploadConfig.maxSize || 5}MB`,
);
continue;
}
try {
const url = await uploadFile(file);
const imgHtml = `<img src="${url}" alt="${file.name}" style="max-width: 100%; height: auto;" />`;
editor.insertContent(imgHtml);
message.success(`${file.name} 上传成功`);
} catch (error) {
message.error(`${file.name} 上传失败: ${error}`);
}
}
} finally {
setUploading(false);
}
};
input.addEventListener('change', handleFileChange);
input.click();
},
[uploadConfig, uploadFile],
);
return (
<Editor
apiKey="xt51qhzvj8q9mxzxytigtp0nu94v4rz7dska2dbqeilkxo99"
init={{
plugins: [
// Core editing features
'anchor',
'autolink',
'charmap',
'codesample',
'emoticons',
'link',
'lists',
'media',
'searchreplace',
'table',
'visualblocks',
'wordcount',
// Your account includes a free trial of TinyMCE premium features
// Try the most popular premium features until Oct 8, 2025:
'checklist',
'mediaembed',
'casechange',
'formatpainter',
'pageembed',
'a11ychecker',
'tinymcespellchecker',
'permanentpen',
'powerpaste',
'advtable',
'advcode',
'advtemplate',
'ai',
'uploadcare',
'mentions',
'tinycomments',
'tableofcontents',
'footnotes',
'mergetags',
'autocorrect',
'typography',
'inlinecss',
'markdown',
'importword',
'exportword',
'exportpdf',
],
menubar: false,
toolbar:
'undo redo | blocks | bold italic forecolor | ' +
'alignleft aligncenter | ' +
'alignright alignjustify | bullist numlist outdent indent customupload | ' +
'removeformat ',
tinycomments_mode: 'embedded',
tinycomments_author: 'Author name',
toolbar_mode: 'sliding',
mergetags_list: [
{ value: 'First.Name', title: 'First Name' },
{ value: 'Email', title: 'Email' },
],
ai_request: (
_: any,
respondWith: { string: (arg0: () => Promise<never>) => any },
) =>
respondWith.string(() =>
Promise.reject('See docs to implement AI Assistant'),
),
language: 'zh-CN',
// 其他配置
convert_urls: false,
remove_script_host: false,
uploadcare_public_key: '0ad3671d77f59c5756dd',
setup: (editor: TinyMCEEditor) => {
// 注册自定义上传按钮
editor.ui.registry.addButton('customupload', {
text: uploading ? '上传中...' : '上传',
icon: 'upload',
tooltip: '上传图片(支持多选)',
enabled: !disabled && !uploading,
onAction: () => {
handleCustomUpload(editor);
},
});
},
// 图片上传配置
images_upload_handler: handleImageUpload,
// 性能配置
browser_spellcheck: true,
contextmenu: 'link image table',
}}
initialValue="Welcome to TinyMCE!"
/>
);
};
export default React.memo(RichEditor);

View File

@@ -1 +1,36 @@
export const formStatusType = { create: '创建', update: '编辑', test: '测试' };
export const formStatusType: { [key: string]: string } = {
create: '创建',
update: '编辑',
test: '测试',
};
export const tenantStatus = [
{ label: '开启', value: 0 },
{ label: '关闭', value: 1 },
];
export const modlaTypeText: { [key: string]: string } = {
edit: '编辑',
add: '新增',
menu: '菜单权限',
data: '数据权限',
prod_status: '商品状态控制',
prod_audit: '商品上架审核',
prod_sku: '',
};
export const SystemDataScopeEnum = {
ALL: 1, // 全部数据权限
DEPT_CUSTOM: 2, // 指定部门数据权限
DEPT_ONLY: 3, // 部门数据权限
DEPT_AND_CHILD: 4, // 部门及以下数据权限
DEPT_SELF: 5, // 仅本人数据权限
};
export const systemDataScopetStatus = [
{ label: '全部数据权限', value: 1 },
{ label: '指定部门数据权限', value: 2 },
{ label: '部门数据权限', value: 3 },
{ label: '部门及以下数据权限', value: 4 },
{ label: '仅本人数据权限', value: 5 },
];

View File

@@ -0,0 +1,131 @@
// src/hooks/antd/useMessage.ts
import { Modal, message, notification } from 'antd';
export const useMessage = () => {
return {
// 消息提示
info(content: string) {
message.info(content);
},
// 错误消息
error(content: string) {
message.error(content);
},
// 成功消息
success(content: string) {
message.success(content);
},
// 警告消息
warning(content: string) {
message.warning(content);
},
// 弹出提示
alert(content: string) {
Modal.info({
title: '提示',
content: content,
okText: '确定',
});
},
// 错误提示
alertError(content: string) {
Modal.error({
title: '提示',
content: content,
okText: '确定',
});
},
// 成功提示
alertSuccess(content: string) {
Modal.success({
title: '提示',
content: content,
okText: '确定',
});
},
// 警告提示
alertWarning(content: string) {
Modal.warning({
title: '提示',
content: content,
okText: '确定',
});
},
// 通知提示
notify(content: string) {
notification.info({
message: content,
});
},
// 错误通知
notifyError(content: string) {
notification.error({
message: content,
});
},
// 成功通知
notifySuccess(content: string) {
notification.success({
message: content,
});
},
// 警告通知
notifyWarning(content: string) {
notification.warning({
message: content,
});
},
// 确认窗体
confirm(content: string, tip?: string) {
return new Promise<boolean>((resolve) => {
Modal.confirm({
title: tip ? tip : '提示',
content: content,
okText: '确定',
cancelText: '取消',
onOk: () => resolve(true),
onCancel: () => resolve(false),
});
});
},
// 删除窗体
delConfirm(content?: string, tip?: string) {
return new Promise<boolean>((resolve) => {
Modal.confirm({
title: tip ? tip : '提示',
content: content ? content : '是否确认删除?',
okText: '确定',
cancelText: '取消',
onOk: () => resolve(true),
onCancel: () => resolve(false),
});
});
},
// 导出窗体
exportConfirm(content?: string, tip?: string) {
return new Promise<boolean>((resolve) => {
Modal.confirm({
title: tip ? tip : '提示',
content: content ? content : '是否确认导出?',
okText: '确定',
cancelText: '取消',
onOk: () => resolve(true),
onCancel: () => resolve(false),
});
});
},
// 提交内容
prompt(content: string, tip: string) {
return new Promise<boolean>((resolve) => {
Modal.confirm({
title: tip,
content: content,
okText: '确定',
cancelText: '取消',
onOk: () => resolve(true),
onCancel: () => resolve(false),
});
});
},
};
};

View File

@@ -0,0 +1,156 @@
import type {
ProColumns,
ProFormColumnsType,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';
import TagEditor from '@/components/TagEditor';
import TinyMCEEditor from '@/components/Tinymce';
export const baseTenantColumns: ProColumns<API.CategoryDO>[] = [
{
title: '类目名称',
dataIndex: 'categoryName',
width: 100,
},
{
title: '类目ID',
dataIndex: 'categoryId',
},
{
title: '类目层级',
dataIndex: 'grade',
hideInSearch: true, // 在搜索表单中隐藏
},
{
title: '父级类目',
dataIndex: 'parentName',
hideInSearch: true, // 在搜索表单中隐藏
},
{
title: '排序权重',
dataIndex: 'sort',
hideInSearch: true, // 在搜索表单中隐藏
},
{
title: '状态',
dataIndex: 'status',
valueType: 'switch',
hideInSearch: true,
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateRange',
hideInSearch: true, // 在搜索表单中隐藏
render: (_, record: API.CategoryDO) =>
dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss'),
},
];
export const formColumns = (data: {
type: string;
grade: number;
}): ProFormColumnsType[] => [
{
title: '类目',
dataIndex: 'grade',
valueType: 'radio',
fieldProps: {
value: data.grade || 1,
options: [
{ label: '一级类目', value: 1 },
{ label: '二级类目', value: 2 },
{ label: '三级类目', value: 3 },
],
disabled: data.type === 'create',
},
},
{
title: '类目名称',
dataIndex: 'username',
formItemProps: {
rules: [
{
required: true,
message: '请输入用户名',
},
],
},
},
{
title: '排序权重',
dataIndex: 'sort',
valueType: 'digit',
},
{
title: '类目描述',
dataIndex: 'description',
valueType: 'textarea',
renderFormItem: () => {
return <TinyMCEEditor />;
},
},
{
title: '关联父级',
dataIndex: 'parentId',
valueType: 'select',
hideInForm: data.grade - 1 === 0,
},
{
title: '类目icon',
dataIndex: 'icon',
},
{
title: '类目标签',
dataIndex: 'tages',
renderFormItem: () => {
return (
<TagEditor
placeholder="输入标签名称"
maxCount={10}
tagProps={{
color: 'blue',
}}
/>
);
},
},
{
title: '类目状态',
dataIndex: 'status',
hideInForm: data.type === 'create',
},
{
title: '类目ID',
dataIndex: 'categoryId',
hideInForm: data.type === 'create',
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateTime',
hideInForm: data.type === 'create',
},
{
title: '创建人',
dataIndex: 'creator',
hideInForm: data.type === 'create',
},
{
title: '更新时间',
dataIndex: 'updateTime',
valueType: 'dateTime',
hideInForm: data.type === 'create',
},
{
title: '更新人',
dataIndex: 'updator',
hideInForm: data.type === 'create',
},
];
// {
// title: "模板内容",
// dataIndex: "content",
// valueType: "textarea",
// },

View File

@@ -0,0 +1,129 @@
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import type { TabsProps } from 'antd';
import { Tabs } from 'antd';
import { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import { getCategoryList } from '@/services/prodApi/category';
import { baseTenantColumns, formColumns } from './config';
const ProdCategory = () => {
const tableRef = useRef<ActionType>(null);
const [type, setType] = useState<'create' | 'update' | 'test'>('create');
const [grade, setGrade] = useState<string>('');
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const onChange = useCallback(
(key: string) => {
setGrade(key);
},
[grade],
);
const onFetch = async (params: API.getProductCategoryCategoryListParams) => {
const data = await getCategoryList({
...params,
grade: grade ? Number(grade) : undefined,
});
return {
data: data,
success: true,
};
};
const handleAdd = () => {
setType('create');
configurableDrawerRef.current?.open();
};
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '新建',
type: 'primary',
icon: <PlusOutlined />,
onClick: handleAdd,
},
];
const handleEdit = async (row: API.CategoryDO) => {
setType('update');
configurableDrawerRef.current?.open(row);
};
const handleSubmit = async (values: API.CategoryDO) => {
console.log('values', values);
// const success = await handleAdd(values as API.CategoryDO);
// if (success) {
// handleClose();
// }
return true;
};
const actionColumns: ProColumns<API.CategoryDO> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
render: (_text: React.ReactNode, record: API.CategoryDO, _: number) => [
<a key="edit" onClick={() => handleEdit(record)}>
</a>,
<a key="detail"></a>,
],
};
const columns = [...baseTenantColumns, actionColumns];
const renderChildren = () => {
return (
<>
<EnhancedProTable<API.CategoryDO>
ref={tableRef}
columns={columns}
rowKey="categoryId"
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="短信渠道"
showIndex={false}
showSelection={false}
/>
<ConfigurableDrawerForm
ref={configurableDrawerRef}
title={formStatusType[type]}
// width="50vw"
columns={formColumns({ grade: Number(grade), type })}
onSubmit={handleSubmit}
/>
</>
);
};
const items: TabsProps['items'] = [
{
key: '',
label: '全部分类',
children: renderChildren(),
},
{
key: '3',
label: '三级分类',
children: renderChildren(),
},
{
key: '2',
label: '二级分类',
children: renderChildren(),
},
{
key: '1',
label: '一级分类',
children: renderChildren(),
},
];
return <Tabs defaultActiveKey={grade} items={items} onChange={onChange} />;
};
export default ProdCategory;

View File

@@ -0,0 +1,5 @@
const ProdList = () => {
return <div>ProdList</div>;
};
export default ProdList;

View File

@@ -0,0 +1,170 @@
import type {
ProColumns,
ProFormColumnsType,
} from '@ant-design/pro-components';
import { Tag } from 'antd';
import dayjs from 'dayjs';
import { tenantStatus } from '@/constants';
import type { DeptVO } from '@/services/system/dept';
import { getStatusLabel } from '@/utils/constant';
export const baseDeptColumns: ProColumns<DeptVO>[] = [
{
title: '部门名称',
dataIndex: 'name',
ellipsis: true,
hideInSearch: true,
},
// { prop: "leaderUserId", label: "负责人", width: 100 },
{
title: '负责人',
dataIndex: 'leaderUserId',
hideInSearch: true,
},
// { prop: "sort", label: "排序", width: 100 },
{
title: '排序',
dataIndex: 'sort',
hideInSearch: true,
},
// {
// prop: "status",
// label: "状态",
// width: 100,
// render: (record) => (
// <ElTag type={record.status == 1 ? "info" : "primary"}>
// {getStatusLabel(tenantStatus, record.status)}
// </ElTag>
// )
// },
{
title: '状态',
dataIndex: 'status',
hideInSearch: true,
render: (_, record: DeptVO) => [
<Tag
key={record.status}
color={record.status === 1 ? 'default' : 'processing'}
>
{getStatusLabel(tenantStatus, record.status)}
</Tag>,
],
},
// {
// prop: "createTime",
// label: "创建时间",
// width: 160,
// render: (row) => dateFormatter(row.createTime)
// },
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateRange',
search: {
transform: (value) => {
return {
'createTime[0]': dayjs(value[0])
.startOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
'createTime[1]': dayjs(value[1])
.endOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
};
},
},
render: (_, record: DeptVO) =>
dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss'),
},
];
export const formColumns = (_type: string): ProFormColumnsType[] => [
{
title: '上级部门',
dataIndex: 'parentId',
valueType: 'treeSelect',
fieldProps: () => {
return {
multiple: true,
placeholder: '请选择上级部门',
options: [{ label: '11', value: 5016 }],
};
},
},
{
title: '部门名称',
dataIndex: 'name',
valueType: 'text',
formItemProps: {
rules: [
{
required: true,
message: '请输入部门名称',
},
],
},
},
{
title: '显示顺序',
dataIndex: 'sort',
valueType: 'digit',
fieldProps: {
min: 0,
},
formItemProps: {
rules: [
{
required: true,
message: '请输入显示顺序',
},
],
},
},
{
title: '负责人',
dataIndex: 'leaderUserId',
formItemProps: {
rules: [
{
required: true,
message: '请选择负责人',
},
],
},
},
{
title: '邮箱',
dataIndex: 'email',
formItemProps: {
rules: [
{
required: true,
message: '请输入邮箱',
},
],
},
},
{
title: '状态',
dataIndex: 'status',
valueType: 'select',
fieldProps: {
options: [
{
label: '正常',
value: 1,
},
{
label: '禁用',
value: 2,
},
],
},
formItemProps: {
rules: [
{
required: true,
},
],
},
},
];

View File

@@ -1,5 +1,136 @@
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Popconfirm } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import {
createDept,
type DeptReqVO,
type DeptVO,
deleteDept,
getDeptPage,
updateDept,
} from '@/services/system/dept';
import { handleTree } from '@/utils/tree';
import { baseDeptColumns, formColumns } from './config';
const SyStemDept = () => {
return <>SyStemDept</>;
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const tableRef = useRef<ActionType>(null);
const [type, setType] = useState<'create' | 'update'>('create');
const [id, setId] = useState<number>(0);
const handleEdit = (record: DeptVO) => {
setType('update');
setId(record.id);
configurableDrawerRef.current?.open(record);
};
const onFetch = async (
params: DeptReqVO & {
pageSize?: number;
current?: number;
},
) => {
const data = await getDeptPage({
...params,
pageNo: params.current,
pageSize: params.pageSize,
});
return {
data: handleTree(data),
success: true,
total: data.total,
};
};
const handleAdd = () => {
setType('create');
configurableDrawerRef.current?.open({});
};
const handleSubmit = useCallback(
async (values: DeptVO) => {
if (type === 'create') {
await createDept(values);
} else {
await updateDept({
...values,
id,
});
}
tableRef.current?.reload();
return true;
},
[type, id],
);
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '新建',
type: 'primary',
icon: <PlusOutlined />,
onClick: handleAdd,
},
];
const actionColumns: ProColumns<DeptVO> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
render: (_text: React.ReactNode, record: DeptVO, _: any, action: any) => [
<a key="editable" onClick={() => handleEdit(record)}>
</a>,
<Popconfirm
title="是否删除?"
key="delete"
onConfirm={async () => {
await deleteDept(record.id);
action?.reload();
}}
okText="是"
cancelText="否"
>
<a></a>
</Popconfirm>,
],
};
const columns = [...baseDeptColumns, actionColumns];
return (
<>
<EnhancedProTable<DeptVO>
ref={tableRef}
columns={columns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="租户列表"
showIndex={false}
showSelection={false}
expandable={{
defaultExpandAllRows: true,
}}
/>
<ConfigurableDrawerForm
ref={configurableDrawerRef}
title={formStatusType[type]}
columns={formColumns(type)}
onSubmit={handleSubmit}
/>
</>
);
};
export default SyStemDept;

View File

@@ -0,0 +1,120 @@
import type {
ProColumns,
ProFormColumnsType,
} from '@ant-design/pro-components';
import { Tag } from 'antd';
import dayjs from 'dayjs';
import { tenantStatus } from '@/constants';
import type { DictTypeVO } from '@/services/system/dict/dict.type';
export const baseDictTypeColumns: ProColumns<DictTypeVO>[] = [
{
title: '字典编号',
dataIndex: 'id',
width: 80,
align: 'left',
hideInSearch: true,
},
{
title: '字典名称',
dataIndex: 'name',
width: 120,
},
{
title: '字典类型',
dataIndex: 'type',
width: 120,
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (_, record) => (
<Tag
key={record.status}
color={record.status === 1 ? 'default' : 'processing'}
>
{record.status === 1 ? '正常' : '禁用'}
</Tag>
),
},
{
title: '备注',
dataIndex: 'remark',
width: 120,
hideInSearch: true, // 在搜索表单中隐藏
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateRange',
search: {
transform: (value) => {
return {
'createTime[0]': dayjs(value[0])
.startOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
'createTime[1]': dayjs(value[1])
.endOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
};
},
},
render: (_, record: DictTypeVO) =>
dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss'),
},
];
export const formColumns = (type: string): ProFormColumnsType[] => [
{
title: '字典名称',
dataIndex: 'name',
valueType: 'text',
colProps: {
span: 12,
},
formItemProps: {
rules: [
{
required: true,
message: '请输入字典名称',
},
],
},
},
{
title: '字典类型',
dataIndex: 'type',
valueType: 'text',
fieldProps: {
disabled: type === 'update',
},
colProps: {
span: 12,
},
formItemProps: {
rules: [
{
required: true,
message: '请输入字典类型',
},
],
},
},
{
title: '状态',
dataIndex: 'status',
valueType: 'select',
fieldProps: {
options: tenantStatus,
},
},
{
title: '备注',
dataIndex: 'remark',
valueType: 'textarea',
colProps: {
span: 24,
},
},
];

View File

@@ -0,0 +1,189 @@
import type {
ProColumns,
ProFormColumnsType,
} from '@ant-design/pro-components';
import { Tag } from 'antd';
import dayjs from 'dayjs';
import { tenantStatus } from '@/constants';
import type { DictDataVO } from '@/services/system/dict/dict.data';
import { getStatusLabel } from '@/utils/constant';
export const baseDictDataColumns: ProColumns<DictDataVO>[] = [
{
title: '字典编码',
dataIndex: 'id',
width: 80,
hideInSearch: true,
},
{
title: '字典标签',
dataIndex: 'label',
width: 120,
},
{
title: '字典键值',
dataIndex: 'value',
width: 120,
},
{
title: '字典排序',
dataIndex: 'sort',
width: 80,
},
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (_, record) => (
<Tag color={record.status === 1 ? 'red' : 'green'}>
{getStatusLabel(tenantStatus, record.status)}
</Tag>
),
},
{
title: '颜色类型',
dataIndex: 'colorType',
width: 80,
},
{
title: 'CSS Class',
dataIndex: 'cssClass',
width: 120,
},
{
title: '备注',
dataIndex: 'remark',
width: 120,
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateRange',
search: {
transform: (value) => {
return {
'createTime[0]': dayjs(value[0])
.startOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
'createTime[1]': dayjs(value[1])
.endOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
};
},
},
render: (_, record: DictDataVO) =>
dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss'),
},
];
export const formColumns = (_type: string): ProFormColumnsType[] => [
{
title: '字典类型',
dataIndex: 'dictType',
fieldProps: {
disabled: true,
},
},
{
title: '字典标签',
dataIndex: 'label',
formItemProps: {
rules: [
{
required: true,
message: '请输入字典标签',
},
],
},
},
{
title: '字典键值',
dataIndex: 'value',
formItemProps: {
rules: [
{
required: true,
message: '请输入字典键值',
},
],
},
},
{
title: '显示排序',
dataIndex: 'sort',
valueType: 'digit',
fieldProps: {
min: 0,
max: 9999,
},
formItemProps: {
rules: [
{
required: true,
message: '请输入排序',
},
],
},
},
{
title: '状态',
dataIndex: 'status',
valueType: 'select',
fieldProps: {
options: [
{
label: '启用',
value: 1,
},
{
label: '禁用',
value: 0,
},
],
},
formItemProps: {
rules: [
{
required: true,
},
],
},
},
{
title: '颜色类型',
dataIndex: 'colorType',
valueType: 'select',
fieldProps: {
options: [
{
label: '默认(waiting)',
value: 'waiting',
},
{
label: '成功(success)',
value: 'success',
},
{
label: '信息(processing)',
value: 'processing',
},
{
label: '失败(error)',
value: 'error',
},
{
label: '警告(warning)',
value: 'warning',
},
],
},
},
{
title: 'CSS Class',
dataIndex: 'cssClass',
},
{
title: '备注',
dataIndex: 'remark',
},
];

View File

@@ -0,0 +1,139 @@
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { useParams } from '@umijs/max';
import { Popconfirm } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import {
createDictData,
type DictDataVO,
deleteDictData,
getDictDataPage,
updateDictData,
} from '@/services/system/dict/dict.data';
import { baseDictDataColumns, formColumns } from './config';
const SyStemDictData = () => {
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const tableRef = useRef<ActionType>(null);
const [type, setType] = useState<'create' | 'update'>('create');
const [id, setId] = useState<number>(0);
const routerParams = useParams();
console.log(routerParams);
const handleEdit = (record: DictDataVO) => {
setType('update');
setId(record.id);
configurableDrawerRef.current?.open(record);
};
const onFetch = async (params: { pageSize?: number; current?: number }) => {
const data = await getDictDataPage({
...params,
dictType: routerParams.type,
pageNo: params.current,
pageSize: params.pageSize,
});
return {
data: data.list,
success: true,
total: data.total,
};
};
const handleAdd = () => {
setType('create');
configurableDrawerRef.current?.open({
dictType: routerParams.type,
});
};
const handleSubmit = useCallback(
async (values: DictDataVO) => {
if (type === 'create') {
await createDictData(values);
} else {
await updateDictData({
...values,
id,
});
}
tableRef.current?.reload();
return true;
},
[type, id],
);
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '新建',
type: 'primary',
icon: <PlusOutlined />,
onClick: handleAdd,
},
];
const actionColumns: ProColumns<DictDataVO> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
render: (
_text: React.ReactNode,
record: DictDataVO,
_: any,
action: any,
) => [
<a key="editable" onClick={() => handleEdit(record)}>
</a>,
<Popconfirm
title="是否删除?"
key="delete"
onConfirm={async () => {
await deleteDictData(record.id);
action?.reload();
}}
okText="是"
cancelText="否"
>
<a></a>
</Popconfirm>,
],
};
const columns = [...baseDictDataColumns, actionColumns];
return (
<>
<EnhancedProTable<DictDataVO>
ref={tableRef}
columns={columns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="租户列表"
showIndex={false}
showSelection={false}
/>
<ConfigurableDrawerForm
ref={configurableDrawerRef}
title={formStatusType[type]}
columns={formColumns(type)}
onSubmit={handleSubmit}
/>
</>
);
};
export default SyStemDictData;

View File

@@ -1,5 +1,144 @@
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Popconfirm } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import {
createDictType,
type DictTypeVO,
deleteDictType,
getDictTypePage,
updateDictType,
} from '@/services/system/dict/dict.type';
import { baseDictTypeColumns, formColumns } from './config';
const SyStemDict = () => {
return <>SyStemDict</>;
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const tableRef = useRef<ActionType>(null);
const [type, setType] = useState<'create' | 'update'>('create');
const [id, setId] = useState<number>(0);
//获取路由数据
const handleEdit = (record: DictTypeVO) => {
setType('update');
setId(record.id);
configurableDrawerRef.current?.open(record);
};
const onFetch = async (params: { pageSize?: number; current?: number }) => {
const data = await getDictTypePage({
...params,
pageNo: params.current,
pageSize: params.pageSize,
});
return {
data: data.list,
success: true,
total: data.total,
};
};
const handleAdd = () => {
setType('create');
configurableDrawerRef.current?.open({});
};
const handleSubmit = useCallback(
async (values: DictTypeVO) => {
if (type === 'create') {
await createDictType(values);
} else {
await updateDictType({
...values,
id,
});
}
tableRef.current?.reload();
return true;
},
[type, id],
);
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '新建',
type: 'primary',
icon: <PlusOutlined />,
onClick: handleAdd,
},
];
const actionColumns: ProColumns<DictTypeVO> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
render: (
_text: React.ReactNode,
record: DictTypeVO,
_: any,
action: any,
) => [
<a key="editable" onClick={() => handleEdit(record)}>
</a>,
<Popconfirm
title="是否删除?"
key="delete"
onConfirm={async () => {
await deleteDictType(record.id);
action?.reload();
}}
okText="是"
cancelText="否"
>
<a></a>
</Popconfirm>,
<a
key="data"
onClick={() =>
history.push({
pathname: '/system/dict/data/' + record.type,
})
}
>
</a>,
],
};
const columns = [...baseDictTypeColumns, actionColumns];
return (
<>
<EnhancedProTable<DictTypeVO>
ref={tableRef}
columns={columns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="租户列表"
showIndex={false}
showSelection={false}
/>
<ConfigurableDrawerForm
ref={configurableDrawerRef}
title={formStatusType[type]}
columns={formColumns(type)}
onSubmit={handleSubmit}
/>
</>
);
};
export default SyStemDict;

View File

@@ -0,0 +1,350 @@
// src/pages/system/menu/config.tsx
import {
type ProColumns,
type ProFormColumnsType,
ProFormRadio,
ProFormText,
} from '@ant-design/pro-components';
import { Switch } from 'antd';
import { getSimpleMenusList, type MenuVO } from '@/services/system/menu';
import { handleTree } from '@/utils/tree';
export const baseMenuColumns: ProColumns<MenuVO>[] = [
{
title: '菜单名称',
dataIndex: 'name',
width: 150,
},
{
title: '图标',
dataIndex: 'icon',
width: 60,
hideInSearch: true,
render: (_, record: MenuVO) => (
<span>
{record.icon ? <i className={`anticon ${record.icon}`} /> : '—'}
</span>
),
},
{
title: '排序',
dataIndex: 'sort',
width: 80,
hideInSearch: true,
},
{
title: '权限标识',
dataIndex: 'permission',
width: 150,
hideInSearch: true,
},
{
title: '组件路径',
dataIndex: 'component',
width: 150,
hideInSearch: true,
},
{
title: '组件名称',
dataIndex: 'componentName',
width: 150,
hideInSearch: true,
},
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (_, record: MenuVO) => (
<Switch
checked={record.status === 1}
disabled={true} // 可后续改为可编辑
/>
),
},
];
export const formColumns = (_type: string): ProFormColumnsType[] => [
{
title: '上级菜单',
dataIndex: 'parentId',
valueType: 'treeSelect',
request: async () => {
const res = await getSimpleMenusList();
console.log(res);
const menu: Tree = { id: 0, name: '主类目', children: [] };
menu.children = handleTree(res);
return [menu];
},
fieldProps: {
fieldNames: { label: 'name', value: 'id', children: 'children' },
placeholder: '请选择上级菜单',
},
},
{
title: '菜单名称',
dataIndex: 'name',
formItemProps: {
rules: [
{
required: true,
message: '请输入菜单名称',
},
],
},
},
{
title: '菜单类型',
dataIndex: 'type',
valueType: 'radioButton',
fieldProps: {
placeholder: '请选择菜单类型',
options: [
{ label: '目录', value: 1 },
{ label: '菜单', value: 2 },
{ label: '按钮', value: 3 },
],
},
formItemProps: {
rules: [
{
required: true,
message: '请输入菜单类型',
},
],
},
},
{
title: '菜单图标',
dataIndex: 'icon',
fieldProps: {
placeholder: '请选择图标',
},
dependencies: ['type'],
renderFormItem: (_schema, _config, form) => {
const type = form.getFieldValue('type');
if (type === 3) return null;
return (
<ProFormText
formItemProps={{
style: {
marginBottom: 0,
},
}}
/>
);
},
},
{
title: '路由地址',
dataIndex: 'path',
tooltip:
'访问的路由地址,如:`user`。如需外网地址时,则以 `http(s)://` 开头',
fieldProps: {
placeholder: '请输入路由地址',
},
formItemProps: {
rules: [
{
required: true,
message: '请输入菜单路径',
},
],
},
dependencies: ['type'],
renderFormItem: (_schema, _config, form) => {
const type = form.getFieldValue('type');
if (type === 3) return null;
return (
<ProFormText
formItemProps={{
style: {
marginBottom: 0,
},
}}
/>
);
},
},
{
title: '组件地址',
dataIndex: 'component',
fieldProps: {
placeholder: '请输入组件地址',
},
formItemProps: {
rules: [
{
required: true,
message: '请输入组件地址',
},
],
},
dependencies: ['type'],
renderFormItem: (_schema, _config, form) => {
const type = form.getFieldValue('type');
if (type !== 2) return null;
return (
<ProFormText
formItemProps={{
style: {
marginBottom: 0,
},
}}
/>
);
},
},
{
title: '组件名称',
dataIndex: 'componentName',
fieldProps: {
placeholder: '请输入组件名称',
},
dependencies: ['type'],
renderFormItem: (_schema, _config, form) => {
const type = form.getFieldValue('type');
if (type !== 2) return null;
return (
<ProFormText
formItemProps={{
style: {
marginBottom: 0,
},
}}
/>
);
},
},
{
title: '权限标识',
dataIndex: 'permission',
tooltip:
"Controller 方法上的权限字符,如:@PreAuthorize(`@ss.hasPermission('system:user:list')`)",
fieldProps: {
placeholder: '请输入权限标识',
},
dependencies: ['type'],
renderFormItem: (_schema, _config, form) => {
const type = form.getFieldValue('type');
if (type === 1) return null;
return (
<ProFormText
formItemProps={{
style: {
marginBottom: 0,
},
}}
/>
);
},
},
{
title: '显示排序',
dataIndex: 'sort',
valueType: 'digit',
fieldProps: {
style: {
width: '100%',
},
placeholder: '请输入排序值',
},
formItemProps: {
rules: [
{
required: true,
message: '请输入排序值',
},
],
},
},
{
title: '菜单状态',
dataIndex: 'status',
valueType: 'radio',
fieldProps: {
options: [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
],
},
},
{
title: '显示状态',
dataIndex: 'visible',
valueType: 'radio',
tooltip: '选择隐藏时,路由将不会出现在侧边栏,但仍然可以访问',
fieldProps: {
options: [
{ label: '显示', value: true },
{ label: '隐藏', value: false },
],
},
dependencies: ['type'],
renderFormItem: (_schema, _config, form) => {
const type = form.getFieldValue('type');
if (type === 3) return null;
return (
<ProFormRadio.Group
formItemProps={{
style: {
marginBottom: 0,
},
}}
/>
);
},
},
{
title: '总是显示',
dataIndex: 'alwaysShow',
valueType: 'radio',
tooltip: '选择不是时,当该菜单只有一个子菜单时,不展示自己,直接展示子菜单',
fieldProps: {
options: [
{ label: '总是', value: true },
{ label: '不是', value: false },
],
},
dependencies: ['type'],
renderFormItem: (_schema, _config, form) => {
const type = form.getFieldValue('type');
if (type === 3) return null;
return (
<ProFormRadio.Group
formItemProps={{
style: {
marginBottom: 0,
},
}}
/>
);
},
},
{
dataIndex: 'keepAlive',
title: '缓存状态',
valueType: 'radio',
tooltip: '选择缓存时,则会被 `keep-alive` 缓存,必须填写「组件名称」字段',
fieldProps: {
options: [
{ label: '总是', value: true },
{ label: '不是', value: false },
],
},
dependencies: ['type'],
renderFormItem: (_schema, _config, form) => {
const type = form.getFieldValue('type');
if (type === 3) return null;
return (
<ProFormRadio.Group
formItemProps={{
style: {
marginBottom: 0,
},
}}
/>
);
},
},
];

View File

@@ -1,5 +1,150 @@
const SyStemMenu = () => {
return <>SyStemMenu</>;
// src/pages/system/menu/index.tsx
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Modal, Popconfirm } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import { useMessage } from '@/hooks/antd/useMessage';
import { CACHE_KEY, useCache } from '@/hooks/web/useCache';
import {
createMenu,
deleteMenu,
getMenuList,
type MenuReqVO,
type MenuVO,
updateMenu,
} from '@/services/system/menu';
import { handleTree } from '@/utils/tree';
import { baseMenuColumns, formColumns } from './config';
const SystemMenu = () => {
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const tableRef = useRef<ActionType>(null);
const { wsCache } = useCache();
const message = useMessage(); // 消息弹窗
const [type, setType] = useState<'create' | 'update'>('create');
const [id, setId] = useState<number>(0);
const { initialState, setInitialState } = useModel('@@initialState');
const handleEdit = (record: MenuVO) => {
setType('update');
setId(record.id);
configurableDrawerRef.current?.open(record);
};
const onFetch = async (params: MenuReqVO) => {
const data = await getMenuList({
...params,
});
return {
data: handleTree(data),
success: true,
total: data.total,
};
};
const handleAdd = () => {
setType('create');
configurableDrawerRef.current?.open({ type: 1 });
};
const handleReload = async () => {
try {
await message.confirm('即将更新缓存刷新浏览器!', '刷新菜单缓存');
// 清空,从而触发刷新
// wsCache.delete(CACHE_KEY.USER);
// wsCache.delete(CACHE_KEY.ROLE_ROUTERS);
await initialState?.fetchUserInfo?.();
// 刷新浏览器
location.reload();
} catch {}
};
const handleSubmit = useCallback(
async (values: MenuVO) => {
if (type === 'create') {
await createMenu(values);
} else {
await updateMenu({
...values,
id,
});
}
tableRef.current?.reload();
return true;
},
[type, id],
);
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '新建',
type: 'primary',
icon: <PlusOutlined />,
onClick: handleAdd,
},
{
key: 'reload',
label: '刷新菜单缓存',
type: 'primary',
icon: <ReloadOutlined />,
onClick: handleReload,
},
];
const actionColumns: ProColumns<MenuVO> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
render: (_text: React.ReactNode, record: MenuVO, _: any, action: any) => [
<a key="editable" onClick={() => handleEdit(record)}>
</a>,
<Popconfirm
title="是否删除?"
key="delete"
onConfirm={async () => {
await deleteMenu(record.id);
action?.reload();
}}
okText="是"
cancelText="否"
>
<a></a>
</Popconfirm>,
],
};
const columns = [...baseMenuColumns, actionColumns];
return (
<>
<EnhancedProTable<MenuVO>
ref={tableRef}
columns={columns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="菜单管理"
showIndex={false}
showSelection={false}
/>
<ConfigurableDrawerForm
ref={configurableDrawerRef}
title={formStatusType[type]}
columns={formColumns(type)}
onSubmit={handleSubmit}
width={900}
/>
</>
);
};
export default SyStemMenu;
export default SystemMenu;

View File

@@ -1,6 +1,5 @@
import type {
ProColumns,
ProDescriptionsItemProps,
ProFormColumnsType,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';
@@ -160,7 +159,7 @@ export const formColumns = (): ProFormColumnsType[] => [
},
];
export const formTestColumns = (type: string): ProFormColumnsType[] => [
export const formTestColumns = (): ProFormColumnsType[] => [
{
title: '模板内容',
dataIndex: 'content',

View File

@@ -15,18 +15,17 @@ import { formStatusType } from '@/constants';
import {
createMailAccount,
deleteMailAccount,
getMailAccount,
getMailAccountPage,
type MailAccountVO,
updateMailAccount,
} from '@/services/system/message/mail/account';
import { baseTenantColumns, formColumns, formTestColumns } from './config';
import { baseTenantColumns, formColumns } from './config';
const SyStemMessageSmsTemplate = () => {
const tableRef = useRef<ActionType>(null);
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const [type, setType] = useState<'create' | 'update' | 'test'>('create');
const testRef = useRef<ConfigurableDrawerFormRef>(null);
// const testRef = useRef<ConfigurableDrawerFormRef>(null);
const [currentItem, setCurrentItem] = useState<MailAccountVO>();
const onFetch = async (
params: MailAccountVO & {
@@ -46,11 +45,11 @@ const SyStemMessageSmsTemplate = () => {
};
};
const handleSend = async (record: MailAccountVO) => {
setType('test');
setCurrentItem(record);
testRef.current?.open(record);
};
// const handleSend = async (record: MailAccountVO) => {
// setType("test");
// setCurrentItem(record);
// testRef.current?.open(record);
// };
const handleEdit = (record: MailAccountVO) => {
setType('update');
@@ -68,10 +67,10 @@ const SyStemMessageSmsTemplate = () => {
if (type === 'create') {
await createMailAccount(values);
message.success('创建成功');
} else {
} else if (currentItem?.id) {
await updateMailAccount({
...values,
id: currentItem!.id,
id: currentItem.id,
});
message.success('编辑成功');
}
@@ -97,7 +96,7 @@ const SyStemMessageSmsTemplate = () => {
fixed: 'right',
width: 120,
render: (
text: React.ReactNode,
_text: React.ReactNode,
record: MailAccountVO,
_: number,
action: ProCoreActionType | undefined,

View File

@@ -0,0 +1,121 @@
import type {
ProColumns,
ProFormColumnsType,
} from '@ant-design/pro-components';
import { Tag } from 'antd';
import dayjs from 'dayjs';
import { tenantStatus } from '@/constants';
import type { PostVO } from '@/services/system/post';
import { getStatusLabel } from '@/utils/constant';
export const basePostColumns: ProColumns<PostVO>[] = [
{
title: '岗位编号',
dataIndex: 'id',
width: 80,
},
{
title: '岗位名称',
dataIndex: 'name',
width: 120,
},
{
title: '岗位编码',
dataIndex: 'code',
width: 120,
},
{
title: '岗位顺序',
dataIndex: 'sort',
width: 80,
},
{
title: '岗位备注',
dataIndex: 'remark',
width: 120,
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (_, record: PostVO) => [
<Tag
key={record.status}
color={record.status === 1 ? 'default' : 'processing'}
>
{getStatusLabel(tenantStatus, record.status)}
</Tag>,
],
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateRange',
search: {
transform: (value) => {
return {
'createTime[0]': dayjs(value[0])
.startOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
'createTime[1]': dayjs(value[1])
.endOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
};
},
},
render: (_, record: PostVO) =>
dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss'),
},
];
export const formColumns = (_type: string): ProFormColumnsType[] => [
{
title: '岗位名称',
dataIndex: 'name',
formItemProps: {
rules: [
{
required: true,
message: '请输入岗位名称',
},
],
},
},
{
title: '岗位编码',
dataIndex: 'code',
formItemProps: {
rules: [
{
required: true,
message: '请输入岗位编码',
},
],
},
},
{
title: '岗位顺序',
dataIndex: 'sort',
valueType: 'digit',
fieldProps: {
placeholder: '请输入排序值',
},
},
{
title: '状态',
dataIndex: 'status',
valueType: 'select',
fieldProps: {
placeholder: '请选择状态',
options: tenantStatus,
},
},
{
title: '备注',
dataIndex: 'remark',
valueType: 'textarea',
fieldProps: {
placeholder: '请输入备注',
},
},
];

View File

@@ -1,5 +1,132 @@
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Popconfirm } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import {
createPost,
deletePost,
getPostPage,
type PostReqVO,
type PostVO,
updatePost,
} from '@/services/system/post';
import { basePostColumns, formColumns } from './config';
const SyStemPost = () => {
return <>SyStemPost</>;
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const tableRef = useRef<ActionType>(null);
const [type, setType] = useState<'create' | 'update'>('create');
const [id, setId] = useState<number>(0);
const handleEdit = (record: PostVO) => {
setType('update');
setId(record.id);
configurableDrawerRef.current?.open(record);
};
const onFetch = async (
params: PostReqVO & {
pageSize?: number;
current?: number;
},
) => {
const data = await getPostPage({
...params,
pageNo: params.current,
pageSize: params.pageSize,
});
return {
data: data.list,
success: true,
total: data.total,
};
};
const handleAdd = () => {
setType('create');
configurableDrawerRef.current?.open({});
};
const handleSubmit = useCallback(
async (values: PostVO) => {
if (type === 'create') {
await createPost(values);
} else {
await updatePost({
...values,
id,
});
}
tableRef.current?.reload();
return true;
},
[type, id],
);
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '新建',
type: 'primary',
icon: <PlusOutlined />,
onClick: handleAdd,
},
];
const actionColumns: ProColumns<PostVO> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
render: (_text: React.ReactNode, record: PostVO, _: any, action: any) => [
<a key="editable" onClick={() => handleEdit(record)}>
</a>,
<Popconfirm
title="是否删除?"
key="delete"
onConfirm={async () => {
await deletePost(record.id);
action?.reload();
}}
okText="是"
cancelText="否"
>
<a></a>
</Popconfirm>,
],
};
const columns = [...basePostColumns, actionColumns];
return (
<>
<EnhancedProTable<PostVO>
ref={tableRef}
columns={columns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="租户列表"
showIndex={false}
showSelection={false}
/>
<ConfigurableDrawerForm
ref={configurableDrawerRef}
title={formStatusType[type]}
columns={formColumns(type)}
onSubmit={handleSubmit}
/>
</>
);
};
export default SyStemPost;

View File

@@ -0,0 +1,143 @@
import type {
ProColumns,
ProFormColumnsType,
} from '@ant-design/pro-components';
import { Tag } from 'antd';
import dayjs from 'dayjs';
import { tenantStatus } from '@/constants';
import type { RoleVO } from '@/services/system/role';
import { getStatusLabel } from '@/utils/constant';
export const baseTenantColumns: ProColumns<RoleVO>[] = [
{
title: '角色编号',
dataIndex: 'id',
width: 100,
hideInSearch: true, // 在搜索表单中隐藏
},
{
title: '角色名称',
dataIndex: 'name',
width: 100,
},
{
title: '角色类型',
dataIndex: 'type',
width: 100,
render: (_, record: RoleVO) => [
<Tag key={record.type} color={record.type === 1 ? 'error' : 'processing'}>
{record.type === 1 ? '内置' : '自定义'}
</Tag>,
],
hideInSearch: true,
},
{
title: '角色标识',
dataIndex: 'code',
width: 150,
render: (_, record: RoleVO) => [
<Tag key={record.code} color={record.type === 1 ? 'error' : 'processing'}>
{record.code}
</Tag>,
],
hideInSearch: true,
},
{
title: '显示顺序',
dataIndex: 'sort',
width: 100,
hideInSearch: true,
},
{
title: '备注',
dataIndex: 'remark',
hideInSearch: true, // 在搜索表单中隐藏
},
{
title: '租户状态',
dataIndex: 'status',
width: 100,
render: (_, record: RoleVO) => [
<Tag
key={record.status}
color={record.status === 1 ? 'default' : 'processing'}
>
{getStatusLabel(tenantStatus, record.status)}
</Tag>,
],
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateRange',
search: {
transform: (value) => {
return {
'createTime[0]': dayjs(value[0])
.startOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
'createTime[1]': dayjs(value[1])
.endOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
};
},
},
render: (_, record: RoleVO) =>
dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss'),
},
];
export const formColumns = (_type: string): ProFormColumnsType[] => [
{
title: '角色名称',
dataIndex: 'name',
formItemProps: {
rules: [
{
required: true,
message: '请输入角色名称',
},
],
},
},
{
title: '角色标识',
dataIndex: 'code',
formItemProps: {
rules: [
{
required: true,
message: '请输入角色名称',
},
],
},
},
{
title: '显示顺序',
dataIndex: 'sort',
valueType: 'digit',
fieldProps: {
placeholder: '请输入显示顺序',
},
},
{
title: '租户状态',
dataIndex: 'status',
valueType: 'select',
fieldProps: {
multiple: true,
placeholder: '请选择租户状态',
options: tenantStatus,
},
},
{
title: '备注',
dataIndex: 'remark',
valueType: 'textarea',
fieldProps: {
placeholder: '请输入备注',
min: 5,
max: 20,
},
},
];

View File

@@ -1,5 +1,132 @@
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Popconfirm } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import {
createRole,
deleteRole,
getRolePage,
type RolePageReqVO,
type RoleVO,
updateRole,
} from '@/services/system/role';
import { baseTenantColumns, formColumns } from './config';
const SyStemRole = () => {
return <>SyStemRole</>;
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const tableRef = useRef<ActionType>(null);
const [type, setType] = useState<'create' | 'update'>('create');
const [id, setId] = useState<number>(0);
const handleEdit = (record: RoleVO) => {
setType('update');
setId(record.id);
configurableDrawerRef.current?.open(record);
};
const onFetch = async (
params: RolePageReqVO & {
pageSize?: number;
current?: number;
},
) => {
const data = await getRolePage({
...params,
pageNo: params.current,
pageSize: params.pageSize,
});
return {
data: data.list,
success: true,
total: data.total,
};
};
const handleAdd = () => {
setType('create');
configurableDrawerRef.current?.open({});
};
const handleSubmit = useCallback(
async (values: RoleVO) => {
if (type === 'create') {
await createRole(values);
} else {
await updateRole({
...values,
id,
});
}
tableRef.current?.reload();
return true;
},
[type, id],
);
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '新建',
type: 'primary',
icon: <PlusOutlined />,
onClick: handleAdd,
},
];
const actionColumns: ProColumns<RoleVO> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
render: (_text: React.ReactNode, record: RoleVO, _: any, action: any) => [
<a key="editable" onClick={() => handleEdit(record)}>
</a>,
<Popconfirm
title="是否删除?"
key="delete"
onConfirm={async () => {
await deleteRole(record.id);
action?.reload();
}}
okText="是"
cancelText="否"
>
<a></a>
</Popconfirm>,
],
};
const columns = [...baseTenantColumns, actionColumns];
return (
<>
<EnhancedProTable<RoleVO>
ref={tableRef}
columns={columns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="租户列表"
showIndex={false}
showSelection={false}
/>
<ConfigurableDrawerForm
ref={configurableDrawerRef}
title={formStatusType[type]}
columns={formColumns(type)}
onSubmit={handleSubmit}
/>
</>
);
};
export default SyStemRole;

View File

@@ -29,7 +29,6 @@ export const baseTenantColumns: ProColumns<TenantVO>[] = [
request: async () => {
const packageList: { id: number; name: string }[] =
await getTenantPackageList();
console.log(packageList);
packageList.map((item) => ({ label: item.name, value: item.id }));
return packageList.map((item) => ({ label: item.name, value: item.id }));
},
@@ -83,7 +82,14 @@ export const baseTenantColumns: ProColumns<TenantVO>[] = [
valueType: 'dateRange',
search: {
transform: (value) => {
return [`${value[0]} 00:00:00`, `${value[1]} 00:00:00`];
return {
'createTime[0]': dayjs(value[0])
.startOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
'createTime[1]': dayjs(value[1])
.endOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
};
},
},
render: (_, record: TenantVO) =>

View File

@@ -1,8 +1,7 @@
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Modal, Popconfirm } from 'antd';
import { Popconfirm } from 'antd';
import dayjs from 'dayjs';
import { ref } from 'process';
import React, { createContext, useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
@@ -93,7 +92,7 @@ const TenantList = () => {
valueType: 'option',
fixed: 'right',
width: 120,
render: (text: React.ReactNode, record: TenantVO, _: any, action: any) => [
render: (_text: React.ReactNode, record: TenantVO, _: any, action: any) => [
<a key="editable" onClick={() => handleEdit(record)}>
</a>,
@@ -122,8 +121,6 @@ const TenantList = () => {
headerTitle="租户列表"
showIndex={false}
showSelection={false}
showActions
maxActionCount={3}
/>
<ConfigurableDrawerForm

View File

@@ -0,0 +1,109 @@
import type {
ProColumns,
ProFormColumnsType,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';
import type { TenantPackageVO } from '@/services/system/tenant/package';
export const baseTenantColumns: ProColumns<TenantPackageVO>[] = [
{
title: '套餐编号',
dataIndex: 'id',
width: 100,
hideInSearch: true, // 在搜索表单中隐藏
},
{
title: '套餐名',
dataIndex: 'name',
},
{
title: '状态',
dataIndex: 'status',
valueType: 'select',
valueEnum: {
all: { text: '全部', status: 'Default' },
open: { text: '未解决', status: 'Error' },
closed: { text: '已解决', status: 'Success' },
},
},
{
title: '备注',
dataIndex: 'remark',
hideInSearch: true, // 在搜索表单中隐藏
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateRange',
search: {
transform: (value) => {
return {
'createTime[0]': dayjs(value[0])
.startOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
'createTime[1]': dayjs(value[1])
.endOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
};
},
},
render: (_, record: TenantPackageVO) =>
dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss'),
},
];
export const formColumns = (_type: string): ProFormColumnsType[] => [
{
title: '套餐名',
dataIndex: 'name',
formItemProps: {
rules: [
{
required: true,
message: '请输入用户名',
},
],
},
},
{
title: '套餐权限',
dataIndex: 'menuIds',
valueType: 'treeSelect',
fieldProps: {
multiple: true,
placeholder: '请选择租户权限',
options: [{ lable: '11', value: 5016 }],
},
},
{
title: '租户状态',
dataIndex: 'status',
valueType: 'radio',
formItemProps: {
rules: [
{
required: true,
message: '请选择租户状态',
},
],
},
fieldProps: {
placeholder: '请选择套餐类型',
options: [
{
label: '开启',
value: 1,
},
{
label: '关闭',
value: 0,
},
],
},
},
{
title: '备注',
dataIndex: 'remark',
valueType: 'textarea',
},
];

View File

@@ -1,5 +1,137 @@
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Popconfirm } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import {
createTenantPackage,
deleteTenantPackage,
getTenantPackagePage,
type TenantPackagePageReqVO,
type TenantPackageVO,
updateTenantPackage,
} from '@/services/system/tenant/package';
import { baseTenantColumns, formColumns } from './config';
const TenantPackage = () => {
return <div>TenantPackage</div>;
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const tableRef = useRef<ActionType>(null);
const [type, setType] = useState<'create' | 'update'>('create');
const [id, setId] = useState<number>(0);
const handleEdit = (record: TenantPackageVO) => {
setType('update');
setId(record.id);
configurableDrawerRef.current?.open(record);
};
const onFetch = async (
params: TenantPackagePageReqVO & {
pageSize?: number;
current?: number;
},
) => {
const data = await getTenantPackagePage({
...params,
pageNo: params.current,
pageSize: params.pageSize,
});
return {
data: data.list,
success: true,
total: data.total,
};
};
const handleAdd = () => {
setType('create');
configurableDrawerRef.current?.open({});
};
const handleSubmit = useCallback(
async (values: TenantPackageVO) => {
if (type === 'create') {
await createTenantPackage(values);
} else {
await updateTenantPackage({
...values,
id,
});
}
tableRef.current?.reload();
return true;
},
[type, id],
);
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '新建',
type: 'primary',
icon: <PlusOutlined />,
onClick: handleAdd,
},
];
const actionColumns: ProColumns<TenantPackageVO> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
render: (
_text: React.ReactNode,
record: TenantPackageVO,
_: any,
action: any,
) => [
<a key="editable" onClick={() => handleEdit(record)}>
</a>,
<Popconfirm
title="是否删除?"
key="delete"
onConfirm={async () => {
await deleteTenantPackage(record.id);
action?.reload();
}}
okText="是"
cancelText="否"
>
<a></a>
</Popconfirm>,
],
};
const columns = [...baseTenantColumns, actionColumns];
return (
<>
<EnhancedProTable<TenantPackageVO>
ref={tableRef}
columns={columns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="租户列表"
showIndex={false}
showSelection={false}
/>
<ConfigurableDrawerForm
ref={configurableDrawerRef}
title={formStatusType[type]}
columns={formColumns(type)}
onSubmit={handleSubmit}
/>
</>
);
};
export default TenantPackage;

View File

@@ -0,0 +1,220 @@
import type {
ProColumns,
ProCoreActionType,
ProFormColumnsType,
} from '@ant-design/pro-components';
import { Modal, message, Switch } from 'antd';
import dayjs from 'dayjs';
import { updateUserStatus } from '@/services/system/user';
import type { UserVO } from '@/services/system/user/index';
export const baseTenantColumns: ProColumns<UserVO>[] = [
{
title: '用户编号',
dataIndex: 'id',
width: 80,
hideInSearch: true, // 在搜索表单中隐藏
},
{
title: '用户名称',
dataIndex: 'username',
width: 100,
},
{
title: '用户昵称',
dataIndex: 'nickname',
width: 100,
hideInSearch: true,
},
{
title: '部门',
dataIndex: 'deptName',
width: 100,
},
{
title: '手机号码',
dataIndex: 'mobile',
width: 100,
},
{
title: '状态',
dataIndex: 'status',
valueType: 'select',
valueEnum: {
all: { text: '全部', status: 'Default' },
open: { text: '未解决', status: 'Error' },
closed: { text: '已解决', status: 'Success' },
},
render: (
_dom: React.ReactNode,
record: UserVO,
_index: number,
action: ProCoreActionType | undefined,
) => [
<Switch
key={record.id}
checked={record.status === 0}
onChange={async (_checked) => {
const text = record.status ? '启用' : '停用';
Modal.confirm({
title: '确认操作',
content: `确认要"${text}""${record.username}"用户吗?`,
onOk: async () => {
const status = record.status === 0 ? 1 : 0;
await updateUserStatus(record.id, status);
message.success('修改成功');
action?.reload();
// 执行状态变更逻辑
},
});
// await message.confirm("修改成功");
}}
></Switch>,
],
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateRange',
search: {
transform: (value) => {
return {
'createTime[0]': dayjs(value[0])
.startOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
'createTime[1]': dayjs(value[1])
.endOf('day')
.format('YYYY-MM-DD HH:mm:ss'),
};
},
},
render: (_, record: UserVO) =>
dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss'),
},
{
title: '备注',
dataIndex: 'remark',
hideInSearch: true, // 在搜索表单中隐藏
},
];
export const formColumns = (type: string): ProFormColumnsType[] => [
{
title: '用户昵称',
dataIndex: 'nickname',
formItemProps: {
rules: [
{
required: true,
message: '请输入用户名',
},
],
},
},
{
title: '归属部门',
dataIndex: 'deptId',
valueType: 'treeSelect',
fieldProps: {
multiple: true,
placeholder: '请选择归属部门',
options: [{ lable: '11', value: 5016 }],
},
},
{
title: '手机号码',
dataIndex: 'mobile',
formItemProps: {
rules: [
{
required: true,
message: '请输入联系手机',
},
],
},
},
// { prop: "email", label: "邮箱", type: "input", inputType: "email" },
{
title: '邮箱',
dataIndex: 'email',
valueType: 'text',
fieldProps: {
type: 'email',
placeholder: '请输入邮箱',
},
formItemProps: {
rules: [
{
required: true,
message: '请输入邮箱',
},
],
},
},
{
title: '用户名称',
dataIndex: 'username',
hideInForm: type === 'update',
},
{
title: '用户密码',
dataIndex: 'password',
valueType: 'password',
hideInForm: type === 'update',
fieldProps: {
placeholder: '请输入用户密码',
autoComplete: 'new-password',
},
formItemProps: {
rules: [
{
required: true,
message: '请输入用户密码',
},
],
},
},
{
title: '用户性别',
dataIndex: 'sex',
valueType: 'select',
fieldProps: {
placeholder: '请选择性别',
options: [
{
label: '男',
value: 1,
},
{
label: '女',
value: 2,
},
],
},
},
{
title: '岗位',
dataIndex: 'postIds',
valueType: 'select',
fieldProps: {
mode: 'multiple',
placeholder: '请选择岗位',
options: [
{
label: '管理员',
value: 1,
},
{
label: '普通用户',
value: 2,
},
],
},
formItemProps: {},
},
{
title: '备注',
dataIndex: 'remark',
valueType: 'textarea',
},
];

View File

@@ -1,5 +1,130 @@
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Popconfirm } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import ConfigurableDrawerForm, {
type ConfigurableDrawerFormRef,
} from '@/components/DrawerForm';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import { formStatusType } from '@/constants';
import {
createUser,
deleteUser,
getUserPage,
type UserReqVO,
type UserVO,
updateUser,
} from '@/services/system/user';
import { baseTenantColumns, formColumns } from './config';
const SyStemUser = () => {
return <>SyStemUser</>;
const configurableDrawerRef = useRef<ConfigurableDrawerFormRef>(null);
const tableRef = useRef<ActionType>(null);
const [type, setType] = useState<'create' | 'update'>('create');
const [id, setId] = useState<number>(0);
const handleEdit = (record: UserVO) => {
setType('update');
setId(record.id);
configurableDrawerRef.current?.open(record);
};
const onFetch = async (
params: UserReqVO & {
pageSize?: number;
current?: number;
},
) => {
const data = await getUserPage({
...params,
pageNo: params.current,
pageSize: params.pageSize,
});
return {
data: data.list,
success: true,
total: data.total,
};
};
const handleAdd = () => {
setType('create');
configurableDrawerRef.current?.open({});
};
const handleSubmit = useCallback(
async (values: UserVO) => {
if (type === 'create') {
await createUser(values);
} else {
await updateUser({
...values,
id,
});
}
tableRef.current?.reload();
return true;
},
[type, id],
);
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '新建',
type: 'primary',
icon: <PlusOutlined />,
onClick: handleAdd,
},
];
const actionColumns: ProColumns<UserVO> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
fixed: 'right',
width: 120,
render: (_text: React.ReactNode, record: UserVO, _: any, action: any) => [
<a key="editable" onClick={() => handleEdit(record)}>
</a>,
<Popconfirm
title="是否删除?"
key="delete"
onConfirm={async () => {
await deleteUser(record.id);
action?.reload();
}}
okText="是"
cancelText="否"
>
<a></a>
</Popconfirm>,
],
};
const columns = [...baseTenantColumns, actionColumns];
return (
<>
<EnhancedProTable<UserVO>
ref={tableRef}
columns={columns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="租户列表"
showIndex={false}
showSelection={false}
/>
<ConfigurableDrawerForm
ref={configurableDrawerRef}
title={formStatusType[type]}
columns={formColumns(type)}
onSubmit={handleSubmit}
/>
</>
);
};
export default SyStemUser;

View File

@@ -3,25 +3,22 @@
import { request } from "@umijs/max";
/** 获取菜单页面的表 GET /product/category/categoryList */
export async function getProductCategoryCategoryList(
export async function getCategoryList(
// 叠加生成的Param类型 (非body参数swagger默认没有生成对象)
params: API.getProductCategoryCategoryListParams,
options?: { [key: string]: any }
) {
return request<API.CommonResultListCategoryDto>(
"/product/category/categoryList",
{
method: "GET",
params: {
...params,
},
...(options || {}),
}
);
return request("/product/category/categoryList", {
method: "GET",
params: {
...params,
},
...(options || {}),
});
}
/** 创建产品类目 创建产品类目 POST /product/category/create */
export async function postProductCategoryCreate(
export async function postCategoryCreate(
body: API.CategorySaveReqVO,
options?: { [key: string]: any }
) {
@@ -36,7 +33,7 @@ export async function postProductCategoryCreate(
}
/** 更新产品类目 更新产品类目 PUT /product/category/update */
export async function putProductCategoryUpdate(
export async function putCategoryUpdate(
body: API.CategorySaveReqVO,
options?: { [key: string]: any }
) {

View File

@@ -0,0 +1,89 @@
import { request } from "@umijs/max";
export interface DeptVO {
id: number;
name: string;
parentId: number;
status: number;
sort: number;
leaderUserId: number;
phone: string;
email: string;
createTime: Date;
}
export interface DeptReqVO extends PageParam {
name?: string;
status?: number;
}
// 查询部门(精简)列表
// export const getSimpleDeptList = async (): Promise<Dept[]> => {
// return await request.get({ url: "/system/dept/simple-list" });
// };
export const getSimpleDeptList = async () => {
return request("/system/dept/simple-list", {
method: "GET",
});
};
// 查询部门列表
// export const getDeptPage = async (params: DeptReq): Promise<Dept[]> => {
// return await request.get({ url: "/system/dept/list", params });
// };
export const getDeptPage = (params: DeptReqVO) => {
return request("/system/dept/list", {
method: "GET",
params,
});
};
// 查询部门详情
// export const getDept = async (id: number) => {
// return await request.get({ url: "/system/dept/get?id=" + id });
// };
export const getDept = (id: number) => {
return request("/system/dept/get", {
method: "GET",
params: { id },
});
};
// 新增部门
// export const createDept = async (data: Dept) => {
// return await request.post({ url: "/system/dept/create", data: data });
// };
export const createDept = (data: DeptVO) => {
return request("/system/dept/create", {
method: "POST",
data,
});
};
// 修改部门
// export const updateDept = async (params: Dept) => {
// return await request.put({ url: "/system/dept/update", data: params });
// };
export const updateDept = (params: DeptVO) => {
return request("/system/dept/update", {
method: "PUT",
data: params,
});
};
// 删除部门
// export const deleteDept = async (id: number) => {
// return await request.delete({ url: "/system/dept/delete?id=" + id });
// };
export const deleteDept = (id: number) => {
return request("/system/dept/delete", {
method: "DELETE",
params: { id },
});
};

View File

@@ -0,0 +1,101 @@
import { request } from "@umijs/max";
export type DictDataVO = {
id: number;
sort: number | undefined;
label: string;
value: string;
dictType: string;
status: number;
colorType: string;
cssClass: string;
remark: string;
createTime: Date;
};
export interface DictDataReqVO extends PageParam {
dictType?: string;
createTime?: Date;
}
// 查询字典数据(精简)列表
// export const getSimpleDictDataList = () => {
// return request.get({ url: "/system/dict-data/simple-list" });
// };
export const getSimpleDictDataList = () => {
return request("/system/dict-data/simple-list", {
method: "GET",
});
};
// 查询字典数据列表
// export const getDictDataPage = (params: PageParam) => {
// return request.get({ url: "/system/dict-data/page", params });
// };
export const getDictDataPage = (params: DictDataReqVO) => {
return request("/system/dict-data/page", {
method: "GET",
params,
});
};
// 查询字典数据详情
// export const getDictData = (id: number) => {
// return request.get({ url: "/system/dict-data/get?id=" + id });
// };
export const getDictData = (id: number) => {
return request("/system/dict-data/get", {
method: "GET",
params: { id },
});
};
// 新增字典数据
// export const createDictData = (data: DictData) => {
// return request.post({ url: "/system/dict-data/create", data });
// };
export const createDictData = (data: DictDataVO) => {
return request("/system/dict-data/create", {
method: "POST",
data,
});
};
// 修改字典数据
// export const updateDictData = (data: DictData) => {
// return request.put({ url: "/system/dict-data/update", data });
// };
export const updateDictData = (data: DictDataVO) => {
return request("/system/dict-data/update", {
method: "PUT",
data,
});
};
// 删除字典数据
// export const deleteDictData = (id: number) => {
// return request.delete({ url: "/system/dict-data/delete?id=" + id });
// };
export const deleteDictData = (id: number) => {
return request("/system/dict-data/delete", {
method: "DELETE",
params: { id },
});
};
// 导出字典类型数据
// export const exportDictData = (params: DictData) => {
// return request.download({ url: "/system/dict-data/export", params });
// };
export const exportDictData = (params: DictDataVO) => {
return request("/system/dict-data/export", {
method: "GET",
params,
});
};

View File

@@ -0,0 +1,101 @@
import { request } from "@umijs/max";
export interface DictTypeVO extends PageParam {
id: number;
name: string;
type: string;
status: number;
remark: string;
createTime: Date;
}
export interface DictReqVO extends PageParam {
name?: string;
status?: number;
type?: string;
createTime?: Date;
}
// 查询字典(精简)列表
// export const getSimpleDictTypeList = () => {
// return request.get({ url: "/system/dict-type/list-all-simple" });
// };
export const getSimpleDictTypeList = () => {
return request("/system/dict-type/list-all-simple", {
method: "GET",
});
};
// 查询字典列表
// export const getDictTypePage = (
// params: DictReq
// ): Promise<PageResult<DictType[]>> => {
// return request.get({ url: "/system/dict-type/page", params });
// };
export const getDictTypePage = (params: PageParam) => {
return request("/system/dict-type/page", {
method: "GET",
params,
});
};
// // 查询字典详情
// export const getDictType = (id?: number) => {
// return request.get({ url: "/system/dict-type/get?id=" + id });
// };
export const getDictType = (id: number) => {
return request("/system/dict-type/get", {
method: "GET",
params: { id },
});
};
// 新增字典
// export const createDictType = (data: DictType) => {
// return request.post({ url: "/system/dict-type/create", data });
// };
export const createDictType = (data: DictTypeVO) => {
return request("/system/dict-type/create", {
method: "POST",
data,
});
};
// 修改字典
// export const updateDictType = (data: DictType) => {
// return request.put({ url: "/system/dict-type/update", data });
// };
export const updateDictType = (data: DictTypeVO) => {
return request("/system/dict-type/update", {
method: "PUT",
data,
});
};
// 删除字典
// export const deleteDictType = (id: number) => {
// return request.delete({ url: "/system/dict-type/delete?id=" + id });
// };
export const deleteDictType = (id: number) => {
return request("/system/dict-type/delete", {
method: "DELETE",
params: { id },
});
};
// 导出字典类型
// export const exportDictType = (params: DictType) => {
// return request.download({ url: "/system/dict-type/export", params });
// };
export const exportDictType = (params: DictTypeVO) => {
return request("/system/dict-type/export", {
method: "POST",
params,
});
};

View File

@@ -19,32 +19,81 @@ export interface MenuVO {
children?: MenuVO[];
}
export interface MenuReqVO {
name?: string;
status?: 0 | 1;
}
// 查询菜单(精简)列表
export const getSimpleMenusList = () => {
return request("/system/menu/simple-list", {
method: "GET",
});
};
// export const getSimpleMenusList = () => {
// return request.get({ url: '/system/menu/simple-list' })
// }
// // 查询菜单列表
export const getMenuList = (params: MenuReqVO) => {
return request("/system/menu/list", {
method: "GET",
params,
});
};
// export const getMenuList = (params) => {
// return request.get({ url: '/system/menu/list', params })
// }
// // 获取菜单详情
export const getMenu = (id: number) => {
return request("/system/menu/get", {
method: "GET",
params: { id },
});
};
// export const getMenu = (id: number) => {
// return request.get({ url: '/system/menu/get?id=' + id })
// }
// // 新增菜单
export const createMenu = (data: MenuVO) => {
return request("/system/menu/create", {
method: "POST",
data,
});
};
// export const createMenu = (data: MenuVO) => {
// return request.post({ url: '/system/menu/create', data })
// }
// // 修改菜单
export const updateMenu = (data: MenuVO) => {
return request("/system/menu/update", {
method: "PUT",
data,
});
};
// export const updateMenu = (data: MenuVO) => {
// return request.put({ url: '/system/menu/update', data })
// }
// // 删除菜单
export const deleteMenu = (id: number) => {
return request("/system/menu/delete", {
method: "DELETE",
params: { id },
});
};
// export const deleteMenu = (id: number) => {
// return request.delete({ url: '/system/menu/delete?id=' + id })
// }

View File

@@ -0,0 +1,87 @@
import { request } from "@umijs/max";
export interface PostVO {
id: number;
name: string;
code: string;
sort: number;
status: number;
remark: string;
createTime?: Date;
}
export interface PostReqVO extends PageParam {
name?: string;
status?: number;
code?: string;
}
// 查询岗位列表
// export const getPostPage = async (params: PostReq) => {
// return await request.get({ url: "/system/post/page", params });
// };
export const getPostPage = (params: PostReqVO) => {
return request("/system/post/page", {
method: "GET",
params,
});
};
// 获取岗位精简信息列表
// export const getSimplePostList = async (): Promise<Post[]> => {
// return await request.get({ url: "/system/post/simple-list" });
// };
export const getSimplePostList = () => {
return request("/system/post/simple-list", {
method: "GET",
});
};
// 查询岗位详情
// export const getPost = async (id: number) => {
// return await request.get({ url: "/system/post/get?id=" + id });
// };
export const getPost = (id: number) => {
return request("/system/post/get", {
method: "GET",
params: { id },
});
};
// 新增岗位
// export const createPost = async (data: Post) => {
// return await request.post({ url: "/system/post/create", data });
// };
export const createPost = async (data: PostVO) => {
return await request("/system/post/create", {
method: "POST",
data,
});
};
// 修改岗位
// export const updatePost = async (data: Post) => {
// return await request.put({ url: "/system/post/update", data });
// };
export const updatePost = async (data: PostVO) => {
return await request("/system/post/update", {
method: "PUT",
data,
});
};
// 删除岗位
// export const deletePost = async (id: number) => {
// return await request.delete({ url: "/system/post/delete?id=" + id });
// };
export const deletePost = async (id: number) => {
return await request("/system/post/delete", {
method: "DELETE",
params: { id },
});
};

View File

@@ -0,0 +1,106 @@
import { request } from "@umijs/max";
export interface RoleVO {
id: number;
name: string;
code: string;
sort: number;
status: number;
type: number;
dataScope: number;
dataScopeDeptIds: number[];
createTime: Date;
menuIds: number[];
}
export interface RolePageReqVO extends PageParam {
name?: string;
code?: string;
status?: string;
createTime?: Date[];
}
export interface UpdateStatusReq {
id: number;
status: number;
}
// 查询角色列表
export const getRolePage = (params: RolePageReqVO) => {
return request("/system/role/page", {
method: "GET",
params,
});
};
// export const getRolePage = async (
// params: RolePageReq
// ): Promise<PageResult<Role[]>> => {
// return await request.get({ url: "/system/role/page", params });
// };
// 查询角色(精简)列表
export const getSimpleRoleList = () => {
return request("/system/role/simple-list", {
method: "GET",
});
};
// export const getSimpleRoleList = async (): Promise<Role[]> => {
// return await request.get({ url: "/system/role/simple-list" });
// };
// 查询角色详情
export const getRole = (id: number) => {
return request("/system/role/get", {
method: "GET",
params: { id },
});
};
// export const getRole = async (id: number) => {
// return await request.get({ url: "/system/role/get?id=" + id });
// };
// 新增角色
export const createRole = (data: RoleVO) => {
return request("/system/role/create", {
method: "POST",
data,
});
};
// export const createRole = async (data: Role) => {
// return await request.post({ url: "/system/role/create", data });
// };
// 修改角色
// export const updateRole = async (data: Role) => {
// return await request.put({ url: "/system/role/update", data });
// };
export const updateRole = (data: RoleVO) => {
return request("/system/role/update", {
method: "PUT",
data,
});
};
// 修改角色状态
export const updateRoleStatus = (data: UpdateStatusReq) => {
return request("/system/role/update-status", {
method: "PUT",
data,
});
};
// export const updateRoleStatus = async (data: UpdateStatusReq) => {
// return await request.put({ url: "/system/role/update-status", data });
// };
// 删除角色
export const deleteRole = (id: number) => {
return request("/system/role/delete", {
method: "DELETE",
params: { id },
});
};
// export const deleteRole = async (id: number) => {
// return await request.delete({ url: "/system/role/delete?id=" + id });
// };

View File

@@ -12,11 +12,27 @@ export interface TenantPackageVO {
createTime: Date;
}
export interface TenantPackagePageReqVO extends PageParam {
name?: string;
contactName?: string;
contactMobile?: string;
status?: number;
createTime?: Date[];
}
// 查询租户套餐列表
// export const getTenantPackagePage = (params: PageParam) => {
// return request.get({ url: '/system/tenant-package/page', params })
// }
export async function getTenantPackagePage(params: TenantPackagePageReqVO) {
return request("/system/tenant-package/page", {
method: "GET",
params,
});
}
// 获得租户
// export const getTenantPackage = (id: number) => {
// return request.get({ url: '/system/tenant-package/get?id=' + id })

View File

@@ -0,0 +1,154 @@
// import request from "@/config/axios";
import { request } from "@umijs/max";
export interface UserVO {
id: number;
username: string;
nickname: string;
deptId: number;
postIds: string[];
email: string;
mobile: string;
sex: number;
avatar: string;
loginIp: string;
status: number;
remark: string;
loginDate: Date;
createTime: Date;
}
// export interface User {
// id: number;
// username: string;
// nickname: string;
// deptId: number;
// postIds: string[];
// email: string;
// mobile: string;
// sex: number;
// avatar: string;
// loginIp: string;
// status: number;
// remark: string;
// loginDate: Date;
// createTime: Date;
// }
export interface UserReqVO extends PageParam {
username?: string;
status?: number;
mobile?: string;
createTime?: Date;
deptId?: number;
}
// export interface UserReq extends PageParam {
// username?: string;
// status?: number;
// mobile?: string;
// createTime?: Date;
// deptId?: number;
// }
// 查询用户管理列表
export const getUserPage = (params: UserReqVO) => {
return request("/system/user/page", {
method: "GET",
params,
});
};
// export const getUserPage = (params: UserReq) => {
// return request.get({ url: "/system/user/page", params });
// };
// 查询用户详情
export const getUser = (id: number) => {
return request("/system/user/get", {
method: "GET",
params: { id },
});
};
// export const getUser = (id: number) => {
// return request.get({ url: "/system/user/get?id=" + id });
// };
// 新增用户
export const createUser = (data: UserVO) => {
return request("/system/user/create", {
method: "POST",
data,
});
};
// export const createUser = (data: User) => {
// return request.post({ url: "/system/user/create", data });
// };
// 修改用户
export const updateUser = (data: UserVO) => {
return request("/system/user/update", {
method: "PUT",
data,
});
};
// export const updateUser = (data: User) => {
// return request.put({ url: "/system/user/update", data });
// };
// 删除用户
export const deleteUser = (id: number) => {
return request("/system/user/delete", {
method: "DELETE",
params: { id },
});
};
// export const deleteUser = (id: number) => {
// return request.delete({ url: "/system/user/delete?id=" + id });
// };
// 用户密码重置
export const resetUserPassword = (id: number, password: string) => {
return request("/system/user/reset-password", {
method: "PUT",
params: { id, password },
});
};
// export const resetUserPassword = (id: number, password: string) => {
// const data = {
// id,
// password
// };
// return request.put({ url: "/system/user/update-password", data: data });
// };
// 用户状态修改
export const updateUserStatus = (id: number, status: number) => {
return request("/system/user/update-status", {
method: "PUT",
data: { id, status },
});
};
// export const updateUserStatus = (id: number, status: number) => {
// const data = {
// id,
// status
// };
// return request.put({ url: "/system/user/update-status", data: data });
// };
// 获取用户精简信息列表
export const getSimpleUserList = () => {
return request("/system/user/simple-list", {
method: "GET",
});
};
// export const getSimpleUserList = (): Promise<User[]> => {
// return request.get({ url: "/system/user/simple-list" });
// };

5
src/types/constant.ts Normal file
View File

@@ -0,0 +1,5 @@
export type Operations = {
handleSearch?: (evt: MouseEvent) => void;
handleReset?: (evt: MouseEvent) => void;
handleExport?: (evt: MouseEvent) => void;
};

22
src/utils/constant.ts Normal file
View File

@@ -0,0 +1,22 @@
// 创建 value 到 label 的映射
const statusMap = (status: { label: string; value: number }[]) =>
new Map(status?.map((item) => [item.value, item.label]));
const packageMap = (status: { id: number; name: string }[]) =>
new Map(status?.map((item) => [item.id, item.name]));
// 获取 label 的函数
export const getStatusLabel = (
status: { label: string; value: number }[],
value: number,
): string => {
return statusMap(status).get(value) || '';
};
// 获取 label 的函数
export const getpackageLabel = (
status: { id: number; name: string }[],
id: number,
): string => {
return packageMap(status).get(id) || '';
};

451
src/utils/tree.ts Normal file
View File

@@ -0,0 +1,451 @@
interface TreeHelperConfig {
id: string;
children: string;
pid: string;
}
const DEFAULT_CONFIG: TreeHelperConfig = {
id: 'id',
children: 'children',
pid: 'pid',
};
export const defaultProps = {
children: 'children',
label: 'name',
value: 'id',
isLeaf: 'leaf',
emitPath: false, // 用于 cascader 组件:在选中节点改变时,是否返回由该节点所在的各级菜单的值所组成的数组,若设置 false则只返回该节点的值
};
const getConfig = (config: Partial<TreeHelperConfig>) =>
Object.assign({}, DEFAULT_CONFIG, config);
// tree from list
export const listToTree = <T = any>(
list: any[],
config: Partial<TreeHelperConfig> = {},
): T[] => {
const conf = getConfig(config) as TreeHelperConfig;
const nodeMap = new Map();
const result: T[] = [];
const { id, children, pid } = conf;
for (const node of list) {
node[children] = node[children] || [];
nodeMap.set(node[id], node);
}
for (const node of list) {
const parent = nodeMap.get(node[pid]);
(parent ? parent.children : result).push(node);
}
return result;
};
export const treeToList = <T = any>(
tree: any,
config: Partial<TreeHelperConfig> = {},
): T => {
config = getConfig(config);
const { children } = config;
const result: any = [...tree];
for (let i = 0; i < result.length; i++) {
if (!children) return result;
if (!result[i][children]) continue;
result.splice(i + 1, 0, ...result[i][children]);
}
return result;
};
export const findNode = <T = any>(
tree: any,
func: Fn,
config: Partial<TreeHelperConfig> = {},
): T | null => {
config = getConfig(config);
const { children } = config;
const list = [...tree];
if (!children) return null;
for (const node of list) {
if (func(node)) return node;
node[children] && list.push(...node[children]);
}
return null;
};
export const findNodeAll = <T = any>(
tree: any,
func: Fn,
config: Partial<TreeHelperConfig> = {},
): T[] => {
config = getConfig(config);
const { children } = config;
const list = [...tree];
const result: T[] = [];
if (!children) return result;
for (const node of list) {
func(node) && result.push(node);
node[children] && list.push(...node[children]);
}
return result;
};
export const findPath = <T = any>(
tree: any,
func: Fn,
config: Partial<TreeHelperConfig> = {},
): T | T[] | null => {
config = getConfig(config);
const path: T[] = [];
const list = [...tree];
const visitedSet = new Set();
const { children } = config;
if (!children) return null;
while (list.length) {
const node = list[0];
if (visitedSet.has(node)) {
path.pop();
list.shift();
} else {
visitedSet.add(node);
node[children] && list.unshift(...node[children]);
path.push(node);
if (func(node)) {
return path;
}
}
}
return null;
};
export const findPathAll = (
tree: any,
func: Fn,
config: Partial<TreeHelperConfig> = {},
) => {
config = getConfig(config);
const path: any[] = [];
const list = [...tree];
const result: any[] = [];
const visitedSet = new Set(),
{ children } = config;
if (!children) return [];
while (list.length) {
const node = list[0];
if (visitedSet.has(node)) {
path.pop();
list.shift();
} else {
visitedSet.add(node);
node[children] && list.unshift(...node[children]);
path.push(node);
func(node) && result.push([...path]);
}
}
return result;
};
export const filter = <T = any>(
tree: T[],
func: (n: T) => boolean,
config: Partial<TreeHelperConfig> = {},
): T[] => {
config = getConfig(config);
const children = config.children as string;
function listFilter(list: T[]) {
return list
.map((node: any) => ({ ...node }))
.filter((node) => {
node[children] = node[children] && listFilter(node[children]);
return func(node) || node[children]?.length;
});
}
return listFilter(tree);
};
export const forEach = <T = any>(
tree: T[],
func: (n: T) => any,
config: Partial<TreeHelperConfig> = {},
): void => {
config = getConfig(config);
const list: any[] = [...tree];
const { children } = config;
for (let i = 0; i < list.length; i++) {
// func 返回true就终止遍历避免大量节点场景下无意义循环引起浏览器卡顿
if (func(list[i])) {
return;
}
children &&
list[i][children] &&
list.splice(i + 1, 0, ...list[i][children]);
}
};
/**
* @description: Extract tree specified structure
*/
export const treeMap = <T = any>(
treeData: T[],
opt: { children?: string; conversion: Fn },
): T[] => {
return treeData.map((item) => treeMapEach(item, opt));
};
/**
* @description: Extract tree specified structure
*/
export const treeMapEach = (
data: any,
{ children = 'children', conversion }: { children?: string; conversion: Fn },
) => {
const haveChildren =
Array.isArray(data[children]) && data[children].length > 0;
const conversionData = conversion(data) || {};
if (haveChildren) {
return {
...conversionData,
[children]: data[children].map((i: number) =>
treeMapEach(i, {
children,
conversion,
}),
),
};
} else {
return {
...conversionData,
};
}
};
/**
* 递归遍历树结构
* @param treeDatas 树
* @param callBack 回调
* @param parentNode 父节点
*/
export const eachTree = (treeDatas: any[], callBack: Fn, parentNode = {}) => {
treeDatas.forEach((element) => {
const newNode = callBack(element, parentNode) || element;
if (element.children) {
eachTree(element.children, callBack, newNode);
}
});
};
/**
* 构造树型结构数据
* @param {*} data 数据源
* @param {*} id id字段 默认 'id'
* @param {*} parentId 父节点字段 默认 'parentId'
* @param {*} children 孩子节点字段 默认 'children'
*/
export const handleTree = (
data: any[],
id?: string,
parentId?: string,
children?: string,
) => {
if (!Array.isArray(data)) {
console.warn('data must be an array');
return [];
}
const config = {
id: id || 'id',
parentId: parentId || 'parentId',
childrenList: children || 'children',
};
const childrenListMap: any = {};
const nodeIds: any = {};
const tree: any[] = [];
for (const d of data) {
const parentId = d[config.parentId];
if (childrenListMap[parentId] == null) {
childrenListMap[parentId] = [];
}
nodeIds[d[config.id]] = d;
childrenListMap[parentId].push(d);
}
for (const d of data) {
const parentId = d[config.parentId];
if (nodeIds[parentId] == null) {
tree.push(d);
}
}
for (const t of tree) {
adaptToChildrenList(t);
}
function adaptToChildrenList(o: { [x: string]: any }) {
if (childrenListMap[o[config.id]] !== null) {
o[config.childrenList] = childrenListMap[o[config.id]];
}
if (o[config.childrenList]) {
for (const c of o[config.childrenList]) {
adaptToChildrenList(c);
}
}
}
return tree;
};
/**
* 构造树型结构数据
* @param {*} data 数据源
* @param {*} id id字段 默认 'id'
* @param {*} parentId 父节点字段 默认 'parentId'
* @param {*} children 孩子节点字段 默认 'children'
* @param {*} rootId 根Id 默认 0
*/
// @ts-expect-error
export const handleTree2 = (data, id, parentId, _children, rootId) => {
id = id || 'id';
parentId = parentId || 'parentId';
// children = children || 'children'
rootId =
rootId ||
Math.min(
...data.map((item: { [x: string]: any }) => {
return item[parentId];
}),
) ||
0;
// 对源数据深度克隆
const cloneData = JSON.parse(JSON.stringify(data));
// 循环所有项
const treeData = cloneData.filter(
(father: { [x: string]: any; children: any }) => {
const branchArr = cloneData.filter((child: { [x: string]: any }) => {
// 返回每一项的子级数组
return father[id] === child[parentId];
});
if (branchArr.length > 0) {
father.children = branchArr;
}
// 返回第一层
return father[parentId] === rootId;
},
);
return treeData !== '' ? treeData : data;
};
/**
* 校验选中的节点,是否为指定 level
*
* @param tree 要操作的树结构数据
* @param nodeId 需要判断在什么层级的数据
* @param level 检查的级别, 默认检查到二级
* @return true 是false 否
*/
export const checkSelectedNode = (
tree: any[],
nodeId: any,
level = 2,
): boolean => {
if (
typeof tree === 'undefined' ||
!Array.isArray(tree) ||
tree.length === 0
) {
console.warn('tree must be an array');
return false;
}
// 校验是否是一级节点
if (tree.some((item) => item.id === nodeId)) {
return false;
}
// 递归计数
let count = 1;
// 深层次校验
function performAThoroughValidation(arr: any[]): boolean {
count += 1;
for (const item of arr) {
if (item.id === nodeId) {
return true;
} else if (
typeof item.children !== 'undefined' &&
item.children.length !== 0
) {
if (performAThoroughValidation(item.children)) {
return true;
}
}
}
return false;
}
for (const item of tree) {
count = 1;
if (performAThoroughValidation(item.children)) {
// 找到后对比是否是期望的层级
if (count >= level) {
return true;
}
}
}
return false;
};
/**
* 获取节点的完整结构
* @param tree 树数据
* @param nodeId 节点 id
*/
export const treeToString = (tree: any[], nodeId: number) => {
if (
typeof tree === 'undefined' ||
!Array.isArray(tree) ||
tree.length === 0
) {
console.warn('tree must be an array');
return '';
}
// 校验是否是一级节点
const node = tree.find((item) => item.id === nodeId);
if (typeof node !== 'undefined') {
return node.name;
}
let str = '';
function performAThoroughValidation(arr: string | any[]) {
if (typeof arr === 'undefined' || !Array.isArray(arr) || arr.length === 0) {
return false;
}
for (const item of arr) {
if (item.id === nodeId) {
str += ` / ${item.name}`;
return true;
} else if (
typeof item.children !== 'undefined' &&
item.children.length !== 0
) {
str += ` / ${item.name}`;
if (performAThoroughValidation(item.children)) {
return true;
}
}
}
return false;
}
for (const item of tree) {
str = `${item.name}`;
if (performAThoroughValidation(item.children)) {
break;
}
}
return str;
};