Initial import of weiyuan frontend
This commit is contained in:
@@ -0,0 +1,823 @@
|
||||
/*
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
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 '@douyinfe/semi-ui';
|
||||
import {
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
LayoutGrid,
|
||||
Network,
|
||||
Building2,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Users,
|
||||
} 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 (
|
||||
<div
|
||||
className={`relative rounded-xl border bg-white/75 backdrop-blur-xl transition-all duration-150 dark:bg-[#0e1430]/65 ${
|
||||
selected
|
||||
? 'border-[var(--semi-color-primary)] shadow-lg ring-2 ring-[var(--semi-color-primary-light-default)]'
|
||||
: 'border-white/60 shadow-[0_10px_30px_-14px_rgba(15,23,42,0.35)] hover:border-[var(--semi-color-primary-light-active)] hover:shadow-lg dark:border-white/10'
|
||||
} ${active ? '' : 'opacity-70'}`}
|
||||
style={{ width: NODE_WIDTH }}
|
||||
>
|
||||
{/* 根节点渐变顶条:一眼区分树的入口 */}
|
||||
{isRoot && (
|
||||
<div className='absolute inset-x-0 top-0 h-[3px] rounded-t-xl bg-gradient-to-r from-[var(--semi-color-primary)] to-[var(--semi-color-primary-light-active)]' />
|
||||
)}
|
||||
<Handle
|
||||
type='target'
|
||||
position={targetPos}
|
||||
className='!w-2.5 !h-2.5 !bg-[var(--semi-color-primary)] !border-2 !border-[var(--surface-card)]'
|
||||
/>
|
||||
<div className='px-3.5 pt-3'>
|
||||
<div className='flex items-center justify-between gap-2'>
|
||||
<div className='flex items-center gap-2 min-w-0'>
|
||||
<span className='inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md bg-brand/10 text-brand'>
|
||||
<DeptIcon size={13} />
|
||||
</span>
|
||||
<span
|
||||
className='text-sm font-semibold text-[var(--text-primary)] truncate'
|
||||
title={dept.name}
|
||||
>
|
||||
{dept.name}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-1 flex-shrink-0'>
|
||||
{childCount > 0 && (
|
||||
<Tooltip
|
||||
content={
|
||||
collapsed
|
||||
? `${t('展开')}(${t('已收起')} ${hiddenCount} ${t('个下级')})`
|
||||
: t('收起下级部门')
|
||||
}
|
||||
>
|
||||
<button
|
||||
type='button'
|
||||
className='nodrag inline-flex h-5 items-center gap-0.5 rounded-md px-1 text-xs text-gray-500 transition-colors hover:bg-brand/10 hover:text-brand dark:text-gray-400'
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onToggleCollapse(dept.id);
|
||||
}}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{collapsed ? (
|
||||
<>
|
||||
<ChevronRight size={13} />
|
||||
<span className='font-medium'>+{hiddenCount}</span>
|
||||
</>
|
||||
) : (
|
||||
<ChevronDown size={13} />
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tag size='small' color={active ? 'green' : 'grey'}>
|
||||
{active ? t('启用') : t('停用')}
|
||||
</Tag>
|
||||
</div>
|
||||
</div>
|
||||
<div className='mt-1.5 flex items-center gap-2 flex-wrap'>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('子部门')} {childCount} · {t('排序')} {dept.sort || 0}
|
||||
</Text>
|
||||
<Tooltip content={t('查看直属成员')}>
|
||||
<button
|
||||
type='button'
|
||||
className='nodrag inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs text-gray-500 transition-colors hover:bg-brand/10 hover:text-brand dark:text-gray-400'
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onShowMembers(dept);
|
||||
}}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Users size={11} />
|
||||
{memberCount}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{modelCount > 0 && (
|
||||
<Tag size='small' color='blue'>
|
||||
{t('模型限制')} {modelCount}
|
||||
</Tag>
|
||||
)}
|
||||
{groupCount > 0 && (
|
||||
<Tag size='small' color='purple'>
|
||||
{t('限定分组')} {groupCount}
|
||||
</Tag>
|
||||
)}
|
||||
</div>
|
||||
{budgetInfo &&
|
||||
(() => {
|
||||
const pct = Math.min(
|
||||
100,
|
||||
Math.round((budgetInfo.used / budgetInfo.cap) * 100),
|
||||
);
|
||||
const danger = pct >= 90;
|
||||
return (
|
||||
<div className='mt-2 rounded-md bg-[var(--semi-color-fill-0)] px-2 py-1'>
|
||||
<div className='flex items-center justify-between gap-2 text-[11px] leading-4'>
|
||||
<span className='text-gray-500 dark:text-gray-400 flex-shrink-0'>
|
||||
{t('预算')} · {budgetInfo.label}
|
||||
</span>
|
||||
<span
|
||||
className={
|
||||
danger
|
||||
? 'font-medium text-[var(--semi-color-danger)] truncate'
|
||||
: 'text-gray-600 dark:text-gray-300 truncate'
|
||||
}
|
||||
title={`${renderQuota(budgetInfo.used, 2)} / ${renderQuota(budgetInfo.cap, 2)}`}
|
||||
>
|
||||
{renderQuota(budgetInfo.used, 2)} /{' '}
|
||||
{renderQuota(budgetInfo.cap, 2)}
|
||||
</span>
|
||||
</div>
|
||||
<div className='mt-1 h-1 overflow-hidden rounded-full bg-black/10 dark:bg-white/10'>
|
||||
<div
|
||||
className='h-full rounded-full transition-all'
|
||||
style={{
|
||||
width: `${pct}%`,
|
||||
background: danger
|
||||
? 'var(--semi-color-danger)'
|
||||
: 'var(--semi-color-primary)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
<div
|
||||
className='nodrag mt-2.5 flex items-center gap-1 border-t border-black/5 px-2 py-1.5 dark:border-white/10'
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<OrgScopedLimitButtons
|
||||
orgId={orgId}
|
||||
record={dept}
|
||||
apiBase='/api/org/dept'
|
||||
scopeLabel='部门'
|
||||
onSaved={onSaved}
|
||||
/>
|
||||
<div className='flex-1' />
|
||||
{/* 停用部门下不允许新建子部门(后端同校验),直接隐藏入口 */}
|
||||
{active && (
|
||||
<Tooltip content={t('添加子部门')}>
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
type='tertiary'
|
||||
icon={<Plus size={14} />}
|
||||
onClick={() => onAddChild(dept)}
|
||||
/>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip content={t('编辑')}>
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
type='tertiary'
|
||||
icon={<Pencil size={14} />}
|
||||
onClick={() => onEdit(dept)}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Popconfirm
|
||||
title={t('确认删除该部门?')}
|
||||
content={t('仅可删除无子部门、无成员的空部门')}
|
||||
onConfirm={() => onDelete(dept)}
|
||||
>
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
type='danger'
|
||||
icon={<Trash2 size={14} />}
|
||||
/>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
<Handle
|
||||
type='source'
|
||||
position={sourcePos}
|
||||
className='!w-2.5 !h-2.5 !bg-[var(--semi-color-primary)] !border-2 !border-[var(--surface-card)]'
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
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 (
|
||||
<>
|
||||
<ReactFlow
|
||||
className='dept-flow-cinema'
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
onConnect={onConnect}
|
||||
isValidConnection={isValidConnection}
|
||||
onNodeDoubleClick={(_, node) => {
|
||||
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 */}
|
||||
<Controls showInteractive={false} position='bottom-right' />
|
||||
<MiniMap
|
||||
pannable
|
||||
zoomable
|
||||
position='top-right'
|
||||
className='!rounded-lg !border !border-white/50 !overflow-hidden dark:!border-white/10'
|
||||
nodeColor={(n) => {
|
||||
const dept = deptMap[parseInt(n.id, 10)];
|
||||
return dept && dept.status === 1
|
||||
? 'var(--semi-color-primary-light-active)'
|
||||
: 'var(--semi-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)',
|
||||
}}
|
||||
/>
|
||||
<Panel position='top-left'>
|
||||
<div className='flex items-center gap-2 rounded-lg border border-white/50 bg-white/60 px-2 py-1.5 shadow-[0_8px_24px_-12px_rgba(15,23,42,0.35)] backdrop-blur-md dark:border-white/10 dark:bg-[#0d1329]/60'>
|
||||
<RadioGroup
|
||||
type='button'
|
||||
buttonSize='small'
|
||||
value={direction}
|
||||
onChange={(e) => onDirectionChange(e.target.value)}
|
||||
>
|
||||
<Radio value='TB'>{t('纵向')}</Radio>
|
||||
<Radio value='LR'>{t('横向')}</Radio>
|
||||
</RadioGroup>
|
||||
<div className='h-4 w-px bg-black/10 dark:bg-white/15' />
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
icon={<LayoutGrid size={13} />}
|
||||
onClick={relayout}
|
||||
>
|
||||
{t('整理布局')}
|
||||
</Button>
|
||||
</div>
|
||||
</Panel>
|
||||
<Panel position='bottom-center'>
|
||||
<Text
|
||||
type='tertiary'
|
||||
size='small'
|
||||
className='rounded-md border border-white/40 bg-white/55 px-2 py-1 backdrop-blur-md dark:border-white/10 dark:bg-[#0d1329]/55'
|
||||
>
|
||||
{t(
|
||||
'拖动节点可自由摆放;从节点边缘拖出连线到另一部门可调整上级;双击节点编辑',
|
||||
)}
|
||||
</Text>
|
||||
</Panel>
|
||||
</ReactFlow>
|
||||
|
||||
{/* 直属成员列表(仅活跃成员;主归属=该部门) */}
|
||||
<SideSheet
|
||||
title={
|
||||
memberSheetDept
|
||||
? `${memberSheetDept.name} · ${t('成员')} ${sheetMembers.length}`
|
||||
: ''
|
||||
}
|
||||
visible={!!memberSheetDept}
|
||||
onCancel={() => setMemberSheetDept(null)}
|
||||
width={380}
|
||||
>
|
||||
{memberSheetDept && (
|
||||
<div className='space-y-3'>
|
||||
<Text type='tertiary' size='small'>
|
||||
{deptFullNameMap[memberSheetDept.id] || memberSheetDept.name}
|
||||
</Text>
|
||||
{sheetMembers.length === 0 ? (
|
||||
<div className='py-10 text-center text-sm text-gray-400'>
|
||||
{t('该部门暂无直属成员')}
|
||||
</div>
|
||||
) : (
|
||||
<div className='space-y-1'>
|
||||
{sheetMembers.map((m) => {
|
||||
const name = m.display_name || m.username || `#${m.user_id}`;
|
||||
return (
|
||||
<div
|
||||
key={m.user_id}
|
||||
className='flex items-center gap-3 rounded-lg px-2 py-1.5 hover:bg-[var(--semi-color-fill-0)]'
|
||||
>
|
||||
<Avatar size='extra-small' color='blue'>
|
||||
{name.slice(0, 1).toUpperCase()}
|
||||
</Avatar>
|
||||
<div className='min-w-0'>
|
||||
<div className='truncate text-sm text-[var(--text-primary,inherit)]'>
|
||||
{name}
|
||||
</div>
|
||||
{m.username && m.username !== name && (
|
||||
<Text
|
||||
type='tertiary'
|
||||
size='small'
|
||||
className='block truncate'
|
||||
>
|
||||
{m.username}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</SideSheet>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 部门组织架构画布(React Flow + dagre 自动布局,影棚风视觉)。
|
||||
* - 多棵树:顶级部门(parent_id=0)各自成树
|
||||
* - 子树可收起/展开(收起后子孙不参与布局,重排并 fitView)
|
||||
* - 节点展示直属成员数,点击打开成员列表侧栏(members 由外部传入)
|
||||
* - 节点展示部门预算用量条(budgets 由外部传入;无预算行/双 0 不限时不展示)
|
||||
* - 深浅色跟随全局主题(colorMode 由外部传入)
|
||||
* - 节点卡片内含操作区:模型/分组限制、加子部门、编辑、删除
|
||||
*/
|
||||
const DeptFlowCanvas = (props) => (
|
||||
<ReactFlowProvider>
|
||||
<FlowInner {...props} />
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
|
||||
export default DeptFlowCanvas;
|
||||
Reference in New Issue
Block a user