/* 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 { formatUserReference } from '../../../helpers/safeDisplay'; import { Trans } from 'react-i18next'; import { ChevronRight as ActionChevronRight, ChevronDown as ActionChevronDown, Users as ActionUsers, Plus as ActionPlus, Pencil as ActionPencil, Trash2 as ActionTrash2, LayoutGrid as ActionLayoutGrid, } from '@/components/common/icons/ActionIcons'; import React, { memo, useCallback, useEffect, useMemo, useRef, useState, } from 'react'; import { useTranslation } from 'react-i18next'; import { ReactFlow, ReactFlowProvider, Controls, MiniMap, Panel, Handle, Position, useNodesState, useEdgesState, useReactFlow, useUpdateNodeInternals, } from '@xyflow/react'; import dagre from '@dagrejs/dagre'; import { Avatar, Button, Popconfirm, RadioGroup, Radio, SideSheet, Tag, Tooltip, Typography, } from '@/components/ui'; import { Network, Building2 } from 'lucide-react'; import OrgScopedLimitButtons from './OrgScopedLimitButtons'; import { buildDeptFullNameMap } from './deptTree'; import { renderQuota } from '../../../helpers/render'; import '@xyflow/react/dist/style.css'; import './DeptFlowCanvas.css'; const { Text } = Typography; // dagre 布局用的节点占位尺寸(与卡片实际渲染尺寸保持一致,决定节点间距)。 // 高度按「带预算行」的卡片取值——无预算的卡片略矮只会让间距更宽松,不会重叠。 const NODE_WIDTH = 264; const NODE_HEIGHT = 144; const parseGroups = (raw) => { if (Array.isArray(raw)) return raw; if (typeof raw === 'string' && raw.trim()) { try { const arr = JSON.parse(raw); if (Array.isArray(arr)) return arr; } catch { /* ignore */ } } return []; }; // 部门预算行 → 卡片展示用摘要:优先周期口径,无周期上限再看总上限;双 0(不限)不展示。 const summarizeBudget = (t, budget) => { if (!budget || budget.status !== 1) return null; const cycleLabels = { daily: t('每日'), weekly: t('每周'), monthly: t('每月'), custom: t('自定义'), }; // used 含预留中份额:与预算中心「used (+reserved 预留)」口径一致, // 否则两页同开时百分比自相矛盾,且接近 cap 时画布不变红失去预警 if (budget.cycle_quota > 0) { return { label: cycleLabels[budget.cycle_type] || t('周期上限'), used: (budget.used_in_cycle || 0) + (budget.reserved_in_cycle || 0), cap: budget.cycle_quota, }; } if (budget.total_quota > 0) { return { label: t('总上限'), used: (budget.used_total || 0) + (budget.reserved_total || 0), cap: budget.total_quota, }; } return null; }; /** 部门卡片节点:信息展示 + 卡片内操作区(操作区带 nodrag,避免与画布拖拽冲突) */ const DeptNode = memo(({ data, selected }) => { const { t } = useTranslation(); const { dept, childCount, memberCount, collapsed, hiddenCount, direction, orgId, budget, onAddChild, onEdit, onDelete, onSaved, onToggleCollapse, onShowMembers, } = data; const budgetInfo = summarizeBudget(t, budget); const active = dept.status === 1; const isRoot = !dept.parent_id; const groupCount = parseGroups(dept.groups).length; const modelCount = dept.model_limits_enabled && dept.model_limits ? dept.model_limits.split(',').filter(Boolean).length : 0; const targetPos = direction === 'LR' ? Position.Left : Position.Top; const sourcePos = direction === 'LR' ? Position.Right : Position.Bottom; const DeptIcon = isRoot ? Building2 : Network; return (
{/* 根节点渐变顶条:一眼区分树的入口 */} {isRoot && (
)}
{dept.name}
{childCount > 0 && ( )} {active ? t('启用') : t('停用')}
{modelCount > 0 && ( {t('模型限制')} {modelCount} )} {groupCount > 0 && ( {t('限定分组')} {groupCount} )}
{budgetInfo && (() => { const pct = Math.min( 100, Math.round((budgetInfo.used / budgetInfo.cap) * 100), ); const danger = pct >= 90; return (
{t('预算')} · {budgetInfo.label} {renderQuota(budgetInfo.used, 2)} /{' '} {renderQuota(budgetInfo.cap, 2)}
); })()}
e.stopPropagation()} >
{/* 停用部门下不允许新建子部门(后端同校验),直接隐藏入口 */} {active && (
); }); DeptNode.displayName = 'DeptNode'; const nodeTypes = { dept: DeptNode }; /** dagre 自动布局:多棵树(森林)各自成块排布 */ const layoutPositions = (depts, direction) => { const g = new dagre.graphlib.Graph(); g.setGraph({ rankdir: direction, nodesep: 36, ranksep: direction === 'LR' ? 96 : 64, marginx: 24, marginy: 24, }); g.setDefaultEdgeLabel(() => ({})); const idSet = new Set(depts.map((d) => d.id)); depts.forEach((d) => { g.setNode(String(d.id), { width: NODE_WIDTH, height: NODE_HEIGHT }); }); depts.forEach((d) => { // 跳过自环(脏数据防护)与悬空父级(当作根节点) if (d.parent_id && d.parent_id !== d.id && idSet.has(d.parent_id)) { g.setEdge(String(d.parent_id), String(d.id)); } }); dagre.layout(g); const positions = {}; depts.forEach((d) => { const n = g.node(String(d.id)); positions[d.id] = { x: n.x - NODE_WIDTH / 2, y: n.y - NODE_HEIGHT / 2, }; }); return positions; }; const FlowInner = ({ orgId, depts, members, budgets, direction, onDirectionChange, colorMode, onAddChild, onEdit, onDelete, onMove, onSaved, }) => { const { t } = useTranslation(); const { fitView } = useReactFlow(); const updateNodeInternals = useUpdateNodeInternals(); // 卸载守卫:pending 的 rAF 回调在画布卸载后不再触碰 React Flow 实例。 // body 里必须复位为 true —— StrictMode 下 effect 会「跑→清理→再跑」, // 只写清理函数会让守卫在开发模式永久为 false,拦死 fitView。 const mountedRef = useRef(true); useEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; }; }, []); const deptMap = useMemo(() => { const m = {}; depts.forEach((d) => { m[d.id] = d; }); return m; }, [depts]); const childCountMap = useMemo(() => { const m = {}; depts.forEach((d) => { if (d.parent_id && d.parent_id !== d.id) m[d.parent_id] = (m[d.parent_id] || 0) + 1; }); return m; }, [depts]); // 每部门的整棵子树规模(不含自身,path 解析祖先链),收起时展示「+N」 const descendantCountMap = useMemo(() => { const m = {}; depts.forEach((d) => { if (!d.path) return; d.path .split('/') .filter(Boolean) .map(Number) .forEach((aid) => { if (aid !== d.id) m[aid] = (m[aid] || 0) + 1; }); }); return m; }, [depts]); // 直属成员:仅活跃成员(/members/all 已过滤),按主归属分桶 const membersByDept = useMemo(() => { const m = {}; (members || []).forEach((mm) => { const k = mm.department_id || 0; if (!m[k]) m[k] = []; m[k].push(mm); }); return m; }, [members]); // 部门预算行按 subject_id 索引,节点卡片展示预算用量 const budgetByDept = useMemo(() => { const m = {}; (budgets || []).forEach((b) => { if (b.subject_id) m[b.subject_id] = b; }); return m; }, [budgets]); // 子树收起:被收起节点的全部子孙不参与布局与渲染(path 前缀判断) const [collapsedIds, setCollapsedIds] = useState(() => new Set()); const toggleCollapse = useCallback((deptId) => { setCollapsedIds((prev) => { const next = new Set(prev); if (next.has(deptId)) next.delete(deptId); else next.add(deptId); return next; }); }, []); const visibleDepts = useMemo(() => { if (collapsedIds.size === 0) return depts; const collapsedPaths = depts .filter((d) => collapsedIds.has(d.id) && d.path) .map((d) => d.path); if (!collapsedPaths.length) return depts; return depts.filter( (d) => !collapsedPaths.some( (p) => d.path && d.path !== p && d.path.startsWith(p), ), ); }, [depts, collapsedIds]); // 对收起的节点添加子部门:先自动展开,否则新建的子部门会被隐藏,像创建失败 const handleAddChild = useCallback( (dept) => { setCollapsedIds((prev) => { if (!prev.has(dept.id)) return prev; const next = new Set(prev); next.delete(dept.id); return next; }); onAddChild(dept); }, [onAddChild], ); // 成员列表侧栏 const [memberSheetDept, setMemberSheetDept] = useState(null); const showMembers = useCallback((dept) => setMemberSheetDept(dept), []); const deptFullNameMap = useMemo(() => buildDeptFullNameMap(depts), [depts]); const { layoutNodes, layoutEdges } = useMemo(() => { const positions = layoutPositions(visibleDepts, direction); const idSet = new Set(visibleDepts.map((d) => d.id)); const nodes = visibleDepts.map((d) => ({ id: String(d.id), type: 'dept', position: positions[d.id], data: { dept: d, childCount: childCountMap[d.id] || 0, memberCount: (membersByDept[d.id] || []).length, collapsed: collapsedIds.has(d.id), hiddenCount: descendantCountMap[d.id] || 0, direction, orgId, budget: budgetByDept[d.id], onAddChild: handleAddChild, onEdit, onDelete, onSaved, onToggleCollapse: toggleCollapse, onShowMembers: showMembers, }, })); const edges = visibleDepts .filter( (d) => d.parent_id && d.parent_id !== d.id && idSet.has(d.parent_id), ) .map((d) => ({ id: `e-${d.parent_id}-${d.id}`, source: String(d.parent_id), target: String(d.id), type: 'smoothstep', // defaultEdgeOptions 只作用于交互新建的边,受控 edges 必须自带样式 style: { strokeWidth: 1.5 }, })); return { layoutNodes: nodes, layoutEdges: edges }; }, [ visibleDepts, direction, childCountMap, membersByDept, budgetByDept, collapsedIds, descendantCountMap, orgId, handleAddChild, onEdit, onDelete, onSaved, toggleCollapse, showMembers, ]); const [nodes, setNodes, onNodesChange] = useNodesState([]); const [edges, setEdges, onEdgesChange] = useEdgesState([]); // 自适应视野:双层 rAF 等 React Flow 完成节点量测后再 fitView(v12 尺寸量测异步); // maxZoom 限制避免节点少时过度放大。 const fitViewSoon = useCallback(() => { requestAnimationFrame(() => { requestAnimationFrame(() => { if (mountedRef.current) { fitView({ padding: 0.2, duration: 300, maxZoom: 1 }); } }); }); }, [fitView]); // 结构指纹:节点集合 + 父子关系 + 排序 + 布局方向 + 收起集合(sort 决定 dagre // 兄弟顺序;收起/展开改变可见节点集,同样触发整体重排 + fitView)。 // 只有结构变化才整体重排 + fitView;普通数据刷新(如改模型/分组限制) // 保留用户手动摆放的位置与选中态,避免视野跳动。 const collapsedKey = useMemo( () => [...collapsedIds].sort((a, b) => a - b).join('.'), [collapsedIds], ); const structureKey = useMemo( () => direction + '|' + collapsedKey + '|' + depts .map((d) => `${d.id}:${d.parent_id}:${d.sort || 0}`) .sort() .join(','), [depts, direction, collapsedKey], ); const prevStructureRef = useRef(''); useEffect(() => { const structureChanged = prevStructureRef.current !== structureKey; prevStructureRef.current = structureKey; if (structureChanged) { setNodes(layoutNodes); setEdges(layoutEdges); fitViewSoon(); } else { setNodes((prev) => { const prevMap = {}; prev.forEach((p) => { prevMap[p.id] = p; }); return layoutNodes.map((n) => prevMap[n.id] ? { ...n, position: prevMap[n.id].position, selected: prevMap[n.id].selected, } : n, ); }); setEdges(layoutEdges); } }, [structureKey, layoutNodes, layoutEdges, setNodes, setEdges, fitViewSoon]); const relayout = useCallback(() => { setNodes(layoutNodes); setEdges(layoutEdges); fitViewSoon(); }, [layoutNodes, layoutEdges, setNodes, setEdges, fitViewSoon]); // 布局方向切换会改变 Handle 挂载边(上下 ↔ 左右),必须通知 React Flow // 重新量测锚点,否则连线仍吸附在节点旧边缘(RF 官方要求)。只量测当前渲染的节点。 useEffect(() => { const ids = visibleDepts.map((d) => String(d.id)); const raf = requestAnimationFrame(() => { if (mountedRef.current) updateNodeInternals(ids); }); return () => cancelAnimationFrame(raf); }, [direction, visibleDepts, updateNodeInternals]); // 连线即移动层级:从父节点拖到子节点。禁止连向自己的祖先链(防环,后端仍有兜底)。 const isValidConnection = useCallback( (conn) => { if (!conn.source || !conn.target || conn.source === conn.target) return false; const source = deptMap[parseInt(conn.source, 10)]; const target = deptMap[parseInt(conn.target, 10)]; if (!source || !target) return false; // 已停用部门不可作为新上级(与后端 MoveDepartmentTx 校验一致,拖线时即时拦截) if (source.status !== 1) return false; if (target.path && source.path && source.path.startsWith(target.path)) return false; return true; }, [deptMap], ); const onConnect = useCallback( (conn) => { const parentId = parseInt(conn.source, 10); const childId = parseInt(conn.target, 10); const child = deptMap[childId]; if (!child || child.parent_id === parentId) return; onMove(childId, parentId); }, [deptMap, onMove], ); const sheetMembers = memberSheetDept ? membersByDept[memberSheetDept.id] || [] : []; return ( <> { const dept = deptMap[parseInt(node.id, 10)]; if (dept) onEdit(dept); }} colorMode={colorMode} fitView minZoom={0.2} maxZoom={1.5} zoomOnDoubleClick={false} deleteKeyCode={null} defaultEdgeOptions={{ type: 'smoothstep', style: { strokeWidth: 1.5 } }} connectionRadius={30} > {/* 影棚风背景由 .dept-flow-cinema 提供(辉光渐变+渐晕),不再渲染点阵 Background */} { const dept = deptMap[parseInt(n.id, 10)]; return dept && dept.status === 1 ? 'var(--ui-color-primary-light-active)' : 'var(--ui-color-fill-2)'; }} maskColor={ colorMode === 'dark' ? 'rgba(3, 7, 18, 0.55)' : 'rgba(226, 232, 240, 0.55)' } style={{ backgroundColor: colorMode === 'dark' ? 'rgba(13, 19, 41, 0.5)' : 'rgba(255, 255, 255, 0.5)', }} />
onDirectionChange(e.target.value)} > {t('纵向')} {t('横向')}
{t( '拖动节点可自由摆放;从节点边缘拖出连线到另一部门可调整上级;双击节点编辑', )} {/* 直属成员列表(仅活跃成员;主归属=该部门) */} setMemberSheetDept(null)} width={380} > {memberSheetDept && (
{deptFullNameMap[memberSheetDept.id] || memberSheetDept.name} {sheetMembers.length === 0 ? (
{t('该部门暂无直属成员')}
) : (
{sheetMembers.map((m) => { const name = formatUserReference( m.display_name || m.username, m.user_id, t('未知用户'), ); return (
{name.slice(0, 1).toUpperCase()}
{name}
{m.username && m.username !== name && ( {m.username} )}
); })}
)}
)}
); }; /** * 部门组织架构画布(React Flow + dagre 自动布局,影棚风视觉)。 * - 多棵树:顶级部门(parent_id=0)各自成树 * - 子树可收起/展开(收起后子孙不参与布局,重排并 fitView) * - 节点展示直属成员数,点击打开成员列表侧栏(members 由外部传入) * - 节点展示部门预算用量条(budgets 由外部传入;无预算行/双 0 不限时不展示) * - 深浅色跟随全局主题(colorMode 由外部传入) * - 节点卡片内含操作区:模型/分组限制、加子部门、编辑、删除 */ const DeptFlowCanvas = (props) => ( ); export default DeptFlowCanvas;