Преглед на файлове

修复系统配置里状态数据从接口回显和字典匹配

pm преди 3 месеца
родител
ревизия
4365205ebc

+ 39 - 6
src/components/DepartmentManagement.tsx

@@ -11,7 +11,8 @@ import { deptApi, DeptVO } from '../api/dept';
 import { userApi } from '../api/user';
 import { UserVO } from '../types';
 import { toast } from 'sonner';
-import { DICT_TYPE, getIntDictOptions, getDictLabel } from '../utils/dict';
+import { DICT_TYPE, getIntDictOptions, getDictLabel, setDictOptions, DictDataType } from '../utils/dict';
+import { dictDataApi } from '../api/DictData';
 import { dateFormatter } from '../utils/formatTime';
 import { handleTree, TreeNode } from '../utils/tree';
 import DeptForm, { DeptFormRef } from './dept/DeptForm';
@@ -32,7 +33,7 @@ export default function DepartmentManagement() {
   const [refreshTable, setRefreshTable] = useState(true);
   const [userList, setUserList] = useState<UserVO[]>([]);
   const [deptStatusUpdating, setDeptStatusUpdating] = useState<Record<number, boolean>>({});
-  const [statusOptions] = useState(() => {
+  const [statusOptions, setStatusOptions] = useState(() => {
     try {
       return getIntDictOptions(DICT_TYPE.COMMON_STATUS);
     } catch (error) {
@@ -42,6 +43,34 @@ export default function DepartmentManagement() {
   });
   const formRef = useRef<DeptFormRef>(null);
 
+  // 加载 COMMON_STATUS 字典数据
+  const loadCommonStatusDict = async () => {
+    try {
+      const response = await dictDataApi.getDictDataPage({
+        pageNo: 1,
+        pageSize: -1,
+        dictType: DICT_TYPE.COMMON_STATUS,
+      });
+      const data = (response as any)?.data || response;
+      const dictList = data?.list || [];
+      if (Array.isArray(dictList) && dictList.length > 0) {
+        const dictOptions: DictDataType[] = dictList.map((item: any) => ({
+          dictType: item.dictType,
+          label: item.label,
+          value: item.value,
+          colorType: item.colorType || '',
+          cssClass: item.cssClass || '',
+        }));
+        setDictOptions(DICT_TYPE.COMMON_STATUS, dictOptions);
+        // 更新状态选项
+        setStatusOptions(getIntDictOptions(DICT_TYPE.COMMON_STATUS));
+        console.log('DepartmentManagement: 获取通用状态字典成功', dictOptions);
+      }
+    } catch (error) {
+      console.error('加载通用状态字典数据失败:', error);
+    }
+  };
+
   // 查询部门列表
   const getList = async () => {
     setLoading(true);
@@ -239,10 +268,12 @@ export default function DepartmentManagement() {
             <TableCell className="text-center">
               {(() => {
                 const status = Number((node as any).status);
-                // 部门管理:0=开启,1=关闭(与通用字典定义相反)
-                const statusLabel = status === 0 ? t('common.enabled') : t('common.disabled');
-                const statusStyle = status === 0
-                  ? 'bg-green-100 text-green-700'
+                // 使用字典值显示状态
+                const statusLabel = getDictLabel(DICT_TYPE.COMMON_STATUS, status) || '-';
+                // 根据字典的 label 来判断颜色:开启/启用显示绿色,禁用/关闭显示灰色
+                const isEnabled = statusLabel === '开启' || statusLabel === '启用' || statusLabel === '正常';
+                const statusStyle = isEnabled 
+                  ? 'bg-green-100 text-green-700' 
                   : 'bg-gray-100 text-gray-700';
                 return (
                   <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusStyle}`}>
@@ -335,6 +366,8 @@ export default function DepartmentManagement() {
     console.log('DepartmentManagement 组件已挂载,开始获取数据');
     const initData = async () => {
       try {
+        // 先加载字典数据
+        await loadCommonStatusDict();
         console.log('开始调用 getList() 获取部门列表');
         await getList();
         console.log('部门列表获取成功');

+ 14 - 6
src/components/PostForm.tsx

@@ -2,6 +2,7 @@ import React, { useState, useImperativeHandle, forwardRef } from 'react';
 import { postApi, PostVO, PostStatus } from '../api/Post';
 import { toast } from 'sonner';
 import { Modal, Form, Input, Button, Select, Spin } from 'antd';
+import { DICT_TYPE, getIntDictOptions } from '../utils/dict';
 import { useTranslation } from 'react-i18next';
 
 interface PostFormProps {
@@ -20,6 +21,9 @@ const PostForm = forwardRef<PostFormRef, PostFormProps>(({ onSuccess }, ref) =>
   const [formLoading, setFormLoading] = useState(false);
   const [currentId, setCurrentId] = useState<number | undefined>();
   const [form] = Form.useForm();
+  
+  // 获取最新的字典选项(每次调用都从缓存中获取最新数据)
+  const getStatusOptions = () => getIntDictOptions(DICT_TYPE.COMMON_STATUS);
 
   // 暴露方法给父组件
   useImperativeHandle(ref, () => ({
@@ -32,11 +36,13 @@ const PostForm = forwardRef<PostFormRef, PostFormProps>(({ onSuccess }, ref) =>
       if (id) {
         loadPostData(id);
       } else {
+        // 从字典中获取默认启用状态值
+        const defaultStatus = getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1;
         form.setFieldsValue({
           name: '',
           code: '',
           sort: 0,
-          status: 0, // 岗位管理:0=启用,1=禁用(与列表显示保持一致)
+          status: defaultStatus,
           remark: '',
         });
         setFormLoading(false);
@@ -56,7 +62,7 @@ const PostForm = forwardRef<PostFormRef, PostFormProps>(({ onSuccess }, ref) =>
         name: data.name,
         code: data.code,
         sort: data.sort ?? 0,
-        status: typeof data.status === 'string' ? Number(data.status) : (data.status ?? PostStatus.ENABLE),
+        status: typeof data.status === 'string' ? Number(data.status) : (data.status ?? (getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1)),
         remark: data.remark || '',
       });
     } catch (error: any) {
@@ -121,7 +127,7 @@ const PostForm = forwardRef<PostFormRef, PostFormProps>(({ onSuccess }, ref) =>
           wrapperCol={{ span: 20 }}
           initialValues={{
             sort: 0,
-            status: 0, // 岗位管理:0=启用,1=禁用(与列表显示保持一致)
+            status: getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1,
             remark: '',
           }}
         >
@@ -161,9 +167,11 @@ const PostForm = forwardRef<PostFormRef, PostFormProps>(({ onSuccess }, ref) =>
             rules={[{ required: true, message: t('common.pleaseSelect') }]}
           >
             <Select placeholder={t('common.pleaseSelect')}>
-              {/* 岗位管理:0=启用,1=禁用(与通用字典定义相反,需与列表显示保持一致) */}
-              <Select.Option value={0}>{t('common.enabled')}</Select.Option>
-              <Select.Option value={1}>{t('common.disabled')}</Select.Option>
+              {getStatusOptions().map((option) => (
+                <Select.Option key={option.value} value={option.value}>
+                  {option.label}
+                </Select.Option>
+              ))}
             </Select>
           </Form.Item>
 

+ 39 - 5
src/components/PostManagement.tsx

@@ -3,7 +3,8 @@ import { Search, Plus, RefreshCw, Edit2, Trash2, Download } from 'lucide-react';
 import { postApi, PostVO, PostStatus, PageParam } from '../api/Post';
 import { toast } from 'sonner';
 import { formatDateTimeFull } from '../utils/formatTime';
-import { DICT_TYPE, getDictLabel } from '../utils/dict';
+import { DICT_TYPE, getDictLabel, getDictOptions, setDictOptions, DictDataType } from '../utils/dict';
+import { dictDataApi } from '../api/DictData';
 import { Modal, Button, Input, Space, Tooltip, Switch as AntdSwitch } from 'antd';
 import { ExclamationCircleOutlined } from '@ant-design/icons';
 import { Button as UIButton } from './ui/button';
@@ -83,6 +84,37 @@ export default function PostManagement() {
     }
   };
 
+  // 加载 COMMON_STATUS 字典数据
+  const loadCommonStatusDict = async () => {
+    try {
+      const response = await dictDataApi.getDictDataPage({
+        pageNo: 1,
+        pageSize: -1,
+        dictType: DICT_TYPE.COMMON_STATUS,
+      });
+      const data = (response as any)?.data || response;
+      const dictList = data?.list || [];
+      if (Array.isArray(dictList) && dictList.length > 0) {
+        const dictOptions: DictDataType[] = dictList.map((item: any) => ({
+          dictType: item.dictType,
+          label: item.label,
+          value: item.value,
+          colorType: item.colorType || '',
+          cssClass: item.cssClass || '',
+        }));
+        setDictOptions(DICT_TYPE.COMMON_STATUS, dictOptions);
+        console.log('PostManagement: 获取通用状态字典成功', dictOptions);
+      }
+    } catch (error) {
+      console.error('加载通用状态字典数据失败:', error);
+    }
+  };
+
+  // 组件挂载时加载字典数据
+  useEffect(() => {
+    loadCommonStatusDict();
+  }, []);
+
   // 组件挂载和分页参数变化时获取数据
   useEffect(() => {
     console.log('PostManagement: useEffect 触发,queryParams =', queryParams);
@@ -346,10 +378,12 @@ export default function PostManagement() {
                   <TableCell className="text-center">
                     {(() => {
                       const status = Number(row.status);
-                      // 岗位管理:0=开启,1=关闭(与通用字典定义相反)
-                      const statusLabel = status === 0 ? t('common.enabled') : t('common.disabled');
-                      const statusStyle = status === 0
-                        ? 'bg-green-100 text-green-700'
+                      // 使用字典值显示状态
+                      const statusLabel = getDictLabel(DICT_TYPE.COMMON_STATUS, status) || '-';
+                      // 根据字典的 label 来判断颜色:开启/启用显示绿色,禁用/关闭显示灰色
+                      const isEnabled = statusLabel === '开启' || statusLabel === '启用' || statusLabel === '正常';
+                      const statusStyle = isEnabled 
+                        ? 'bg-green-100 text-green-700' 
                         : 'bg-gray-100 text-gray-700';
                       return (
                         <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusStyle}`}>

+ 9 - 6
src/components/RoleForm.tsx

@@ -22,6 +22,9 @@ const RoleForm = forwardRef<RoleFormRef, RoleFormProps>(({ onSuccess }, ref) =>
   const [formLoading, setFormLoading] = useState(false);
   const [currentId, setCurrentId] = useState<number | undefined>();
   const [form] = Form.useForm();
+  
+  // 获取最新的字典选项(每次调用都从缓存中获取最新数据)
+  const getStatusOptions = () => getIntDictOptions(DICT_TYPE.COMMON_STATUS);
 
   // 暴露方法给父组件
   useImperativeHandle(ref, () => ({
@@ -34,11 +37,13 @@ const RoleForm = forwardRef<RoleFormRef, RoleFormProps>(({ onSuccess }, ref) =>
       if (id) {
         loadRoleData(id);
       } else {
+        // 从字典中获取默认启用状态值
+        const defaultStatus = getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1;
         form.setFieldsValue({
           name: '',
           code: '',
           sort: 0,
-          status: CommonStatusEnum.ENABLE,
+          status: defaultStatus,
           remark: '',
         });
         setFormLoading(false);
@@ -58,7 +63,7 @@ const RoleForm = forwardRef<RoleFormRef, RoleFormProps>(({ onSuccess }, ref) =>
         name: data.name,
         code: data.code,
         sort: data.sort ?? 0,
-        status: typeof data.status === 'string' ? Number(data.status) : (data.status ?? CommonStatusEnum.ENABLE),
+        status: typeof data.status === 'string' ? Number(data.status) : (data.status ?? (getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1)),
         remark: data.remark || '',
       });
     } catch (error: any) {
@@ -105,8 +110,6 @@ const RoleForm = forwardRef<RoleFormRef, RoleFormProps>(({ onSuccess }, ref) =>
     }
   };
 
-  const statusOptions = getIntDictOptions(DICT_TYPE.COMMON_STATUS);
-
   return (
     <Modal
       title={dialogTitle}
@@ -127,7 +130,7 @@ const RoleForm = forwardRef<RoleFormRef, RoleFormProps>(({ onSuccess }, ref) =>
           wrapperCol={{ span: 20 }}
           initialValues={{
             sort: 0,
-            status: CommonStatusEnum.ENABLE,
+            status: getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1,
             remark: '',
           }}
         >
@@ -167,7 +170,7 @@ const RoleForm = forwardRef<RoleFormRef, RoleFormProps>(({ onSuccess }, ref) =>
             rules={[{ required: true, message: t('role.statusRequired') }]}
           >
             <Select placeholder={t('role.statusPlaceholder')} style={{ maxWidth: '400px' }}>
-              {statusOptions.map((option) => (
+              {getStatusOptions().map((option) => (
                 <Select.Option key={option.value} value={option.value}>
                   {option.label}
                 </Select.Option>

+ 52 - 25
src/components/RoleManagement.tsx

@@ -3,7 +3,7 @@ import { Search, Plus, RefreshCw, Edit2, Trash2, Download, Settings, Shield } fr
 import { roleApi, RoleVO, PageParam } from '../api/Role';
 import { toast } from 'sonner';
 import { formatDateTimeFull } from '../utils/formatTime';
-import { getIntDictOptions, DICT_TYPE, getDictLabel, setDictOptions, DictDataType } from '../utils/dict';
+import { getIntDictOptions, DICT_TYPE, getDictLabel, getDictOptions, setDictOptions, DictDataType } from '../utils/dict';
 import { dictDataApi } from '../api/DictData';
 import { Modal, Button, Input, Space, Tooltip } from 'antd';
 import { ExclamationCircleOutlined } from '@ant-design/icons';
@@ -35,26 +35,51 @@ export default function RoleManagement() {
   // 加载字典数据
   const loadDictData = async () => {
     try {
-      const response = await dictDataApi.getDictDataPage({
-        pageNo: 1,
-        pageSize: -1,
-        dictType: DICT_TYPE.SYSTEM_ROLE_TYPE,
-      });
-      const data = (response as any)?.data || response;
-      const dictList = data?.list || [];
-      if (Array.isArray(dictList) && dictList.length > 0) {
-        const dictOptions: DictDataType[] = dictList.map((item: any) => ({
-            dictType: item.dictType,
-            label: item.label,
-            value: item.value,
-            colorType: item.colorType || '',
-            cssClass: item.cssClass || '',
-          }));
-          setDictOptions(DICT_TYPE.SYSTEM_ROLE_TYPE, dictOptions);
-        console.log('RoleManagement: 获取角色类型字典成功', dictOptions);
+      // 并行加载角色类型和通用状态字典
+      const [roleTypeResponse, commonStatusResponse] = await Promise.all([
+        dictDataApi.getDictDataPage({
+          pageNo: 1,
+          pageSize: -1,
+          dictType: DICT_TYPE.SYSTEM_ROLE_TYPE,
+        }),
+        dictDataApi.getDictDataPage({
+          pageNo: 1,
+          pageSize: -1,
+          dictType: DICT_TYPE.COMMON_STATUS,
+        }),
+      ]);
+
+      // 处理角色类型字典
+      const roleTypeData = (roleTypeResponse as any)?.data || roleTypeResponse;
+      const roleTypeList = roleTypeData?.list || [];
+      if (Array.isArray(roleTypeList) && roleTypeList.length > 0) {
+        const roleTypeOptions: DictDataType[] = roleTypeList.map((item: any) => ({
+          dictType: item.dictType,
+          label: item.label,
+          value: item.value,
+          colorType: item.colorType || '',
+          cssClass: item.cssClass || '',
+        }));
+        setDictOptions(DICT_TYPE.SYSTEM_ROLE_TYPE, roleTypeOptions);
+        console.log('RoleManagement: 获取角色类型字典成功', roleTypeOptions);
+      }
+
+      // 处理通用状态字典
+      const commonStatusData = (commonStatusResponse as any)?.data || commonStatusResponse;
+      const commonStatusList = commonStatusData?.list || [];
+      if (Array.isArray(commonStatusList) && commonStatusList.length > 0) {
+        const commonStatusOptions: DictDataType[] = commonStatusList.map((item: any) => ({
+          dictType: item.dictType,
+          label: item.label,
+          value: item.value,
+          colorType: item.colorType || '',
+          cssClass: item.cssClass || '',
+        }));
+        setDictOptions(DICT_TYPE.COMMON_STATUS, commonStatusOptions);
+        console.log('RoleManagement: 获取通用状态字典成功', commonStatusOptions);
       }
     } catch (error) {
-      console.error('加载角色类型字典数据失败:', error);
+      console.error('加载字典数据失败:', error);
     }
   };
 
@@ -196,16 +221,18 @@ export default function RoleManagement() {
   };
 
 
-  // 获取状态标签
+  // 获取状态标签(使用字典值)
   const getStatusLabel = (status: number) => {
-    // 角色管理:0=开启,1=关闭(与通用字典定义相反)
-    return status === 0 ? t('role.enabled') : t('role.disabled');
+    return getDictLabel(DICT_TYPE.COMMON_STATUS, status) || '-';
   };
 
-  // 获取状态样式
+  // 获取状态样式(使用字典值)
   const getStatusStyle = (status: number) => {
-    return status === 0
-      ? 'bg-green-100 text-green-700'
+    const statusLabel = getDictLabel(DICT_TYPE.COMMON_STATUS, status) || '-';
+    // 根据字典的 label 来判断颜色:开启/启用显示绿色,禁用/关闭显示灰色
+    const isEnabled = statusLabel === '开启' || statusLabel === '启用' || statusLabel === '正常';
+    return isEnabled 
+      ? 'bg-green-100 text-green-700' 
       : 'bg-gray-100 text-gray-700';
   };
 

+ 7 - 7
src/components/dept/DeptForm.tsx

@@ -5,7 +5,6 @@ import { userApi } from '../../api/user';
 import { UserVO } from '../../types';
 import { toast } from 'sonner';
 import { DICT_TYPE, getIntDictOptions } from '../../utils/dict';
-import { CommonStatusEnum } from '../../utils/constants';
 import { handleTree, TreeNode } from '../../utils/tree';
 import { useTranslation } from 'react-i18next';
 
@@ -27,7 +26,8 @@ const DeptForm = forwardRef<DeptFormRef, DeptFormProps>(({ onSuccess }, ref) =>
   const [form] = Form.useForm();
   const [deptTree, setDeptTree] = useState<TreeNode[]>([]);
   const [userList, setUserList] = useState<UserVO[]>([]);
-  const [statusOptions, setStatusOptions] = useState(getIntDictOptions(DICT_TYPE.COMMON_STATUS));
+  // 获取最新的字典选项(每次调用都从缓存中获取最新数据)
+  const getStatusOptions = () => getIntDictOptions(DICT_TYPE.COMMON_STATUS);
 
   // 打开弹窗
   const open = async (type: string, id?: number, parentId?: number) => {
@@ -70,7 +70,7 @@ const DeptForm = forwardRef<DeptFormRef, DeptFormProps>(({ onSuccess }, ref) =>
           leaderUserId: deptData.leaderUserId,
           phone: deptData.phone || '',
           email: deptData.email || '',
-          status: deptData.status ?? CommonStatusEnum.ENABLE,
+          status: deptData.status ?? (getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1),
         });
       } catch (error) {
         toast.error(error.message || t('common.error'));
@@ -86,7 +86,7 @@ const DeptForm = forwardRef<DeptFormRef, DeptFormProps>(({ onSuccess }, ref) =>
         leaderUserId: undefined,
         phone: '',
         email: '',
-        status: CommonStatusEnum.ENABLE,
+        status: getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1,
       });
     }
   };
@@ -105,7 +105,7 @@ const DeptForm = forwardRef<DeptFormRef, DeptFormProps>(({ onSuccess }, ref) =>
         ...values,
         parentId: values.parentId ?? 0,
         sort: values.sort ?? 0,
-        status: values.status ?? CommonStatusEnum.ENABLE,
+        status: values.status ?? (getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1),
       };
 
       if (formType === 'create') {
@@ -167,7 +167,7 @@ const DeptForm = forwardRef<DeptFormRef, DeptFormProps>(({ onSuccess }, ref) =>
           initialValues={{
             parentId: 0,
             sort: 0,
-            status: CommonStatusEnum.ENABLE,
+            status: getStatusOptions().find(opt => opt.label === '启用' || opt.colorType === 'success')?.value ?? getStatusOptions()[0]?.value ?? 1,
           }}
         >
           <Form.Item
@@ -250,7 +250,7 @@ const DeptForm = forwardRef<DeptFormRef, DeptFormProps>(({ onSuccess }, ref) =>
           >
             <Select
               placeholder={t('form.deptStatusPlaceholder')}
-              options={statusOptions.map((dict) => ({
+              options={getStatusOptions().map((dict) => ({
                 label: dict.label,
                 value: dict.value,
               }))}