/*
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, { useContext, useEffect, useState, useRef } from 'react';
import { Banner, Button, Card, Checkbox, Form, Spin } from '@/components/ui';
import { API, isRoot, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
import {
ADMIN_DELEGATION_OPTIONS,
ADMIN_DELEGATION_OPTION_KEY as OPTION_KEY,
} from '../../../constants/settingTabs';
import { parseAdminDelegation } from '../../../helpers/adminDelegation';
import { StatusContext } from '../../../context/Status';
export default function SettingsAdminDelegation(props) {
const { t } = useTranslation();
const [statusState, statusDispatch] = useContext(StatusContext);
const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState([]);
const [savedRaw, setSavedRaw] = useState('');
const refForm = useRef();
useEffect(() => {
const raw = props.options?.[OPTION_KEY] ?? '';
setSavedRaw(raw);
const tabs = parseAdminDelegation(raw);
setSelected(tabs);
refForm.current?.setValues({ [OPTION_KEY]: tabs });
}, [props.options]);
// 该配置项属于权限下放的「控制开关」,仅超级管理员可见可改(后端亦强制 root-only)。
if (!isRoot()) {
return null;
}
function onSubmit() {
const value = JSON.stringify(selected);
if (value === JSON.stringify(parseAdminDelegation(savedRaw))) {
showSuccess(t('保存成功'));
return;
}
setLoading(true);
API.put('/api/option/', { key: OPTION_KEY, value })
.then((res) => {
const { success, message } = res.data;
if (success) {
setSavedRaw(value);
statusDispatch({
type: 'set',
payload: { ...statusState?.status, [OPTION_KEY]: value },
});
showSuccess(t('保存成功'));
props.refresh?.();
} else {
showError(message);
}
})
.catch(() => {
showError(t('保存失败,请重试'));
})
.finally(() => {
setLoading(false);
});
}
return (
{
const unknown = parseAdminDelegation(savedRaw).filter(
(key) =>
!ADMIN_DELEGATION_OPTIONS.some((item) => item.key === key),
);
setSelected([...new Set([...unknown, ...value])]);
}}
>
{ADMIN_DELEGATION_OPTIONS.map((tab) => (
{t(tab.labelKey)}
))}
);
}