Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,141 @@
/*
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
*/
/* 部门画布「影棚」皮肤:去点阵,改用品牌色辉光 + 渐晕背景;
卡片/工具条/控件/小地图统一磨玻璃。深浅色跟随 React Flow
colorMode(容器上的 .dark/.light 类,与全局主题一致)。 */
.dept-flow-cinema {
--dfc-glow: color-mix(in srgb, var(--semi-color-primary) 16%, transparent);
--dfc-glow-soft: color-mix(
in srgb,
var(--semi-color-primary) 9%,
transparent
);
/* 不支持 color-mix 的旧内核退化为纯渐变底 */
background: linear-gradient(180deg, #f7f9fd 0%, #edf1f8 100%);
background: radial-gradient(
1100px 520px at 50% -8%,
var(--dfc-glow),
transparent 62%
),
radial-gradient(
900px 480px at 88% 110%,
var(--dfc-glow-soft),
transparent 60%
),
linear-gradient(180deg, #f7f9fd 0%, #edf1f8 100%);
}
.dept-flow-cinema.dark {
background: linear-gradient(180deg, #0b1020 0%, #0d1329 55%, #090e1c 100%);
background: radial-gradient(
1100px 520px at 50% -8%,
color-mix(in srgb, var(--semi-color-primary) 24%, transparent),
transparent 62%
),
radial-gradient(
900px 480px at 88% 110%,
rgba(56, 189, 248, 0.1),
transparent 60%
),
linear-gradient(180deg, #0b1020 0%, #0d1329 55%, #090e1c 100%);
}
/* 四周渐晕(vignette):盖在节点上、面板下,视觉聚焦画布中心 */
.dept-flow-cinema::after {
content: '';
position: absolute;
inset: 0;
z-index: 4;
pointer-events: none;
background: radial-gradient(
120% 90% at 50% 45%,
transparent 60%,
rgba(15, 23, 42, 0.07) 100%
);
}
.dept-flow-cinema.dark::after {
background: radial-gradient(
120% 90% at 50% 45%,
transparent 55%,
rgba(0, 0, 0, 0.45) 100%
);
}
/* 连线:品牌色 + 轻辉光 */
.dept-flow-cinema .react-flow__edge-path {
stroke: color-mix(
in srgb,
var(--semi-color-primary) 55%,
rgba(148, 163, 184, 0.45)
);
filter: drop-shadow(0 0 3px var(--dfc-glow));
}
.dept-flow-cinema .react-flow__edge.selected .react-flow__edge-path {
stroke: var(--semi-color-primary);
}
.dept-flow-cinema .react-flow__connection-path {
stroke: var(--semi-color-primary);
}
/* 缩放控件:磨玻璃 */
.dept-flow-cinema .react-flow__controls {
overflow: hidden;
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.55);
background: rgba(255, 255, 255, 0.6);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
box-shadow: 0 8px 24px -12px rgba(15, 23, 42, 0.35);
}
.dept-flow-cinema .react-flow__controls-button {
border-bottom: 1px solid rgba(148, 163, 184, 0.25);
background: transparent;
}
.dept-flow-cinema .react-flow__controls-button:hover {
background: rgba(148, 163, 184, 0.15);
}
.dept-flow-cinema.dark .react-flow__controls {
border-color: rgba(255, 255, 255, 0.12);
background: rgba(13, 19, 41, 0.55);
box-shadow: 0 8px 24px -12px rgba(0, 0, 0, 0.6);
}
.dept-flow-cinema.dark .react-flow__controls-button {
border-bottom-color: rgba(255, 255, 255, 0.08);
}
.dept-flow-cinema.dark .react-flow__controls-button svg {
fill: #cbd5e1;
}
/* 小地图:磨玻璃 */
.dept-flow-cinema .react-flow__minimap {
border-radius: 10px;
overflow: hidden;
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
@@ -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;
@@ -0,0 +1,62 @@
/*
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, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { TreeSelect } from '@douyinfe/semi-ui';
import { buildDeptTreeData } from './deptTree';
// 部门树选择(受控):按组织架构展示层级,默认只允许选末级部门(成员主归属
// 挂末级,报表沿 path 上卷);停用部门置灰。清空 = 不分配(onChange 回 0)。
const DeptTreeSelect = ({
depts,
value,
onChange,
disableNonLeaf = true,
excludeSubtreeOf = null,
placeholder,
style,
...rest
}) => {
const { t } = useTranslation();
const treeData = useMemo(
() =>
buildDeptTreeData(depts, {
disableNonLeaf,
excludeSubtreeOf,
disabledLabel: t('已停用'),
}),
[depts, disableNonLeaf, excludeSubtreeOf, t],
);
return (
<TreeSelect
treeData={treeData}
value={value || undefined}
onChange={(v) => onChange?.(v || 0)}
showClear
filterTreeNode
showFilteredOnly
expandAll
placeholder={placeholder || t('未分配(清空即不归属任何部门)')}
style={{ width: '100%', ...style }}
{...rest}
/>
);
};
export default DeptTreeSelect;
@@ -0,0 +1,646 @@
/*
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, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Table,
Button,
Select,
Empty,
Spin,
Progress,
Typography,
} from '@douyinfe/semi-ui';
import OrgPanel from './OrgPanel';
import { VChart } from '@visactor/react-vchart';
import { initVChartSemiTheme } from '@visactor/vchart-semi-theme';
import {
RefreshCw,
PieChart,
TrendingUp,
BarChart3,
Crown,
} from 'lucide-react';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import { renderQuota } from '../../../helpers/render';
import { useActualTheme } from '../../../context/Theme';
const { Text } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
/* 系列色运行时读取品牌 token(--brand-*),随主题预设整套切换。
* 不再硬编码(旧值 #14b8a6 在 azure 等预设下与全站主色打架)。 */
const readBrandColors = () => {
if (typeof window === 'undefined') {
return { brand: '#1668dc', brand2: '#13c2c2' };
}
const style = getComputedStyle(document.documentElement);
return {
brand: style.getPropertyValue('--brand-primary').trim() || '#1668dc',
brand2: style.getPropertyValue('--accent-teal').trim() || '#13c2c2',
};
};
const getChartTokens = (isDark) => ({
axisLabel: isDark ? '#94a3b8' : '#64748b',
axisLine: isDark ? 'rgba(148, 163, 184, 0.28)' : '#e5e7eb',
grid: isDark ? 'rgba(148, 163, 184, 0.14)' : '#edf2f7',
tooltipBg: isDark ? 'rgba(15, 23, 42, 0.96)' : 'rgba(255, 255, 255, 0.98)',
tooltipBorder: isDark ? 'rgba(148, 163, 184, 0.22)' : '#e5e7eb',
tooltipText: isDark ? '#e2e8f0' : '#0f172a',
tooltipMuted: isDark ? '#94a3b8' : '#64748b',
});
const chartTooltipStyle = (tokens) => ({
panel: {
backgroundColor: tokens.tooltipBg,
borderColor: tokens.tooltipBorder,
shadowBlur: 18,
shadowColor: 'rgba(15, 23, 42, 0.25)',
},
titleLabel: { fontColor: tokens.tooltipText },
keyLabel: { fontColor: tokens.tooltipMuted },
valueLabel: { fontColor: tokens.tooltipText },
});
const chartAxisLine = (tokens) => ({
visible: true,
style: { stroke: tokens.axisLine },
});
const chartTick = (tokens) => ({
visible: true,
style: { stroke: tokens.axisLine },
});
const chartGrid = (tokens) => ({
visible: true,
style: { stroke: tokens.grid, lineDash: [4, 4] },
});
// 环比徽标:本期 vs 上期。增长绿、下降红;无上期数据时灰显。
// 状态色统一走 Semi 语义 token(与页面各处使用进度条同一套红绿,且随明暗主题自适应)。
const DeltaBadge = ({ cur, prev, t }) => {
if (!prev || prev <= 0) {
return <span className='text-xs text-gray-400'>{t('无上期对比')}</span>;
}
const pct = ((cur - prev) / prev) * 100;
const up = pct >= 0;
return (
<span
className='text-xs font-medium'
style={{
color: up ? 'var(--semi-color-success)' : 'var(--semi-color-danger)',
}}
>
{up ? '▲' : '▼'} {Math.abs(pct).toFixed(1)}%
<span className='text-gray-400 ml-1'>{t('较上期')}</span>
</span>
);
};
const KpiCard = ({ label, value, sub }) => (
<div className='px-4 py-3 rounded-xl bg-[var(--semi-color-fill-0)]'>
<div className='text-xs text-gray-500 mb-1'>{label}</div>
<div className='text-lg font-semibold text-gray-900 dark:text-white truncate'>
{value}
</div>
{sub ? <div className='mt-0.5'>{sub}</div> : null}
</div>
);
// 把 time 维度的小时行聚合成趋势序列:>7 天按天汇总,否则按小时。
const buildTrend = (rows, rangeDays, field) => {
if (!rows || rows.length === 0) return [];
if (rangeDays > 7) {
const map = new Map();
rows.forEach((r) => {
const day = (r.name || '').slice(0, 10);
if (!day) return;
map.set(day, (map.get(day) || 0) + (r[field] || 0));
});
return Array.from(map, ([date, value]) => ({ date, value })).sort((a, b) =>
a.date < b.date ? -1 : 1,
);
}
return rows
.map((r) => ({ date: r.name || String(r.key), value: r[field] || 0 }))
.sort((a, b) => (a.date < b.date ? -1 : 1));
};
const sumField = (rows, field) =>
(rows || []).reduce((s, r) => s + (r[field] || 0), 0);
const localizeAnalyticsRows = (rows, dimension, t) =>
(rows || []).map((row) => {
let name = row.name;
if (row.key === '0') {
const zeroName = {
department: t('未分配部门'),
project: t('未绑定项目'),
member: t('未归属成员'),
token: t('未绑定令牌'),
}[dimension];
if (zeroName) name = zeroName;
} else if (dimension === 'member' && name === `成员#${row.key}`) {
name = `${t('成员')}#${row.key}`;
} else if (dimension === 'token' && name === `令牌#${row.key}`) {
name = `${t('令牌')}#${row.key}`;
}
return name === row.name ? row : { ...row, name };
});
// 多维用量分析面板(§5.6):经营看板视角——KPI+环比、消耗趋势折线、维度分布柱状、明细表。
// 仅 admin + analytics 特性开启时挂载(前端门控),后端接口仍 admin+feature 鉴权。
const OrgAnalyticsPanel = ({ orgId }) => {
const { t } = useTranslation();
const actualTheme = useActualTheme();
const isDarkMode = actualTheme === 'dark';
const chartTokens = useMemo(() => getChartTokens(isDarkMode), [isDarkMode]);
// 系列色跟随品牌 token:明暗切换(isDarkMode)与预设注入(theme-tokens-applied 事件)都会刷新
const [brandColors, setBrandColors] = useState(readBrandColors);
useEffect(() => {
const refresh = () => setBrandColors(readBrandColors());
refresh();
window.addEventListener('theme-tokens-applied', refresh);
return () => window.removeEventListener('theme-tokens-applied', refresh);
}, [isDarkMode]);
const [dimension, setDimension] = useState('model');
const [rangeDays, setRangeDays] = useState(7);
const [trendMetric, setTrendMetric] = useState('quota');
const [breakdownRows, setBreakdownRows] = useState([]);
const [trendRows, setTrendRows] = useState([]);
const [prevRows, setPrevRows] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
initVChartSemiTheme({ isWatchingThemeSwitch: true });
}, []);
const dimensions = useMemo(
() => [
{ label: t('模型'), value: 'model' },
{ label: t('项目'), value: 'project' },
{ label: t('部门'), value: 'department' },
{ label: t('成员'), value: 'member' },
{ label: t('令牌'), value: 'token' },
{ label: t('时间'), value: 'time' },
],
[t],
);
const dimLabel =
dimensions.find((d) => d.value === dimension)?.label || t('维度');
const fetchAll = useCallback(
async (fresh = false) => {
if (!orgId) return;
setLoading(true);
try {
// 按分钟归一化时间窗,保证 30s 缓存可命中,同时只遗漏当前未完成分钟。
const end = Math.floor(Date.now() / 60000) * 60;
const span = rangeDays * 86400;
const start = end - span;
const prevStart = start - span;
// 仅「刷新」按钮 fresh=true 时带 nocache 拿最新;维度/时间切换走 30s 缓存。
const nc = fresh ? '&nocache=1' : '';
const get = (dim, s, e) =>
API.get(
`/api/org/analytics?dimension=${dim}&start=${s}&end=${e}${nc}`,
{
headers: getOrgHeaders(orgId),
},
).then((r) => {
// 后端以 HTTP 200 返回 success:false(如特性关闭/越权)时,抛错让 catch 提示,
// 而非静默展示空图表,避免误以为「无数据」。
if (r.data && r.data.success === false) {
throw new Error(r.data.message || t('加载用量分析失败'));
}
return r.data?.data?.rows || [];
});
const reqs = [get('time', start, end), get('time', prevStart, start)];
if (dimension !== 'time') reqs.push(get(dimension, start, end));
const [timeRows, prevTimeRows, breakdown] = await Promise.all(reqs);
const localizedTimeRows = localizeAnalyticsRows(timeRows, 'time', t);
setTrendRows(localizedTimeRows);
setPrevRows(localizeAnalyticsRows(prevTimeRows, 'time', t));
setBreakdownRows(
dimension === 'time'
? localizedTimeRows
: localizeAnalyticsRows(breakdown || [], dimension, t),
);
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId, dimension, rangeDays, t],
);
useEffect(() => {
fetchAll(false);
}, [fetchAll]);
// KPI:本期/上期总量 + 环比;日均;Top1 消耗对象
const curQuota = useMemo(() => sumField(trendRows, 'quota'), [trendRows]);
const curReq = useMemo(
() => sumField(trendRows, 'request_count'),
[trendRows],
);
const prevQuota = useMemo(() => sumField(prevRows, 'quota'), [prevRows]);
const prevReq = useMemo(
() => sumField(prevRows, 'request_count'),
[prevRows],
);
const topRow = useMemo(() => {
if (dimension === 'time') return null;
return (
[...breakdownRows].sort((a, b) => (b.quota || 0) - (a.quota || 0))[0] ||
null
);
}, [breakdownRows, dimension]);
// 趋势折线 spec
const trendData = useMemo(
() =>
buildTrend(
trendRows,
rangeDays,
trendMetric === 'requests' ? 'request_count' : 'quota',
),
[trendRows, rangeDays, trendMetric],
);
const isMoney = trendMetric === 'quota';
const trendSpec = useMemo(() => {
if (!trendData.length) return null;
return {
type: 'area',
background: 'transparent',
data: [{ id: 'trend', values: trendData }],
xField: 'date',
yField: 'value',
point: { visible: trendData.length <= 60, size: 3 },
line: { style: { lineWidth: 2, stroke: brandColors.brand } },
area: {
style: {
fill: {
gradient: 'linear',
x0: 0,
y0: 0,
x1: 0,
y1: 1,
stops: [
{ offset: 0, color: brandColors.brand, opacity: 0.35 },
{ offset: 1, color: brandColors.brand, opacity: 0.02 },
],
},
},
},
tooltip: {
visible: true,
style: chartTooltipStyle(chartTokens),
dimension: {
visible: true,
content: [
{
key: () => (isMoney ? t('消耗') : t('请求数')),
value: (datum) =>
isMoney
? renderQuota(datum?.value || 0, 2)
: `${(datum?.value || 0).toLocaleString()} ${t('次')}`,
},
],
},
},
crosshair: {
xField: {
visible: true,
line: { visible: true, style: { stroke: chartTokens.axisLine } },
},
},
axes: [
{
orient: 'bottom',
label: { style: { angle: -45, fill: chartTokens.axisLabel } },
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
},
{
orient: 'left',
grid: chartGrid(chartTokens),
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
label: {
style: { fill: chartTokens.axisLabel },
formatMethod: (v) => (isMoney ? renderQuota(v, 0) : Math.round(v)),
},
},
],
};
}, [trendData, isMoney, t, chartTokens, brandColors]);
// 维度分布柱状 spec(Top 10,横向)
const barData = useMemo(() => {
if (dimension === 'time') return [];
return [...breakdownRows]
.sort((a, b) => (b.quota || 0) - (a.quota || 0))
.slice(0, 10)
.map((r) => ({ name: r.name || '-', value: r.quota || 0 }));
}, [breakdownRows, dimension]);
const barSpec = useMemo(() => {
if (!barData.length) return null;
return {
type: 'bar',
background: 'transparent',
data: [{ id: 'bar', values: barData }],
direction: 'horizontal',
xField: 'value',
yField: 'name',
color: [brandColors.brand2],
barMaxWidth: 22,
label: {
visible: true,
position: 'right',
style: { fill: chartTokens.axisLabel },
formatMethod: (text, datum) =>
renderQuota(
datum && datum.value != null ? datum.value : Number(text) || 0,
2,
),
},
tooltip: {
visible: true,
style: chartTooltipStyle(chartTokens),
mark: {
content: [
{
key: (datum) => datum?.name,
value: (datum) => renderQuota(datum?.value || 0, 2),
},
],
},
},
axes: [
{
orient: 'left',
label: { style: { fill: chartTokens.axisLabel } },
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
},
{
orient: 'bottom',
grid: chartGrid(chartTokens),
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
label: {
style: { fill: chartTokens.axisLabel },
formatMethod: (v) => renderQuota(v, 0),
},
},
],
};
}, [barData, chartTokens, brandColors]);
// 明细表:占比分母用「当前维度行的合计」而非时间维度总量,
// 保证表内各行占比之和恒为 100%(两者数学上应相等,但用自身合计更稳健)。
const breakdownTotal = useMemo(
() => sumField(breakdownRows, 'quota'),
[breakdownRows],
);
const columns = useMemo(
() => [
{ title: dimLabel, dataIndex: 'name', width: 200 },
{
title: t('消耗占比'),
render: (_, r) => {
const pct =
breakdownTotal > 0 ? ((r.quota || 0) / breakdownTotal) * 100 : 0;
return (
<div className='flex items-center gap-2'>
<Progress
percent={Math.round(pct)}
style={{ flex: 1 }}
stroke={brandColors.brand2}
showInfo={false}
/>
<span className='text-xs text-gray-500 whitespace-nowrap'>
{renderQuota(r.quota || 0, 2)} ({pct.toFixed(1)}%)
</span>
</div>
);
},
},
{ title: t('请求数'), dataIndex: 'request_count', width: 100 },
{
title: t('Token (入/出)'),
width: 160,
render: (_, r) =>
`${r.prompt_tokens || 0} / ${r.completion_tokens || 0}`,
},
],
[dimLabel, breakdownTotal, t, brandColors],
);
const rangeOptions = [
{ label: t('近 7 天'), value: 7 },
{ label: t('近 30 天'), value: 30 },
{ label: t('近 90 天'), value: 90 },
];
return (
<div className='space-y-4'>
{/* 控制区 */}
<OrgPanel>
<div className='flex flex-wrap items-center justify-between gap-3'>
<div className='flex items-center gap-2'>
<PieChart size={18} className='text-brand-deep' />
<Text strong>{t('企业用量分析')}</Text>
<Text type='tertiary' size='small'>
{t('趋势 · 结构 · 与消耗明细一致')}
</Text>
</div>
<div className='flex items-center gap-2'>
<Select
value={dimension}
onChange={setDimension}
optionList={dimensions}
style={{ width: 110 }}
/>
<Select
value={rangeDays}
onChange={setRangeDays}
optionList={rangeOptions}
style={{ width: 110 }}
/>
<Button
theme='light'
icon={<RefreshCw size={14} />}
loading={loading}
onClick={() => fetchAll(true)}
>
{t('刷新')}
</Button>
</div>
</div>
{/* KPI + 环比 */}
<div className='grid grid-cols-2 lg:grid-cols-4 gap-4 mt-4'>
<KpiCard
label={t('本期总消耗')}
value={renderQuota(curQuota, 2)}
sub={<DeltaBadge cur={curQuota} prev={prevQuota} t={t} />}
/>
<KpiCard
label={t('本期总请求')}
value={curReq.toLocaleString()}
sub={<DeltaBadge cur={curReq} prev={prevReq} t={t} />}
/>
<KpiCard
label={t('日均消耗')}
value={renderQuota(rangeDays > 0 ? curQuota / rangeDays : 0, 2)}
sub={
<span className='text-xs text-gray-400'>
{t('近 {{n}} 天均值', { n: rangeDays })}
</span>
}
/>
<KpiCard
label={t('消耗最高')}
value={topRow ? topRow.name : '-'}
sub={
topRow ? (
<span className='text-xs text-amber-500 inline-flex items-center gap-1'>
<Crown size={11} /> {renderQuota(topRow.quota || 0, 2)}
</span>
) : (
<span className='text-xs text-gray-400'>
{dimension === 'time' ? t('按时间维度无排名') : '-'}
</span>
)
}
/>
</div>
</OrgPanel>
{/* 消耗趋势折线 */}
<OrgPanel>
<div className='flex items-center justify-between mb-3'>
<div className='flex items-center gap-2'>
<TrendingUp size={16} className='text-brand-deep' />
<Text strong>{t('用量趋势')}</Text>
</div>
<Select
value={trendMetric}
onChange={setTrendMetric}
optionList={[
{ label: t('消耗'), value: 'quota' },
{ label: t('请求数'), value: 'requests' },
]}
style={{ width: 100 }}
size='small'
/>
</div>
{loading ? (
<div className='flex justify-center py-12'>
<Spin size='large' />
</div>
) : trendSpec ? (
<div className='rounded-2xl border border-gray-100/70 dark:border-white/5 bg-white/60 dark:bg-slate-950/25 p-2'>
<VChart
key={`trend-${actualTheme}`}
spec={trendSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 280 }}
/>
</div>
) : (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
)}
</OrgPanel>
{/* 维度分布柱状(time 维度不展示,趋势图已覆盖) */}
{dimension !== 'time' && (
<OrgPanel>
<div className='flex items-center gap-2 mb-3'>
<BarChart3 size={16} className='text-brand-deep' />
<Text strong>{t('{{dim}}消耗分布', { dim: dimLabel })}</Text>
<Text type='tertiary' size='small'>
{t('Top 10')}
</Text>
</div>
{loading ? (
<div className='flex justify-center py-12'>
<Spin size='large' />
</div>
) : barSpec ? (
<div className='rounded-2xl border border-gray-100/70 dark:border-white/5 bg-white/60 dark:bg-slate-950/25 p-2'>
<VChart
key={`bar-${actualTheme}`}
spec={barSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: Math.max(220, barData.length * 34 + 60) }}
/>
</div>
) : (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
)}
</OrgPanel>
)}
{/* 明细表 */}
<OrgPanel>
<div className='flex items-center gap-2 mb-3'>
<Text strong>{t('{{dim}}明细', { dim: dimLabel })}</Text>
</div>
{loading ? (
<div className='flex justify-center py-12'>
<Spin size='large' />
</div>
) : breakdownRows.length === 0 ? (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
) : (
<Table
columns={columns}
dataSource={breakdownRows}
rowKey='key'
pagination={
breakdownRows.length > 20
? { pageSize: 20, showSizeChanger: false }
: false
}
/>
)}
</OrgPanel>
</div>
);
};
export default OrgAnalyticsPanel;
@@ -0,0 +1,221 @@
/*
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 from 'react';
import { Button, Input, Radio, RadioGroup } from '@douyinfe/semi-ui';
import { Check, Image as ImageIcon, Palette, Type, UserRound } from 'lucide-react';
import OrgPanel from './OrgPanel';
import {
CARTOON_AVATAR_PRESETS,
USER_AVATAR_TYPES,
getCartoonAvatarDataUrl,
getInitialAvatarDataUrl,
} from '../../../helpers';
const AVATAR_TYPE_OPTIONS = [
{
value: USER_AVATAR_TYPES.PRESET,
label: '卡通形象',
desc: '从系统内置卡通头像中选择,适合默认展示',
icon: Palette,
},
{
value: USER_AVATAR_TYPES.INITIAL,
label: '姓名首字',
desc: '根据用户名自动生成简洁文字头像',
icon: Type,
},
{
value: USER_AVATAR_TYPES.CUSTOM,
label: '图片链接',
desc: '填写公网图片 URL,使用自己的头像',
icon: ImageIcon,
},
];
/*
* 企业中心头像设置区块。
* 与个人中心的 AvatarSection 分开:企业空间是实底卡片 + 品牌色体系(OrgPanel),
* 而非个人中心的毛玻璃 + 玫红渐变,避免颜色与整站主体色冲突。
*/
const OrgAvatarSection = ({
t,
userState,
avatarSettings,
handleAvatarSettingChange,
saveAvatarSettings,
saving,
}) => {
const username =
userState?.user?.display_name || userState?.user?.username || 'User';
const previewUrl =
avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM &&
avatarSettings.customAvatarUrl
? avatarSettings.customAvatarUrl
: avatarSettings.avatarType === USER_AVATAR_TYPES.INITIAL
? getInitialAvatarDataUrl(username, 128)
: getCartoonAvatarDataUrl(avatarSettings.avatarPreset, 128);
const customAvatarInvalid =
avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM &&
!avatarSettings.customAvatarUrl?.trim();
const activeDesc =
AVATAR_TYPE_OPTIONS.find(
(item) => item.value === avatarSettings.avatarType,
)?.desc || '';
return (
<OrgPanel
title={t('头像设置')}
subtitle={t('选择你在平台内展示的头像样式')}
icon={UserRound}
padding='p-5'
actions={
<Button
theme='solid'
loading={saving}
disabled={customAvatarInvalid}
onClick={saveAvatarSettings}
>
{t('保存头像')}
</Button>
}
>
<div className='grid grid-cols-1 xl:grid-cols-[240px_1fr] gap-5 items-start'>
{/* 实时预览:品牌色描边,实底卡面 */}
<div className='flex flex-col items-center text-center rounded-xl border border-[var(--border-subtle)] bg-brand/[0.04] px-5 py-6'>
<div className='relative mb-4'>
<img
src={previewUrl}
alt={t('头像预览')}
className='w-24 h-24 rounded-2xl object-cover ring-2 ring-brand/30'
/>
<span className='absolute -bottom-0.5 -right-0.5 h-5 w-5 rounded-full bg-emerald-500 border-2 border-[var(--surface-card)]' />
</div>
<div className='text-sm font-semibold text-[var(--text-primary)] truncate max-w-full'>
{username}
</div>
<div className='mt-1.5 text-xs text-gray-500 dark:text-gray-400 leading-relaxed'>
{t('该头像会同步展示在右上角用户入口和体验中心文本对话中。')}
</div>
<span className='mt-3 inline-flex items-center rounded-full bg-brand/10 text-brand px-2.5 py-0.5 text-xs font-medium'>
{t('实时预览')}
</span>
</div>
{/* 头像类型 + 具体选择 */}
<div>
<label className='block text-xs font-medium text-[var(--text-secondary)] mb-2'>
{t('头像类型')}
</label>
<RadioGroup
type='button'
value={avatarSettings.avatarType}
onChange={(e) =>
handleAvatarSettingChange('avatarType', e.target.value)
}
className='!flex !flex-wrap !gap-2'
>
{AVATAR_TYPE_OPTIONS.map((option) => {
const Icon = option.icon;
return (
<Radio key={option.value} value={option.value}>
<span className='inline-flex items-center gap-1.5'>
<Icon size={14} />
{t(option.label)}
</span>
</Radio>
);
})}
</RadioGroup>
<p className='mt-2 text-xs text-gray-500 dark:text-gray-400'>
{t(activeDesc)}
</p>
{avatarSettings.avatarType === USER_AVATAR_TYPES.PRESET && (
<div className='mt-5'>
<label className='block text-xs font-medium text-[var(--text-secondary)] mb-2.5'>
{t('选择卡通形象')}
</label>
<div className='grid grid-cols-2 sm:grid-cols-4 gap-3'>
{CARTOON_AVATAR_PRESETS.map((preset) => {
const selected = avatarSettings.avatarPreset === preset.id;
return (
<button
key={preset.id}
type='button'
onClick={() => {
handleAvatarSettingChange(
'avatarType',
USER_AVATAR_TYPES.PRESET,
);
handleAvatarSettingChange('avatarPreset', preset.id);
}}
className={`group relative flex flex-col items-center rounded-xl border p-3 transition-colors duration-150 ${
selected
? 'border-brand bg-brand/[0.06]'
: 'border-[var(--border-subtle)] bg-[var(--surface-card)] hover:border-brand/40'
}`}
>
<img
src={getCartoonAvatarDataUrl(preset.id, 96)}
alt={preset.label}
className='w-14 h-14 rounded-xl object-cover transition-transform group-hover:scale-105'
/>
<div className='mt-2 text-xs font-medium text-[var(--text-primary)] truncate max-w-full'>
{t(preset.label)}
</div>
{selected && (
<span className='absolute top-1.5 right-1.5 inline-flex h-4 w-4 items-center justify-center rounded-full bg-brand text-white'>
<Check size={11} strokeWidth={3} />
</span>
)}
</button>
);
})}
</div>
</div>
)}
{avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM && (
<div className='mt-5 rounded-xl border border-[var(--border-subtle)] bg-brand/[0.04] p-4'>
<Input
value={avatarSettings.customAvatarUrl}
onChange={(value) =>
handleAvatarSettingChange('customAvatarUrl', value)
}
placeholder={t(
'请输入图片 URL,例如 https://example.com/avatar.png',
)}
prefix={<ImageIcon size={15} className='text-brand ml-1' />}
showClear
/>
<p className='mt-2 text-xs text-gray-500 dark:text-gray-400'>
{t('支持公网图片链接。若图片加载失败,会回退到默认卡通头像。')}
</p>
</div>
)}
</div>
</div>
</OrgPanel>
);
};
export default OrgAvatarSection;
@@ -0,0 +1,71 @@
/*
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 from 'react';
/**
* 企业中心签名渐变区(方案 A+ 签名层的核心组件)。
*
* 冲击力护栏:每页至多使用一次;品牌渐变全部走 --brand-* token,
* 随主题预设整套切换。亮色 = 品牌渐变实底;暗色 = midnight glow
* (深底 + 渐变辉光边缘),两套模式各有性格。
*
* @param {React.ReactNode} eyebrow 顶部小字(如时段问候/版块名)
* @param {React.ReactNode} title 大标题
* @param {React.ReactNode} [subtitle] 副文案
* @param {React.ReactNode} [actions] 右侧操作区
* @param {React.ReactNode} [children] 底部扩展槽(如 KPI 行)
* @param {string} [className]
*/
const OrgHero = ({ eyebrow, title, subtitle, actions, children, className = '' }) => (
<div
className={`relative overflow-hidden rounded-xl border border-brand/20 bg-gradient-to-br from-brand-from via-brand-via to-brand-to text-white shadow-[var(--elevation-md)] dark:border-white/10 dark:from-brand-via/30 dark:via-neutral-950 dark:to-neutral-950 ${className}`}
>
{/* 暗色 midnight glow:左上角品牌辉光,亮色下渐变实底本身就是签名,不再叠加 */}
<div className='pointer-events-none absolute -left-16 -top-24 hidden h-56 w-56 rounded-full bg-brand-from/25 blur-3xl dark:block' />
<div className='pointer-events-none absolute inset-x-0 top-0 hidden h-px bg-gradient-to-r from-transparent via-white/25 to-transparent dark:block' />
<div className='relative px-5 py-5 sm:px-6 sm:py-6'>
<div className='flex items-start justify-between gap-4 flex-wrap'>
<div className='min-w-0'>
{eyebrow && (
<div className='mb-1 text-xs font-medium text-white/75 dark:text-brand-from/90'>
{eyebrow}
</div>
)}
<h1 className='text-xl sm:text-2xl font-bold tracking-tight truncate'>
{title}
</h1>
{subtitle && (
<p className='mt-1 max-w-2xl text-sm text-white/70 dark:text-gray-400'>
{subtitle}
</p>
)}
</div>
{actions && (
<div className='org-hero-actions flex items-center gap-2 flex-wrap justify-end'>
{actions}
</div>
)}
</div>
{children && <div className='mt-4'>{children}</div>}
</div>
</div>
);
export default OrgHero;
@@ -0,0 +1,44 @@
/*
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 from 'react';
import { Modal } from '@douyinfe/semi-ui';
/*
* 企业中心统一弹窗包装。
*
* Semi Modal 渲染到 body 的 portal,企业中心的 .org-center 作用域样式
* 够不着它,必须通过 className 挂载精修样式(styles/org.css 的 .org-modal,
* 沿用 index.css 中 .notice-modal-enhanced 的先例模式)。
* 企业中心所有 <Modal> 一律使用本组件,不要直接引 Semi Modal。
*/
const withOrgClass = (className) =>
className ? `org-modal ${className}` : 'org-modal';
const OrgModal = ({ className, ...rest }) => (
<Modal className={withOrgClass(className)} {...rest} />
);
/* 命令式 API 同样注入 className(如 OrgModal.confirm({...})) */
['confirm', 'info', 'success', 'warning', 'error'].forEach((method) => {
OrgModal[method] = (config = {}) =>
Modal[method]({ ...config, className: withOrgClass(config.className) });
});
OrgModal.destroyAll = Modal.destroyAll;
export default OrgModal;
@@ -0,0 +1,101 @@
/*
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, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Input, Toast, Typography } from '@douyinfe/semi-ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgModal from './OrgModal';
const { Text } = Typography;
/*
* 成员自助编辑昵称弹窗(PUT /api/org/me/profile)。
* 工作台 hero 与个人设置页共用;自管输入态,打开时以 currentName 初始化。
*/
const OrgNicknameModal = ({
visible,
onClose,
orgId,
currentName,
onSuccess,
}) => {
const { t } = useTranslation();
const [value, setValue] = useState('');
const [saving, setSaving] = useState(false);
useEffect(() => {
if (visible) {
setValue(currentName || '');
}
}, [visible, currentName]);
const submit = async () => {
const name = value.trim();
if (!name) {
showError(t('昵称不能为空'));
return;
}
setSaving(true);
try {
const res = await API.put(
'/api/org/me/profile',
{ display_name: name },
{ headers: { 'X-Org-Id': String(orgId) } },
);
if (res.data.success) {
Toast.success(t('昵称已更新'));
onClose();
onSuccess?.(name);
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSaving(false);
}
};
return (
<OrgModal
title={t('编辑昵称')}
visible={visible}
onOk={submit}
onCancel={onClose}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={saving}
>
<Text type='tertiary' size='small'>
{t('昵称用于成员排行与用量分析中标识您,最多 20 个字符')}
</Text>
<Input
value={value}
onChange={setValue}
maxLength={20}
placeholder={t('请输入昵称')}
style={{ marginTop: 12 }}
onEnterPress={submit}
/>
</OrgModal>
);
};
export default OrgNicknameModal;
@@ -0,0 +1,57 @@
/*
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 from 'react';
/**
* 企业中心统一页面标题区。
* 所有企业页(/org/*)共用,保证标题字号、副标题、右侧操作区写法一致。
*
* @param {React.ComponentType} [icon] 可选的 lucide 图标组件(如 Wallet)
* @param {React.ReactNode} title 主标题
* @param {React.ReactNode} [subtitle] 副标题(一句话说明本页用途)
* @param {React.ReactNode} [actions] 右侧操作区(刷新/新建等按钮)
*/
const OrgPageHeader = ({ icon: Icon, title, subtitle, actions }) => (
<div className='mb-5 flex items-start justify-between gap-4 flex-wrap'>
<div className='flex items-center gap-3 min-w-0'>
{Icon && (
<div className='flex-shrink-0 inline-flex h-9 w-9 items-center justify-center rounded-lg bg-brand/10 text-brand'>
<Icon size={18} />
</div>
)}
<div className='min-w-0'>
<h1 className='text-lg sm:text-xl font-semibold tracking-tight text-[var(--text-primary)] truncate'>
{title}
</h1>
{subtitle && (
<p className='text-[13px] text-gray-500 dark:text-gray-400 mt-0.5 max-w-3xl'>
{subtitle}
</p>
)}
</div>
</div>
{actions && (
<div className='flex items-center gap-2 flex-wrap justify-end'>
{actions}
</div>
)}
</div>
);
export default OrgPageHeader;
@@ -0,0 +1,83 @@
/*
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 from 'react';
/**
* 企业中心统一卡片容器(方案 A+ 底盘层)。
* 实底表面 + 小圆角 + 1px 细边框 + 极轻海拔,靠边框分层,不用毛玻璃;
* 消除「裸表格」「Semi Card」「卡片表格」并存的不一致。
*
* @param {React.ReactNode} [title] 可选卡片标题(提供时渲染统一头部)
* @param {React.ReactNode} [subtitle] 标题下方副说明
* @param {React.ComponentType} [icon] 标题左侧 lucide 图标
* @param {React.ReactNode} [actions] 头部右侧操作区
* @param {string} [className] 追加类名
* @param {string} [padding] 内容内边距类,默认 'p-4';表格场景可传 'p-0' / 'p-2'
* @param {string} [bodyClassName] 内容容器追加类名
*/
const OrgPanel = ({
children,
title,
subtitle,
icon: Icon,
actions,
className = '',
padding = 'p-4',
bodyClassName = '',
}) => {
const hasHeader = title || actions;
return (
<div
className={`relative overflow-hidden rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-xs)] ${className}`}
>
{hasHeader && (
<div className='flex items-start justify-between gap-3 flex-wrap border-b border-[var(--border-subtle)] px-5 py-3.5'>
<div className='flex items-center gap-2.5 min-w-0'>
{Icon && (
<span className='inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand'>
<Icon size={16} />
</span>
)}
<div className='min-w-0'>
{title && (
<div className='text-sm font-semibold text-[var(--text-primary)] truncate'>
{title}
</div>
)}
{subtitle && (
<div className='mt-0.5 text-xs text-gray-500 dark:text-gray-400'>
{subtitle}
</div>
)}
</div>
</div>
{actions && (
<div className='flex items-center gap-2 flex-wrap justify-end'>
{actions}
</div>
)}
</div>
)}
<div className={`${padding} ${bodyClassName}`}>{children}</div>
</div>
);
};
export default OrgPanel;
@@ -0,0 +1,118 @@
/*
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, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Input, Toast, Typography } from '@douyinfe/semi-ui';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgModal from './OrgModal';
const { Text } = Typography;
const EMPTY_FORM = { old: '', next: '', confirm: '' };
/*
* 成员自助改密弹窗(POST /api/org/account/change-password,方案 §12.8)。
* 工作台 hero 与个人设置页共用;打开时清空表单。
*/
const OrgPasswordModal = ({ visible, onClose }) => {
const { t } = useTranslation();
const [form, setForm] = useState(EMPTY_FORM);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (visible) {
setForm(EMPTY_FORM);
}
}, [visible]);
const submit = async () => {
const { old: oldPwd, next, confirm } = form;
if (!oldPwd || !next) {
showError(t('请输入原密码和新密码'));
return;
}
if (next !== confirm) {
showError(t('两次输入的新密码不一致'));
return;
}
// 与后端一致:8-20 位 + 至少两类字符
if (next.length < 8 || next.length > 20) {
showError(t('新密码长度需为 8-20 位'));
return;
}
setSaving(true);
try {
const res = await API.post('/api/org/account/change-password', {
old_password: oldPwd,
new_password: next,
});
if (res.data.success) {
Toast.success(t('密码已修改'));
onClose();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
} finally {
setSaving(false);
}
};
return (
<OrgModal
title={t('修改密码')}
visible={visible}
onOk={submit}
onCancel={onClose}
okText={t('保存')}
cancelText={t('取消')}
confirmLoading={saving}
>
<Text type='tertiary' size='small'>
{t('新密码需为 8-20 位,且至少包含字母、数字、符号中的两类')}
</Text>
<Input
mode='password'
value={form.old}
onChange={(v) => setForm((prev) => ({ ...prev, old: v }))}
placeholder={t('原密码')}
style={{ marginTop: 12 }}
/>
<Input
mode='password'
value={form.next}
onChange={(v) => setForm((prev) => ({ ...prev, next: v }))}
placeholder={t('新密码')}
style={{ marginTop: 10 }}
/>
<Input
mode='password'
value={form.confirm}
onChange={(v) => setForm((prev) => ({ ...prev, confirm: v }))}
placeholder={t('确认新密码')}
style={{ marginTop: 10 }}
onEnterPress={submit}
/>
</OrgModal>
);
};
export default OrgPasswordModal;
@@ -0,0 +1,265 @@
/*
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, { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Select, Toast, Tooltip } from '@douyinfe/semi-ui';
import { Layers } from 'lucide-react';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgModal from './OrgModal';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
// 解析分组字段:兼容 JSON 字符串/数组;为空表示该维度未配置分组。
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 [];
};
/**
* 部门/项目「模型 / 分组」限制配置入口(操作列复用组件)。
* 生效规则:成员个人、项目、部门按维度取交集,由后端鉴权链路裁决。
*
* props:
* - orgId
* - record: 行数据(含 model_limits_enabled / model_limits / groups)
* - apiBase: '/api/org/dept' 或 '/api/org/project'
* - scopeLabel: '部门' | '项目'(用于弹窗标题与文案)
* - onSaved: 保存成功后回调(刷新列表)
*/
const OrgScopedLimitButtons = ({ orgId, record, apiBase, scopeLabel, onSaved }) => {
const { t } = useTranslation();
const [modelModalVisible, setModelModalVisible] = useState(false);
const [orgModels, setOrgModels] = useState([]);
const [loadingModels, setLoadingModels] = useState(false);
const [selectedModels, setSelectedModels] = useState([]);
const [groupsModalVisible, setGroupsModalVisible] = useState(false);
const [orgGroups, setOrgGroups] = useState([]);
const [selectedGroups, setSelectedGroups] = useState([]);
const scopeName = record?.name || '';
const openModelModal = useCallback(async () => {
setSelectedModels(
record.model_limits_enabled && record.model_limits
? record.model_limits.split(',').filter(Boolean)
: [],
);
setModelModalVisible(true);
setLoadingModels(true);
try {
const res = await API.get('/api/org/models', { headers: getOrgHeaders(orgId) });
if (res.data.success) {
setOrgModels((res.data.data || []).map((m) => ({ label: m, value: m })));
}
} catch {
/* ignore */
}
setLoadingModels(false);
}, [orgId, record]);
const openGroupsModal = useCallback(async () => {
setSelectedGroups(parseGroups(record?.groups));
setGroupsModalVisible(true);
try {
const res = await API.get('/api/org/info', { headers: getOrgHeaders(orgId) });
if (res.data.success) {
const org = res.data.data?.organization || {};
let groups = [];
if (Array.isArray(org.groups)) {
groups = org.groups;
} else if (typeof org.groups === 'string' && org.groups.trim()) {
try {
groups = JSON.parse(org.groups);
} catch {
groups = [];
}
}
if (!groups.length && org.group) groups = [org.group];
setOrgGroups(groups.map((g) => ({ label: g, value: g })));
}
} catch {
/* ignore */
}
}, [orgId, record]);
const handleModelSave = useCallback(async () => {
const enabled = selectedModels.length > 0;
try {
const res = await API.put(
`${apiBase}/${record.id}/models`,
{ model_limits_enabled: enabled, model_limits: selectedModels.join(',') },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('模型限制已更新'));
setModelModalVisible(false);
onSaved && onSaved();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
}, [apiBase, record, orgId, selectedModels, onSaved, t]);
const handleGroupsSave = useCallback(async () => {
try {
const res = await API.put(
`${apiBase}/${record.id}/groups`,
{ groups: selectedGroups },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('分组已更新'));
setGroupsModalVisible(false);
onSaved && onSaved();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
}, [apiBase, record, orgId, selectedGroups, onSaved, t]);
const modelConfigured = record.model_limits_enabled;
const groupConfigured = parseGroups(record?.groups).length > 0;
return (
<>
<Tooltip content={t('设置该{{scope}}成员默认可用的模型范围(与成员/项目/部门限制取交集)', { scope: t(scopeLabel) })}>
<Button
size='small'
theme='light'
type={modelConfigured ? 'primary' : 'tertiary'}
icon={<Layers size={14} />}
onClick={openModelModal}
>
{t('模型')}
</Button>
</Tooltip>
<Tooltip content={t('设置该{{scope}}成员默认可调用的分组(与成员/项目/部门限制取交集)', { scope: t(scopeLabel) })}>
<Button
size='small'
theme='light'
type={groupConfigured ? 'primary' : 'tertiary'}
icon={<Layers size={14} />}
onClick={openGroupsModal}
>
{t('分组')}
</Button>
</Tooltip>
{/* 模型限制 Modal */}
<OrgModal
title={`${t(scopeLabel)}${t('模型限制')}${scopeName ? ` - ${scopeName}` : ''}`}
visible={modelModalVisible}
onOk={handleModelSave}
onCancel={() => setModelModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
width={520}
>
<div className='space-y-3'>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t(
'限制该{{scope}}成员默认可使用的模型。留空则该维度不限制;若成员个人、项目、部门同时配置,最终可用模型取交集。',
{ scope: t(scopeLabel) },
)}
</p>
<div>
<label className='flex items-center gap-1.5 text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
<Layers size={14} className='text-brand' />
{t('可用模型')}
<span className='text-xs text-gray-400 font-normal ml-1'>
({t('留空则不限制')})
</span>
</label>
<Select
multiple
value={selectedModels}
onChange={setSelectedModels}
optionList={orgModels}
loading={loadingModels}
placeholder={t('选择可用模型,留空则支持所有模型')}
filter
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
</div>
</div>
</OrgModal>
{/* 可调用分组 Modal */}
<OrgModal
title={`${t(scopeLabel)}${t('可调用分组')}${scopeName ? ` - ${scopeName}` : ''}`}
visible={groupsModalVisible}
onOk={handleGroupsSave}
onCancel={() => setGroupsModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
width={520}
>
<div className='space-y-3'>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t(
'设置该{{scope}}成员默认可调用的分组,只能从企业已配置的可用分组中选择。留空则该维度不限制;若成员个人、项目、部门同时配置,最终可用分组取交集。',
{ scope: t(scopeLabel) },
)}
</p>
<div>
<label className='flex items-center gap-1.5 text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
<Layers size={14} className='text-brand' />
{t('可调用分组')}
<span className='text-xs text-gray-400 font-normal ml-1'>
({t('留空则不限制')})
</span>
</label>
<Select
multiple
value={selectedGroups}
onChange={setSelectedGroups}
optionList={orgGroups}
placeholder={t('选择可调用的分组')}
filter
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
</div>
</div>
</OrgModal>
</>
);
};
export default OrgScopedLimitButtons;
@@ -0,0 +1,47 @@
/*
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 from 'react';
import { SideSheet } from '@douyinfe/semi-ui';
/*
* 企业中心统一侧滑面板包装。与 OrgModal 同理:SideSheet 走 portal,
* 通过 className 挂载 styles/org.css 的 .org-sidesheet 精修样式。
* 企业中心所有 <SideSheet> 一律使用本组件。
*
* 移动端适配:调用方普遍传固定像素宽(如技能详情的 720),在手机上会超出视口——
* Semi 把 width 作为内联样式打在 .semi-sidesheet-inner 上,面板 right:0 定位,
* 超出的部分被推到屏幕左侧外并裁掉。这里统一把像素宽钳到视口内。
*
* 用 min() 钳制而不是「窄屏一律 100%」:企业中心的移动端导航抽屉是
* placement='left' width={260} closable={false},一旦被强制拉满整个视口,
* 遮罩被完全盖住(点不到 maskClosable)、又没有关闭按钮,用户会被困在抽屉里。
* 钳制语义下 260px 本来就没超出视口,保持原样。
*
* 字符串宽度(如 '95%')原样透传;placement 也不拦截——Semi 对 top/bottom
* 侧滑本来就忽略 width(见 sideSheet/index.js 的 isVertical 分支)。
*/
const OrgSideSheet = ({ className, width, ...rest }) => (
<SideSheet
className={className ? `org-sidesheet ${className}` : 'org-sidesheet'}
width={typeof width === 'number' ? `min(${width}px, 100vw)` : width}
{...rest}
/>
);
export default OrgSideSheet;
@@ -0,0 +1,160 @@
/*
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 from 'react';
import useCountUp from '../../../hooks/common/useCountUp';
/**
* 企业中心统一统计卡(KPI 卡,方案 A+ 底盘层)。
* 实底、紧凑、tabular-nums 等宽数字;图标品牌色浅底(不再渐变实底);
* 数值可选 count-up 滚动(签名层动效,respect prefers-reduced-motion)。
*
* @param {React.ComponentType} icon lucide 图标组件
* @param {React.ReactNode} label 标题(兼容旧用法的 title)
* @param {React.ReactNode} title label 的别名
* @param {React.ReactNode} value 主数值(直接展示)
* @param {number} [countTo] 数值 count-up 目标;提供时优先于 value 渲染
* @param {(n:number)=>React.ReactNode} [formatter] countTo 的格式化函数(默认 toLocaleString)
* @param {number} [decimals] countTo 保留小数位,默认 0
* @param {React.ReactNode} [hint] 副说明(兼容旧用法的 subtitle)
* @param {React.ReactNode} [subtitle] hint 的别名
* @param {React.ReactNode} [extra] 底部扩展槽(进度条等)
* @param {string} [tone] 'brand' | 'amber' | 'rose' | 'sky' | 'violet'
* @param {boolean} [danger] 危险态(红色强调),等价于 tone='rose'
* @param {boolean} [loading] 骨架加载态
* @param {boolean} [compact] 紧凑横向布局(用于密集 KPI 行)
* @param {string} [className] 追加类名
*/
// tone -> 图标浅底色/数值强调色。底盘层原则:色彩只用于图标与语义强调,不再渐变铺装饰。
const TONES = {
brand: {
icon: 'bg-brand/10 text-brand',
value: 'text-[var(--text-primary)]',
},
amber: {
icon: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',
value: 'text-[var(--text-primary)]',
},
rose: {
icon: 'bg-rose-500/10 text-rose-600 dark:text-rose-400',
value: 'text-rose-600 dark:text-rose-400',
},
sky: {
icon: 'bg-sky-500/10 text-sky-600 dark:text-sky-400',
value: 'text-[var(--text-primary)]',
},
violet: {
icon: 'bg-violet-500/10 text-violet-600 dark:text-violet-400',
value: 'text-[var(--text-primary)]',
},
};
const OrgStatCard = ({
icon: Icon,
label,
title,
value,
countTo,
formatter,
decimals = 0,
hint,
subtitle,
extra,
tone = 'brand',
danger = false,
loading = false,
compact = false,
className = '',
}) => {
const resolvedTone = danger ? 'rose' : tone;
const palette = TONES[resolvedTone] || TONES.brand;
const heading = label ?? title;
const sub = hint ?? subtitle;
const hasCountUp = typeof countTo === 'number';
const animated = useCountUp(hasCountUp ? countTo : 0, { decimals });
const displayValue = hasCountUp
? (formatter ? formatter(animated) : animated.toLocaleString())
: value;
return (
<div
className={`rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-xs)] ${compact ? 'p-3' : 'p-4'} ${className}`}
>
<div className={`flex ${compact ? 'items-center gap-3' : 'flex-col'}`}>
<div className={`flex items-center gap-2.5 ${compact ? '' : 'mb-2.5'}`}>
{Icon && (
<span
className={`inline-flex flex-shrink-0 items-center justify-center rounded-lg ${palette.icon} ${compact ? 'h-8 w-8' : 'h-9 w-9'}`}
>
<Icon size={compact ? 15 : 17} />
</span>
)}
{compact && (
<div className='flex min-w-0 flex-col'>
<span className='truncate text-xs font-medium text-gray-500 dark:text-gray-400'>
{heading}
</span>
{loading ? (
<span className='org-skeleton mt-1 h-4 w-16 rounded bg-gray-200 dark:bg-neutral-700' />
) : (
<span
className={`truncate text-sm font-semibold tabular-nums ${palette.value}`}
>
{displayValue}
</span>
)}
</div>
)}
{!compact && (
<span className='text-[13px] font-medium text-gray-500 dark:text-gray-400'>
{heading}
</span>
)}
</div>
{!compact &&
(loading ? (
<div className='space-y-2'>
<div className='org-skeleton h-7 w-24 rounded bg-gray-200 dark:bg-neutral-700' />
{(sub || extra) && (
<div className='org-skeleton h-4 w-28 rounded bg-gray-100 dark:bg-neutral-800' />
)}
</div>
) : (
<>
<div
className={`text-2xl font-semibold tracking-tight tabular-nums ${palette.value}`}
>
{displayValue}
</div>
{sub && (
<div className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
{sub}
</div>
)}
{extra && <div className='mt-3'>{extra}</div>}
</>
))}
</div>
</div>
);
};
export default OrgStatCard;
@@ -0,0 +1,78 @@
/*
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 from 'react';
import { Spin } from '@douyinfe/semi-ui';
import { Inbox } from 'lucide-react';
/**
* 企业中心统一「加载中 / 空数据」占位块。
* 替代各页自造的空态 div 与零散的 Spin 写法,统一图标、文案排版与留白。
* 既可独立使用,也可作为 Semi Table 的 empty 槽。
*
* @param {boolean} [loading] 加载态:渲染居中 Spin
* @param {React.ComponentType} [icon] 空态图标(默认 Inbox)
* @param {React.ReactNode} [title] 空态主文案
* @param {React.ReactNode} [description] 空态副文案
* @param {React.ReactNode} [action] 空态操作区(如「新建」按钮)
* @param {string} [className] 追加类名
*/
const OrgStateBlock = ({
loading = false,
icon: Icon = Inbox,
title,
description,
action,
className = '',
}) => {
if (loading) {
return (
<div
className={`flex items-center justify-center py-16 ${className}`}
>
<Spin size='large' />
</div>
);
}
return (
<div
className={`flex flex-col items-center justify-center px-6 py-14 text-center ${className}`}
>
{/* 仪式感空状态:品牌浅底同心圆图标,空态也是被设计过的时刻 */}
<div className='mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-brand/5'>
<div className='inline-flex h-11 w-11 items-center justify-center rounded-full bg-brand/10 text-brand'>
<Icon size={22} strokeWidth={1.75} />
</div>
</div>
{title && (
<div className='text-sm font-semibold text-[var(--text-primary)]'>
{title}
</div>
)}
{description && (
<div className='mt-1 max-w-sm text-xs text-gray-500 dark:text-gray-400'>
{description}
</div>
)}
{action && <div className='mt-4'>{action}</div>}
</div>
);
};
export default OrgStateBlock;
@@ -0,0 +1,79 @@
/*
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, { useEffect } from 'react';
import { TabPane, Tabs } from '@douyinfe/semi-ui';
import { useSearchParams } from 'react-router-dom';
/**
* 企业中心合并页通用的二级页签容器。
*
* 页签状态同步到 ?tab=,让旧路由的重定向(如 /org/skill-library →
* /org/skill-center?tab=library)与收藏链接可以直达指定页签。
* tabs 数组允许传 falsy 项(站点级模块开关关掉的页签),会被过滤;
* 只剩一个可见页签时不渲染页签条,直接铺内容,避免"单页签"的怪异观感。
*/
const OrgSubpageTabs = ({ tabs }) => {
const [searchParams, setSearchParams] = useSearchParams();
const visible = (tabs || []).filter(Boolean);
const requested = searchParams.get('tab');
const activeKey =
visible.length > 0 && visible.some((item) => item.key === requested)
? requested
: visible[0]?.key;
// ?tab= 指向不存在/已被模块开关关掉的页签时,回落到第一个可见页签并把 URL
// 一并纠正——否则地址栏还挂着无效的 tab,转发给同事仍会落到这里再回落一次,
// URL 与实际内容长期不符。hook 顺序要求这个 effect 在任何 early return 之前。
useEffect(() => {
if (!activeKey || requested === activeKey) return;
const next = new URLSearchParams(searchParams);
next.set('tab', activeKey);
setSearchParams(next, { replace: true });
}, [requested, activeKey, searchParams, setSearchParams]);
if (visible.length === 0) return null;
if (visible.length === 1) return visible[0].node;
return (
<div className='org-subpage-tabs'>
<Tabs
type='line'
// 必须惰性渲染:Semi 默认 lazyRender=false 会把所有 TabPane 的 children
// 立即挂载,于是两个子页会同时拉数、各自的 PageGuide 抽屉(SideSheet 走
// Portal,不受非激活 pane 的 display:none 约束)在首访时叠着弹出,
// 且两个 guideKey 一起被 markSeen,用户再也看不到本该出现的那一份。
// keepDOM 默认 true,切回已访问过的页签不会重新拉数。
lazyRender
activeKey={activeKey}
onChange={(key) => {
// 就地改写 tab,保留其余 query(子页面可能带自己的筛选参数);
// 直接传对象字面量会把整串 query 冲掉。
const next = new URLSearchParams(searchParams);
next.set('tab', key);
setSearchParams(next, { replace: true });
}}
>
{visible.map((item) => (
<TabPane key={item.key} tab={item.label} itemKey={item.key}>
{item.node}
</TabPane>
))}
</Tabs>
</div>
);
};
export default OrgSubpageTabs;
@@ -0,0 +1,107 @@
/*
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
*/
// 部门树构建工具:/api/org/dept 返回按 sort asc, id asc 排序的扁平列表,
// 这里按 parent_id 组装成 Semi Tree/TreeSelect 的 treeData。
/**
* buildDeptTreeData 扁平部门列表 → Semi treeData。
*
* @param {Array} depts 后端返回的部门列表(保持返回顺序即层内排序)
* @param {Object} options
* - disableNonLeaf 有子部门的节点不可选(成员主归属只允许挂末级部门)
* - excludeSubtreeOf 排除某部门自身及其整棵子树(编辑部门选上级时防环),
* 传含 id/path 的部门对象
* - disabledLabel 停用部门的后缀文案(外部传入以走 i18n)
*/
export function buildDeptTreeData(depts, options = {}) {
const {
disableNonLeaf = true,
excludeSubtreeOf = null,
disabledLabel = '已停用',
} = options;
const excluded = (d) =>
excludeSubtreeOf &&
(d.id === excludeSubtreeOf.id ||
(excludeSubtreeOf.path &&
d.path &&
d.path.startsWith(excludeSubtreeOf.path)));
const visible = (depts || []).filter((d) => !excluded(d));
const childCount = {};
visible.forEach((d) => {
childCount[d.parent_id] = (childCount[d.parent_id] || 0) + 1;
});
const idSet = new Set(visible.map((d) => d.id));
const nodeMap = {};
visible.forEach((d) => {
const stopped = d.status !== 1;
const nonLeafBlocked = disableNonLeaf && (childCount[d.id] || 0) > 0;
nodeMap[d.id] = {
label: stopped ? `${d.name}(${disabledLabel})` : d.name,
value: d.id,
key: String(d.id),
disabled: stopped || nonLeafBlocked,
children: [],
};
});
const roots = [];
visible.forEach((d) => {
const node = nodeMap[d.id];
if (d.parent_id && idSet.has(d.parent_id)) {
nodeMap[d.parent_id].children.push(node);
} else {
// 顶级部门;父节点缺失/被排除的孤儿也挂根兜底,避免整棵子树消失
roots.push(node);
}
});
// 叶子节点去掉空 children,避免渲染多余的展开箭头
Object.values(nodeMap).forEach((n) => {
if (n.children.length === 0) delete n.children;
});
return roots;
}
/**
* buildDeptFullNameMap 部门 id → 全路径名(如「华南事业部 / 研发中心 / 平台组」)。
* 基于 path 字段("/1/4/9/")解析祖先链;path 异常时退回自身名称。
*/
export function buildDeptFullNameMap(depts) {
const nameById = {};
(depts || []).forEach((d) => {
nameById[d.id] = d.name;
});
const map = {};
(depts || []).forEach((d) => {
const names = (d.path || '')
.split('/')
.filter(Boolean)
.map((seg) => nameById[Number(seg)])
.filter(Boolean);
map[d.id] = names.length ? names.join(' / ') : d.name;
});
return map;
}
/** hasChildDept 某部门当前是否存在子部门 */
export function hasChildDept(depts, deptId) {
return (depts || []).some((d) => d.parent_id === deptId);
}
@@ -0,0 +1,54 @@
/*
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
*/
// 企业中心统一状态语义色映射(Semi Tag color)。
// 统一各页面 Tag 颜色口径,避免「pending 一会 amber 一会 orange」「停用一会红一会灰」。
const ORG_STATUS_COLOR = {
// 审批 / 流程
pending: 'amber',
approved: 'green',
rejected: 'red',
canceled: 'grey',
expired: 'grey',
processing: 'blue',
// 启停 / 成员 / 令牌
active: 'green',
enabled: 'green',
normal: 'green',
disabled: 'grey',
inactive: 'grey',
offboarded: 'grey',
banned: 'red',
// 充值 / 支付
paid: 'green',
success: 'green',
failed: 'red',
// 额度
exhausted: 'grey',
};
/**
* 取企业状态对应的统一 Semi Tag 颜色。未知状态回退 grey。
* @param {string} status 状态键(小写)
* @returns {string} Semi Tag color
*/
export const orgStatusColor = (status) =>
ORG_STATUS_COLOR[String(status || '').toLowerCase()] || 'grey';
export default orgStatusColor;