11 Commits

Author SHA1 Message Date
2821e864da feat: add字典管理
Some checks failed
coverage CI / build (push) Has been cancelled
2025-10-17 16:50:13 +08:00
b4d3535b91 feat: 添加字典方法
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-27 15:52:40 +08:00
39f9e0e714 Merge branch 'wuxichen' of http://gitea.tashowz.com/tashow/tashow-manager into qianpw
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-26 16:38:32 +08:00
9c510636c5 feat: 完善菜单管理
Some checks failed
coverage CI / build (push) Has been cancelled
2025-09-25 17:51:46 +08:00
10f78b7cff feat: 添加信息提示hooks 2025-09-25 17:51:05 +08:00
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
64 changed files with 7458 additions and 312 deletions

View File

@@ -4,8 +4,8 @@ NODE_ENV=development
VITE_DEV=true VITE_DEV=true
# 请求路径 # 请求路径
# VITE_BASE_URL='http://114.132.60.20:48080' VITE_BASE_URL='http://114.132.60.20:48080'
VITE_BASE_URL='http://192.168.1.114:48080' # 理君 # VITE_BASE_URL='http://192.168.1.114:48080' # 理君
# 文件上传类型server - 后端上传, client - 前端直连上传,仅支持 S3 服务 # 文件上传类型server - 后端上传, client - 前端直连上传,仅支持 S3 服务
@@ -14,6 +14,8 @@ VITE_UPLOAD_TYPE=server
# 接口地址 # 接口地址
VITE_API_URL=/admin-api VITE_API_URL=/admin-api
VITE_API_URL_PREFIX=/ai/sample/create
# 是否删除debugger # 是否删除debugger
VITE_DROP_DEBUGGER=false VITE_DROP_DEBUGGER=false

View File

@@ -15,7 +15,8 @@ export default {
// localhost:8000/api/** -> https://preview.pro.ant.design/api/** // localhost:8000/api/** -> https://preview.pro.ant.design/api/**
'/admin-api/': { '/admin-api/': {
// 要代理的地址 // 要代理的地址
target: 'http://114.132.60.20:48080', // target: 'http://114.132.60.20:48080',
target: 'http://192.168.1.231:48080',
// 配置了这个可以从 http 代理到 https // 配置了这个可以从 http 代理到 https
// 依赖 origin 的功能可能需要这个,比如 cookie // 依赖 origin 的功能可能需要这个,比如 cookie
changeOrigin: true, 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({ res.json({
data: [ data: [
{ {
id: '000000001', id: "000000001",
avatar: avatar:
'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/MSbDR4FR2MUAAAAAAAAAAAAAFl94AQBr', "https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/MSbDR4FR2MUAAAAAAAAAAAAAFl94AQBr",
title: '你收到了 14 份新周报', title: "你收到了 14 份新周报",
datetime: '2017-08-09', datetime: "2017-08-09",
type: 'notification', 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',
}, },
], ],
}); });
}; };
export default { export default {
'GET /api/notices': getNotices, "GET /api/notices": getSampleTag,
}; };

View File

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

29
pnpm-lock.yaml generated
View File

@@ -17,6 +17,9 @@ importers:
'@ant-design/v5-patch-for-react-19': '@ant-design/v5-patch-for-react-19':
specifier: ^1.0.3 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) 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: antd:
specifier: ^5.26.4 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) version: 5.27.3(date-fns@2.30.0)(moment@2.30.1)(react-dom@19.1.1(react@19.1.1))(react@19.1.1)
@@ -38,6 +41,9 @@ importers:
react-dom: react-dom:
specifier: ^19.1.0 specifier: ^19.1.0
version: 19.1.1(react@19.1.1) version: 19.1.1(react@19.1.1)
tinymce:
specifier: ^8.1.2
version: 8.1.2
web-storage-cache: web-storage-cache:
specifier: ^1.1.1 specifier: ^1.1.1
version: 1.1.1 version: 1.1.1
@@ -2551,6 +2557,16 @@ packages:
'@types/react-dom': '@types/react-dom':
optional: true 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': '@tootallnate/once@1.1.2':
resolution: {integrity: sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==} resolution: {integrity: sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==}
engines: {node: '>= 6'} engines: {node: '>= 6'}
@@ -10246,6 +10262,9 @@ packages:
tinyexec@1.0.1: tinyexec@1.0.1:
resolution: {integrity: sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==} resolution: {integrity: sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==}
tinymce@8.1.2:
resolution: {integrity: sha512-KITxHEEHRlxC5xOnxA123eAJ67NgsWxNphtItWt9TRu07DiTZrWIqJeIKRX9euE51/l3kJO4WQiqoBXKTJJGsA==}
titleize@3.0.0: titleize@3.0.0:
resolution: {integrity: sha512-KxVu8EYHDPBdUYdKZdKtU2aj2XfEx9AfjXxE/Aj0vT06w2icA09Vus1rh6eSu1y01akYg6BjIK/hxyLJINoMLQ==} resolution: {integrity: sha512-KxVu8EYHDPBdUYdKZdKtU2aj2XfEx9AfjXxE/Aj0vT06w2icA09Vus1rh6eSu1y01akYg6BjIK/hxyLJINoMLQ==}
engines: {node: '>=12'} engines: {node: '>=12'}
@@ -14715,6 +14734,14 @@ snapshots:
'@types/react': 19.1.12 '@types/react': 19.1.12
'@types/react-dom': 19.1.9(@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@1.1.2': {}
'@tootallnate/once@2.0.0': {} '@tootallnate/once@2.0.0': {}
@@ -24850,6 +24877,8 @@ snapshots:
tinyexec@1.0.1: {} tinyexec@1.0.1: {}
tinymce@8.1.2: {}
titleize@3.0.0: {} titleize@3.0.0: {}
tldts-core@6.1.86: {} tldts-core@6.1.86: {}

View File

@@ -1,15 +1,9 @@
import type { Settings as LayoutSettings } from '@ant-design/pro-components'; import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components'; import { SettingDrawer } from '@ant-design/pro-components';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max'; import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history, Link, Navigate } from '@umijs/max'; import { history, Navigate } from '@umijs/max';
import { Modal, Spin } from 'antd'; import { Spin } from 'antd';
import React, { import React from 'react';
Children,
Component,
createContext,
JSX,
Suspense,
} from 'react';
import { import {
AvatarDropdown, AvatarDropdown,
AvatarName, AvatarName,
@@ -18,17 +12,14 @@ import {
SelectLang, SelectLang,
} from '@/components'; } from '@/components';
import { getInfo } from '@/services/login'; 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 defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig'; import { errorConfig } from './requestErrorConfig';
import '@ant-design/v5-patch-for-react-19'; import '@ant-design/v5-patch-for-react-19';
import { getAccessToken, getRefreshToken, getTenantId } from '@/utils/auth';
import { import { useDictStore } from '@/hooks/stores/dict';
transformBackendMenuToFlatRoutes, import { getAccessToken, getTenantId } from '@/utils/auth';
transformMenuToRoutes,
} from '@/utils/menuUtils';
import { CACHE_KEY, useCache } from './hooks/web/useCache'; import { CACHE_KEY, useCache } from './hooks/web/useCache';
import { MenuVO } from './services/system/menu';
const isDev = process.env.NODE_ENV === 'development'; const isDev = process.env.NODE_ENV === 'development';
const isDevOrTest = isDev || process.env.CI; const isDevOrTest = isDev || process.env.CI;
@@ -46,6 +37,7 @@ export async function getInitialState(): Promise<{
fetchUserInfo?: () => Promise<UserInfoVO | undefined>; fetchUserInfo?: () => Promise<UserInfoVO | undefined>;
}> { }> {
const { wsCache } = useCache(); const { wsCache } = useCache();
const dictStore = useDictStore();
const fetchUserInfo = async () => { const fetchUserInfo = async () => {
// history.push(loginPath); // history.push(loginPath);
try { try {
@@ -57,6 +49,10 @@ export async function getInitialState(): Promise<{
wsCache.set(CACHE_KEY.USER, data); wsCache.set(CACHE_KEY.USER, data);
wsCache.set(CACHE_KEY.ROLE_ROUTERS, data.menus); wsCache.set(CACHE_KEY.ROLE_ROUTERS, data.menus);
if (!dictStore.getIsSetDict) {
await dictStore.setDictMap();
}
// 转换菜单格式 // 转换菜单格式
return data; return data;
@@ -198,7 +194,7 @@ export const request: RequestConfig = {
}; };
// 如果有token则添加Authorization头 // 如果有token则添加Authorization头
if (token) { if (token) {
headers['Authorization'] = `Bearer ${getAccessToken()}`; headers.Authorization = `Bearer ${getAccessToken()}`;
} }
return { url, options: { ...options, headers } }; return { url, options: { ...options, headers } };
}, },
@@ -241,7 +237,7 @@ export function patchClientRoutes({ routes }: { routes: any }) {
const parentId = routes[routerIndex].id; const parentId = routes[routerIndex].id;
if (globalMenus) { if (globalMenus) {
routes[routerIndex]['routes'].push(...loopMenuItem(globalMenus, parentId)); routes[routerIndex].routes.push(...loopMenuItem(globalMenus, parentId));
} }
} }
@@ -308,7 +304,7 @@ const findFirstLeafRoute = (menuItem: any, parent = '/'): string | null => {
// 递归查找第一个叶子节点 // 递归查找第一个叶子节点
for (const child of menuItem.children) { for (const child of menuItem.children) {
const leafRoute = findFirstLeafRoute(child, menuItem.path + '/'); const leafRoute = findFirstLeafRoute(child, `${menuItem.path}/`);
if (leafRoute) { if (leafRoute) {
return leafRoute; return leafRoute;
} }

View File

@@ -1,16 +1,15 @@
import { CloseOutlined } from '@ant-design/icons';
import type { ProFormColumnsType } from '@ant-design/pro-components'; 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 { Button, type ColProps, Drawer, Space, Typography } from 'antd';
import type { FormInstance } from 'antd/lib';
import React, { forwardRef, useImperativeHandle } from 'react'; import React, { forwardRef, useImperativeHandle } from 'react';
const { Title } = Typography;
interface ConfigurableDrawerFormProps { interface ConfigurableDrawerFormProps {
title?: string; title?: string;
columns: ProFormColumnsType[]; columns: ProFormColumnsType[];
onSubmit?: (values: any) => Promise<boolean>; onSubmit?: (values: any) => Promise<boolean>;
initialValues?: Record<string, any>; initialValues?: Record<string, any>;
width?: number; width?: number | string;
labelCol?: ColProps; labelCol?: ColProps;
wrapperCol?: ColProps; wrapperCol?: ColProps;
} }
@@ -40,7 +39,7 @@ const ConfigurableDrawerForm = forwardRef<
const [formData, setFormData] = React.useState(initialValues || {}); const [formData, setFormData] = React.useState(initialValues || {});
const [loading, setLoading] = React.useState<boolean>(false); const [loading, setLoading] = React.useState<boolean>(false);
// 添加表单实例引用 // 添加表单实例引用
const formRef = React.useRef<any>(null); const formRef = React.useRef<FormInstance>(null);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
open: (data) => { open: (data) => {
if (data) { if (data) {
@@ -70,31 +69,31 @@ const ConfigurableDrawerForm = forwardRef<
setLoading(false); setLoading(false);
} }
}; };
const customHeader = ( // const customHeader = (
<div // <div
style={{ // style={{
display: 'flex', // display: "flex",
justifyContent: 'space-between', // justifyContent: "space-between",
alignItems: 'center', // alignItems: "center",
padding: '0 0px 16px 0px', // padding: "0 0px 16px 0px",
borderBottom: '1px solid #f0f0f0', // borderBottom: "1px solid #f0f0f0",
marginBottom: '16px', // marginBottom: "16px",
}} // }}
> // >
<Title level={4} style={{ margin: 0 }}> // <Title level={4} style={{ margin: 0 }}>
{title} // {title}
</Title> // </Title>
<Button // <Button
type="text" // type="text"
icon={<CloseOutlined />} // icon={<CloseOutlined />}
onClick={() => setOpen(false)} // onClick={() => setOpen(false)}
style={{ // style={{
border: 'none', // border: "none",
boxShadow: 'none', // boxShadow: "none",
}} // }}
/> // />
</div> // </div>
); // );
return ( return (
<Drawer <Drawer
title={title} title={title}

View File

@@ -4,30 +4,12 @@ import { PlusOutlined } from '@ant-design/icons';
import { import {
type ActionType, type ActionType,
type ParamsType, type ParamsType,
ProColumns,
ProTable, ProTable,
TableDropdown,
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { Button, Space } from 'antd'; import { Button, Space, Table } from 'antd';
import React, { import React, { forwardRef, useCallback, useMemo, useState } from 'react';
act, import { formatPaginationTotal } from '@/utils/antd/tableHelpers';
forwardRef, import type { BaseRecord, EnhancedProTableProps } from './types';
useCallback,
useMemo,
useRef,
useState,
} from 'react';
import {
buildTableDropdownMenuItems,
formatPaginationTotal,
handleTableDropdownSelect,
} from '@/utils/antd/tableHelpers';
import {
type BaseRecord,
type EnhancedProTableProps,
TableAction,
ToolbarAction,
} from './types';
function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>( function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
props: EnhancedProTableProps<T, U>, props: EnhancedProTableProps<T, U>,
@@ -36,21 +18,22 @@ function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
const { const {
columns, columns,
request, request,
actions = [], // actions = [],
permissions = [], // permissions = [],
checkPermission = () => true, checkPermission = () => true,
toolbarActions, toolbarActions,
showIndex = true, showIndex = true,
showSelection = true, showSelection = true,
showActions = true, // showActions = true,
maxActionCount = 2, // maxActionCount = 2,
onAdd, // onAdd,
onEdit, // onEdit,
onDelete, // onDelete,
onView, // onView,
onExport, // onExport,
customToolbarRender, // customToolbarRender,
customActionRender, customActionRender,
rowKey = 'id',
...restProps ...restProps
} = props; } = props;
@@ -59,88 +42,48 @@ function EnhancedProTable<T extends BaseRecord, U extends ParamsType = any>(
// 行选择配置 // 行选择配置
const rowSelection = useMemo(() => { const rowSelection = useMemo(() => {
if (!showSelection) return undefined; if (!showSelection) return undefined;
return { return {
selectedRowKeys, selectedRowKeys,
selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
onChange: (keys: React.Key[], rows: T[]) => { onChange: (keys: React.Key[], rows: T[]) => {
setSelectedRowKeys(keys); setSelectedRowKeys(keys);
setSelectedRows(rows); setSelectedRows(rows);
}, },
getCheckboxProps: (record: T) => ({ getCheckboxProps: (record: T) => ({
name: record.id?.toString(), name: record[rowKey]?.toString(),
}), }),
}; };
}, [showSelection, selectedRowKeys]); }, [showSelection, selectedRowKeys]);
// 表格提醒渲染 const toolBarRender = useCallback(() => {
const tableAlertRender = useCallback( const toolbarElements =
({ selectedRowKeys, onCleanSelected }: any) => { toolbarActions?.map((action) => {
if (!showSelection || selectedRowKeys.length === 0) return false; return (
<Button
return ( key={action.key}
<Space size={24}> type={action.type}
<span> danger={action.danger}
{selectedRowKeys.length} disabled={action.disabled}
<a style={{ marginLeft: 8 }} onClick={onCleanSelected}> icon={<PlusOutlined />}
onClick={() => action.onClick(selectedRowKeys, selectedRows)}
</a> >
</span> {action.label}
</Space> </Button>
); );
}, }) || [];
[showSelection], return toolbarElements;
); }, [toolbarActions]);
const toolBarRender = useCallback(
(
action: ActionType | undefined,
rows: {
selectedRowKeys?: (string | number)[] | undefined;
selectedRows?: T[] | undefined;
},
) => {
const toolbarElements =
toolbarActions?.map((action) => {
return (
<Button
key={action.key}
type={action.type}
danger={action.danger}
disabled={action.disabled}
icon={<PlusOutlined />}
onClick={() => action.onClick(selectedRowKeys, selectedRows)}
>
{action.label}
</Button>
);
}) || [];
// return [
// <Button
// key="button"
// icon={<PlusOutlined />}
// onClick={}
// type="primary"
// >
// 新建
// </Button>,
// ];
return toolbarElements;
},
[toolbarActions],
);
return ( return (
<ProTable<T, U> <ProTable<T, U>
{...restProps} {...restProps}
columns={columns} columns={columns}
actionRef={ref} actionRef={ref}
request={request} request={request}
rowKey="id" rowKey={rowKey}
rowSelection={rowSelection} rowSelection={rowSelection}
toolBarRender={toolBarRender} toolBarRender={toolBarRender}
manualRequest={false} manualRequest={false}
showSorterTooltip showSorterTooltip
tableAlertRender={tableAlertRender}
// tableAlertOptionRender={tableAlertOptionRender}
scroll={{ x: 'max-content' }} scroll={{ x: 'max-content' }}
search={{ search={{
labelWidth: 'auto', labelWidth: 'auto',

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,176 @@
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, getSample } 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('file', file);
// formData.append("type", "audio"); // 可以添加额外参数
const response = await createSample(formData);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
};
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);
onProgress?.({ percent: 100 });
if (result.success && result.data) {
// 构造返回数据
const responseData = {
url: result.data.url,
name: result.data.filename || (file as File).name,
uid: (file as any).uid,
status: 'done' as const,
response: result.data,
};
onSuccess?.(responseData);
message.success('音频上传成功!');
} 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

@@ -0,0 +1,93 @@
import type { TagProps } from 'antd';
import { Tag } from 'antd';
import React, { useMemo } from 'react';
import { isHexColor } from '@/utils/color';
import { isArray, isBoolean, isNumber, isString } from '@/utils/common';
import type { DictDataType } from '@/utils/dict';
import { getDictOptions } from '@/utils/dict';
interface DictTagProps {
type: string;
value: string | number | boolean | Array<string | number | boolean>;
// 字符串分隔符 只有当 value 传入值为字符串时有效
separator?: string;
// 每个 tag 之间的间隔,默认为 5px
gutter?: string;
}
const DictTag: React.FC<DictTagProps> = ({
type,
value,
separator = ',',
gutter = '5px',
}) => {
const valueArr = useMemo(() => {
// 1. 是 Number 类型和 Boolean 类型的情况
if (isNumber(value) || isBoolean(value)) {
return [String(value)];
}
// 2. 是字符串(进一步判断是否有包含分隔符号 -> separator
else if (isString(value)) {
return value.split(separator);
}
// 3. 数组
else if (isArray(value)) {
return value.map(String);
}
return [];
}, [value, separator]);
// 解决自定义字典标签值为零时标签不渲染的问题
if (!type || value === undefined || value === null || value === '') {
return null;
}
const dictOptions = getDictOptions(type);
return (
<div
className="dict-tag"
style={{
display: 'inline-flex',
gap: gutter,
justifyContent: 'center',
alignItems: 'center',
}}
>
{dictOptions
.filter((dict: DictDataType) => valueArr.includes(String(dict.value)))
.map((dict: DictDataType) => {
// 处理 tag 类型
const colorType: TagProps['color'] = dict.colorType || undefined;
// if (dict.colorType !== "primary" && dict.colorType !== "default") {
// colorType = dict.colorType || undefined;
// }
// 处理自定义颜色
const customColor =
dict?.cssClass && isHexColor(dict?.cssClass)
? dict?.cssClass
: undefined;
console.log(customColor, 'customColor');
console.log(colorType, 'colorType');
return (
<Tag
key={`${dict.value}-${dict.label}`}
color={customColor || colorType}
style={{
...(customColor ? { color: '#fff' } : {}), // 自定义背景颜色时文字为白色
margin: 0, // 去除默认 margin使用 gap 控制间距
}}
>
{dict.label}
</Tag>
);
})}
</div>
);
};
export default DictTag;

View File

@@ -1 +1,43 @@
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 },
];
// ========== COMMON 模块 ==========
// 全局通用状态枚举
export const CommonStatusEnum = {
ENABLE: 0, // 开启
DISABLE: 1, // 禁用
};

View File

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

111
src/hooks/stores/dict.ts Normal file
View File

@@ -0,0 +1,111 @@
import { CACHE_KEY, useCache } from '@/hooks/web/useCache';
import type { DictDataVO } from '@/services/system/dict/dict.data';
import { getSimpleDictDataList } from '@/services/system/dict/dict.data';
export interface DictValueType {
value: any;
label: string;
clorType?: string;
cssClass?: string;
}
export interface DictTypeType {
dictType: string;
dictValue: DictValueType[];
}
export interface DictState {
dictMap: Record<string, any[]>;
isSetDict: boolean;
}
export const useDictStore = () => {
const { wsCache } = useCache();
const state: DictState = {
dictMap: {},
isSetDict: false,
};
const getDictMap = (): Recordable => {
const dictMap = wsCache.get(CACHE_KEY.DICT_CACHE);
if (dictMap) {
state.dictMap = dictMap;
}
return state.dictMap;
};
const getIsSetDict = (): boolean => {
return state.isSetDict;
};
const setDictMap = async () => {
const dictMap = wsCache.get(CACHE_KEY.DICT_CACHE);
if (dictMap) {
state.dictMap = dictMap;
state.isSetDict = true;
} else {
const res = await getSimpleDictDataList();
// 设置数据
const dictDataMap: Record<string, any[]> = {};
res.forEach((dictData: DictDataVO) => {
// 获得 dictType 层级
if (!dictDataMap[dictData.dictType]) {
dictDataMap[dictData.dictType] = [];
}
// 处理 dictValue 层级
dictDataMap[dictData.dictType].push({
value: dictData.value,
label: dictData.label,
colorType: dictData.colorType,
cssClass: dictData.cssClass,
});
});
state.dictMap = dictDataMap;
state.isSetDict = true;
wsCache.set(CACHE_KEY.DICT_CACHE, dictDataMap, { exp: 60 }); // 60 秒 过期
}
};
const getDictByType = (type: string) => {
if (!state.isSetDict) {
setDictMap();
}
return state.dictMap[type];
};
const resetDict = async () => {
wsCache.delete(CACHE_KEY.DICT_CACHE);
const res = await getSimpleDictDataList();
// 设置数据
const dictDataMap: Record<string, any[]> = {};
res.forEach((dictData: DictDataVO) => {
// 获得 dictType 层级
if (!dictDataMap[dictData.dictType]) {
dictDataMap[dictData.dictType] = [];
}
// 处理 dictValue 层级
dictDataMap[dictData.dictType].push({
value: dictData.value,
label: dictData.label,
colorType: dictData.colorType,
cssClass: dictData.cssClass,
});
});
state.dictMap = dictDataMap;
state.isSetDict = true;
wsCache.set(CACHE_KEY.DICT_CACHE, dictDataMap, { exp: 60 }); // 60 秒 过期
};
return {
state,
getDictMap,
getIsSetDict,
setDictMap,
getDictByType,
resetDict,
};
};

View File

@@ -0,0 +1,136 @@
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: 'sample_name',
},
{
title: '注释',
dataIndex: 'remark',
hideInSearch: true,
},
{
title: '标签',
hideInTable: true,
dataIndex: 'tag_name',
},
{
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,81 @@
import {
ProForm,
ProFormCascader,
ProFormCheckbox,
ProFormColorPicker,
ProFormDigit,
ProFormDigitRange,
ProFormGroup,
ProFormRadio,
ProFormSelect,
ProFormSlider,
ProFormSwitch,
ProFormText,
} from '@ant-design/pro-components';
import { Switch } from 'antd';
import type { FormInstance } from 'antd/lib';
import Mock from 'mockjs';
import { useRef, useState } from 'react';
import TagEditor from '@/components/TagEditor';
export const waitTime = (time: number = 100) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(true);
}, time);
});
};
const SampleTagDetail = () => {
const [readonly, setReadonly] = useState(false);
const formRef = useRef<FormInstance>(null);
return (
<>
{/* <Switch
style={{
marginBlockEnd: 16,
}}
checked={readonly}
checkedChildren="编辑"
unCheckedChildren="只读"
onChange={setReadonly}
/> */}
<ProForm
readonly={readonly}
name="validate_other"
formRef={formRef}
initialValues={{
sample_name: '1111',
}}
onValuesChange={(_, values) => {
console.log(values);
}}
onFinish={async (value) => console.log(value)}
>
<ProFormGroup title="预览">{/* <audio></audio> */}</ProFormGroup>
<ProFormGroup title="基本信息">
<ProFormText
width="md"
name="sample_name"
placeholder="请输入样本名称"
rules={[{ required: true, message: '样本名称不能为空' }]}
/>
<ProFormText width="md" name="remark" placeholder="请输入注释" />
</ProFormGroup>
<ProFormGroup
title="标签"
style={{
gap: '0 32px',
}}
>
<ProForm.Item name="tags">
<TagEditor placeholder="输入标签名称" maxCount={10} />
</ProForm.Item>
</ProFormGroup>
</ProForm>
</>
);
};
export default SampleTagDetail;

View File

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

View File

@@ -0,0 +1,61 @@
import type { ActionType } from '@ant-design/pro-components';
import React, { useRef } from 'react';
import EnhancedProTable from '@/components/EnhancedProTable';
import type { ToolbarAction } from '@/components/EnhancedProTable/types';
import UploadCard from '@/components/Upload/UploadCard';
import { baseTenantColumns } from './config';
import SampleTagDetail from './detail';
import styles from './index.module.less';
const SampleTag: React.FC = () => {
const tableRef = useRef<ActionType>(null);
// const [detail, setDetail] = useState<any>(null);
// const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
const handleAll = () => {
// console.log(tableRef.current.getSelectedRowKeys());
};
const toolbarActions: ToolbarAction[] = [
{
key: 'add',
label: '批量编辑',
type: 'primary',
onClick: handleAll,
},
];
const onFetch = async (_params: API.getProductCategoryCategoryListParams) => {
// const data = await getCategoryList({
// ...params,
// });
const data: any = [
{ sample_name: 111, id: 1, remark: 222 },
{ sample_name: 22, id: 2, remark: 33 },
];
return {
data: data,
success: true,
};
};
return (
<>
<UploadCard />
<div className={styles['tag-content']}>
<EnhancedProTable<API.CategoryDO>
ref={tableRef}
columns={baseTenantColumns}
request={onFetch}
toolbarActions={toolbarActions}
headerTitle="样本列表"
showIndex={false}
showSelection={true}
/>
<div className="detail">
<SampleTagDetail />
</div>
</div>
</>
);
};
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 = () => { 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; export default SyStemDept;

View File

@@ -0,0 +1,120 @@
import type {
ProColumns,
ProFormColumnsType,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';
import DictTag from '@/components/XTag';
import { tenantStatus } from '@/constants';
import type { DictTypeVO } from '@/services/system/dict/dict.type';
import { DICT_TYPE } from '@/utils/dict';
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,
valueType: 'select',
render: (_, record) => {
return (
<DictTag type={DICT_TYPE.COMMON_STATUS} value={record.status}></DictTag>
);
},
},
{
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,197 @@
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,
render: (_, record) => (
<Tag color={record.cssClass || record.colorType}>{record.label}</Tag>
),
},
{
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,
render: (_, record) => (
<Tag color={record.colorType}>{record.colorType}</Tag>
),
},
{
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: 0,
},
{
label: '禁用',
value: 1,
},
],
},
formItemProps: {
rules: [
{
required: true,
},
],
},
},
{
title: '颜色类型',
dataIndex: 'colorType',
valueType: 'select',
fieldProps: {
options: [
{
label: <Tag color="default">(default)</Tag>,
value: 'default',
},
{
label: <Tag color="success">(success)</Tag>,
value: 'success',
},
{
label: <Tag color="processing">(processing)</Tag>,
value: 'processing',
},
{
label: <Tag color="error">(error)</Tag>,
value: 'error',
},
{
label: <Tag color="warning">(warning)</Tag>,
value: 'warning',
},
],
},
},
{
title: 'CSS Class',
dataIndex: 'cssClass',
tooltip: '输入rgb颜色值或#16进制颜色值',
},
{
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 = () => { 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; export default SyStemDict;

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,10 +2,10 @@ import type {
ProColumns, ProColumns,
ProFormColumnsType, ProFormColumnsType,
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { DatePicker, Modal, Popconfirm } from 'antd'; import { Tag } from 'antd';
import { FormInstance } from 'antd/lib';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { deleteTenant, type TenantVO } from '@/services/system/tenant/list'; import type { TenantVO } from '@/services/system/tenant/list';
import { getTenantPackageList } from '@/services/system/tenant/package'; import { getTenantPackageList } from '@/services/system/tenant/package';
export const baseTenantColumns: ProColumns<TenantVO>[] = [ export const baseTenantColumns: ProColumns<TenantVO>[] = [
@@ -29,9 +29,22 @@ export const baseTenantColumns: ProColumns<TenantVO>[] = [
request: async () => { request: async () => {
const packageList: { id: number; name: string }[] = const packageList: { id: number; name: string }[] =
await getTenantPackageList(); await getTenantPackageList();
console.log(packageList); const newData = packageList.map((item) => ({
packageList.map((item) => ({ label: item.name, value: item.id })); label: item.name,
return packageList.map((item) => ({ label: item.name, value: item.id })); value: item.id,
}));
const defData = [{ value: 0, label: '系统' }];
return [...defData, ...newData];
},
render: (dom, record) => {
return (
<Tag
key={record.id}
color={record.packageId === 0 ? 'error' : 'success'}
>
{dom}
</Tag>
);
}, },
// valueEnum: { // valueEnum: {
// all: { text: "全部", status: "Default" }, // all: { text: "全部", status: "Default" },
@@ -83,7 +96,14 @@ export const baseTenantColumns: ProColumns<TenantVO>[] = [
valueType: 'dateRange', valueType: 'dateRange',
search: { search: {
transform: (value) => { 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) => render: (_, record: TenantVO) =>

View File

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

View File

@@ -0,0 +1,161 @@
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/get", {
method: "GET",
params,
});
};
export const getSample = async (id: number) => {
return request("/ai/sample/get", {
method: "GET",
params: { id },
});
};
// 查询部门列表
// export const getDeptPage = async (params: DeptReq): Promise<Dept[]> => {
// return await request.get({ url: "/system/dept/list", params });
// };
export const getDeptPage = (params: SampleReqVo) => {
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 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 deleteDept = async (id: number) => {
// return await request.delete({ url: "/system/dept/delete?id=" + id });
// };
export const deleteSample = (id: number) => {
return request("/ai/sample/delete", {
method: "DELETE",
params: { id },
});
};

View File

@@ -0,0 +1,210 @@
export interface Prod extends PageParam {
/**
* 商品简称
*/
abbreviation?: string;
/**
* 是否特殊日期节假日周末什么的0关1开
*/
additionalFeeSwitch?: number;
/**
* 是否特殊时段0关1开
*/
additionalSwitch?: number;
/**
* 品牌
*/
brand?: string;
/**
* 简要描述,卖点等
*/
brief?: string;
/**
* 商品分类
*/
categoryId?: number;
/**
* 详细描述
*/
content?: string;
/**
* 创建时间
*/
createTime?: string;
/**
* 创建者,目前使用 SysUser 的 id 编号
*
* 使用 String 类型的原因是,未来可能会存在非数值的情况,留好拓展性。
*/
creator?: string;
/**
* 是否删除
*/
deleted?: number;
/**
* 是否紧急响应服务0关1开
*/
emergencySwitch?: number;
/**
* 商品轮播图片,以,分割
*/
imgs?: string;
/**
* 是否置灰0否1是
*/
isProhibit?: number;
/**
* 关键词
*/
keyword?: string;
/**
* 是否接单上线0关1开
*/
orderLimitSwitch?: number;
/**
* 商品主图
*/
pic?: string;
/**
* 审核备注
*/
processNotes?: string;
/**
* 产品ID
*/
prodId?: number;
/**
* 商品名称
*/
prodName?: string;
/**
* 商品编号
*/
prodNumber?: string;
/**
* 是否开启区域0关1开
*/
regionSwitch?: number;
/**
* 是否预约0关1开
*/
reservationSwitch?: number;
/**
* seo搜索
*/
seoSearch?: string;
/**
* seo标题
*/
seoShortName?: string;
/**
* 分享话术
*/
shareContent?: string;
/**
* 分享图
*/
shareImage?: string;
/**
* 店铺id
*/
shopId?: number;
/**
* 销量
*/
soldNum?: number;
/**
* 默认是1正常状态出售中, 0下架仓库中 2待审核
*/
status?: number;
/**
* 标签
*/
tag?: string[];
/**
* 展示的权重
*/
top?: number;
/**
* 更新者,目前使用 SysUser 的 id 编号
*
* 使用 String 类型的原因是,未来可能会存在非数值的情况,留好拓展性。
*/
updater?: string;
/**
* 最后更新时间
*/
updateTime?: string;
/**
* 版本 乐观锁
*/
version?: number;
/**
* 视频
*/
video?: string;
/**
* 是否开启体重配置0关1开
*/
weightSwitch?: number;
/**
* 商品轮播图片,以,分割
*/
whiteImg?: string;
[property: string]: any;
}
export interface SkuList {
skuName: string; //规格名称
basePrice?: number; //基准价格 *
price?: number; //"当前价"
isSpecs?: number; //默认规格
stocksFlg?: number; //库存类型
status?: number; //状态
stocks?: number; //可售数量
isShelf?: number; //上/下架
skuId?: number;
isExist?: number;
propIds?: string;
deleteTime?: number; //删除时间
remainingDays?: number; //保留时间
id?: number;
// 添加索引签名,允许动态属性
[key: string]: string | number | undefined;
}
export interface SkuPropValues {
id?: number;
propValue: string;
valueId: number;
state: 0 | 1; // 0禁用1启用
isExist: 0 | 1; //是否新增 0否1是
sort: number;
isExpire: 0 | 1 /**是否失效0否1是**/;
}
export interface SkuConfig {
propName: string; //规格名字
propId: number;
id?: number;
isExist?: number; // //是否新增 0否1是
prodPropValues: SkuPropValues[]; //规格值
}
export interface ProdDetail {
prodName: string; //商品名称
abbreviation?: string; //商品简称
brief?: string; //商品概述
prodNumber?: string; //商品编码
brand?: string; //品牌
shopId?: string; //商品所有权
categoryId?: number; //关联类目
tag?: string[]; //商品标签
skuList: SkuList[];
prodPropSaveReqVO: SkuConfig;
}
export interface ProdReq extends PageParam {
name?: string;
status?: 0 | 1 | 2; //状态 1正常状态出售中, 0下架仓库中 2待审核
prodName?: string; // 商品名称
createTime?: Date; //创建时间
}

View File

@@ -3,25 +3,22 @@
import { request } from "@umijs/max"; import { request } from "@umijs/max";
/** 获取菜单页面的表 GET /product/category/categoryList */ /** 获取菜单页面的表 GET /product/category/categoryList */
export async function getProductCategoryCategoryList( export async function getCategoryList(
// 叠加生成的Param类型 (非body参数swagger默认没有生成对象) // 叠加生成的Param类型 (非body参数swagger默认没有生成对象)
params: API.getProductCategoryCategoryListParams, params: API.getProductCategoryCategoryListParams,
options?: { [key: string]: any } options?: { [key: string]: any }
) { ) {
return request<API.CommonResultListCategoryDto>( return request("/product/category/categoryList", {
"/product/category/categoryList", method: "GET",
{ params: {
method: "GET", ...params,
params: { },
...params, ...(options || {}),
}, });
...(options || {}),
}
);
} }
/** 创建产品类目 创建产品类目 POST /product/category/create */ /** 创建产品类目 创建产品类目 POST /product/category/create */
export async function postProductCategoryCreate( export async function postCategoryCreate(
body: API.CategorySaveReqVO, body: API.CategorySaveReqVO,
options?: { [key: string]: any } options?: { [key: string]: any }
) { ) {
@@ -36,7 +33,7 @@ export async function postProductCategoryCreate(
} }
/** 更新产品类目 更新产品类目 PUT /product/category/update */ /** 更新产品类目 更新产品类目 PUT /product/category/update */
export async function putProductCategoryUpdate( export async function putCategoryUpdate(
body: API.CategorySaveReqVO, body: API.CategorySaveReqVO,
options?: { [key: string]: any } 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[]; children?: MenuVO[];
} }
export interface MenuReqVO {
name?: string;
status?: 0 | 1;
}
// 查询菜单(精简)列表 // 查询菜单(精简)列表
export const getSimpleMenusList = () => {
return request("/system/menu/simple-list", {
method: "GET",
});
};
// export const getSimpleMenusList = () => { // export const getSimpleMenusList = () => {
// return request.get({ url: '/system/menu/simple-list' }) // 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) => { // export const getMenuList = (params) => {
// return request.get({ url: '/system/menu/list', 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) => { // export const getMenu = (id: number) => {
// return request.get({ url: '/system/menu/get?id=' + id }) // 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) => { // export const createMenu = (data: MenuVO) => {
// return request.post({ url: '/system/menu/create', data }) // 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) => { // export const updateMenu = (data: MenuVO) => {
// return request.put({ url: '/system/menu/update', data }) // 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) => { // export const deleteMenu = (id: number) => {
// return request.delete({ url: '/system/menu/delete?id=' + id }) // 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; createTime: Date;
} }
export interface TenantPackagePageReqVO extends PageParam {
name?: string;
contactName?: string;
contactMobile?: string;
status?: number;
createTime?: Date[];
}
// 查询租户套餐列表 // 查询租户套餐列表
// export const getTenantPackagePage = (params: PageParam) => { // export const getTenantPackagePage = (params: PageParam) => {
// return request.get({ url: '/system/tenant-package/page', params }) // 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) => { // export const getTenantPackage = (id: number) => {
// return request.get({ url: '/system/tenant-package/get?id=' + id }) // 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;
};

174
src/utils/color.ts Normal file
View File

@@ -0,0 +1,174 @@
/**
* 判断是否 十六进制颜色值.
* 输入形式可为 #fff000 #f00
*
* @param String color 十六进制颜色值
* @return Boolean
*/
export const isHexColor = (color: string) => {
const reg = /^#([0-9a-fA-F]{3}|[0-9a-fA-f]{6})$/;
return reg.test(color);
};
/**
* RGB 颜色值转换为 十六进制颜色值.
* r, g, 和 b 需要在 [0, 255] 范围内
*
* @return String 类似#ff00ff
* @param r
* @param g
* @param b
*/
export const rgbToHex = (r: number, g: number, b: number) => {
// tslint:disable-next-line:no-bitwise
const hex = ((r << 16) | (g << 8) | b).toString(16);
return `#${new Array(Math.abs(hex.length - 7)).join('0')}${hex}`;
};
/**
* Transform a HEX color to its RGB representation
* @param {string} hex The color to transform
* @returns The RGB representation of the passed color
*/
export const hexToRGB = (hex: string, opacity?: number) => {
let sHex = hex.toLowerCase();
if (isHexColor(hex)) {
if (sHex.length === 4) {
let sColorNew = '#';
for (let i = 1; i < 4; i += 1) {
sColorNew += sHex.slice(i, i + 1).concat(sHex.slice(i, i + 1));
}
sHex = sColorNew;
}
const sColorChange: number[] = [];
for (let i = 1; i < 7; i += 2) {
sColorChange.push(parseInt(`0x${sHex.slice(i, i + 2)}`, 10));
}
return opacity
? `RGBA(${sColorChange.join(',')},${opacity})`
: `RGB(${sColorChange.join(',')})`;
}
return sHex;
};
export const colorIsDark = (color: string) => {
if (!isHexColor(color)) return;
const [r, g, b] = hexToRGB(color)
.replace(/(?:\(|\)|rgb|RGB)*/g, '')
.split(',')
.map((item) => Number(item));
return r * 0.299 + g * 0.578 + b * 0.114 < 192;
};
/**
* Darkens a HEX color given the passed percentage
* @param {string} color The color to process
* @param {number} amount The amount to change the color by
* @returns {string} The HEX representation of the processed color
*/
export const darken = (color: string, amount: number) => {
color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color;
amount = Math.trunc((255 * amount) / 100);
return `#${subtractLight(color.substring(0, 2), amount)}${subtractLight(
color.substring(2, 4),
amount,
)}${subtractLight(color.substring(4, 6), amount)}`;
};
/**
* Lightens a 6 char HEX color according to the passed percentage
* @param {string} color The color to change
* @param {number} amount The amount to change the color by
* @returns {string} The processed color represented as HEX
*/
export const lighten = (color: string, amount: number) => {
color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color;
amount = Math.trunc((255 * amount) / 100);
return `#${addLight(color.substring(0, 2), amount)}${addLight(
color.substring(2, 4),
amount,
)}${addLight(color.substring(4, 6), amount)}`;
};
/* Suma el porcentaje indicado a un color (RR, GG o BB) hexadecimal para aclararlo */
/**
* Sums the passed percentage to the R, G or B of a HEX color
* @param {string} color The color to change
* @param {number} amount The amount to change the color by
* @returns {string} The processed part of the color
*/
const addLight = (color: string, amount: number) => {
const cc = parseInt(color, 16) + amount;
const c = cc > 255 ? 255 : cc;
return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`;
};
/**
* Calculates luminance of an rgb color
* @param {number} r red
* @param {number} g green
* @param {number} b blue
*/
const luminanace = (r: number, g: number, b: number) => {
const a = [r, g, b].map((v) => {
v /= 255;
return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
};
/**
* Calculates contrast between two rgb colors
* @param {string} rgb1 rgb color 1
* @param {string} rgb2 rgb color 2
*/
const contrast = (rgb1: string[], rgb2: number[]) => {
return (
(luminanace(~~rgb1[0], ~~rgb1[1], ~~rgb1[2]) + 0.05) /
(luminanace(rgb2[0], rgb2[1], rgb2[2]) + 0.05)
);
};
/**
* Determines what the best text color is (black or white) based con the contrast with the background
* @param hexColor - Last selected color by the user
*/
export const calculateBestTextColor = (hexColor: string) => {
const rgbColor = hexToRGB(hexColor.substring(1));
const contrastWithBlack = contrast(rgbColor.split(','), [0, 0, 0]);
return contrastWithBlack >= 12 ? '#000000' : '#FFFFFF';
};
/**
* Subtracts the indicated percentage to the R, G or B of a HEX color
* @param {string} color The color to change
* @param {number} amount The amount to change the color by
* @returns {string} The processed part of the color
*/
const subtractLight = (color: string, amount: number) => {
const cc = parseInt(color, 16) - amount;
const c = cc < 0 ? 0 : cc;
return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`;
};
// 预设颜色
export const PREDEFINE_COLORS = [
'#ff4500',
'#ff8c00',
'#ffd700',
'#90ee90',
'#00ced1',
'#1e90ff',
'#c71585',
'#409EFF',
'#909399',
'#C0C4CC',
'#b7390b',
'#ff7800',
'#fad400',
'#5b8c5f',
'#00babd',
'#1f73c3',
'#711f57',
];

396
src/utils/common.ts Normal file
View File

@@ -0,0 +1,396 @@
import type { SkuConfig, SkuList } from '@/services/prod/prod-manager';
/**
* @param str 需要转驼峰的下划线字符串
* @returns 字符串驼峰
*/
export const underlineToHump = (str: string): string => {
if (!str) return '';
return str.replace(/-(\w)/g, (_, letter: string) => {
return letter.toUpperCase();
});
};
export const setCssVar = (
prop: string,
val: any,
dom = document.documentElement,
) => {
dom.style.setProperty(prop, val);
};
/**
* @param str 需要转下划线的驼峰字符串
* @returns 字符串下划线
*/
export const humpToUnderline = (str: string): string => {
return str.replace(/([A-Z])/g, '-$1').toLowerCase();
};
// copy to vben-admin
const objectToString = Object.prototype.toString;
export const is = (val: unknown, type: string) => {
return objectToString.call(val) === `[object ${type}]`;
};
export const isDef = <T = unknown>(val?: T): val is T => {
return typeof val !== 'undefined';
};
export const isUnDef = <T = unknown>(val?: T): val is T => {
return !isDef(val);
};
export const isObject = (val: any): val is Record<any, any> => {
return val !== null && is(val, 'Object');
};
export const isEmpty = (val: any): boolean => {
if (val === null || val === undefined || typeof val === 'undefined') {
return true;
}
if (isArray(val) || isString(val)) {
return val.length === 0;
}
if (val instanceof Map || val instanceof Set) {
return val.size === 0;
}
if (isObject(val)) {
return Object.keys(val).length === 0;
}
return false;
};
export const isDate = (val: unknown): val is Date => {
return is(val, 'Date');
};
export const isNull = (val: unknown): val is null => {
return val === null;
};
export const isNullAndUnDef = (val: unknown): val is null | undefined => {
return isUnDef(val) && isNull(val);
};
export const isNullOrUnDef = (val: unknown): val is null | undefined => {
return isUnDef(val) || isNull(val);
};
export const isNumber = (val: unknown): val is number => {
return is(val, 'Number');
};
export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
return (
is(val, 'Promise') &&
isObject(val) &&
isFunction(val.then) &&
isFunction(val.catch)
);
};
export const isString = (val: unknown): val is string => {
return is(val, 'String');
};
export const isFunction = (val: unknown): val is (...args: any[]) => any => {
return typeof val === 'function';
};
export const isBoolean = (val: unknown): val is boolean => {
return is(val, 'Boolean');
};
export const isRegExp = (val: unknown): val is RegExp => {
return is(val, 'RegExp');
};
export const isArray = (val: any): val is Array<any> => {
return val && Array.isArray(val);
};
export const isWindow = (val: any): val is Window => {
return typeof window !== 'undefined' && is(val, 'Window');
};
export const isElement = (val: unknown): val is Element => {
return isObject(val) && !!val.tagName;
};
export const isMap = (val: unknown): val is Map<any, any> => {
return is(val, 'Map');
};
export const isServer = typeof window === 'undefined';
export const isClient = !isServer;
export const isUrl = (path: string): boolean => {
// fix:修复hash路由无法跳转的问题
const reg =
/(((^https?:(?:\/\/)?)(?:[-:&=+$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%#/.\w-_]*)?\??(?:[-+=&%@.\w_]*)#?(?:[\w]*))?)$/;
return reg.test(path);
};
export const isDark = (): boolean => {
return window.matchMedia('(prefers-color-scheme: dark)').matches;
};
// 是否是图片链接
export const isImgPath = (path: string): boolean => {
return /(https?:\/\/|data:image\/).*?\.(png|jpg|jpeg|gif|svg|webp|ico)/gi.test(
path,
);
};
export const isEmptyVal = (val: any): boolean => {
return val === '' || val === null || val === undefined;
};
export const isExternal = (path: string): boolean => {
return /https?/.test(path);
};
/**
* 查找数组对象的某个下标
* @param {Array} ary 查找的数组
* @param {Functon} fn 判断的方法
*/
// eslint-disable-next-line
export const findIndex = <T = Recordable>(ary: Array<T>, fn: Fn): number => {
if (ary.findIndex) {
return ary.findIndex(fn);
}
let index = -1;
ary.some((item: T, i: number, ary: Array<T>) => {
const ret: T = fn(item, i, ary);
if (ret) {
index = i;
return true;
}
return false;
});
return index;
};
// 笛卡尔积函数
function cartesianProduct<T>(...arrays: T[][]): T[][] {
return arrays.reduce(
(acc, curr) => {
const result: T[][] = [];
acc.forEach((a) => {
curr.forEach((c) => {
result.push([...a, c]);
});
});
return result;
},
[[]] as T[][],
);
}
export function generateSkuTableData(data: SkuConfig[]): SkuList[] {
// 过滤掉prodPropValues为空的配置
const validData = data.filter((config) => config.prodPropValues.length > 0);
// 如果所有配置都被过滤掉了,返回空数组
if (validData.length === 0) {
return [];
}
const propValueArrays = validData.map((config) => config.prodPropValues);
const combinations = cartesianProduct<{
propValue: string;
valueId?: number;
state?: number;
isExist?: number;
}>(...propValueArrays);
return combinations.map((combination, index) => {
const skuItem: SkuList = {
skuName: combination.map((item) => item.propValue).join(','),
basePrice: 0,
isSpecs: index === 0 ? 1 : 0,
status: 1,
stocks: 0,
isShelf: 1,
// propIds: combination.map((item) => item.valueId).join(",")
};
// 只添加有效配置的动态属性
validData.forEach((config, configIndex) => {
(skuItem as any)[config.propName] = combination[configIndex].propValue;
});
return skuItem;
});
}
// 根据删除的SKU规格更新data状态
function updateDataByDeletedSku(
data: SkuConfig[],
deletedSkuName: string,
): SkuConfig[] {
// 解析删除的SKU名称获取各个属性值
const deletedValues = deletedSkuName.split(',').map((v) => v.trim());
// 深拷贝data以避免修改原数据
const updatedData = JSON.parse(JSON.stringify(data)) as SkuConfig[];
// 遍历每个属性配置
updatedData.forEach((config, configIndex) => {
if (configIndex < deletedValues.length) {
const targetValue = deletedValues[configIndex];
// 找到对应的属性值并设置为失效
config.prodPropValues.forEach(
(propValue: {
propValue: string;
state?: number;
isExist?: number;
}) => {
if (propValue.propValue === targetValue) {
propValue.state = 0; // 设置为失效
propValue.isExist = 0; // 设置为不存在
}
},
);
}
});
return updatedData;
}
// 批量处理多个删除的SKU
function _updateDataByDeletedSkus(
data: SkuConfig[],
deletedSkuNames: string[],
): SkuConfig[] {
let updatedData = JSON.parse(JSON.stringify(data)) as SkuConfig[];
deletedSkuNames.forEach((skuName) => {
updatedData = updateDataByDeletedSku(updatedData, skuName);
});
return updatedData;
}
// 根据属性名和属性值直接设置失效状态
function _updateDataByPropValue(
data: SkuConfig[],
propName: string,
propValue: string,
state: 0 | 1 = 0,
): SkuConfig[] {
const updatedData = JSON.parse(JSON.stringify(data)) as SkuConfig[];
const targetConfig = updatedData.find(
(config) => config.propName === propName,
);
if (targetConfig) {
const targetPropValue = targetConfig.prodPropValues.find(
(pv: {
propValue: string;
state?: number;
isExist?: number;
isExpire?: number;
}) => pv.propValue === propValue,
);
if (targetPropValue) {
targetPropValue.state = state;
targetPropValue.isExist = state;
}
}
return updatedData;
}
// 重新生成有效的SKU列表过滤掉失效的属性值
export function generateValidSkuTableData(data: SkuConfig[]): SkuList[] {
console.log(data);
// 过滤出有效的属性值
const validData = data
.map((config) => ({
...config,
prodPropValues: config.prodPropValues.filter(
(pv: { isExpire: number }) => pv.isExpire === 0,
),
}))
.filter((config) => config.prodPropValues.length > 0);
if (validData.length === 0) {
return [];
}
const propValueArrays = validData.map((config) => config.prodPropValues);
const combinations = cartesianProduct<{
propValue: string;
valueId?: number;
state?: number;
isExist?: number;
isExpire?: number;
}>(...propValueArrays);
return combinations.map((combination) => {
const skuItem: SkuList = {
skuName: combination.map((item) => item.propValue).join(','),
properties: combination.map((item) => item.propValue).join(','),
basePrice: 0,
isSpecs: 0,
status: 1,
stocks: 0,
stocksFlg: 1,
isShelf: 1,
isExist: combination.some((item) => item.isExist) ? 1 : 0,
};
validData.forEach((config, configIndex) => {
(skuItem as any)[config.propName] = combination[configIndex].propValue;
});
return skuItem;
});
}
export const generateUUID = () => {
if (typeof crypto === 'object') {
if (typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
if (
typeof crypto.getRandomValues === 'function' &&
typeof Uint8Array === 'function'
) {
const callback = (c: any) => {
const num = Number(c);
return (
num ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))
).toString(16);
};
return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, callback);
}
}
let timestamp = Date.now();
let performanceNow =
(typeof performance !== 'undefined' &&
performance.now &&
performance.now() * 1000) ||
0;
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
let random = Math.random() * 16;
if (timestamp > 0) {
random = ((timestamp + random) % 16) | 0;
timestamp = Math.floor(timestamp / 16);
} else {
random = ((performanceNow + random) % 16) | 0;
performanceNow = Math.floor(performanceNow / 16);
}
return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16);
});
};

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) || '';
};

263
src/utils/dict.ts Normal file
View File

@@ -0,0 +1,263 @@
/**
* 数据字典工具类
*/
import { useDictStore } from '@/hooks/stores/dict';
export type AntDesignInfoType =
| 'default'
| 'primary'
| 'success'
| 'info'
| 'warning'
| 'danger'
| undefined;
/**
* 获取 dictType 对应的数据字典数组
*
* @param dictType 数据类型
* @returns {*|Array} 数据字典数组
*/
export interface DictDataType {
dictType: string;
label: string;
value: string | number | boolean;
colorType: AntDesignInfoType;
cssClass: string;
}
export interface NumberDictDataType extends DictDataType {
value: number;
}
export interface StringDictDataType extends DictDataType {
value: string;
}
export const getDictOptions = (dictType: string) => {
const dictStore = useDictStore();
return dictStore.getDictByType(dictType) || [];
};
export const getIntDictOptions = (dictType: string): NumberDictDataType[] => {
// 获得通用的 DictDataType 列表
const dictOptions: DictDataType[] = getDictOptions(dictType);
// 转换成 number 类型的 NumberDictDataType 类型
// why 需要特殊转换:避免 IDEA 在 v-for="dict in getIntDictOptions(...)" 时el-option 的 key 会告警
const dictOption: NumberDictDataType[] = [];
dictOptions.forEach((dict: DictDataType) => {
dictOption.push({
...dict,
value: parseInt(`${dict.value}`, 10),
});
});
return dictOption;
};
export const getStrDictOptions = (dictType: string) => {
// 获得通用的 DictDataType 列表
const dictOptions: DictDataType[] = getDictOptions(dictType);
// 转换成 string 类型的 StringDictDataType 类型
// why 需要特殊转换:避免 IDEA 在 v-for="dict in getStrDictOptions(...)" 时el-option 的 key 会告警
const dictOption: StringDictDataType[] = [];
dictOptions.forEach((dict: DictDataType) => {
dictOption.push({
...dict,
value: `${dict.value}`,
});
});
return dictOption;
};
export const getBoolDictOptions = (dictType: string) => {
const dictOption: DictDataType[] = [];
const dictOptions: DictDataType[] = getDictOptions(dictType);
dictOptions.forEach((dict: DictDataType) => {
dictOption.push({
...dict,
value: `${dict.value}` === 'true',
});
});
return dictOption;
};
/**
* 获取指定字典类型的指定值对应的字典对象
* @param dictType 字典类型
* @param value 字典值
* @return DictDataType 字典对象
*/
export const getDictObj = (
dictType: string,
value: any,
): DictDataType | undefined => {
const dictOptions: DictDataType[] = getDictOptions(dictType);
for (const dict of dictOptions) {
if (dict.value === `${value}`) {
return dict;
}
}
return undefined;
};
/**
* 获得字典数据的文本展示
*
* @param dictType 字典类型
* @param value 字典数据的值
* @return 字典名称
*/
export const getDictLabel = (dictType: string, value: any): string => {
const dictOptions: DictDataType[] = getDictOptions(dictType);
let dictLabel = '';
dictOptions.forEach((dict: DictDataType) => {
if (dict.value === `${value}`) {
dictLabel = dict.label;
}
});
return dictLabel;
};
export enum DICT_TYPE {
USER_TYPE = 'user_type',
COMMON_STATUS = 'common_status',
TERMINAL = 'terminal', // 终端
DATE_INTERVAL = 'date_interval', // 数据间隔
// ========== 产品 模块 ==========
PROD_STATUS = 'prod_status',
CATEGORY_STATUS = 'category_status',
// ========== SYSTEM 模块 ==========
SYSTEM_USER_SEX = 'system_user_sex',
SYSTEM_MENU_TYPE = 'system_menu_type',
SYSTEM_ROLE_TYPE = 'system_role_type',
SYSTEM_DATA_SCOPE = 'system_data_scope',
SYSTEM_NOTICE_TYPE = 'system_notice_type',
SYSTEM_LOGIN_TYPE = 'system_login_type',
SYSTEM_LOGIN_RESULT = 'system_login_result',
SYSTEM_SMS_CHANNEL_CODE = 'system_sms_channel_code',
SYSTEM_SMS_TEMPLATE_TYPE = 'system_sms_template_type',
SYSTEM_SMS_SEND_STATUS = 'system_sms_send_status',
SYSTEM_SMS_RECEIVE_STATUS = 'system_sms_receive_status',
SYSTEM_OAUTH2_GRANT_TYPE = 'system_oauth2_grant_type',
SYSTEM_MAIL_SEND_STATUS = 'system_mail_send_status',
SYSTEM_NOTIFY_TEMPLATE_TYPE = 'system_notify_template_type',
SYSTEM_SOCIAL_TYPE = 'system_social_type',
// ========== INFRA 模块 ==========
INFRA_BOOLEAN_STRING = 'infra_boolean_string',
INFRA_JOB_STATUS = 'infra_job_status',
INFRA_JOB_LOG_STATUS = 'infra_job_log_status',
INFRA_API_ERROR_LOG_PROCESS_STATUS = 'infra_api_error_log_process_status',
INFRA_CONFIG_TYPE = 'infra_config_type',
INFRA_CODEGEN_TEMPLATE_TYPE = 'infra_codegen_template_type',
INFRA_CODEGEN_FRONT_TYPE = 'infra_codegen_front_type',
INFRA_CODEGEN_SCENE = 'infra_codegen_scene',
INFRA_FILE_STORAGE = 'infra_file_storage',
INFRA_OPERATE_TYPE = 'infra_operate_type',
// ========== BPM 模块 ==========
BPM_MODEL_TYPE = 'bpm_model_type',
BPM_MODEL_FORM_TYPE = 'bpm_model_form_type',
BPM_TASK_CANDIDATE_STRATEGY = 'bpm_task_candidate_strategy',
BPM_PROCESS_INSTANCE_STATUS = 'bpm_process_instance_status',
BPM_TASK_STATUS = 'bpm_task_status',
BPM_OA_LEAVE_TYPE = 'bpm_oa_leave_type',
BPM_PROCESS_LISTENER_TYPE = 'bpm_process_listener_type',
BPM_PROCESS_LISTENER_VALUE_TYPE = 'bpm_process_listener_value_type',
// ========== PAY 模块 ==========
PAY_CHANNEL_CODE = 'pay_channel_code', // 支付渠道编码类型
PAY_ORDER_STATUS = 'pay_order_status', // 商户支付订单状态
PAY_REFUND_STATUS = 'pay_refund_status', // 退款订单状态
PAY_NOTIFY_STATUS = 'pay_notify_status', // 商户支付回调状态
PAY_NOTIFY_TYPE = 'pay_notify_type', // 商户支付回调状态
PAY_TRANSFER_STATUS = 'pay_transfer_status', // 转账订单状态
PAY_TRANSFER_TYPE = 'pay_transfer_type', // 转账订单状态
// ========== MP 模块 ==========
MP_AUTO_REPLY_REQUEST_MATCH = 'mp_auto_reply_request_match', // 自动回复请求匹配类型
MP_MESSAGE_TYPE = 'mp_message_type', // 消息类型
// ========== Member 会员模块 ==========
MEMBER_POINT_BIZ_TYPE = 'member_point_biz_type', // 积分的业务类型
MEMBER_EXPERIENCE_BIZ_TYPE = 'member_experience_biz_type', // 会员经验业务类型
// ========== MALL - 商品模块 ==========
PRODUCT_SPU_STATUS = 'product_spu_status', //商品状态
// ========== MALL - 交易模块 ==========
EXPRESS_CHARGE_MODE = 'trade_delivery_express_charge_mode', //快递的计费方式
TRADE_AFTER_SALE_STATUS = 'trade_after_sale_status', // 售后 - 状态
TRADE_AFTER_SALE_WAY = 'trade_after_sale_way', // 售后 - 方式
TRADE_AFTER_SALE_TYPE = 'trade_after_sale_type', // 售后 - 类型
TRADE_ORDER_TYPE = 'trade_order_type', // 订单 - 类型
TRADE_ORDER_STATUS = 'trade_order_status', // 订单 - 状态
TRADE_ORDER_ITEM_AFTER_SALE_STATUS = 'trade_order_item_after_sale_status', // 订单项 - 售后状态
TRADE_DELIVERY_TYPE = 'trade_delivery_type', // 配送方式
BROKERAGE_ENABLED_CONDITION = 'brokerage_enabled_condition', // 分佣模式
BROKERAGE_BIND_MODE = 'brokerage_bind_mode', // 分销关系绑定模式
BROKERAGE_BANK_NAME = 'brokerage_bank_name', // 佣金提现银行
BROKERAGE_WITHDRAW_TYPE = 'brokerage_withdraw_type', // 佣金提现类型
BROKERAGE_RECORD_BIZ_TYPE = 'brokerage_record_biz_type', // 佣金业务类型
BROKERAGE_RECORD_STATUS = 'brokerage_record_status', // 佣金状态
BROKERAGE_WITHDRAW_STATUS = 'brokerage_withdraw_status', // 佣金提现状态
// ========== MALL - 营销模块 ==========
PROMOTION_DISCOUNT_TYPE = 'promotion_discount_type', // 优惠类型
PROMOTION_PRODUCT_SCOPE = 'promotion_product_scope', // 营销的商品范围
PROMOTION_COUPON_TEMPLATE_VALIDITY_TYPE = 'promotion_coupon_template_validity_type', // 优惠劵模板的有限期类型
PROMOTION_COUPON_STATUS = 'promotion_coupon_status', // 优惠劵的状态
PROMOTION_COUPON_TAKE_TYPE = 'promotion_coupon_take_type', // 优惠劵的领取方式
PROMOTION_CONDITION_TYPE = 'promotion_condition_type', // 营销的条件类型枚举
PROMOTION_BARGAIN_RECORD_STATUS = 'promotion_bargain_record_status', // 砍价记录的状态
PROMOTION_COMBINATION_RECORD_STATUS = 'promotion_combination_record_status', // 拼团记录的状态
PROMOTION_BANNER_POSITION = 'promotion_banner_position', // banner 定位
// ========== CRM - 客户管理模块 ==========
CRM_AUDIT_STATUS = 'crm_audit_status', // CRM 审批状态
CRM_BIZ_TYPE = 'crm_biz_type', // CRM 业务类型
CRM_BUSINESS_END_STATUS_TYPE = 'crm_business_end_status_type', // CRM 商机结束状态类型
CRM_RECEIVABLE_RETURN_TYPE = 'crm_receivable_return_type', // CRM 回款的还款方式
CRM_CUSTOMER_INDUSTRY = 'crm_customer_industry', // CRM 客户所属行业
CRM_CUSTOMER_LEVEL = 'crm_customer_level', // CRM 客户级别
CRM_CUSTOMER_SOURCE = 'crm_customer_source', // CRM 客户来源
CRM_PRODUCT_STATUS = 'crm_product_status', // CRM 商品状态
CRM_PERMISSION_LEVEL = 'crm_permission_level', // CRM 数据权限的级别
CRM_PRODUCT_UNIT = 'crm_product_unit', // CRM 产品单位
CRM_FOLLOW_UP_TYPE = 'crm_follow_up_type', // CRM 跟进方式
// ========== ERP - 企业资源计划模块 ==========
ERP_AUDIT_STATUS = 'erp_audit_status', // ERP 审批状态
ERP_STOCK_RECORD_BIZ_TYPE = 'erp_stock_record_biz_type', // 库存明细的业务类型
// ========== AI - 人工智能模块 ==========
AI_PLATFORM = 'ai_platform', // AI 平台
AI_MODEL_TYPE = 'ai_model_type', // AI 模型类型
AI_IMAGE_STATUS = 'ai_image_status', // AI 图片状态
AI_MUSIC_STATUS = 'ai_music_status', // AI 音乐状态
AI_GENERATE_MODE = 'ai_generate_mode', // AI 生成模式
AI_WRITE_TYPE = 'ai_write_type', // AI 写作类型
AI_WRITE_LENGTH = 'ai_write_length', // AI 写作长度
AI_WRITE_FORMAT = 'ai_write_format', // AI 写作格式
AI_WRITE_TONE = 'ai_write_tone', // AI 写作语气
AI_WRITE_LANGUAGE = 'ai_write_language', // AI 写作语言
// ========== IOT - 物联网模块 ==========
IOT_NET_TYPE = 'iot_net_type', // IOT 联网方式
IOT_VALIDATE_TYPE = 'iot_validate_type', // IOT 数据校验级别
IOT_PRODUCT_STATUS = 'iot_product_status', // IOT 产品状态
IOT_PRODUCT_DEVICE_TYPE = 'iot_product_device_type', // IOT 产品设备类型
IOT_DATA_FORMAT = 'iot_data_format', // IOT 数据格式
IOT_PROTOCOL_TYPE = 'iot_protocol_type', // IOT 接入网关协议
IOT_DEVICE_STATE = 'iot_device_state', // IOT 设备状态
IOT_THING_MODEL_TYPE = 'iot_thing_model_type', // IOT 产品功能类型
IOT_DATA_TYPE = 'iot_data_type', // IOT 数据类型
IOT_THING_MODEL_UNIT = 'iot_thing_model_unit', // IOT 物模型单位
IOT_RW_TYPE = 'iot_rw_type', // IOT 读写类型
IOT_PLUGIN_DEPLOY_TYPE = 'iot_plugin_deploy_type', // IOT 插件部署类型
IOT_PLUGIN_STATUS = 'iot_plugin_status', // IOT 插件状态
IOT_PLUGIN_TYPE = 'iot_plugin_type', // IOT 插件类型
IOT_DATA_BRIDGE_DIRECTION_ENUM = 'iot_data_bridge_direction_enum', // 桥梁方向
IOT_DATA_BRIDGE_TYPE_ENUM = 'iot_data_bridge_type_enum', // 桥梁类型
}

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;
};