8 Commits

Author SHA1 Message Date
ed92397237 feat: requestEventBus
Some checks failed
coverage CI / build (push) Has been cancelled
2025-10-13 16:52:24 +08:00
9eb4f52f0e feat: 样本管理 2025-10-13 16:50:21 +08:00
4e9ebc76f7 feat: upload
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-25 13:51:24 +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
69 changed files with 8565 additions and 368 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 服务
@@ -14,6 +14,8 @@ VITE_UPLOAD_TYPE=server
# 接口地址
VITE_API_URL=/admin-api
VITE_API_URL_PREFIX=/ai/sample/create
# 是否删除debugger
VITE_DROP_DEBUGGER=false

View File

@@ -15,7 +15,7 @@ export default {
// localhost:8000/api/** -> https://preview.pro.ant.design/api/**
'/admin-api/': {
// 要代理的地址
target: 'http://114.132.60.20:48080',
target: 'http://192.168.1.231:48080',
// 配置了这个可以从 http 代理到 https
// 依赖 origin 的功能可能需要这个,比如 cookie
changeOrigin: true,

14
mock/ap.ts Normal file
View File

@@ -0,0 +1,14 @@
import type { Request, Response } from "express";
import mockjs from "mockjs";
const getTags = (_: Request, res: Response) => {
return res.json({
data: mockjs.mock({
"list|100": [{ name: "@city", "value|1-100": 150, "type|0-2": 1 }],
}),
});
};
export default {
"GET /api/tags": getTags,
};

View File

@@ -1,117 +1,20 @@
import type { Request, Response } from 'express';
import type { Request, Response } from "express";
const getNotices = (_req: Request, res: Response) => {
const getSampleTag = (_req: Request, res: Response) => {
res.json({
data: [
{
id: '000000001',
id: "000000001",
avatar:
'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/MSbDR4FR2MUAAAAAAAAAAAAAFl94AQBr',
title: '你收到了 14 份新周报',
datetime: '2017-08-09',
type: 'notification',
},
{
id: '000000002',
avatar:
'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/hX-PTavYIq4AAAAAAAAAAAAAFl94AQBr',
title: '你推荐的 曲妮妮 已通过第三轮面试',
datetime: '2017-08-08',
type: 'notification',
},
{
id: '000000003',
avatar:
'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/jHX5R5l3QjQAAAAAAAAAAAAAFl94AQBr',
title: '这种模板可以区分多种通知类型',
datetime: '2017-08-07',
read: true,
type: 'notification',
},
{
id: '000000004',
avatar:
'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/Wr4mQqx6jfwAAAAAAAAAAAAAFl94AQBr',
title: '左侧图标用于区分不同的类型',
datetime: '2017-08-07',
type: 'notification',
},
{
id: '000000005',
avatar:
'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/Mzj_TbcWUj4AAAAAAAAAAAAAFl94AQBr',
title: '内容不要超过两行字,超出时自动截断',
datetime: '2017-08-07',
type: 'notification',
},
{
id: '000000006',
avatar:
'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/eXLzRbPqQE4AAAAAAAAAAAAAFl94AQBr',
title: '曲丽丽 评论了你',
description: '描述信息描述信息描述信息',
datetime: '2017-08-07',
type: 'message',
clickClose: true,
},
{
id: '000000007',
avatar:
'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/w5mRQY2AmEEAAAAAAAAAAAAAFl94AQBr',
title: '朱偏右 回复了你',
description: '这种模板用于提醒谁与你发生了互动,左侧放『谁』的头像',
datetime: '2017-08-07',
type: 'message',
clickClose: true,
},
{
id: '000000008',
avatar:
'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/wPadR5M9918AAAAAAAAAAAAAFl94AQBr',
title: '标题',
description: '这种模板用于提醒谁与你发生了互动,左侧放『谁』的头像',
datetime: '2017-08-07',
type: 'message',
clickClose: true,
},
{
id: '000000009',
title: '任务名称',
description: '任务需要在 2017-01-12 20:00 前启动',
extra: '未开始',
status: 'todo',
type: 'event',
},
{
id: '000000010',
title: '第三方紧急代码变更',
description:
'冠霖提交于 2017-01-06需在 2017-01-07 前完成代码变更任务',
extra: '马上到期',
status: 'urgent',
type: 'event',
},
{
id: '000000011',
title: '信息安全考试',
description: '指派竹尔于 2017-01-09 前完成更新并发布',
extra: '已耗时 8 天',
status: 'doing',
type: 'event',
},
{
id: '000000012',
title: 'ABCD 版本发布',
description:
'冠霖提交于 2017-01-06需在 2017-01-07 前完成代码变更任务',
extra: '进行中',
status: 'processing',
type: 'event',
"https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/MSbDR4FR2MUAAAAAAAAAAAAAFl94AQBr",
title: "你收到了 14 份新周报",
datetime: "2017-08-09",
type: "notification",
},
],
});
};
export default {
'GET /api/notices': getNotices,
"GET /api/notices": getSampleTag,
};

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,8 @@
"jsencrypt": "^3.5.4",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-infinite-scroll-component": "^6.1.0",
"tinymce": "^8.1.2",
"web-storage-cache": "^1.1.1"
},
"devDependencies": {

48
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,12 @@ importers:
react-dom:
specifier: ^19.1.0
version: 19.1.1(react@19.1.1)
react-infinite-scroll-component:
specifier: ^6.1.0
version: 6.1.0(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 +2560,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'}
@@ -9007,6 +9026,11 @@ packages:
react: ^16.6.0 || ^17.0.0 || ^18.0.0
react-dom: ^16.6.0 || ^17.0.0 || ^18.0.0
react-infinite-scroll-component@6.1.0:
resolution: {integrity: sha512-SQu5nCqy8DxQWpnUVLx7V7b7LcA37aM7tvoWjTLZp1dk6EJibM5/4EJKzOnl07/BsM1Y40sKLuqjCwwH/xV0TQ==}
peerDependencies:
react: '>=16.0.0'
react-intl@3.12.1:
resolution: {integrity: sha512-cgumW29mwROIqyp8NXStYsoIm27+8FqnxykiLSawWjOxGIBeLuN/+p2srei5SRIumcJefOkOIHP+NDck05RgHg==}
peerDependencies:
@@ -10216,6 +10240,10 @@ packages:
thread-stream@0.15.2:
resolution: {integrity: sha512-UkEhKIg2pD+fjkHQKyJO3yoIvAP3N6RlNFt2dUhcS1FGvCD1cQa1M/PGknCLFIyZdtJOWQjejp7bdNqmN7zwdA==}
throttle-debounce@2.3.0:
resolution: {integrity: sha512-H7oLPV0P7+jgvrk+6mwwwBDmxTaxnu9HMXmloNLXwnNO0ZxZ31Orah2n8lU1eMPvsaowP2CX+USCgyovXfdOFQ==}
engines: {node: '>=8'}
throttle-debounce@5.0.2:
resolution: {integrity: sha512-B71/4oyj61iNH0KeCamLuE2rmKuTO5byTOSVwECM5FA7TiAiAW+UqTKZ9ERueC4qvgSttUhdmq1mXC3kJqGX7A==}
engines: {node: '>=12.22'}
@@ -10246,6 +10274,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 +14746,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': {}
@@ -23275,6 +23314,11 @@ snapshots:
react-fast-compare: 3.2.2
shallowequal: 1.1.0
react-infinite-scroll-component@6.1.0(react@19.1.1):
dependencies:
react: 19.1.1
throttle-debounce: 2.3.0
react-intl@3.12.1(@types/react@19.1.12)(react@19.1.1):
dependencies:
'@formatjs/intl-displaynames': 1.2.10
@@ -24827,6 +24871,8 @@ snapshots:
dependencies:
real-require: 0.1.0
throttle-debounce@2.3.0: {}
throttle-debounce@5.0.2: {}
through@2.3.8: {}
@@ -24850,6 +24896,8 @@ snapshots:
tinyexec@1.0.1: {}
tinymce@8.1.2: {}
titleize@3.0.0: {}
tldts-core@6.1.86: {}

View File

@@ -1,15 +1,9 @@
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history, Link, Navigate } from '@umijs/max';
import { Modal, Spin } from 'antd';
import React, {
Children,
Component,
createContext,
JSX,
Suspense,
} from 'react';
import { history, Navigate } from '@umijs/max';
import { Spin } from 'antd';
import React from 'react';
import {
AvatarDropdown,
AvatarName,
@@ -18,17 +12,13 @@ import {
SelectLang,
} from '@/components';
import { getInfo } from '@/services/login';
import type { TokenType, UserInfoVO, UserVO } from '@/services/login/types';
import type { UserInfoVO } from '@/services/login/types';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import '@ant-design/v5-patch-for-react-19';
import { getAccessToken, getRefreshToken, getTenantId } from '@/utils/auth';
import {
transformBackendMenuToFlatRoutes,
transformMenuToRoutes,
} from '@/utils/menuUtils';
import { getAccessToken, getTenantId } from '@/utils/auth';
import { CACHE_KEY, useCache } from './hooks/web/useCache';
import { MenuVO } from './services/system/menu';
const isDev = process.env.NODE_ENV === 'development';
const isDevOrTest = isDev || process.env.CI;
@@ -198,7 +188,7 @@ export const request: RequestConfig = {
};
// 如果有token则添加Authorization头
if (token) {
headers['Authorization'] = `Bearer ${getAccessToken()}`;
headers.Authorization = `Bearer·${getAccessToken()}`;
}
return { url, options: { ...options, headers } };
},
@@ -235,20 +225,19 @@ export const request: RequestConfig = {
// umi 4 使用 modifyRoutes
export function patchClientRoutes({ routes }: { routes: any }) {
const { wsCache } = useCache();
console.log(2222);
const globalMenus = wsCache.get(CACHE_KEY.ROLE_ROUTERS);
const routerIndex = routes.findIndex((item: any) => item.path === '/');
const parentId = routes[routerIndex].id;
if (globalMenus) {
routes[routerIndex]['routes'].push(...loopMenuItem(globalMenus, parentId));
routes[routerIndex].routes.push(...loopMenuItem(globalMenus, parentId));
}
}
const loopMenuItem = (menus: any[], pId: number | string): any[] => {
return menus.flatMap((item) => {
let Component: React.ComponentType<any> | null = null;
console.log(findFirstLeafRoute(item), 'item');
// console.log(findFirstLeafRoute(item), 'item');
if (item.component && item.component.length > 0) {
// 防止配置了路由,但本地暂未添加对应的页面,产生的错误
Component = React.lazy(() => {
@@ -299,7 +288,7 @@ const loopMenuItem = (menus: any[], pId: number | string): any[] => {
});
};
const findFirstLeafRoute = (menuItem: any, parent = '/'): string | null => {
const _findFirstLeafRoute = (menuItem: any, parent = '/'): string | null => {
// 如果没有子菜单,返回当前路径
if (!menuItem.children || menuItem.children.length === 0) {
@@ -308,7 +297,8 @@ const findFirstLeafRoute = (menuItem: any, parent = '/'): string | null => {
// 递归查找第一个叶子节点
for (const child of menuItem.children) {
const leafRoute = findFirstLeafRoute(child, menuItem.path + '/');
// const leafRoute = findFirstLeafRoute(child, menuItem.path + "/");
const leafRoute = _findFirstLeafRoute(child, `${menuItem.path}/`);
if (leafRoute) {
return leafRoute;
}

View File

@@ -1,16 +1,15 @@
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 type { FormInstance } from 'antd/lib';
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;
}
@@ -40,7 +39,7 @@ const ConfigurableDrawerForm = forwardRef<
const [formData, setFormData] = React.useState(initialValues || {});
const [loading, setLoading] = React.useState<boolean>(false);
// 添加表单实例引用
const formRef = React.useRef<any>(null);
const formRef = React.useRef<FormInstance>(null);
useImperativeHandle(ref, () => ({
open: (data) => {
if (data) {
@@ -70,31 +69,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

@@ -1,33 +1,14 @@
// components/EnhancedProTable/EnhancedProTable.tsx
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 { Button } from 'antd';
import React, { forwardRef, useCallback } 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,69 +17,80 @@ function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
const {
columns,
request,
actions = [],
permissions = [],
checkPermission = () => true,
// actions = [],
// permissions = [],
// checkPermission = () => true,
toolbarActions,
showIndex = true,
showSelection = true,
showActions = true,
maxActionCount = 2,
onAdd,
onEdit,
onDelete,
onView,
onExport,
customToolbarRender,
customActionRender,
// showIndex = true,
// showActions = true,
// maxActionCount = 2,
// onAdd,
// onEdit,
// onDelete,
// onView,
// onExport,
// customToolbarRender,
// showSelection = true,
rowKey = 'id',
// onRow,
// rowClassName,
// enableRowClick = false,
// clickableRowClassName = "clickable-row", // 添加可点击样式
...restProps
} = props;
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
const [selectedRows, setSelectedRows] = useState<T[]>([]);
// 行选择配置
const rowSelection = useMemo(() => {
if (!showSelection) return undefined;
// const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
// const [selectedRows, setSelectedRows] = useState<T[]>([]);
// // 行选择配置
// const rowSelection = useMemo(() => {
// if (!showSelection) return undefined;
// return {
// selectedRowKeys,
// selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
// onChange: (keys: React.Key[], rows: T[]) => {
// setSelectedRowKeys(keys);
// setSelectedRows(rows);
// },
// getCheckboxProps: (record: T) => ({
// name: record[rowKey]?.toString(),
// }),
// };
// }, [showSelection, selectedRowKeys]);
return {
selectedRowKeys,
onChange: (keys: React.Key[], rows: T[]) => {
setSelectedRowKeys(keys);
setSelectedRows(rows);
},
getCheckboxProps: (record: T) => ({
name: record.id?.toString(),
}),
};
}, [showSelection, selectedRowKeys]);
// // 处理行点击事件
// const handleRowClick = useCallback(
// (record: T, index?: number) => {
// console.log("handleRowClick");
// if (!enableRowClick) return {};
// return {
// onClick: (event: React.MouseEvent<HTMLElement>) => {
// // 阻止事件冒泡到其他元素
// event.stopPropagation();
// 表格提醒渲染
const tableAlertRender = useCallback(
({ selectedRowKeys, onCleanSelected }: any) => {
if (!showSelection || selectedRowKeys.length === 0) return false;
// // 如果点击的是 checkbox 或其他交互元素,不处理行选中
// const target = event.target as HTMLElement;
// console.log("handleRowClick");
// if (
// target.closest(".ant-checkbox") ||
// target.closest(".ant-btn") ||
// target.closest(".ant-dropdown") ||
// target.closest("a")
// ) {
// return;
// }
return (
<Space size={24}>
<span>
{selectedRowKeys.length}
<a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
</a>
</span>
</Space>
);
},
[showSelection],
);
// // // 切换选中状态
// // handleRowSelect(record, !isSelected);
const toolBarRender = useCallback(
(
action: ActionType | undefined,
rows: {
selectedRowKeys?: (string | number)[] | undefined;
selectedRows?: T[] | undefined;
},
) => {
// // // 调用原始的 onRow 点击事件
// onRow?.(record, index)?.onClick?.(event);
// },
// };
// },
// [enableRowClick, onRow]
// );
const toolBarRender = useCallback(() => {
const toolbarElements =
toolbarActions?.map((action) => {
return (
@@ -107,40 +99,26 @@ function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
type={action.type}
danger={action.danger}
disabled={action.disabled}
icon={<PlusOutlined />}
onClick={() => action.onClick(selectedRowKeys, selectedRows)}
// icon={action.icon ?? <PlusOutlined />}
onClick={() => action.onClick()}
>
{action.label}
</Button>
);
}) || [];
// return [
// <Button
// key="button"
// icon={<PlusOutlined />}
// onClick={}
// type="primary"
// >
// 新建
// </Button>,
// ];
return toolbarElements;
},
[toolbarActions],
);
}, [toolbarActions]);
return (
<ProTable<T, U>
{...restProps}
columns={columns}
actionRef={ref}
request={request}
rowKey="id"
rowSelection={rowSelection}
rowKey={rowKey}
rowSelection={props.rowSelection ?? false}
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,12 +52,14 @@ 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 属性
enableRowClick?: boolean; //开启行内点击
clickableRowClassName?: string;
actions?: TableAction<T>[];
toolbarActions?: ToolbarAction[];
permissions?: string[];
@@ -73,11 +74,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,301 @@
// GroupTagCore.less
.group-tag-core {
width: 100%;
border: 1px solid #f0f0f0;
border-radius: 6px;
overflow: hidden;
// 编辑模式下的整体样式
&.edit-mode {
.search-wrapper {
.ant-input-affix-wrapper {
background-color: #f5f5f5;
.ant-input {
background-color: #f5f5f5;
cursor: not-allowed;
}
}
}
}
.search-wrapper {
padding: 8px;
border-bottom: 1px solid #f0f0f0;
.ant-input-affix-wrapper {
width: 100%;
}
}
.content-wrapper {
flex: 1;
overflow: hidden;
.loading-wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 200px;
text-align: center;
}
.split-layout {
display: flex;
height: 100%;
.groups-panel {
width: 200px;
border-right: 1px solid #f0f0f0;
display: flex;
flex-direction: column;
.panel-header {
padding: 8px 12px;
background-color: #fafafa;
border-bottom: 1px solid #f0f0f0;
display: flex;
justify-content: space-between;
align-items: center;
font-weight: 500;
font-size: 14px;
}
.groups-list {
overflow: auto;
height: 40vh;
.group-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
cursor: pointer;
transition: background-color 0.2s;
border-bottom: 1px solid #f5f5f5;
&:hover {
background-color: #f5f5f5;
}
&.active {
background-color: #e6f7ff;
border-color: #91d5ff;
}
&.editing {
background-color: #fff7e6;
cursor: default;
&:hover {
background-color: #fff7e6;
}
}
&.disabled {
cursor: not-allowed;
opacity: 0.6;
&:hover {
background-color: inherit;
}
&.active:hover {
background-color: #e6f7ff;
}
}
.group-content {
flex: 1;
display: flex;
justify-content: space-between;
align-items: center;
.group-name {
font-size: 13px;
color: #262626;
}
.edit-input-wrapper {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
.ant-input {
flex: 1;
font-size: 12px;
}
.edit-actions {
display: flex;
gap: 2px;
.ant-btn {
padding: 0;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
.anticon {
font-size: 10px;
}
}
}
}
}
.ant-checkbox-wrapper {
margin-left: 8px;
}
}
}
}
.tags-panel {
flex: 1;
display: flex;
flex-direction: column;
.panel-header {
padding: 8px 12px;
background-color: #fafafa;
border-bottom: 1px solid #f0f0f0;
display: flex;
justify-content: space-between;
align-items: center;
font-weight: 500;
font-size: 14px;
}
.tags-list {
overflow: auto;
height: 40vh;
padding: 4px 0;
.loading-wrapper {
display: flex;
justify-content: center;
align-items: center;
height: 60px;
}
.infinite-scroll-container {
height: 50vh !important;
overflow-y: auto;
}
.tag-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 12px;
transition: background-color 0.2s;
&:hover {
background-color: #f5f5f5;
}
&.editing {
background-color: #fff7e6;
&:hover {
background-color: #fff7e6;
}
}
&.disabled {
opacity: 0.6;
&:hover {
background-color: inherit;
}
}
.ant-checkbox-wrapper {
flex: 1;
span:last-child {
color: #595959;
font-size: 13px;
}
}
.tag-name-only {
flex: 1;
color: #8c8c8c;
font-size: 13px;
.anticon {
color: #bfbfbf;
}
}
.tag-actions {
display: flex;
gap: 2px;
opacity: 0;
transition: opacity 0.2s;
.ant-btn {
padding: 0;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
.anticon {
font-size: 10px;
}
}
}
&:hover .tag-actions {
opacity: 1;
}
.edit-input-wrapper {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
.ant-input {
flex: 1;
font-size: 12px;
}
.edit-actions {
display: flex;
gap: 2px;
.ant-btn {
padding: 0;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
.anticon {
font-size: 10px;
}
}
}
}
}
.ant-empty {
padding: 40px 20px;
.ant-empty-description {
color: #8c8c8c;
font-size: 12px;
}
}
}
}
}
}
}

View File

@@ -0,0 +1,343 @@
// GroupTagCore.tsx - 修复缺失函数和API参数
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import {
Button,
type CheckboxChangeEvent,
Input,
message,
Space,
Spin,
} from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import type { GroupItem, GroupTagCoreProps, TagItem } from './types';
import './GroupTagCore.less';
import { renderGroups, renderTags } from './component';
import TagsModal from './TagsModal';
const GroupTagCore: React.FC<GroupTagCoreProps> = (props) => {
const {
requset: { groupsApi, tagsApi },
editable = false,
value = [],
onChange,
} = props;
const [isInEditMode, _setIsInEditMode] = useState<boolean>(false);
// 编辑状态
const [loading, setLoading] = useState<boolean>(false);
const [loadingTags, setLoadingTags] = useState<boolean>(false);
const [groups, setGroups] = useState<GroupItem[]>([]);
const [currentGroup, setCurrentGroup] = useState<GroupItem>();
const [modalType, setModalType] = useState<'add' | 'edit' | 'delete'>();
const [type, setType] = useState<'group' | 'tag'>('group');
const [visible, setVisible] = useState<boolean>(false);
const [name, setName] = useState<string>('');
const [total, setTotal] = useState<number>(0);
const [currentId, setCurrentId] = useState<number>();
const [tagsModalValue, setTagsModalValue] = useState<{
tagName?: string;
groupIds?: number[];
id?: number;
}>({});
const [pageNo, setPageNo] = useState<number>(1);
const fetchGroups = useCallback(async () => {
try {
setLoading(true);
const groups = await groupsApi.get();
groups.length && setCurrentGroup(groups[0]);
setGroups(groups);
setCurrentId(groups[0].id);
} finally {
setLoading(false);
}
}, [groupsApi]);
const fetchTagsApi = useCallback(async () => {
try {
setLoadingTags(true);
const res = await tagsApi.get({ groupId: currentId, pageNo: 1 });
const newGroup = { ...currentGroup, tags: res.list };
const newData = groups.map((g) => (g.id === currentId ? newGroup : g));
setGroups(newData as GroupItem[]);
setCurrentGroup(newGroup as GroupItem);
setTotal(res.total);
setPageNo(1);
} finally {
setLoadingTags(false);
}
}, [tagsApi, groups, currentId]);
useEffect(() => {
fetchGroups();
}, []);
useEffect(() => {
if (currentId) {
fetchTagsApi();
}
}, [currentId]);
const onGroupClick = (group: GroupItem) => {
if (currentId !== group.id) {
setCurrentId(group.id);
setCurrentGroup(group);
}
};
useEffect(() => {
if (modalType === 'edit' && visible) {
if (type === 'group' && currentGroup) {
setName(currentGroup.groupName);
} else if (type === 'tag' && tagsModalValue) {
setName(tagsModalValue.tagName || '');
}
}
if (modalType === 'add') {
setName('');
}
}, [type, modalType, currentGroup, tagsModalValue, visible]);
const handleGroup = (type: 'add' | 'edit' | 'delete') => {
setType('group');
setModalType(type);
if (type === 'add' || type === 'edit') {
setVisible(true);
}
};
const handleTag = (type: 'add' | 'edit' | 'delete', tag?: TagItem) => {
setType('tag');
setModalType(type);
if (type === 'add' || type === 'edit') {
setVisible(true);
}
if (type === 'edit') {
setTagsModalValue({ tagName: tag?.tagName, id: tag?.id });
}
};
const handleAdd = async (value: {
groupName?: string;
groupIds?: number[];
tagName?: string;
}) => {
if (type === 'group') {
const id = await groupsApi.create({ groupName: value.groupName });
setGroups([{ id, groupName: value.groupName || '' }, ...groups]);
} else {
await tagsApi.create(value);
message.success('添加成功');
fetchTagsApi();
}
setVisible(false);
};
const handleEdit = async (value: {
tagName?: string;
groupIds?: number[];
}) => {
if (type === 'group') {
try {
setLoading(true);
await groupsApi.update({ id: currentGroup?.id, groupName: name });
const newData = groups.map((item) => {
if (item.id === currentGroup?.id) {
const itemData = { ...item, groupName: name };
setCurrentGroup(itemData);
return itemData;
} else {
return item;
}
});
setGroups(newData);
} finally {
setLoading(false);
}
} else {
await tagsApi.update({
groupIds: [currentGroup?.id],
id: tagsModalValue?.id,
...value,
});
message.success('修改成功');
const newTag = currentGroup?.tags?.map((tag) => {
if (tag.id === tagsModalValue?.id) {
return { ...tag, tagName: value.tagName };
} else {
return tag;
}
});
const newGroup = { ...currentGroup, tags: newTag };
setCurrentGroup(newGroup as GroupItem);
}
setVisible(false);
};
const handleDelete = async (type: 'group' | 'tag', id: number) => {
if (type === 'group' && currentGroup) {
await groupsApi.delete(id);
const newGroups = groups.filter((group) => group.id !== id);
setGroups(newGroups);
if (id === currentId) {
setCurrentId(newGroups[0].id);
setCurrentGroup(newGroups[0]);
}
} else {
tagsApi.delete(id);
}
};
const handleConfirm = useCallback(
async (value: { tagName?: string; groupIds?: number[] }) => {
if (modalType === 'add') {
await handleAdd(value);
}
if (modalType === 'edit') {
await handleEdit(value);
}
},
[visible, type, modalType],
);
const handleCancle = useCallback(() => {
setVisible(false);
}, [visible]);
const onTagItemChange = (tag: TagItem, e: CheckboxChangeEvent) => {
if (e.target.checked) {
const data = [...value, tag];
onChange?.(data);
} else if (!editable) {
const data = value.filter((item) => item.id !== tag.id);
onChange?.(data);
}
};
const loadMoreData = async () => {
const res = await tagsApi.get({ groupId: currentId, pageNo: pageNo + 1 });
if (res.list.length === 0) {
return;
}
const newGroup = {
...currentGroup,
tags: [...(currentGroup?.tags || []), ...res.list],
};
setCurrentGroup(newGroup as GroupItem);
setPageNo((prev) => prev + 1);
};
const onSearchTags = async (e: React.KeyboardEvent<HTMLInputElement>) => {
const searchValue = (e.target as HTMLInputElement).value;
const res = await tagsApi.get({
groupId: currentId,
pageNo: 1,
tagName: searchValue,
});
const newGroup = {
...currentGroup,
tags: res.list,
};
document.getElementById('scrollableDiv')?.scrollTo(0, 0);
setCurrentGroup(newGroup as GroupItem);
setPageNo(1);
};
return (
<div className={`group-tag-core`}>
<div className="search-wrapper">
<Input
prefix={<SearchOutlined />}
placeholder="搜索"
onPressEnter={onSearchTags}
allowClear
disabled={isInEditMode}
/>
</div>
<div className="content-wrapper">
{loading ? (
<div className="loading-wrapper">
<Spin />
<div style={{ marginTop: 8 }}>...</div>
</div>
) : (
<div className="split-layout">
{/* 左侧分组列表 */}
<div className="groups-panel">
<div className="panel-header">
<span></span>
{editable && !isInEditMode && (
<Button
type="text"
size="small"
icon={<PlusOutlined />}
onClick={() => handleGroup('add')}
>
</Button>
)}
</div>
<div className="groups-list">
{renderGroups({
editable,
groups,
currentId,
onGroupClick,
onEdit: () => handleGroup('edit'),
onDelete: (id) => handleDelete('group', id),
})}
</div>
</div>
{/* 右侧标签列表 */}
<div className="tags-panel">
<div className="panel-header">
<span></span>
<Space>
{editable && currentGroup && !isInEditMode && (
<Button
type="text"
size="small"
icon={<PlusOutlined />}
onClick={() => handleTag('add')}
>
</Button>
)}
</Space>
</div>
<div className="tags-list" id="scrollableDiv">
<Spin spinning={loadingTags}>
{renderTags({
editable,
value,
list: currentGroup?.tags ?? [],
total,
loadMoreData,
onEdit: (tag) => handleTag('edit', tag),
onDelete: (id) => handleDelete('tag', id),
onTagItemChange: onTagItemChange,
})}
</Spin>
</div>
</div>
</div>
)}
</div>
{/* 添加标签Modal */}
<TagsModal
value={tagsModalValue}
visible={visible}
type={type}
modalType={modalType}
onCancel={handleCancle}
onConfirm={handleConfirm}
groups={groups}
/>
</div>
);
};
export default GroupTagCore;

View File

@@ -0,0 +1,63 @@
// GroupTagModal.tsx - 修复死循环问题
import { Modal } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import GroupTagCore from './GroupTagCore';
import type { GroupTagModalProps, TagItem } from './types';
const GroupTagModal: React.FC<GroupTagModalProps> = ({
visible,
title,
width,
editable,
request,
onCancel,
onChange,
}) => {
const [data, setData] = useState<TagItem[]>([]);
const handleOk = () => {
if (onChange) {
// const ids = data.map((item) => item.id);
onChange(data);
}
onCancel();
};
useEffect(() => {
if (!visible) {
setData([]);
}
}, [visible]);
const handleChange = useCallback(
(data: TagItem[]) => {
setData(data);
},
[data],
);
return (
<Modal
title={title}
open={visible}
onCancel={onCancel}
onOk={handleOk}
width={width}
okText="确定"
cancelText="取消"
destroyOnHidden
maskClosable={false}
>
<GroupTagCore
value={data}
requset={request}
editable={editable}
onChange={handleChange}
/>
</Modal>
);
};
export default GroupTagModal;

View File

@@ -0,0 +1,400 @@
// GroupTagSelect.less - 添加编辑模式样式
.group-tag-select-wrapper {
width: 100%;
.group-tag-select {
width: 100%;
.ant-select-selector {
min-height: 32px;
}
.selected-tag {
margin: 2px;
font-size: 12px;
line-height: 20px;
border-radius: 4px;
}
}
&.disabled {
.selected-tag {
background-color: #f0f0f0;
border-color: #d9d9d9;
color: rgba(0, 0, 0, 0.25);
}
}
}
.group-tag-select-dropdown-wrapper {
.ant-select-dropdown {
padding: 0;
width: 600px !important;
min-width: 600px !important;
}
}
.group-tag-select-dropdown {
padding: 0;
width: 100%;
// 编辑模式下的整体样式
&.edit-mode {
.search-wrapper {
.ant-input-affix-wrapper {
background-color: #f5f5f5;
.ant-input {
background-color: #f5f5f5;
cursor: not-allowed;
}
}
}
}
.search-wrapper {
padding: 8px;
border-bottom: 1px solid #f0f0f0;
.ant-input-affix-wrapper {
width: 100%;
}
}
.content-wrapper {
height: 400px;
overflow: hidden;
.loading-wrapper {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
text-align: center;
}
.split-layout {
display: flex;
height: 100%;
.groups-panel {
width: 200px;
border-right: 1px solid #f0f0f0;
display: flex;
flex-direction: column;
.panel-header {
padding: 8px 12px;
background-color: #fafafa;
border-bottom: 1px solid #f0f0f0;
display: flex;
justify-content: space-between;
align-items: center;
font-weight: 500;
font-size: 14px;
}
.groups-list {
flex: 1;
overflow-y: auto;
.group-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
cursor: pointer;
transition: background-color 0.2s;
border-bottom: 1px solid #f5f5f5;
&:hover {
background-color: #f5f5f5;
}
&.active {
background-color: #e6f7ff;
border-color: #91d5ff;
}
// 编辑状态样式
&.editing {
background-color: #fff7e6;
cursor: default;
&:hover {
background-color: #fff7e6;
}
}
// 禁用状态样式
&.disabled {
cursor: not-allowed;
opacity: 0.6;
&:hover {
background-color: inherit;
}
&.active:hover {
background-color: #e6f7ff;
}
}
.group-content {
flex: 1;
display: flex;
justify-content: space-between;
align-items: center;
.group-name {
font-size: 13px;
color: #262626;
}
// 编辑输入框样式
.edit-input-wrapper {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
.ant-input {
flex: 1;
font-size: 12px;
}
.edit-actions {
display: flex;
gap: 2px;
.ant-btn {
padding: 0;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
.anticon {
font-size: 10px;
}
}
}
}
}
.ant-checkbox-wrapper {
margin-left: 8px;
}
}
}
}
.tags-panel {
flex: 1;
display: flex;
flex-direction: column;
.panel-header {
padding: 8px 12px;
background-color: #fafafa;
border-bottom: 1px solid #f0f0f0;
display: flex;
justify-content: space-between;
align-items: center;
font-weight: 500;
font-size: 14px;
}
.tags-list {
flex: 1;
overflow-y: auto;
padding: 4px 0;
.loading-wrapper {
display: flex;
justify-content: center;
align-items: center;
height: 60px;
}
.tag-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 12px;
transition: background-color 0.2s;
&:hover {
background-color: #f5f5f5;
}
// 编辑状态样式
&.editing {
background-color: #fff7e6;
&:hover {
background-color: #fff7e6;
}
}
// 禁用状态样式
&.disabled {
opacity: 0.6;
&:hover {
background-color: inherit;
}
}
.ant-checkbox-wrapper {
flex: 1;
span:last-child {
color: #595959;
font-size: 13px;
}
}
// 编辑状态下只显示标签名称的样式
.tag-name-only {
flex: 1;
color: #8c8c8c;
font-size: 13px;
.anticon {
color: #bfbfbf;
}
}
// 标签操作按钮
.tag-actions {
display: flex;
gap: 2px;
opacity: 0;
transition: opacity 0.2s;
.ant-btn {
padding: 0;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
.anticon {
font-size: 10px;
}
}
}
&:hover .tag-actions {
opacity: 1;
}
// 编辑输入框样式
.edit-input-wrapper {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
.ant-input {
flex: 1;
font-size: 12px;
}
.edit-actions {
display: flex;
gap: 2px;
.ant-btn {
padding: 0;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
.anticon {
font-size: 10px;
}
}
}
}
}
.ant-empty {
padding: 40px 20px;
.ant-empty-description {
color: #8c8c8c;
font-size: 12px;
}
}
}
}
}
}
}
// 响应式设计
@media (max-width: 768px) {
.group-tag-select-dropdown-wrapper {
.ant-select-dropdown {
width: 90vw !important;
min-width: 320px !important;
}
}
.group-tag-select-dropdown {
.content-wrapper {
height: 300px;
.split-layout {
.groups-panel {
width: 120px;
.panel-header {
font-size: 12px;
padding: 6px 8px;
}
.groups-list {
.group-item {
padding: 6px 8px;
.group-name {
font-size: 12px;
}
}
}
}
.tags-panel {
.panel-header {
font-size: 12px;
padding: 6px 8px;
}
.tags-list {
.tag-item {
padding: 4px 8px;
.ant-checkbox-wrapper {
span:last-child {
font-size: 12px;
}
}
.tag-name-only {
font-size: 12px;
}
}
}
}
}
}
}
}

View File

@@ -0,0 +1,100 @@
// GroupTagSelect.tsx - 适配真实数据结构
import { Select, Tag } from 'antd';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import GroupTagCore from './GroupTagCore';
import type { GroupTagSelectProps, TagItem } from './types';
import './GroupTagSelect.less';
const GroupTagSelect: React.FC<GroupTagSelectProps> = ({
value = [],
onChange,
placeholder = '请选择标签',
className = '',
request,
editable = false,
}) => {
const [dropdownVisible, setDropdownVisible] = useState(false);
const [selectedTags, setSelectedTags] = useState<TagItem[]>([]);
useEffect(() => {
const v = selectedTags.map((tag) => tag.id);
onChange?.(v);
}, [selectedTags]);
const onTagsItem = (value: TagItem[]) => {
console.log(value, 'value');
setSelectedTags(value);
};
// 渲染下拉内容
const dropdownRender = useCallback(
() => (
<GroupTagCore
value={selectedTags}
requset={request}
editable={false}
onChange={onTagsItem}
/>
),
[selectedTags, request, editable],
);
// const
// 获取选中标签的详细信息
const options = useMemo(() => {
return selectedTags.map((item: TagItem) => ({
...item,
label: item.tagName,
value: item.id,
}));
}, [selectedTags]);
return (
<div className={`group-tag-select-wrapper ${className}`}>
<Select
mode="multiple"
value={value}
fieldNames={{ label: 'tagName', value: 'id' }}
onChange={(newValue) => {
// console.log(newValue, "newValue");
const selectedItems = options.filter((option) =>
newValue.includes(option.id),
);
setSelectedTags(selectedItems);
onChange?.(selectedItems as unknown as number[]);
}}
placeholder={placeholder}
className="group-tag-select"
popupRender={dropdownRender}
classNames={{
popup: {
root: 'group-tag-select-dropdown-wrapper',
},
}}
popupMatchSelectWidth={false}
dropdownStyle={{
width: 600,
minWidth: 600,
}}
options={options}
tagRender={(props) => {
const { label, closable, onClose } = props;
console.log(props);
return (
<Tag closable={closable} onClose={onClose} className="selected-tag">
{label}
</Tag>
);
}}
showSearch={false}
onSelect={() => {}}
onDeselect={() => {}}
allowClear={true}
onClear={() => setSelectedTags([])}
open={dropdownVisible}
onOpenChange={setDropdownVisible}
/>
</div>
);
};
export default GroupTagSelect;

View File

@@ -0,0 +1,98 @@
import { Form, Input, Modal, Select } from 'antd';
import { useEffect, useState } from 'react';
interface TagsModalProps {
visible: boolean;
type: 'group' | 'tag';
modalType?: 'add' | 'edit' | 'delete';
onCancel: () => void;
groups: { id: number; groupName: string }[];
value: {
id?: number;
tagName?: string;
groupIds?: number[];
groupName?: string;
};
onConfirm: (values: { tagName: string; groupIds?: number[] }) => void;
}
const TagsModal = (props: TagsModalProps) => {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
const { value, visible, type, modalType, groups, onCancel, onConfirm } =
props;
useEffect(() => {
form.setFieldsValue(value);
return () => {
form.resetFields();
setLoading(false);
};
}, [visible, value]);
const handleOk = async () => {
try {
setLoading(true);
const values = await form.validateFields();
await onConfirm(values);
} finally {
setLoading(false);
}
};
return (
<Modal
title={`${modalType === 'add' ? '添加' : '编辑'}${
type === 'group' ? '分组' : '标签'
}`}
open={visible}
onOk={handleOk}
onCancel={onCancel}
okText="确定"
confirmLoading={loading}
cancelText="取消"
destroyOnHidden
width={400}
>
<Form
name="form"
form={form}
labelCol={{ span: 4 }}
wrapperCol={{ span: 20 }}
style={{ maxWidth: 600, marginTop: 30 }}
>
{type === 'tag' && modalType === 'add' && (
<Form.Item
label="分组"
name="groupIds"
rules={[{ required: true, message: '请选择分组' }]}
>
<Select
mode="multiple"
style={{ width: '100%', marginBottom: 10 }}
options={groups}
placeholder="请选择分组"
fieldNames={{ label: 'groupName', value: 'id' }}
></Select>
</Form.Item>
)}
{type === 'tag' ? (
<Form.Item
label="标签"
name="tagName"
rules={[{ required: true, message: '请输入标签' }]}
>
<Input placeholder="请输入标签" />
</Form.Item>
) : (
<Form.Item
label="分组"
name="groupName"
rules={[{ required: true, message: '请输入分组' }]}
>
<Input placeholder="请输入分组" />
</Form.Item>
)}
</Form>
</Modal>
);
};
export default TagsModal;

View File

@@ -0,0 +1,179 @@
import { DeleteFilled, EditFilled } from '@ant-design/icons';
import {
Button,
Checkbox,
type CheckboxChangeEvent,
Divider,
Empty,
List,
Skeleton,
} from 'antd';
import InfiniteScroll from 'react-infinite-scroll-component';
import type { GroupItem, TagItem } from './types';
interface GroupsProps {
groups: GroupItem[];
onGroupClick: (group: GroupItem) => void;
currentId?: number;
editable?: boolean;
total?: number;
loadMoreData?: () => void;
pageSize?: number;
onEdit?: () => void;
onDelete?: (id: number) => void;
}
export const renderGroups = (data: GroupsProps) => {
const {
groups,
currentId,
total = groups.length,
onEdit,
onDelete,
loadMoreData,
onGroupClick,
pageSize = 10,
editable = false,
} = data;
const hasMore = groups.length < total * pageSize;
if (groups.length === 0) {
return (
<Empty description="暂无分组" image={Empty.PRESENTED_IMAGE_SIMPLE} />
);
}
return (
<InfiniteScroll
dataLength={groups.length}
next={loadMoreData ? loadMoreData : () => {}}
hasMore={loadMoreData ? hasMore : false}
loader={<Skeleton avatar paragraph={{ rows: 1 }} active />}
endMessage={loadMoreData ? <Divider plain>线</Divider> : ''}
scrollableTarget="scrollableDiv"
>
<List
dataSource={groups}
renderItem={(item) => (
<List.Item
key={item.id}
onClick={() => onGroupClick(item)}
className={`group-item ${currentId === item.id ? 'active' : ''}`}
>
<div>{item.groupName}</div>
{editable && (
<div className="group-options">
<Button
type="link"
size="small"
icon={<EditFilled />}
onClick={(e) => {
e.stopPropagation();
onEdit?.();
}}
/>
<Button
type="link"
size="small"
icon={<DeleteFilled />}
onClick={(e) => {
e.stopPropagation();
onDelete?.(item.id);
}}
/>
</div>
)}
</List.Item>
)}
/>
</InfiniteScroll>
);
};
interface GroupTagProps {
list: TagItem[];
total: number;
// onTagItemClick: (tag: TagItem) => void;
onEdit?: (tag: TagItem) => Promise<void> | void;
loadMoreData: () => void;
onDelete?: (id: number) => void;
editable?: boolean;
pageSize?: number;
value: TagItem[];
onTagItemChange: (tag: TagItem, e: CheckboxChangeEvent) => void;
}
export const renderTags = (data: GroupTagProps) => {
const {
list,
total = list.length,
loadMoreData,
onEdit,
onDelete,
onTagItemChange,
editable,
value,
} = data;
if (list.length === 0) {
return (
<Empty description="暂无分组" image={Empty.PRESENTED_IMAGE_SIMPLE} />
);
}
console.log(list.length);
return (
<InfiniteScroll
dataLength={list.length}
next={loadMoreData}
hasMore={list.length < total}
loader={<Skeleton paragraph={{ rows: 1 }} active />}
endMessage={<Divider plain>线</Divider>}
scrollableTarget="scrollableDiv"
>
<List
dataSource={list}
renderItem={(item) => (
<List.Item
key={item.id}
// onClick={() => onTagItemClick(item)}
className="tag-item"
>
<div>
{!editable && (
<Checkbox
checked={
// value.find((tag) => tag.id === item.id) ? true : false
!!value.find((tag) => tag.id === item.id)
}
onChange={(e) => onTagItemChange(item, e)}
style={{ marginRight: '8px' }}
/>
)}
{item.tagName}
</div>
{editable && (
<div className="group-options">
<Button
type="link"
size="small"
icon={<EditFilled />}
onClick={(e) => {
e.stopPropagation();
onEdit?.(item);
// onEditGroup(item.id);
}}
/>
<Button
type="link"
size="small"
icon={<DeleteFilled />}
onClick={(e) => {
e.stopPropagation();
onDelete?.(item.id);
}}
/>
</div>
)}
</List.Item>
)}
/>
</InfiniteScroll>
);
};

View File

@@ -0,0 +1,96 @@
// types.ts
export interface TagItem {
id: number;
tagName: string;
createTime: string;
groupId?: number; // 可选因为API返回的数据可能没有这个字段
}
export interface GroupItem {
id: number;
groupName: string;
createTime?: string;
tags?: TagItem[];
}
// API响应类型
export interface TagsResponse {
list: TagItem[];
total: number;
}
// export interface GroupsResponse {
// data: GroupItem[];
// }
// 核心组件的Props
export interface GroupTagCoreProps {
// groups: GroupItem[];
requset: RequsetConfig;
height?: number;
editable?: boolean;
onChange?: (value: TagItem[]) => void;
value: TagItem[];
// selectedTags: number[];
// onTagChange?: (selectedTags: number[]) => void;
// onGroupClick?: (groupId: number) => void;
// onLoadMoreTags?: (groupId: number, page: number) => Promise<TagsResponse>;
// loading?: boolean;
// loadingGroups?: Set<number>;
// loadingMoreTags?: Set<number>;
// editable?: boolean;
// onAddGroup?: () => void;
// onAddTag?: (groupId: number) => void;
// onDeleteGroup?: (groupId: number) => Promise<void> | void;
// onDeleteTag?: (tagId: number) => Promise<void> | void;
// onEditGroup?: (groupId: number, newName: string) => Promise<void> | void;
// onEditTag?: (tagId: number, newName: string) => Promise<void> | void;
// className?: string;
// height?: number;
// showSearch?: boolean;
// pageSize?: number;
}
interface RequsetConfig<T = any> {
groupsApi: {
get: (params?: T) => Promise<any>;
create: (params: any) => Promise<any>;
delete: (id: number) => Promise<any>;
update: (params: T) => Promise<any>;
};
tagsApi: {
get: (params?: T) => Promise<any>;
create: (params: T) => Promise<any>;
delete: (id: number) => Promise<any>;
update: (params: T) => Promise<any>;
};
}
// Select组件的Props
export interface GroupTagSelectProps {
value?: number[];
onChange?: (value: number[]) => void;
placeholder?: string;
className?: string;
request: RequsetConfig;
editable?: boolean;
// onAddGroup?: (groupName: string) => Promise<void> | void;
// onAddTag?: (groupId: number, tagName: string) => Promise<void> | void;
// onDeleteGroup?: (groupId: number) => Promise<void> | void;
// onDeleteTag?: (tagId: number) => Promise<void> | void;
// pageSize?: number;
}
// Modal组件的Props
export interface GroupTagModalProps {
visible: boolean;
editable?: boolean;
onChange?: (value: TagItem[]) => void;
className?: string;
onCancel: () => void;
request: RequsetConfig;
onOk?: (selectedTags: TagItem[]) => void;
title?: string;
width?: number;
height?: number;
value?: TagItem[];
}

View File

@@ -0,0 +1,170 @@
// RenameRule.less
.rename-rule-card {
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
.rename-rule-card-preview {
display: flex;
.left {
width: 200px;
}
}
&:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
transform: translateY(-2px);
}
.ant-card-head {
background: linear-gradient(135deg, #1890ff, #36cfc9);
border-radius: 8px 8px 0 0;
.ant-card-head-title {
color: white;
font-weight: 600;
}
.ant-card-extra {
.ant-btn {
border-radius: 6px;
transition: all 0.3s ease;
&:hover {
background: rgba(255, 255, 255, 0.3) !important;
transform: translateY(-1px);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
}
}
.ant-card-body {
padding: 24px;
}
// 输入框样式
.ant-input,
.ant-input-number,
.ant-select-selector {
border-radius: 6px;
transition: all 0.3s ease;
&:focus,
&.ant-select-focused {
border-color: #40a9ff;
box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}
}
// 行间距
.ant-row {
align-items: center;
.ant-col {
display: flex;
align-items: center;
}
}
// 预览信息样式
.preview-info {
background: #f6f8fa;
border: 1px solid #e1e4e8;
border-radius: 6px;
padding: 12px 16px;
margin-top: 8px;
.ant-typography {
margin: 0;
}
}
// Checkbox 样式
.ant-checkbox-wrapper {
.ant-checkbox {
&.ant-checkbox-checked {
.ant-checkbox-inner {
background-color: #1890ff;
border-color: #1890ff;
}
}
}
}
// 响应式设计
@media (max-width: 768px) {
.ant-card-body {
padding: 16px;
}
.ant-row {
margin-bottom: 16px;
.ant-col {
margin-bottom: 8px;
&:last-child {
margin-bottom: 0;
}
}
}
.ant-card-extra {
.ant-space {
flex-direction: column;
width: 100%;
.ant-btn {
width: 100%;
}
}
}
}
// 暗色主题
@media (prefers-color-scheme: dark) {
background: #1f1f1f;
border-color: #303030;
.ant-card-head {
background: linear-gradient(135deg, #1668dc, #13c2c2);
}
.preview-info {
background: #262626;
border-color: #434343;
}
}
// 动画效果
.ant-space-item {
transition: all 0.3s ease;
}
// 禁用状态
.ant-input:disabled,
.ant-input-number:disabled {
background-color: #f5f5f5;
opacity: 0.6;
cursor: not-allowed;
}
}
// 全局动画
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.rename-rule-card {
animation: fadeIn 0.3s ease-out;
}

View File

@@ -0,0 +1,398 @@
// RenameRule.tsx - 修复占位符替换顺序
import {
DownOutlined,
ExclamationCircleOutlined,
QuestionCircleOutlined,
UpOutlined,
} from '@ant-design/icons';
import {
Alert,
Button,
Card,
Input,
InputNumber,
Select,
Space,
Tooltip,
Typography,
} from 'antd';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import './index.less';
const { Text } = Typography;
const { Option } = Select;
export interface FileItem {
id: number;
originalName: string;
}
export interface RenameRule {
pattern: string;
startNumber: number;
numberDirection: 'up' | 'down';
matchPattern: string;
useMatch: boolean;
numberPadding: number;
}
export interface RenameResult extends FileItem {
newName: string;
isChanged: boolean;
isMatched: boolean;
}
interface RenameRuleProps {
files: FileItem[];
onPreview?: (results: RenameResult[]) => void;
onRename?: (results: RenameResult[]) => void;
loading?: boolean;
className?: string;
}
// 占位符配置
// const PLACEHOLDERS = [
// { key: "$n", desc: "数字序号(不补零)", example: "1, 2, 3..." },
// { key: "$nn", desc: "数字序号(2位补零)", example: "01, 02, 03..." },
// { key: "$nnn", desc: "数字序号(3位补零)", example: "001, 002, 003..." },
// { key: "$nnnn", desc: "数字序号(4位补零)", example: "0001, 0002, 0003..." },
// { key: "$name", desc: "原文件名", example: "photo1" },
// { key: "$ext", desc: "扩展名(不含点)", example: "jpg" },
// { key: "$EXT", desc: "扩展名(大写)", example: "JPG" },
// ];
const RenameRuleComponent: React.FC<RenameRuleProps> = ({
files,
onPreview,
className,
}) => {
const [rule, setRule] = useState<RenameRule>({
pattern: '',
startNumber: 1,
numberDirection: 'up',
matchPattern: '',
useMatch: false,
numberPadding: 2,
});
const [matchError, setMatchError] = useState<string>('');
// 初始化时自动设置模式
useEffect(() => {
console.log(files);
if (files.length > 0 && !rule.pattern) {
setRule((prev) => ({ ...prev, pattern: '$name$nn' }));
}
}, [files, rule.pattern]);
// 安全的正则表达式匹配
const isFileMatched = useCallback(
(file: FileItem, pattern: string): boolean => {
if (!pattern.trim()) return true;
try {
const regex = new RegExp(pattern, 'i');
const fullFileName = file.originalName;
return (
regex.test(file.originalName) ||
// regex.test(file.extension) ||
// regex.test(file.extension?.replace(".", "")) ||
regex.test(fullFileName)
);
} catch (error) {
console.warn('正则表达式错误:', error);
setMatchError(
`正则表达式错误: ${
error instanceof Error ? error.message : '未知错误'
}`,
);
return false;
}
},
[],
);
// 修复的占位符替换函数
const replacePlaceholders = useCallback(
(pattern: string, file: FileItem, fileIndex: number) => {
let result = pattern;
// 计算序号
let number: number;
if (rule.numberDirection === 'up') {
number = rule.startNumber + fileIndex;
} else {
number = rule.startNumber - fileIndex;
}
// 先用临时标记替换非数字占位符
const tempMarkers = {
name: '___TEMP_NAME___',
ext: '___TEMP_EXT___',
EXT: '___TEMP_EXT_UPPER___',
};
// 第一步:替换非数字占位符为临时标记
result = result.replace(/\$name/g, tempMarkers.name);
result = result.replace(/\$EXT/g, tempMarkers.EXT);
result = result.replace(/\$ext/g, tempMarkers.ext);
// 第二步:替换数字占位符(按长度从长到短,避免冲突)
result = result.replace(/\$nnnn/g, number.toString().padStart(4, '0'));
result = result.replace(/\$nnn/g, number.toString().padStart(3, '0'));
result = result.replace(/\$nn/g, number.toString().padStart(2, '0'));
result = result.replace(/\$n/g, number.toString());
// 第三步:将临时标记替换为实际值
result = result.replace(
new RegExp(tempMarkers.name, 'g'),
file.originalName,
);
// result = result.replace(
// new RegExp(tempMarkers.ext, "g"),
// // file.extension.replace(".", "")
// );
// result = result.replace(
// new RegExp(tempMarkers.EXT, "g"),
// file.extension.replace(".", "").toUpperCase()
// );
return result;
},
[rule.startNumber, rule.numberDirection],
);
// 使用 useMemo 缓存计算结果
const previewResults = useMemo(() => {
setMatchError('');
const matchedFiles: FileItem[] = [];
const allResults: RenameResult[] = [];
files.forEach((file) => {
const isMatched = rule.useMatch
? isFileMatched(file, rule.matchPattern)
: true;
if (isMatched) {
matchedFiles.push(file);
}
});
files.forEach((file) => {
const isMatched = rule.useMatch
? isFileMatched(file, rule.matchPattern)
: true;
if (!isMatched || !rule.pattern) {
allResults.push({
...file,
newName: file.originalName,
isChanged: false,
isMatched,
});
return;
}
const matchedIndex = matchedFiles.findIndex((f) => f.id === file.id);
const newName = replacePlaceholders(rule.pattern, file, matchedIndex);
const isChanged = newName !== file.originalName;
allResults.push({
...file,
newName,
isChanged,
isMatched,
});
});
return allResults;
}, [files, rule, isFileMatched, replacePlaceholders]);
// 调用预览回调
useEffect(() => {
if (onPreview) {
onPreview(previewResults);
}
}, [previewResults]);
// // 重置规则
// const handleReset = useCallback(() => {
// setRule({
// pattern: "$name$nn",
// startNumber: 1,
// numberDirection: "up",
// matchPattern: "",
// useMatch: false,
// numberPadding: 2,
// });
// setMatchError("");
// }, []);
// 规则更新处理函数
const updateRule = useCallback((updates: Partial<RenameRule>) => {
setRule((prev) => ({ ...prev, ...updates }));
if (updates.matchPattern !== undefined) {
setMatchError('');
}
}, []);
// // 插入占位符
// const insertPlaceholder = useCallback(
// (placeholder: string) => {
// const input = document.querySelector(
// ".pattern-input"
// ) as HTMLInputElement;
// if (input) {
// const start = input.selectionStart || 0;
// const end = input.selectionEnd || 0;
// const currentValue = rule.pattern;
// const newValue =
// currentValue.slice(0, start) + placeholder + currentValue.slice(end);
// updateRule({ pattern: newValue });
// setTimeout(() => {
// input.focus();
// input.setSelectionRange(
// start + placeholder.length,
// start + placeholder.length
// );
// }, 0);
// }
// },
// [rule.pattern, updateRule]
// );
// // 递增起始编号
// const incrementStartNumber = useCallback(() => {
// updateRule({ startNumber: rule.startNumber + 1 });
// }, [rule.startNumber, updateRule]);
// // 递减起始编号
// const decrementStartNumber = useCallback(() => {
// updateRule({ startNumber: Math.max(0, rule.startNumber - 1) });
// }, [rule.startNumber, updateRule]);
// 快速设置常用模式
const setQuickPattern = useCallback(
(pattern: string) => {
updateRule({ pattern });
},
[updateRule],
);
return (
<Card className={`rename-rule-card ${className || ''}`}>
<div className="rename-rule-card-preview">
<div className="left">
<Text strong style={{ marginBottom: 8, display: 'block' }}>
:
</Text>
{previewResults.map((item) => (
<p key={item.id}>{`${item.newName}`}</p>
))}
</div>
<Space direction="vertical" style={{ width: '100%' }} size="large">
{/* 错误提示 */}
{matchError && (
<Alert
message="匹配模式错误"
description={matchError}
type="error"
icon={<ExclamationCircleOutlined />}
closable
onClose={() => setMatchError('')}
/>
)}
<Space wrap>
<Text strong>:</Text>
<Button
size="small"
onClick={() => setQuickPattern('$name$nn')}
type={rule.pattern === '$name$nn' ? 'primary' : 'default'}
>
+
</Button>
<Button
size="small"
onClick={() => setQuickPattern('$nn_$name')}
type={rule.pattern === '$nn_$name' ? 'primary' : 'default'}
>
+
</Button>
<Button
size="small"
onClick={() => setQuickPattern('新文件$nnn')}
type={rule.pattern === '新文件$nnn' ? 'primary' : 'default'}
>
+
</Button>
<Button
size="small"
onClick={() => setQuickPattern('$name_副本$nn')}
type={rule.pattern === '$name_副本$nn' ? 'primary' : 'default'}
>
+
</Button>
</Space>
{/* 命名模式 */}
<Space>
<Input
className="pattern-input"
placeholder="例如: $name$nn 或 新文件$nnn"
value={rule.pattern}
allowClear
onChange={(e) => updateRule({ pattern: e.target.value })}
suffix={
<Tooltip title="使用占位符创建命名规则">
<QuestionCircleOutlined style={{ color: '#bfbfbf' }} />
</Tooltip>
}
/>
</Space>
<Input
placeholder="例如: photo (匹配包含photo的文件) 或 \.jpg$ (匹配jpg文件)"
value={rule.matchPattern}
allowClear
onChange={(e) => updateRule({ matchPattern: e.target.value })}
/>
<Space>
<Text strong>:</Text>
<InputNumber
min={0}
max={9999}
value={rule.startNumber}
onChange={(value) => updateRule({ startNumber: value || 1 })}
style={{ width: '60%', textAlign: 'center' }}
controls={true}
/>
<Select
value={rule.numberDirection}
onChange={(value) => updateRule({ numberDirection: value })}
style={{ width: '100%' }}
>
<Option value="up">
<Space>
<UpOutlined />
</Space>
</Option>
<Option value="down">
<Space>
<DownOutlined />
</Space>
</Option>
</Select>
</Space>
</Space>
</div>
</Card>
);
};
export default React.memo(RenameRuleComponent);

View File

@@ -0,0 +1,111 @@
// 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[], active?: number) => void;
placeholder?: string;
maxCount?: number;
tagProps?: TagProps;
disabled?: boolean;
editable?: boolean;
}
const TagEditor: React.FC<TagEditorProps> = ({
value = [],
onChange,
placeholder = '请输入标签',
maxCount,
tagProps,
editable = true,
disabled = false,
}) => {
// const [tags, setTags] = useState<string[]>(value);
const [inputVisible, setInputVisible] = useState(false);
const [inputValue, setInputValue] = useState('');
const tags = useMemo(() => {
console.log(value);
return value || [];
}, [value]);
const handleClose = (removedTag: string) => {
const active = tags.indexOf(removedTag);
const newTags = tags.filter((tag) => tag !== removedTag);
onChange?.(newTags, active);
};
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 &&
editable &&
!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

@@ -0,0 +1,8 @@
.uploader-card {
background-color: #fff;
:global {
.ant-upload-drag {
background-color: #fff;
}
}
}

View File

@@ -0,0 +1,167 @@
import {
DeleteOutlined,
FileTextOutlined,
PlayCircleOutlined,
} from '@ant-design/icons';
import { message, Upload } from 'antd';
import type { RcFile, UploadFile, UploadProps } from 'antd/lib/upload';
import React, { useState } from 'react';
import { createSample } from '@/services/ai/sample';
import styles from './index.module.less';
const { Dragger } = Upload;
interface AudioUploaderProps {
value?: UploadFile[] | UploadFile | null;
onChange?: (file: UploadFile[] | UploadFile | null) => void;
maxSize?: number;
accept?: string;
disabled?: boolean;
maxCount?: number;
placeholder?: string;
}
const AudioUploader: React.FC<AudioUploaderProps> = ({
value,
onChange,
maxSize = 10,
accept = '.mp3,.wav,.flac,.aac,.ogg',
disabled = false,
maxCount = 10,
placeholder = '点击或拖拽音频文件到此区域上传',
}) => {
const [fileList, setFileList] = useState<UploadFile[]>(() => {
if (Array.isArray(value)) {
return value;
} else if (value) {
return [value];
}
return [];
});
const [uploading, setUploading] = useState<boolean>(false);
const beforeUpload = (file: RcFile): boolean => {
const isAudio = file.type.startsWith('audio/');
if (!isAudio) {
message.error('只能上传音频文件!');
return false;
}
// 检查文件大小
const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
if (!isLtMaxSize) {
message.error(`音频文件大小不能超过 ${maxSize}MB`);
return false;
}
// 检查文件数量限制
if (fileList.length >= maxCount) {
message.error(`最多只能上传 ${maxCount} 个文件!`);
return false;
}
return true;
};
// 实际的后端接口上传
const uploadToServer = async (file: File) => {
const formData = new FormData();
formData.append('files', file);
const response = await createSample(formData);
message.success('上传成功!');
return response;
};
const customRequest: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options;
try {
setUploading(true);
// 模拟进度更新
onProgress?.({ percent: 10 });
// 调用后端接口
const result = await uploadToServer(file as File);
console.log(result, 'res');
onProgress?.({ percent: 100 });
if (result) {
// 构造返回数据
const responseData = {
url: result[0].fileUrl,
name: result[0].fileName || (file as File).name,
uid: (file as any).uid,
status: 'done' as const,
response: result,
};
onSuccess?.(responseData);
} else {
throw new Error(result.message || '上传失败');
}
} catch (error) {
console.error('Upload error:', error);
onError?.(error as Error);
message.error(`上传失败: ${(error as Error).message}`);
} finally {
setUploading(false);
}
};
// const handleChange: UploadProps["onChange"] = ({
// fileList: newFileList,
// file,
// }) => {
// setFileList(newFileList);
// onChange?.(newFileList);
// };
const handleRemove = (file: UploadFile): boolean => {
const newFileList = fileList.filter((item) => item.uid !== file.uid);
setFileList(newFileList);
onChange?.(newFileList);
return true;
};
const handlePreview = (file: UploadFile): void => {
const audioUrl = file.url || (file.response as any)?.url;
if (audioUrl) {
const audio = new Audio(audioUrl);
audio.play().catch(() => {
message.error('音频播放失败');
});
}
};
const uploadProps: UploadProps = {
name: 'file',
multiple: true,
fileList,
accept,
disabled: disabled || uploading,
beforeUpload,
customRequest,
// onChange: handleChange,
onRemove: handleRemove,
onPreview: handlePreview,
showUploadList: {
showPreviewIcon: true,
showRemoveIcon: true,
previewIcon: <PlayCircleOutlined />,
removeIcon: <DeleteOutlined />,
},
};
return (
<div className={styles['uploader-card']}>
<Dragger {...uploadProps}>
<p className="">
<FileTextOutlined style={{ fontSize: 36 }} />
</p>
<p className="ant-upload-text">{placeholder}</p>
<p className="ant-upload-hint">
{accept} {maxCount}
</p>
</Dragger>
</div>
);
};
export default AudioUploader;

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,83 @@
// 使用示例 - App.tsx
import { Modal, message, Space } from 'antd';
import React, { useEffect, useState } from 'react';
import RenameRule, {
type FileItem,
type RenameResult,
} from '@/components/RenameRule';
import { updateSamples } from '@/services/ai/sample';
const TagManager: React.FC<{
visible: boolean;
files: FileItem[];
onCancel?: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
onOk?: () => void;
}> = ({ visible, files: beforeFiles, onCancel, onOk }) => {
const [files, setFiles] = useState<FileItem[]>(beforeFiles);
useEffect(() => {
setFiles(beforeFiles);
}, [beforeFiles]);
const [previewResults, setPreviewResults] = useState<RenameResult[]>([]);
const [loading, setLoading] = useState(false);
// 预览回调o+
const handlePreview = (results: RenameResult[]) => {
setPreviewResults(results);
};
const handleOk = async () => {
try {
setLoading(true);
const results = previewResults.map((result) => ({
id: result.id,
sampleName: `${result.newName}`,
}));
await updateSamples(results);
onOk?.();
message.success('重命名成功');
} finally {
setLoading(false);
}
};
// // 重命名回调
// const handleRename = async (results: RenameResult[]) => {
// setLoading(true);
// try {
// console.log("执行预览:", results);
// // 模拟API调用
// await new Promise((resolve) => setTimeout(resolve, 1000));
// message.success(`成功重命名 ${results.length} 个文件`);
// } catch (error) {
// message.error("重命名失败");
// } finally {
// setLoading(false);
// }
// };
return (
<Modal
width={800}
onCancel={onCancel}
onOk={handleOk}
open={visible}
title="重命名文件"
>
<div style={{ padding: '24px' }}>
<Space direction="vertical" style={{ width: '100%' }} size="large">
{/* 独立的重命名规则组件 */}
<RenameRule
files={files}
onPreview={handlePreview}
// onRename={handleRename}
loading={loading}
/>
</Space>
</div>
</Modal>
);
};
export default TagManager;

View File

@@ -0,0 +1,173 @@
import type { ProColumns } from '@ant-design/pro-components';
import GroupTagSelect from '@/components/GroupTag/GroupTagSelect';
import {
type AiSampleRespVO,
createSampleTag,
createSampleTagGroup,
deleteSampleTag,
deleteSampleTagGroup,
getSampleTagGroup,
getSampleTagPage,
updateSampleTag,
updateSampleTagGroup,
} from '@/services/ai/sample';
export const baseTenantColumns: ProColumns<AiSampleRespVO>[] = [
{
title: '样本名称',
dataIndex: 'sampleName',
// width: 500,
},
{
title: '注释',
dataIndex: 'remark',
hideInSearch: true,
},
{
title: '标签',
hideInTable: true,
dataIndex: 'tag_name',
valueType: 'select',
search: {
transform: (value) => {
console.log(value);
return value.join(',');
},
},
renderFormItem: (_) => {
return (
<GroupTagSelect
request={{
groupsApi: {
get: getSampleTagGroup,
create: createSampleTagGroup,
delete: deleteSampleTagGroup,
update: updateSampleTagGroup,
},
tagsApi: {
get: getSampleTagPage,
create: createSampleTag,
delete: deleteSampleTag,
update: updateSampleTag,
},
}}
editable
placeholder="请选择技术栈"
/>
);
},
},
{
title: '样本格式',
hideInTable: true,
dataIndex: 'sample_mine_type',
},
];
// 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,332 @@
import { ProForm, ProFormGroup, ProFormText } from '@ant-design/pro-components';
import { Button, message, Space, Tag } from 'antd';
import type { RowSelectionType } from 'antd/es/table/interface';
import type { FormInstance } from 'antd/lib';
import dayjs from 'dayjs';
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import GroupTagModal from '@/components/GroupTag/GroupTagModal';
import type { TagItem } from '@/components/GroupTag/types';
import type { FileItem } from '@/components/RenameRule';
import {
createSampleTag,
createSampleTagGroup,
deleteSample,
deleteSampleTag,
deleteSampleTagGroup,
deleteSampleTagRelate,
getSampleTagGroup,
getSampleTagPage,
relateSample,
updateSamples,
updateSampleTag,
updateSampleTagGroup,
} from '@/services/ai/sample';
import TagManager from './components/tag-manager';
interface SampleTagDetailProps<T> {
onRefresh?: (type?: string) => void;
type: RowSelectionType;
data?: T[];
}
const SampleTagDetail = <T extends Record<string, any>>(
props: SampleTagDetailProps<T>,
) => {
const formRef = useRef<FormInstance>(null);
const { type = 'radio', data } = props;
const [modalVisible, setModalVisible] = useState<boolean>(false);
const [tagManagerVisible, setTagManagerVisible] = useState<boolean>(false);
const [value, setValue] = useState<{
tagId?: number | number[];
id?: number;
remark?: string;
sampleIds?: number[];
tags?: TagItem[];
updateTime?: number;
createTime?: number;
sampleSize?: number;
sampleMineType?: string;
sampleTime?: number;
}>({});
const handleAddTag = useCallback(() => {
setModalVisible(true);
}, [modalVisible]);
// const radioData = data && data[0];
// // 当 radioData 改变时更新表单值
useEffect(() => {
if (type === 'radio') {
const item = data?.[0];
setValue({ ...item, sampleIds: [item?.id] });
} else {
const sampleIds = data?.map((sample) => sample.id) || [];
const tags = data?.map((sample) => {
return sample.tags;
});
const map = new Map();
const tags_total = tags
?.flat()
.filter((v) => !map.has(v.id) && map.set(v.id, v));
setValue({ tags: tags_total as TagItem[], sampleIds });
}
}, [type, data]);
useEffect(() => {
formRef.current?.setFieldsValue(value);
}, [value]);
const tagNames = useMemo<FileItem[]>(() => {
return (
data?.map((tag) => {
return {
id: tag.id,
originalName: tag.sampleName,
};
}) || []
);
}, [data]);
const onListAddTag = async (tags: TagItem[]) => {
const sampleIds = data?.map((sample) => sample.id);
const ids = tags?.map((tag) => tag.id);
await relateSample({ tagId: ids, sampleIds: sampleIds as number[] });
setModalVisible(false);
const map = new Map();
const newTags = [...(value.tags || []), ...tags];
const tags_total = newTags
?.flat()
.filter((v) => !map.has(v.id) && map.set(v.id, v));
setValue({ ...value, tags: tags_total });
// 执行刷新回调
message.success('添加标签成功');
if (props.onRefresh) {
props.onRefresh();
}
};
const handleDeleteAll = async () => {
const ids = data?.map((sample) => sample.id);
if (ids) {
await deleteSample(ids.join(','));
message.success('删除成功');
if (props.onRefresh) {
props.onRefresh('delete');
}
}
};
// 下载
const handleDownloadAll = () => {};
const handleTagManager = () => {
setTagManagerVisible(true);
};
const forMap = (tags: TagItem[]) => (
<div style={{ display: 'inline-block', marginBottom: 10 }}>
{tags.map((tag) => (
<Tag
closable
key={tag.id}
style={{ marginBottom: 10 }}
onClose={async (e) => {
e.preventDefault();
await deleteSampleTagRelate({
sampleIds: value.sampleIds || [],
tagId: [tag.id],
});
message.success('删除成功');
props?.onRefresh?.();
setValue({ ...value, tags: tags.filter((t) => t.id !== tag.id) });
}}
>
{tag.tagName}
</Tag>
))}
</div>
);
const onRename = () => {
props.onRefresh?.();
setTagManagerVisible(false);
};
return (
<>
<ProForm name="validate_other" formRef={formRef} submitter={false}>
{type === 'radio' && (
<ProFormGroup title="预览">
{data?.[0].sampleFilePath && (
<audio
controls
preload="true"
crossOrigin="anonymous"
style={{ marginBottom: 24 }}
>
<source src={data[0].sampleFilePath} />
<track kind="captions" />
</audio>
)}
</ProFormGroup>
)}
<ProFormGroup title="基本信息">
{type === 'radio' && (
<ProFormText
width="md"
name="sampleName"
placeholder="请输入样本名称"
fieldProps={{
onBlur: async (e) => {
if (e.target.value) {
const newData =
data?.map((sample) => {
return {
id: sample.id,
sampleName: e.target.value,
};
}) || [];
await updateSamples(newData);
props?.onRefresh?.();
message.success('更新成功');
}
},
}}
rules={[{ required: true, message: '样本名称不能为空' }]}
/>
)}
<ProFormText
width="md"
fieldProps={{
onBlur: async (e) => {
if (e.target.value) {
const newData =
data?.map((sample) => {
return {
id: sample.id,
remark: e.target.value,
};
}) || [];
await updateSamples(newData);
props?.onRefresh?.();
}
},
}}
name="remark"
placeholder="请输入注释"
/>
</ProFormGroup>
<ProFormGroup title="标签">
{/* <Form.Item name="tag"> */}
{forMap(value.tags || [])}
</ProFormGroup>
<Button
type="dashed"
block
style={{ marginBottom: 24 }}
onClick={handleAddTag}
>
</Button>
<ProFormGroup title="文本信息" block></ProFormGroup>
<Space size={10} style={{ width: '100%', marginBottom: 12 }}>
<span>: </span>
<span>{dayjs(value.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
</Space>
<Space size={10} style={{ width: '100%', marginBottom: 12 }}>
<span></span>
<span>{dayjs(value.updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
</Space>
<Space size={10} style={{ width: '100%', marginBottom: 12 }}>
<span>: </span>
<span>{value.sampleSize}</span>
</Space>
<Space size={10} style={{ width: '100%', marginBottom: 12 }}>
<span>: </span>
<span>{value.sampleMineType}</span>
</Space>
<Space size={10} style={{ width: '100%', marginBottom: 12 }}>
<span>: </span>
<span>{value.sampleTime}</span>
</Space>
{type === 'checkbox' && (
<>
<ProFormGroup title="其他"></ProFormGroup>
<Button
block
style={{ marginBottom: 24 }}
onClick={handleTagManager}
>
</Button>
<Button
block
style={{ marginBottom: 24 }}
onClick={handleDownloadAll}
>
</Button>
<Button
block
color="danger"
style={{ marginBottom: 24 }}
onClick={handleDeleteAll}
>
</Button>
</>
)}
</ProForm>
<GroupTagModal
visible={modalVisible}
onCancel={() => setModalVisible(false)}
onChange={onListAddTag}
editable={false}
value={value?.tags}
request={{
groupsApi: {
get: getSampleTagGroup,
create: createSampleTagGroup,
delete: deleteSampleTagGroup,
update: updateSampleTagGroup,
},
tagsApi: {
get: getSampleTagPage,
create: createSampleTag,
delete: deleteSampleTag,
update: updateSampleTag,
},
}}
title="管理技术标签"
width={800}
height={500}
/>
<TagManager
visible={tagManagerVisible}
files={tagNames}
onOk={onRename}
onCancel={() => setTagManagerVisible(false)}
></TagManager>
<Space style={{ width: '100%', justifyContent: 'center', padding: 12 }}>
<Button color="danger" onClick={() => {}}>
</Button>
<Button color="danger" variant="solid" onClick={handleDeleteAll}>
</Button>
</Space>
</>
);
};
export default React.memo(SampleTagDetail) as <T extends Record<string, any>>(
props: SampleTagDetailProps<T>,
) => React.ReactElement;

View File

@@ -0,0 +1,21 @@
.tag-content {
display: flex;
width: 100%;
background: #fff;
overflow: auto;
:global {
.ant-pro-table {
flex: 1 auto;
}
.detail {
display: flex;
flex-direction: column;
border-left: 1px solid #e8e8e8;
width: 400px;
padding: 16px;
form {
flex: 1;
}
}
}
}

View File

@@ -0,0 +1,127 @@
import type { ActionType } from '@ant-design/pro-components';
import type { RowSelectionType } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import GroupTagModal from '@/components/GroupTag/GroupTagModal';
import UploadCard from '@/components/Upload/UploadCard';
import {
type AiSampleRespVO,
createSampleTag,
createSampleTagGroup,
deleteSampleTag,
deleteSampleTagGroup,
getSamplePage,
getSampleTagGroup,
getSampleTagPage,
type SampleReqVo,
updateSampleTag,
updateSampleTagGroup,
} from '@/services/ai/sample';
import { baseTenantColumns } from './config';
import SampleTagDetail from './detail';
import styles from './index.module.less';
const SampleTag: React.FC = () => {
const tableRef = useRef<ActionType>(null);
const [modalVisible, setModalVisible] = useState(false);
const [selectedRows, setSelectedRows] = useState<AiSampleRespVO[]>([]);
const [selectTableType, setSelectTableType] =
useState<RowSelectionType>('radio');
const handleAll = (selectTableType: RowSelectionType) => {
setSelectedRows([]);
setSelectTableType(selectTableType === 'radio' ? 'checkbox' : 'radio');
};
const handleTags = () => {
setModalVisible(true);
};
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: selectTableType === 'checkbox' ? '取消编辑' : '批量编辑',
onClick: () => handleAll(selectTableType),
},
{
key: 'tags',
label: '标签管理',
type: 'primary',
onClick: handleTags,
},
];
const onFetch = async (params: SampleReqVo) => {
const data = await getSamplePage({
...params,
});
return {
data: data.list,
total: data.total,
success: true,
};
};
const onRefresh = (type?: string) => {
tableRef.current?.reload();
tableRef.current?.onValuesChange({}, {});
type && setSelectedRows([]);
};
return (
<>
<UploadCard />
<div className={styles['tag-content']}>
<EnhancedProTable<AiSampleRespVO>
ref={tableRef}
columns={baseTenantColumns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="样本列表"
showIndex={false}
enableRowClick={true}
rowSelection={{
type: selectTableType,
selectedRowKeys: selectedRows.map((item) => item.id) as React.Key[],
onChange: (_, selectedRows) => {
setSelectedRows(selectedRows);
},
}}
/>
{selectedRows.length > 0 && (
<div className="detail">
<SampleTagDetail<AiSampleRespVO>
type={selectTableType}
data={selectedRows}
onRefresh={onRefresh}
/>
</div>
)}
</div>
<GroupTagModal
visible={modalVisible}
onCancel={() => setModalVisible(false)}
editable={true}
request={{
groupsApi: {
get: getSampleTagGroup,
create: createSampleTagGroup,
delete: deleteSampleTagGroup,
update: updateSampleTagGroup,
},
tagsApi: {
get: getSampleTagPage,
create: createSampleTag,
delete: deleteSampleTag,
update: updateSampleTag,
},
}}
title="管理技术标签"
width={800}
height={500}
/>
</>
);
};
export default SampleTag;

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,125 @@
// src/pages/system/menu/config.tsx
import type {
ProColumns,
ProFormColumnsType,
} from '@ant-design/pro-components';
import { Switch } from 'antd';
import type { MenuVO } from '@/services/system/menu';
export const baseMenuColumns: ProColumns<MenuVO>[] = [
{
title: '菜单名称',
dataIndex: 'name',
width: 150,
},
{
title: '图标',
dataIndex: 'icon',
width: 60,
render: (_, record: MenuVO) => (
<span>
{record.icon ? <i className={`anticon ${record.icon}`} /> : '—'}
</span>
),
},
{
title: '排序',
dataIndex: 'sort',
width: 80,
},
{
title: '权限标识',
dataIndex: 'permission',
width: 150,
},
{
title: '组件路径',
dataIndex: 'component',
width: 150,
},
{
title: '组件名称',
dataIndex: 'componentName',
width: 150,
},
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (_, record: MenuVO) => (
<Switch
checked={record.status === 1}
disabled={true} // 可后续改为可编辑
/>
),
},
];
export const formColumns = (_type: string): ProFormColumnsType[] => [
{
title: '菜单名称',
dataIndex: 'name',
formItemProps: {
rules: [
{
required: true,
message: '请输入菜单名称',
},
],
},
},
{
title: '图标',
dataIndex: 'icon',
valueType: 'select',
fieldProps: {
placeholder: '请选择图标',
options: [
{ label: '商品', value: 'icon-product' },
{ label: '系统', value: 'icon-system' },
{ label: '用户', value: 'icon-user' },
{ label: '设置', value: 'icon-setting' },
],
},
},
{
title: '排序',
dataIndex: 'sort',
valueType: 'digit',
fieldProps: {
placeholder: '请输入排序值',
},
},
{
title: '权限标识',
dataIndex: 'permission',
fieldProps: {
placeholder: '请输入权限标识',
},
},
{
title: '组件路径',
dataIndex: 'component',
fieldProps: {
placeholder: '请输入组件路径',
},
},
{
title: '组件名称',
dataIndex: 'componentName',
fieldProps: {
placeholder: '请输入组件名称',
},
},
{
title: '状态',
dataIndex: 'status',
valueType: 'select',
fieldProps: {
options: [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
],
},
},
];

View File

@@ -1,5 +1,126 @@
const SyStemMenu = () => {
return <>SyStemMenu</>;
// src/pages/system/menu/index.tsx
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 {
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 [type, setType] = useState<'create' | 'update'>('create');
const [id, setId] = useState<number>(0);
const handleEdit = (record: MenuVO) => {
setType('update');
setId(record.id);
configurableDrawerRef.current?.open(record);
};
export default SyStemMenu;
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({});
};
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,
},
];
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}
/>
</>
);
};
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

@@ -1,25 +1,19 @@
import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import { request } from '@umijs/max';
import { message, notification } from 'antd';
import { deleteUserCache } from '@/hooks/web/useCache';
import {
getAccessToken,
getRefreshToken,
getTenantId,
setToken,
} from './utils/auth';
import { message } from 'antd';
import { getAccessToken, getRefreshToken, setToken } from './utils/auth';
const tenantEnable = process.env.VITE_APP_TENANT_ENABLE;
// const tenantEnable = process.env.VITE_APP_TENANT_ENABLE;
// const { result_code, base_url, request_timeout } = config;
// 错误处理方案: 错误类型
enum ErrorShowType {
SILENT = 0,
WARN_MESSAGE = 1,
ERROR_MESSAGE = 2,
NOTIFICATION = 3,
REDIRECT = 9,
}
// enum ErrorShowType {
// SILENT = 0,
// WARN_MESSAGE = 1,
// ERROR_MESSAGE = 2,
// NOTIFICATION = 3,
// REDIRECT = 9,
// }
// 与后端约定的响应数据格式
interface ResponseStructure {
success: boolean;
@@ -27,27 +21,28 @@ interface ResponseStructure {
code?: number;
msg?: string;
}
const ignoreMsgs = [
'无效的刷新令牌', // 刷新令牌被删除时,不用提示
'刷新令牌已过期', // 使用刷新令牌,刷新获取新的访问令牌时,结果因为过期失败,此时需要忽略。否则,会导致继续 401无法跳转到登出界面
];
// const ignoreMsgs = [
// "无效的刷新令牌", // 刷新令牌被删除时,不用提示
// "刷新令牌已过期", // 使用刷新令牌,刷新获取新的访问令牌时,结果因为过期失败,此时需要忽略。否则,会导致继续 401无法跳转到登出界面
// ];
import { EventEmitter } from 'events';
export const requestEventBus = new EventEmitter();
const errorCode: { [key: string]: string } = {
'400': '请求参数不正确',
'401': '账号未登录',
'403': '当前操作没有权限',
'404': '访问资源不存在',
'405': '请求方法不正确',
'423': '请求失败,请稍后重试',
'429': '请求失败,请稍后重试',
'500': '系统异常',
'501': '功能未实现/未开启',
'502': '错误的配置项',
'900': '重复请求,请稍后重试',
default: '系统未知错误,请反馈给管理员',
};
// const errorCode: { [key: string]: string } = {
// "400": "请求参数不正确",
// "401": "账号未登录",
// "403": "当前操作没有权限",
// "404": "访问资源不存在",
// "405": "请求方法不正确",
// "423": "请求失败,请稍后重试",
// "429": "请求失败,请稍后重试",
// "500": "系统异常",
// "501": "功能未实现/未开启",
// "502": "错误的配置项",
// "900": "重复请求,请稍后重试",
// default: "系统未知错误,请反馈给管理员",
// };
/**
* @name 错误处理
@@ -113,7 +108,7 @@ export const errorConfig: RequestConfig = {
const errorInfo: ResponseStructure | undefined = error.info;
if (error.name === 'BizError') {
if (errorInfo) {
const { msg, code } = errorInfo;
const { msg } = errorInfo;
message.error(msg);
}
} else if (error.response) {
@@ -123,7 +118,7 @@ export const errorConfig: RequestConfig = {
} else if (error.request) {
message.error('None response! Please retry.');
} else {
message.error('发送请求时出了点问题:' + error.msg);
message.error(`发送请求时出了点问题:${error.msg}`);
}
},
},
@@ -165,6 +160,9 @@ export const errorConfig: RequestConfig = {
// // 如果是忽略的错误码,直接返回 msg 异常
// return Promise.reject(msg);
// }
if (!config.url) {
throw new Error('请求URL不能为空');
}
// 发送请求时出了点问题
if (code === 401) {
if (!isRefreshToken) {
@@ -181,21 +179,25 @@ export const errorConfig: RequestConfig = {
setToken(refreshTokenRes);
// 发出 token 刷新事件
requestEventBus.emit('token-refreshed');
} catch (e) {
} catch (_) {
// 为什么需要 catch 异常呢?刷新失败时,请求因为 Promise.reject 触发异常。
// 提示是否要登出。即不回放当前请求!不然会形成递归
return handleAuthorized();
} finally {
isRefreshToken = false;
}
return request(config.url!, config);
return request(config.url, config);
} else {
console.log('刷新令牌失败');
//添加到队列,等待刷新获取到新的令牌
return new Promise((resolve) => {
requestList.push(() => {
config.headers!.Authorization = 'Bearer ' + getAccessToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
resolve(request(config.url!, config));
if (!config.url) {
throw new Error('请求URL不能为空');
}
if (config.headers)
config.headers.Authorization = `Bearer ${getAccessToken()}`; // 让每个请求携带自定义token 请根据实际情况自行修改
resolve(request(config.url, config));
});
});
}

View File

@@ -0,0 +1,246 @@
import { request } from "@umijs/max";
export interface SampleVo {
/**
* 创建时间
*/
createTime?: string[];
/**
* 页码,从 1 开始", example = "1
*/
remark?: string;
/**
* 样本文件id
*/
sampleFileId?: number;
/**
* 样本格式
*/
sampleMineType?: string;
/**
* 样本名称
*/
sampleName?: string;
/**
* 样本大小
*/
sampleSize?: string;
/**
* 样本时长
*/
sampleTime?: string[];
}
/**
* 返回数据
*
* PageResultAiSampleRespVO
*/
export interface PageResultAiSampleRespVO {
/**
* 数据
*/
list?: AiSampleRespVO[];
/**
* 总量
*/
total?: number;
}
/**
* com.tashow.cloud.ai.controller.admin.aisample.vo.AiSampleRespVO
*
* AiSampleRespVO
*/
export interface AiSampleRespVO {
/**
* 创建时间
*/
createTime?: string;
/**
* 主键
*/
id?: number;
/**
* 样本注释
*/
remark?: string;
/**
* 样本文件id
*/
sampleFileId?: number;
/**
* 样本格式
*/
sampleMineType?: string;
/**
* 样本名称
*/
sampleName?: string;
/**
* 样本大小
*/
sampleSize?: string;
/**
* 样本时长
*/
sampleTime?: string;
}
export interface SampleReqVo extends PageParam {
name?: string;
status?: number;
}
// 获得样本库分页
export const getSamplePage = async (params: SampleReqVo) => {
return request("/ai/sample/page", {
method: "GET",
params,
});
};
export const getSample = async (id: number) => {
return request("/ai/sample/get", {
method: "GET",
params: { id },
});
};
// 创建样本库
export const createSample = (formData: FormData) => {
return request("/ai/sample/create", {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
data: formData,
});
};
export const updateSample = (params: SampleReqVo) => {
return request("/ai/sample/update", {
method: "PUT",
data: params,
});
};
export const deleteSample = (id: string) => {
return request("/ai/sample/delete", {
method: "DELETE",
params: { id },
});
};
//获得样本标签分组库列表
export const getSampleTagGroup = async () => {
return request("/ai/sampleTagGroup/list", {
method: "GET",
});
};
//创建样本标签分组库
export const createSampleTagGroup = (data: { groupName: string }) => {
return request("/ai/sampleTagGroup/create", {
method: "POST",
data,
});
};
//添加关联标签
export const relateSample = (data: {
tagId: number[];
sampleIds: number[];
}) => {
return request("/ai/sample/relate", {
method: "PUT",
data,
});
};
// 删除管理标签
export const deleteSampleTagRelate = (data: {
tagId: number[];
sampleIds: number[];
}) => {
return request("/ai/sample/deleteRelate", {
method: "DELETE",
data,
});
};
//更新样本库
export const updateSamples = (
params: { id: number; remark?: string; sampleName?: string }[]
) => {
return request("/ai/sample/updates", {
method: "PUT",
data: params,
});
};
// 删除样本标签分组库
export const deleteSampleTagGroup = async (id?: number) => {
return request("/ai/sampleTagGroup/delete", {
method: "DELETE",
params: { id },
});
};
//更新样本标签分组库
export const updateSampleTagGroup = async (params: {
id: number;
groupName: string;
}) => {
return request("/ai/sampleTagGroup/update", {
method: "PUT",
data: params,
});
};
//获得样本标签库分页
export const getSampleTagPage = async (params: {
groupId?: number;
pageNo?: number;
pageSize?: number;
}) => {
return request("/ai/sampleTag/page", {
method: "GET",
params,
});
};
//创建样本标签库
export const createSampleTag = (data: {
groupIds: number[];
tagName: string;
}) => {
return request("/ai/sampleTag/create", {
method: "POST",
data,
});
};
// 删除样本标签库
export const deleteSampleTag = async (id?: number) => {
return request("/ai/sampleTag/delete", {
method: "DELETE",
params: { id },
});
};
//更新样本标签库
export const updateSampleTag = async (params: {
groupIds: number[];
tagName: string;
}) => {
return request("/ai/sampleTag/update", {
method: "PUT",
data: params,
});
};

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",
{
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;
};