/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Banner, Button, Form, Toast, Empty, Spin } from '@/components/ui'; import { RefreshCw, Plus, Network } from 'lucide-react'; import { API } from '../../helpers/api'; import { showError } from '../../helpers'; import { useActualTheme } from '../../context/Theme'; import OrgPageHeader from './components/OrgPageHeader'; import OrgPanel from './components/OrgPanel'; import OrgModal from './components/OrgModal'; import DeptFlowCanvas from './components/DeptFlowCanvas'; import { buildDeptTreeData } from './components/deptTree'; const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) }); // 部门管理:组织架构画布(多棵树)+ 节点内操作;移动走后端 MoveDepartmentTx 级联 path const OrgDepartments = ({ orgId }) => { const { t } = useTranslation(); const actualTheme = useActualTheme(); const [list, setList] = useState([]); const [loading, setLoading] = useState(false); const [loaded, setLoaded] = useState(false); const [modalVisible, setModalVisible] = useState(false); const [editing, setEditing] = useState(null); // null=新建,否则为编辑对象 const [createParentId, setCreateParentId] = useState(0); // 新建时预填父部门 const [formApi, setFormApi] = useState(null); const [saving, setSaving] = useState(false); const [direction, setDirection] = useState('TB'); // TB 纵向 / LR 横向 const [members, setMembers] = useState([]); // 活跃成员(含 department_id),供画布展示成员数/列表 const [budgets, setBudgets] = useState([]); // 部门预算行,供画布节点展示预算用量 // 预算拦截是否生效:false 时不渲染用量条(used 恒为 0,显示会误导管理员"本月没花钱") const [budgetEnforced, setBudgetEnforced] = useState(null); const fetchList = useCallback(async () => { if (!orgId) return; setLoading(true); try { const [res, mres, bres] = await Promise.all([ API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }), // 成员数据仅是画布辅助信息:网络失败兜底为 null,不连坐部门树 API.get('/api/org/members/all', { headers: getOrgHeaders(orgId), }).catch(() => null), // 部门预算仅是画布辅助信息:失败/未开启预算功能时静默降级为不展示。 // skipErrorHandler:若后端将来把 feature 未开改成真 4xx,.catch 拦不住 // axios 全局拦截器的 toast,必须在请求层显式静默 API.get('/api/org/budget?subject_type=department', { headers: getOrgHeaders(orgId), skipErrorHandler: true, }).catch(() => null), ]); if (res.data.success) { setList(res.data.data || []); } else { showError(res.data.message); } // 成员列表仅用于画布展示,拉取失败不阻塞部门树 if (mres?.data?.success) setMembers(mres.data.data || []); if (bres?.data?.success) { // 新后端返回 {items, enforcement_enabled};兼容旧后端直接返回数组 const payload = bres.data.data; const items = Array.isArray(payload) ? payload : payload?.items || []; setBudgets(items.filter((b) => b.subject_type === 'department')); setBudgetEnforced( Array.isArray(payload) ? null : (payload?.enforcement_enabled ?? null), ); } } catch (err) { showError(err.message); } finally { setLoading(false); setLoaded(true); } }, [orgId]); useEffect(() => { fetchList(); }, [fetchList]); // 上级部门树:编辑时排除自身及其整棵子树(path 前缀判断,避免选出环)。 // 与成员分配不同,上级可以是任意层级节点(disableNonLeaf=false),停用部门不可作新上级。 const parentTreeData = useMemo( () => [ { label: t('顶级部门'), value: 0, key: '0' }, ...buildDeptTreeData(list, { disableNonLeaf: false, excludeSubtreeOf: editing, disabledLabel: t('已停用'), }), ], [list, editing, t], ); // 弹窗内实时跟踪所选上级(表单值变化同步),用于「上级已有直属成员」提示 const [modalParentId, setModalParentId] = useState(0); const memberCountByDept = useMemo(() => { const m = {}; members.forEach((mm) => { if (mm.department_id) m[mm.department_id] = (m[mm.department_id] || 0) + 1; }); return m; }, [members]); const parentMemberCount = modalParentId > 0 ? memberCountByDept[modalParentId] || 0 : 0; const openCreate = useCallback((parentId = 0) => { setEditing(null); setCreateParentId(parentId); setModalParentId(parentId); setModalVisible(true); }, []); const openEdit = useCallback((record) => { setEditing(record); setModalParentId(record.parent_id || 0); setModalVisible(true); }, []); const handleAddChild = useCallback( (parent) => openCreate(parent.id), [openCreate], ); useEffect(() => { if (modalVisible && formApi) { if (editing) { formApi.setValues({ name: editing.name, parent_id: editing.parent_id || 0, sort: editing.sort || 0, status: editing.status || 1, }); } else { formApi.setValues({ name: '', parent_id: createParentId, sort: 0, status: 1, }); } } }, [modalVisible, editing, createParentId, formApi]); const handleSubmit = async () => { if (!formApi || saving) return; let values; try { values = await formApi.validate(); } catch { return; } setSaving(true); try { let res; if (editing) { res = await API.put(`/api/org/dept/${editing.id}`, values, { headers: getOrgHeaders(orgId), }); } else { res = await API.post('/api/org/dept', values, { headers: getOrgHeaders(orgId), }); } if (res.data.success) { Toast.success(editing ? t('部门已更新') : t('部门已创建')); setModalVisible(false); fetchList(); } else { showError(res.data.message); } } catch (err) { showError(err.message); } finally { setSaving(false); } }; const handleDelete = useCallback( async (record) => { try { const res = await API.delete(`/api/org/dept/${record.id}`, { headers: getOrgHeaders(orgId), }); if (res.data.success) { Toast.success(t('部门已删除')); fetchList(); } else { showError(res.data.message); } } catch (err) { showError(err.message); } }, [orgId, t, fetchList], ); // 画布连线触发:把 childId 移到 parentId 之下(后端 MoveDepartmentTx 防环并级联 path) const handleMove = useCallback( async (childId, parentId) => { try { const res = await API.put( `/api/org/dept/${childId}`, { parent_id: parentId }, { headers: getOrgHeaders(orgId) }, ); if (res.data.success) { Toast.success(t('部门层级已调整')); } else { showError(res.data.message); } } catch (err) { showError(err.message); } finally { fetchList(); } }, [orgId, t, fetchList], ); return (
} />
{!loaded && loading ? (
) : list.length === 0 ? (
) : ( )}
setModalVisible(false)} okText={t('保存')} cancelText={t('取消')} confirmLoading={saving} > {parentMemberCount > 0 && ( )}
setModalParentId((prev) => values.parent_id ?? prev) } > {editing && ( )}
); }; export default OrgDepartments;