61294dc597
来源:luoguang/monkey-ai weiyuan@bfdfb339 的 web/(经 sync/main-weiyuan-web-bfdfb339 同步)
同步基准:总仓库 a2ca13cb = 本仓库初始导入 d8f3aee2
冲突处理原则:保留 ui-optimization 的 UI(样式/结构/组件),嫁接 weiyuan 的功能逻辑。
- i18n:按键三方合并;ours 的「令牌→密钥」改名键上移植 theirs 的术语修订
- task-logs / OrgLogs:ours 已手工移植同一功能(6ad95e2),保留 ours
- 删除:OrgCreate(theirs 下线 /org/create)、旧 image 组件与 VideoRegenerateModal(theirs 体验中心重写)、
OrgAvatarSection / PricingBentoPage / CommissionConsole(ours 重构中已移除)
- 测试:users-pagination 的 i18next mock 补 t();theirs 新增文件补 license header
370 lines
12 KiB
React
370 lines
12 KiB
React
/*
|
||
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 { Banner, Button, Form, Toast, Empty, Spin } from '@/components/ui';
|
||
import { RefreshCw, Plus, Network } from 'lucide-react';
|
||
import { API } from '../../helpers/api';
|
||
import { showError } from '../../helpers';
|
||
import { useActualTheme } from '../../context/Theme';
|
||
import OrgPageHeader from './components/OrgPageHeader';
|
||
import OrgPanel from './components/OrgPanel';
|
||
import OrgModal from './components/OrgModal';
|
||
import DeptFlowCanvas from './components/DeptFlowCanvas';
|
||
import { buildDeptTreeData } from './components/deptTree';
|
||
|
||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||
|
||
// 部门管理:组织架构画布(多棵树)+ 节点内操作;移动走后端 MoveDepartmentTx 级联 path
|
||
const OrgDepartments = ({ orgId }) => {
|
||
const { t } = useTranslation();
|
||
const actualTheme = useActualTheme();
|
||
const [list, setList] = useState([]);
|
||
const [loading, setLoading] = useState(false);
|
||
const [loaded, setLoaded] = useState(false);
|
||
const [modalVisible, setModalVisible] = useState(false);
|
||
const [editing, setEditing] = useState(null); // null=新建,否则为编辑对象
|
||
const [createParentId, setCreateParentId] = useState(0); // 新建时预填父部门
|
||
const [formApi, setFormApi] = useState(null);
|
||
const [saving, setSaving] = useState(false);
|
||
const [direction, setDirection] = useState('TB'); // TB 纵向 / LR 横向
|
||
const [members, setMembers] = useState([]); // 活跃成员(含 department_id),供画布展示成员数/列表
|
||
const [budgets, setBudgets] = useState([]); // 部门预算行,供画布节点展示预算用量
|
||
// 预算拦截是否生效:false 时不渲染用量条(used 恒为 0,显示会误导管理员"本月没花钱")
|
||
const [budgetEnforced, setBudgetEnforced] = useState(null);
|
||
|
||
const fetchList = useCallback(async () => {
|
||
if (!orgId) return;
|
||
setLoading(true);
|
||
try {
|
||
const [res, mres, bres] = await Promise.all([
|
||
API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }),
|
||
// 成员数据仅是画布辅助信息:网络失败兜底为 null,不连坐部门树
|
||
API.get('/api/org/members/all', {
|
||
headers: getOrgHeaders(orgId),
|
||
}).catch(() => null),
|
||
// 部门预算仅是画布辅助信息:失败/未开启预算功能时静默降级为不展示。
|
||
// skipErrorHandler:若后端将来把 feature 未开改成真 4xx,.catch 拦不住
|
||
// axios 全局拦截器的 toast,必须在请求层显式静默
|
||
API.get('/api/org/budget?subject_type=department', {
|
||
headers: getOrgHeaders(orgId),
|
||
skipErrorHandler: true,
|
||
}).catch(() => null),
|
||
]);
|
||
if (res.data.success) {
|
||
setList(res.data.data || []);
|
||
} else {
|
||
showError(res.data.message);
|
||
}
|
||
// 成员列表仅用于画布展示,拉取失败不阻塞部门树
|
||
if (mres?.data?.success) setMembers(mres.data.data || []);
|
||
if (bres?.data?.success) {
|
||
// 新后端返回 {items, enforcement_enabled};兼容旧后端直接返回数组
|
||
const payload = bres.data.data;
|
||
const items = Array.isArray(payload) ? payload : payload?.items || [];
|
||
setBudgets(items.filter((b) => b.subject_type === 'department'));
|
||
setBudgetEnforced(
|
||
Array.isArray(payload)
|
||
? null
|
||
: (payload?.enforcement_enabled ?? null),
|
||
);
|
||
}
|
||
} catch (err) {
|
||
showError(err.message);
|
||
} finally {
|
||
setLoading(false);
|
||
setLoaded(true);
|
||
}
|
||
}, [orgId]);
|
||
|
||
useEffect(() => {
|
||
fetchList();
|
||
}, [fetchList]);
|
||
|
||
// 上级部门树:编辑时排除自身及其整棵子树(path 前缀判断,避免选出环)。
|
||
// 与成员分配不同,上级可以是任意层级节点(disableNonLeaf=false),停用部门不可作新上级。
|
||
const parentTreeData = useMemo(
|
||
() => [
|
||
{ label: t('顶级部门'), value: 0, key: '0' },
|
||
...buildDeptTreeData(list, {
|
||
disableNonLeaf: false,
|
||
excludeSubtreeOf: editing,
|
||
disabledLabel: t('已停用'),
|
||
}),
|
||
],
|
||
[list, editing, t],
|
||
);
|
||
|
||
// 弹窗内实时跟踪所选上级(表单值变化同步),用于「上级已有直属成员」提示
|
||
const [modalParentId, setModalParentId] = useState(0);
|
||
const memberCountByDept = useMemo(() => {
|
||
const m = {};
|
||
members.forEach((mm) => {
|
||
if (mm.department_id)
|
||
m[mm.department_id] = (m[mm.department_id] || 0) + 1;
|
||
});
|
||
return m;
|
||
}, [members]);
|
||
const parentMemberCount =
|
||
modalParentId > 0 ? memberCountByDept[modalParentId] || 0 : 0;
|
||
|
||
const openCreate = useCallback((parentId = 0) => {
|
||
setEditing(null);
|
||
setCreateParentId(parentId);
|
||
setModalParentId(parentId);
|
||
setModalVisible(true);
|
||
}, []);
|
||
|
||
const openEdit = useCallback((record) => {
|
||
setEditing(record);
|
||
setModalParentId(record.parent_id || 0);
|
||
setModalVisible(true);
|
||
}, []);
|
||
|
||
const handleAddChild = useCallback(
|
||
(parent) => openCreate(parent.id),
|
||
[openCreate],
|
||
);
|
||
|
||
useEffect(() => {
|
||
if (modalVisible && formApi) {
|
||
if (editing) {
|
||
formApi.setValues({
|
||
name: editing.name,
|
||
parent_id: editing.parent_id || 0,
|
||
sort: editing.sort || 0,
|
||
status: editing.status || 1,
|
||
});
|
||
} else {
|
||
formApi.setValues({
|
||
name: '',
|
||
parent_id: createParentId,
|
||
sort: 0,
|
||
status: 1,
|
||
});
|
||
}
|
||
}
|
||
}, [modalVisible, editing, createParentId, formApi]);
|
||
|
||
const handleSubmit = async () => {
|
||
if (!formApi || saving) return;
|
||
let values;
|
||
try {
|
||
values = await formApi.validate();
|
||
} catch {
|
||
return;
|
||
}
|
||
setSaving(true);
|
||
try {
|
||
let res;
|
||
if (editing) {
|
||
res = await API.put(`/api/org/dept/${editing.id}`, values, {
|
||
headers: getOrgHeaders(orgId),
|
||
});
|
||
} else {
|
||
res = await API.post('/api/org/dept', values, {
|
||
headers: getOrgHeaders(orgId),
|
||
});
|
||
}
|
||
if (res.data.success) {
|
||
Toast.success(editing ? t('部门已更新') : t('部门已创建'));
|
||
setModalVisible(false);
|
||
fetchList();
|
||
} else {
|
||
showError(res.data.message);
|
||
}
|
||
} catch (err) {
|
||
showError(err.message);
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
const handleDelete = useCallback(
|
||
async (record) => {
|
||
try {
|
||
const res = await API.delete(`/api/org/dept/${record.id}`, {
|
||
headers: getOrgHeaders(orgId),
|
||
});
|
||
if (res.data.success) {
|
||
Toast.success(t('部门已删除'));
|
||
fetchList();
|
||
} else {
|
||
showError(res.data.message);
|
||
}
|
||
} catch (err) {
|
||
showError(err.message);
|
||
}
|
||
},
|
||
[orgId, t, fetchList],
|
||
);
|
||
|
||
// 画布连线触发:把 childId 移到 parentId 之下(后端 MoveDepartmentTx 防环并级联 path)
|
||
const handleMove = useCallback(
|
||
async (childId, parentId) => {
|
||
try {
|
||
const res = await API.put(
|
||
`/api/org/dept/${childId}`,
|
||
{ parent_id: parentId },
|
||
{ headers: getOrgHeaders(orgId) },
|
||
);
|
||
if (res.data.success) {
|
||
Toast.success(t('部门层级已调整'));
|
||
} else {
|
||
showError(res.data.message);
|
||
}
|
||
} catch (err) {
|
||
showError(err.message);
|
||
} finally {
|
||
fetchList();
|
||
}
|
||
},
|
||
[orgId, t, fetchList],
|
||
);
|
||
|
||
return (
|
||
<div className='uc-page'>
|
||
<OrgPageHeader
|
||
icon={Network}
|
||
title={t('组织架构')}
|
||
subtitle={t('组织架构与部门预算')}
|
||
actions={
|
||
<>
|
||
<Button
|
||
theme='light'
|
||
icon={<RefreshCw size={14} />}
|
||
loading={loading}
|
||
onClick={fetchList}
|
||
>
|
||
{t('刷新')}
|
||
</Button>
|
||
<Button
|
||
theme='solid'
|
||
icon={<Plus size={14} />}
|
||
onClick={() => openCreate(0)}
|
||
>
|
||
{t('新建顶级部门')}
|
||
</Button>
|
||
</>
|
||
}
|
||
/>
|
||
|
||
<OrgPanel padding='p-0'>
|
||
<div className='h-[calc(100vh-270px)] min-h-[480px]'>
|
||
{!loaded && loading ? (
|
||
<div className='flex h-full items-center justify-center'>
|
||
<Spin size='large' />
|
||
</div>
|
||
) : list.length === 0 ? (
|
||
<div className='flex h-full items-center justify-center'>
|
||
<Empty
|
||
description={t('暂无部门,创建第一个部门开始搭建组织架构')}
|
||
>
|
||
<Button
|
||
theme='solid'
|
||
icon={<Plus size={14} />}
|
||
onClick={() => openCreate(0)}
|
||
>
|
||
{t('新建顶级部门')}
|
||
</Button>
|
||
</Empty>
|
||
</div>
|
||
) : (
|
||
<DeptFlowCanvas
|
||
orgId={orgId}
|
||
depts={list}
|
||
members={members}
|
||
budgets={budgetEnforced === false ? [] : budgets}
|
||
direction={direction}
|
||
onDirectionChange={setDirection}
|
||
colorMode={actualTheme === 'dark' ? 'dark' : 'light'}
|
||
onAddChild={handleAddChild}
|
||
onEdit={openEdit}
|
||
onDelete={handleDelete}
|
||
onMove={handleMove}
|
||
onSaved={fetchList}
|
||
/>
|
||
)}
|
||
</div>
|
||
</OrgPanel>
|
||
|
||
<OrgModal
|
||
title={editing ? t('编辑部门') : t('新建部门')}
|
||
visible={modalVisible}
|
||
onOk={handleSubmit}
|
||
onCancel={() => setModalVisible(false)}
|
||
okText={t('保存')}
|
||
cancelText={t('取消')}
|
||
confirmLoading={saving}
|
||
>
|
||
{parentMemberCount > 0 && (
|
||
<Banner
|
||
type='info'
|
||
closeIcon={null}
|
||
className='mb-3'
|
||
description={t(
|
||
'所选上级部门已有 {{n}} 名直属成员,新增下级后建议将这些成员迁移到末级部门',
|
||
{ n: parentMemberCount },
|
||
)}
|
||
/>
|
||
)}
|
||
<Form
|
||
getFormApi={setFormApi}
|
||
onValueChange={(values) =>
|
||
setModalParentId((prev) => values.parent_id ?? prev)
|
||
}
|
||
>
|
||
<Form.Input
|
||
field='name'
|
||
label={t('部门名称')}
|
||
rules={[{ required: true, message: t('请输入部门名称') }]}
|
||
/>
|
||
<Form.TreeSelect
|
||
field='parent_id'
|
||
label={t('上级部门')}
|
||
treeData={parentTreeData}
|
||
filterTreeNode
|
||
showFilteredOnly
|
||
expandAll
|
||
style={{ width: '100%' }}
|
||
/>
|
||
<Form.InputNumber
|
||
field='sort'
|
||
label={t('排序')}
|
||
style={{ width: '100%' }}
|
||
/>
|
||
{editing && (
|
||
<Form.Select
|
||
field='status'
|
||
label={t('状态')}
|
||
optionList={[
|
||
{ label: t('启用'), value: 1 },
|
||
{ label: t('停用'), value: 2 },
|
||
]}
|
||
style={{ width: '100%' }}
|
||
/>
|
||
)}
|
||
</Form>
|
||
</OrgModal>
|
||
</div>
|
||
);
|
||
};
|
||
|
||
export default OrgDepartments;
|