/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import 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) => ( {renderQuota(v || 0, 2)} ); /** * 预算中心 → 部门资金(企业管理员)。 * 资金操作固定为“企业未分配户 ↔ 所选部门”(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 {t('已归档')}; if (row.dept_status === 2) return ( {t('已停用')} ); return null; }; const columns = [ { title: t('部门'), dataIndex: 'name', render: (v, r) => ( {v} {statusTag(r)} ), }, { 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) => ( {renderQuota(r.account?.balance || 0, 2)} ), }, { title: t('操作'), width: 220, fixed: 'right', render: (_, r) => { const isArchived = r.account?.status === FUND_ACCOUNT_STATUS.ARCHIVED; return ( {canTransfer && !isArchived && ( <> )} {r.account && ( )} ); }, }, ]; const archivedRows = archived.map((a) => ({ key: `archived-${a.id}`, name: a.name, account: a, dept_status: 2, })); if (error && !overview) { return ( {t('重试')}} /> ); } if (!overview) return ; const transferRow = transfer?.row; const isRecall = transfer?.mode === 'recall'; return (
{operable ? t('已开启') : t('未开启')} {operable ? ( ) : ( )}
} >
{established && ( <> } onClick={() => setLedgerAccount({ id: unallocated.id, name: t('企业未分配户'), }) } > {t('查看流水')} ) : null } /> )}
{error && (
{t('数据刷新失败,请重试')}
)} {anomaly && ( )} {state === FUND_STATE.OFF && ( )} {established && ( {t('包含已归档部门')} } padding='p-2' > {accountsError ? ( {t('重试')}} /> ) : overview.department_count === 0 && rows.length === 0 ? ( navigate('/org/departments')}> {t('前往部门管理')} } /> ) : ( )} )} 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} /> setLedgerAccount(null)} /> ); }; export default OrgDeptFunds;