Files
monkey-ai-web/src/pages/Organization/fund/OrgDeptFunds.jsx
T
qiubaishen db3dba1e96 sync: 同步 monkey-ai@weiyuan(ddc5b9443) 的 web/ 到 ui-optimization
- 合入 weiyuan 新功能前端:分佣 V2 / 伙伴工作台、智能路由、企业资金与分析、官网设置与预约演示等,
  semi-ui 已全部迁移到 antd 6 / @/components/ui,不重新引入 Semi
- 分佣二级菜单与页头去重、伙伴入口探测(企业伙伴走企业中心「企业分佣」)、超管侧栏入口恢复
- 适配层 DatePicker / TimePicker 统一 onChange(Date|Date[]|null, 文本) 契约;生产构建剔除调试日志
- 图片链接刷新:同任务请求复用、后台刷新不弹全局错误、离页停止批量请求
- 恢复 bun.lock(与 package-lock.json 共存);docs 规范与 CHANGELOG 更新
- 停止跟踪 .env.playwright.local(本地登录凭据,已加入 .gitignore)
2026-11-18 10:22:02 +08:00

549 lines
18 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,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { Alert, Button, Switch, Tag, Typography } from 'antd';
import { Building2, Layers, PiggyBank, Power, Wallet } from 'lucide-react';
import Table from '../../../components/ui/CenterActionTable';
// 流水入口:ActionIcons 无 ScrollText,使用账本语义的 ReceiptText
import { ReceiptText as ScrollText } from '@/components/common/icons/ActionIcons';
import OrgPanel from '../components/OrgPanel';
import OrgStatCard from '../components/OrgStatCard';
import OrgStateBlock from '../components/OrgStateBlock';
import OrgModal from '../components/OrgModal';
import { OrgRowActions } from '../components/OrgListCard';
import { showError, showSuccess } from '../../../helpers/utils';
import { renderQuota } from '../../../helpers/render';
import { orgFundApi } from './fundApi';
import { FUND_ACCOUNT_STATUS, FUND_STATE, buildFundTree } from './fundFormat';
import FundTransferModal from './FundTransferModal';
import FundLedgerSheet from './FundLedgerSheet';
const { Text } = Typography;
// 每行自身账户四项指标(F-26):不混入子部门
const metricCell = (v) => (
<span className='tabular-nums'>{renderQuota(v || 0, 2)}</span>
);
/**
* 预算中心 → 部门资金(企业管理员)。
* 资金操作固定为“企业未分配户 ↔ 所选部门”(AUTH-01);分配与回收不改变企业总剩余。
*/
const OrgDeptFunds = ({ orgId }) => {
const { t } = useTranslation();
const navigate = useNavigate();
const [overview, setOverview] = useState(null);
const [rows, setRows] = useState([]);
const [archived, setArchived] = useState([]);
const [includeArchived, setIncludeArchived] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [toggling, setToggling] = useState(false);
const [transfer, setTransfer] = useState(null); // { mode, row }
const [ledgerAccount, setLedgerAccount] = useState(null);
const state = overview?.fund_state ?? FUND_STATE.NEVER;
const established = state !== FUND_STATE.NEVER;
const operable = state === FUND_STATE.ON;
// 资金数据异常(4.8):提示并禁用分配回收,服务端同样拦截
const anomaly = !!overview?.anomaly;
const canTransfer = operable && !anomaly;
const [accountsError, setAccountsError] = useState(false);
// 快速切换“包含已归档部门”等会并发多次加载:只采纳最新一次
const seqRef = useRef(0);
const load = useCallback(async () => {
if (!orgId) return;
const seq = ++seqRef.current;
setLoading(true);
setError('');
try {
const ov = await orgFundApi.overview(orgId);
if (seq !== seqRef.current) return;
if (!ov?.data?.success) {
setError(ov?.data?.message || t('加载失败,请重试'));
return;
}
let nextRows = [];
let nextArchived = [];
let accErr = false;
if (ov.data.data?.fund_state !== FUND_STATE.NEVER) {
try {
const ac = await orgFundApi.accounts(orgId, includeArchived);
if (ac?.data?.success) {
nextRows = ac.data.data?.departments || [];
nextArchived = ac.data.data?.archived || [];
} else accErr = true;
} catch {
accErr = true;
}
if (seq !== seqRef.current) return;
}
// 概览与账户列表一起落地;列表失败时显示错误态,不用空列表冒充“没有数据”(4.8)
setOverview(ov.data.data);
setRows(nextRows);
setArchived(nextArchived);
setAccountsError(accErr);
} catch {
if (seq === seqRef.current) setError(t('加载失败,请重试'));
} finally {
if (seq === seqRef.current) setLoading(false);
}
}, [orgId, includeArchived, t]);
useEffect(() => {
load();
}, [load]);
const tree = useMemo(() => buildFundTree(rows), [rows]);
// 稳定引用:流水抽屉的加载回调依赖它,内联箭头函数会让抽屉每次渲染都重新请求
const fetchLedger = useCallback(
(id, params) => orgFundApi.ledger(orgId, id, params),
[orgId],
);
const unallocated = overview?.unallocated;
const confirmEnable = () => {
const first = state === FUND_STATE.NEVER;
OrgModal.confirm({
title: first ? t('开启部门资金管理') : t('重新开启部门资金管理'),
content: first
? t(
'开启后,有部门的成员将使用所属部门资金。各部门初始可用余额为 0,分配资金前将无法调用模型;未归属部门的成员继续使用企业未分配资金。是否开启?',
)
: t(
'将沿用原部门账户及历史数据。请在开启后重新分配资金,余额不足的部门成员将无法调用模型。',
),
okText: t('确认开启'),
cancelText: t('取消'),
onOk: async () => {
setToggling(true);
try {
const res = await orgFundApi.enable(orgId);
if (res?.data?.success) {
showSuccess(
first
? t('部门资金管理已开启,请分配部门资金')
: t('部门资金管理已开启'),
);
load();
} else {
showError(res?.data?.message || t('操作失败,请重试'));
}
} catch {
showError(t('操作失败,请重试'));
} finally {
setToggling(false);
}
},
});
};
const tryDisable = async () => {
setToggling(true);
try {
const res = await orgFundApi.closeCheck(orgId);
if (!res?.data?.success) {
showError(res?.data?.message || t('加载失败,请重试'));
return;
}
const check = res.data.data || {};
if (check.depts_with_balance > 0) {
OrgModal.warning({
title: t('关闭部门资金管理'),
content: t(
'暂不能关闭:仍有 {{n}} 个部门存在可用余额,请逐个回收后重试。',
{ n: check.depts_with_balance },
),
okText: t('知道了'),
hasCancel: false,
});
return;
}
if (check.pending_consumption > 0) {
OrgModal.warning({
title: t('关闭部门资金管理'),
content: t('仍有消费正在结算,请稍后重试'),
okText: t('知道了'),
hasCancel: false,
});
return;
}
OrgModal.confirm({
title: t('关闭部门资金管理'),
content: t(
'关闭后,所有成员统一使用企业未分配资金,现有预算限额继续生效。部门账户和历史记录将保留。是否关闭?',
),
okText: t('确认关闭'),
cancelText: t('取消'),
onOk: async () => {
try {
const r = await orgFundApi.disable(orgId);
if (r?.data?.success) {
showSuccess(t('部门资金管理已关闭'));
} else {
showError(r?.data?.message || t('操作失败,请重试'));
}
} catch {
showError(t('操作失败,请重试'));
} finally {
load();
}
},
});
} catch {
showError(t('加载失败,请重试'));
} finally {
setToggling(false);
}
};
const statusTag = (row) => {
if (row.account?.status === FUND_ACCOUNT_STATUS.ARCHIVED)
return <Tag variant='filled'>{t('已归档')}</Tag>;
if (row.dept_status === 2)
return (
<Tag color='default' variant='filled'>
{t('已停用')}
</Tag>
);
return null;
};
const columns = [
{
title: t('部门'),
dataIndex: 'name',
render: (v, r) => (
<span className='inline-flex items-center gap-1.5 min-w-0'>
<span className='truncate max-w-[240px]' title={r.pathLabel || v}>
{v}
</span>
{statusTag(r)}
</span>
),
},
{
title: t('累计转入'),
width: 130,
align: 'right',
render: (_, r) => metricCell(r.account?.total_in),
},
{
title: t('累计转出'),
width: 130,
align: 'right',
render: (_, r) => metricCell(r.account?.total_out),
},
{
title: t('累计消耗'),
width: 130,
align: 'right',
render: (_, r) => metricCell(r.account?.total_consumed),
},
{
title: t('可用余额'),
width: 140,
align: 'right',
render: (_, r) => (
<span className='tabular-nums font-semibold'>
{renderQuota(r.account?.balance || 0, 2)}
</span>
),
},
{
title: t('操作'),
width: 220,
fixed: 'right',
render: (_, r) => {
const isArchived = r.account?.status === FUND_ACCOUNT_STATUS.ARCHIVED;
return (
<OrgRowActions>
{canTransfer && !isArchived && (
<>
<Button
size='small'
type='link'
disabled={r.dept_status === 2}
onClick={() => setTransfer({ mode: 'allocate', row: r })}
>
{t('分配')}
</Button>
<Button
size='small'
type='link'
onClick={() => setTransfer({ mode: 'recall', row: r })}
>
{t('回收')}
</Button>
</>
)}
{r.account && (
<Button
size='small'
type='link'
onClick={() =>
setLedgerAccount({ id: r.account.id, name: r.name })
}
>
{t('流水')}
</Button>
)}
</OrgRowActions>
);
},
},
];
const archivedRows = archived.map((a) => ({
key: `archived-${a.id}`,
name: a.name,
account: a,
dept_status: 2,
}));
if (error && !overview) {
return (
<OrgStateBlock
title={t('加载失败,请重试')}
description={error}
action={<Button onClick={load}>{t('重试')}</Button>}
/>
);
}
if (!overview) return <OrgStateBlock loading />;
const transferRow = transfer?.row;
const isRecall = transfer?.mode === 'recall';
return (
<div className='flex flex-col gap-4'>
<OrgPanel
icon={Power}
title={t('部门资金管理')}
subtitle={
established
? `${t('分配与回收不改变企业总剩余;资金与预算限额分别计算')} ${t('资金余额为 0 时无法继续消费;预算上限为 0 表示不限')}`
: t(
'开启后,可将企业资金分配给部门独立使用。未开启时,所有成员继续使用企业资金池,现有预算限额仍生效。',
)
}
actions={
<div className='flex items-center gap-2'>
<Tag color={operable ? 'success' : 'default'} variant='filled'>
{operable ? t('已开启') : t('未开启')}
</Tag>
{operable ? (
<Button danger loading={toggling} onClick={tryDisable}>
{t('关闭')}
</Button>
) : (
<Button type='primary' loading={toggling} onClick={confirmEnable}>
{state === FUND_STATE.OFF ? t('重新开启') : t('开启')}
</Button>
)}
</div>
}
>
<div className='grid grid-cols-1 sm:grid-cols-3 gap-3'>
<OrgStatCard
icon={Wallet}
label={t('企业总剩余')}
value={renderQuota(overview.enterprise_total || 0, 2)}
hint={t('主池 {{main}} · 赠送 {{gift}}', {
main: renderQuota(overview.quota || 0, 2),
gift: renderQuota(overview.gift_quota || 0, 2),
})}
/>
{established && (
<>
<OrgStatCard
icon={PiggyBank}
tone='amber'
label={t('企业未分配可用')}
value={renderQuota(unallocated?.balance || 0, 2)}
hint={
unallocated ? (
<Button
size='small'
type='link'
icon={<ScrollText size={16} />}
onClick={() =>
setLedgerAccount({
id: unallocated.id,
name: t('企业未分配户'),
})
}
>
{t('查看流水')}
</Button>
) : null
}
/>
<OrgStatCard
icon={Layers}
tone='sky'
label={t('部门可用合计')}
value={renderQuota(overview.dept_available_sum || 0, 2)}
/>
</>
)}
</div>
{error && (
<div className='mt-3 flex items-center gap-2 text-xs'>
<Typography.Text type='danger' className='text-xs'>
{t('数据刷新失败,请重试')}
</Typography.Text>
<Button size='small' type='link' onClick={load}>
{t('重试')}
</Button>
</div>
)}
</OrgPanel>
{anomaly && (
<Alert
type='error'
showIcon
title={t('资金数据异常,请联系平台管理员')}
/>
)}
{state === FUND_STATE.OFF && (
<Alert
type='info'
showIcon
title={t(
'部门资金管理未开启,当前统一使用企业资金。可查看原资金账户与流水,不能分配或回收。',
)}
/>
)}
{established && (
<OrgPanel
icon={Building2}
title={t('部门账户')}
subtitle={t(
'每行仅统计该部门自身账户,不含子部门;回收只回收所选部门自身余额。',
)}
actions={
<span className='inline-flex items-center gap-2 text-sm'>
<Switch
size='small'
checked={includeArchived}
onChange={setIncludeArchived}
aria-label={t('包含已归档部门')}
/>
<Text className='text-xs'>{t('包含已归档部门')}</Text>
</span>
}
padding='p-2'
>
{accountsError ? (
<OrgStateBlock
title={t('加载失败,请重试')}
action={<Button onClick={load}>{t('重试')}</Button>}
/>
) : overview.department_count === 0 && rows.length === 0 ? (
<OrgStateBlock
title={t('暂无部门,请先在部门管理中创建部门')}
action={
<Button onClick={() => navigate('/org/departments')}>
{t('前往部门管理')}
</Button>
}
/>
) : (
<Table
key={`${includeArchived}-${rows.length}-${archived.length}`}
columns={columns}
dataSource={[...tree, ...(includeArchived ? archivedRows : [])]}
loading={loading}
rowKey='key'
pagination={false}
expandable={{ defaultExpandAllRows: true }}
size='middle'
scroll={{ x: 900 }}
/>
)}
</OrgPanel>
)}
<FundTransferModal
visible={!!transfer}
mode={transfer?.mode}
sourceLabel={
isRecall
? transferRow?.pathLabel || transferRow?.name
: t('企业未分配户')
}
targetLabel={
isRecall
? t('企业未分配户')
: transferRow?.pathLabel || transferRow?.name
}
sourceBalance={
isRecall
? transferRow?.account?.balance || 0
: unallocated?.balance || 0
}
targetBalance={
isRecall
? unallocated?.balance || 0
: transferRow?.account?.balance || 0
}
submit={(body) =>
isRecall
? orgFundApi.recall(orgId, {
...body,
dept_id: transferRow.department_id,
})
: orgFundApi.allocate(orgId, {
...body,
dept_id: transferRow.department_id,
})
}
lookup={(opId) => orgFundApi.transfer(orgId, opId)}
onClose={() => setTransfer(null)}
onDone={load}
/>
<FundLedgerSheet
key={ledgerAccount?.id || 'closed'}
visible={!!ledgerAccount}
account={ledgerAccount}
fetchLedger={fetchLedger}
onClose={() => setLedgerAccount(null)}
/>
</div>
);
};
export default OrgDeptFunds;