| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393 |
- 'use client';
- import { useEffect, useMemo, useState } from 'react';
- import {
- FileText,
- Plus,
- RefreshCw,
- Search,
- Download,
- Upload,
- SlidersHorizontal,
- Layers,
- CheckCircle2,
- X,
- } from 'lucide-react';
- import { toast } from 'react-hot-toast';
- import { retroConfirm } from '@/lib/dialog';
- import ConfigurationTable from '@/components/admin/configurations/ConfigurationTable';
- import ConfigurationModal from '@/components/admin/configurations/ConfigurationModal';
- import ConfigurationDetailDrawer from '@/components/admin/configurations/ConfigurationDetailDrawer';
- import ConfigurationExportModal from '@/components/admin/configurations/ConfigurationExportModal';
- import ConfigurationImportModal from '@/components/admin/configurations/ConfigurationImportModal';
- import { DynamicConfiguration } from '@/types';
- import { configService } from '@/lib/services';
- function normalizeConfig(item: Partial<DynamicConfiguration>): DynamicConfiguration {
- let val = '';
- if (item.config_value !== null && item.config_value !== undefined) {
- if (typeof item.config_value === 'string') {
- val = item.config_value;
- } else {
- try {
- val = JSON.stringify(item.config_value, null, 2);
- } catch {
- val = String(item.config_value);
- }
- }
- }
- return {
- id: item.id || 0,
- config_key: String(item.config_key || ''),
- config_value: val,
- description: String(item.description || ''),
- type: String(item.type || ''),
- created_at: item.created_at,
- updated_at: item.updated_at,
- };
- }
- export default function AdminConfigurationsPage() {
- const [configs, setConfigs] = useState<DynamicConfiguration[]>([]);
- const [loading, setLoading] = useState(true);
- const [keyword, setKeyword] = useState('');
- const [selectedType, setSelectedType] = useState<string>('all');
- const [keyLookup, setKeyLookup] = useState('');
- const [isModalOpen, setModalOpen] = useState(false);
- const [isDrawerOpen, setDrawerOpen] = useState(false);
- const [isExportModalOpen, setExportModalOpen] = useState(false);
- const [isImportModalOpen, setImportModalOpen] = useState(false);
- const [activeConfig, setActiveConfig] = useState<DynamicConfiguration | null>(null);
- const fetchConfigs = async () => {
- setLoading(true);
- try {
- const res = await configService.getAll();
- const list = res?.data || [];
- setConfigs(Array.isArray(list) ? list.map(normalizeConfig) : []);
- } catch (e: any) {
- toast.error('读取配置失败: ' + (e.response?.data?.message || e.message || '未知错误'));
- setConfigs([]);
- } finally {
- setLoading(false);
- }
- };
- useEffect(() => {
- fetchConfigs();
- }, []);
- const handleLookupByKey = async () => {
- const targetKey = keyLookup.trim();
- if (!targetKey) {
- toast.error('请输入要查询的配置 Key');
- return;
- }
- setLoading(true);
- try {
- const res = await configService.getByKey(targetKey);
- const item = res?.data;
- if (item) {
- setConfigs([normalizeConfig(item)]);
- toast.success(`找到配置 "${targetKey}"`);
- } else {
- toast.error(`未找到 Key 为 "${targetKey}" 的配置`);
- setConfigs([]);
- }
- } catch (e: any) {
- toast.error('查询失败: ' + (e.response?.data?.message || e.message || '未知错误'));
- } finally {
- setLoading(false);
- }
- };
- const handleResetSearch = () => {
- setKeyword('');
- setSelectedType('all');
- setKeyLookup('');
- fetchConfigs();
- };
- const filteredConfigs = useMemo(() => {
- const q = keyword.trim().toLowerCase();
- return configs.filter((c) => {
- const configKey = String(c.config_key || '').toLowerCase();
- const desc = String(c.description || '').toLowerCase();
- const configVal = String(c.config_value || '').toLowerCase();
- const configType = String(c.type || '').toLowerCase();
- const matchKeyword =
- !q ||
- configKey.includes(q) ||
- desc.includes(q) ||
- configVal.includes(q) ||
- configType.includes(q);
- const valTrimmed = String(c.config_value || '').trim();
- const isJson = valTrimmed.startsWith('{') || valTrimmed.startsWith('[');
- const computedType = (c.type || (isJson ? 'json' : 'string')).toLowerCase();
- const matchType =
- selectedType === 'all' ||
- (selectedType === 'json' && (computedType === 'json' || isJson)) ||
- (selectedType === 'string' && (computedType === 'string' || computedType === 'text')) ||
- (selectedType === 'boolean' && computedType === 'boolean') ||
- (selectedType === 'number' && computedType === 'number');
- return matchKeyword && matchType;
- });
- }, [configs, keyword, selectedType]);
- const stats = useMemo(() => {
- const total = configs.length;
- let jsonCount = 0;
- let stringCount = 0;
- configs.forEach((c) => {
- const valTrimmed = String(c.config_value || '').trim();
- const isJson = valTrimmed.startsWith('{') || valTrimmed.startsWith('[');
- if (isJson || (c.type && c.type.toLowerCase() === 'json')) {
- jsonCount++;
- } else {
- stringCount++;
- }
- });
- return { total, jsonCount, stringCount };
- }, [configs]);
- const handleOpenCreate = () => {
- setActiveConfig(null);
- setModalOpen(true);
- };
- const handleOpenEdit = (config: DynamicConfiguration) => {
- setActiveConfig(config);
- setModalOpen(true);
- };
- const handleOpenDetails = (config: DynamicConfiguration) => {
- setActiveConfig(config);
- setDrawerOpen(true);
- };
- const handleDelete = async (config: DynamicConfiguration) => {
- const ok = await retroConfirm({
- title: '[ CONFIRM // 永久删除配置项 ]',
- message: `警告:确定要永久删除配置项 "${config.config_key}" 吗?此操作不可撤销!`,
- type: 'danger',
- confirmText: '[ 确认删除 ]',
- });
- if (!ok) return;
- try {
- await configService.delete(config.config_key);
- toast.success(`配置 "${config.config_key}" 已删除`);
- fetchConfigs();
- } catch (e: any) {
- toast.error('删除失败: ' + (e.response?.data?.message || e.message || '未知错误'));
- }
- };
- return (
- <div className="space-y-6 font-mono">
- {/* 顶部标头 */}
- <div className="bg-neutral-100 border-2 border-black p-6 shadow-[6px_6px_0px_#000] flex flex-col md:flex-row md:items-center justify-between gap-4">
- <div>
- <div className="text-[10px] font-bold text-neutral-500 uppercase tracking-widest">[ DYNAMIC-CONFIGS // 系统变量热加载 ]</div>
- <h1 className="text-xl sm:text-2xl font-black text-black uppercase mt-1">动态系统配置与环境变量中枢</h1>
- <p className="text-xs text-neutral-600 font-sans mt-0.5">
- 热更新全局汇率、通知网关秘钥、业务开关及限流规则,无需重启服务器即时生效。
- </p>
- </div>
- {/* 顶部右侧主要操作 */}
- <div className="flex flex-wrap items-center gap-2">
- <button
- onClick={fetchConfigs}
- disabled={loading}
- className="p-2 bg-neutral-50 hover:bg-neutral-200 border-2 border-black text-black transition shadow-[2px_2px_0px_#000]"
- title="刷新配置列表"
- >
- <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
- </button>
- <button
- onClick={() => setExportModalOpen(true)}
- className="flex items-center gap-1.5 px-3 py-1.5 bg-white hover:bg-neutral-100 text-black border-2 border-black font-bold text-xs shadow-[2px_2px_0px_#000] uppercase"
- >
- <Download size={13} />
- <span>[ 导出 ]</span>
- </button>
- <button
- onClick={() => setImportModalOpen(true)}
- className="flex items-center gap-1.5 px-3 py-1.5 bg-white hover:bg-neutral-100 text-black border-2 border-black font-bold text-xs shadow-[2px_2px_0px_#000] uppercase"
- >
- <Upload size={13} />
- <span>[ 导入 ]</span>
- </button>
- <button
- onClick={handleOpenCreate}
- className="flex items-center gap-1.5 px-4 py-1.5 bg-amber-300 hover:bg-amber-400 text-black border-2 border-black font-black text-xs shadow-[2px_2px_0px_#000] uppercase whitespace-nowrap"
- >
- <Plus size={14} />
- <span>[ 新建配置项 ]</span>
- </button>
- </div>
- </div>
- {/* 2. 统计指标卡片 */}
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5">
- <div className="bg-white border-2 border-black p-4 shadow-[4px_4px_0px_#000] flex flex-col justify-between space-y-1">
- <div className="flex items-center justify-between border-b-2 border-black pb-1.5">
- <span className="text-[10px] font-black uppercase text-black">[ 全局配置项总数 ]</span>
- <SlidersHorizontal size={14} className="text-black" />
- </div>
- <div className="text-2xl font-black text-black">{stats.total} 个</div>
- <div className="text-[10px] text-neutral-500 font-sans">热加载系统环境</div>
- </div>
- <div className="bg-white border-2 border-black p-4 shadow-[4px_4px_0px_#000] flex flex-col justify-between space-y-1">
- <div className="flex items-center justify-between border-b-2 border-black pb-1.5">
- <span className="text-[10px] font-black uppercase text-black">[ JSON 结构化变量 ]</span>
- <Layers size={14} className="text-black" />
- </div>
- <div className="text-2xl font-black text-black">{stats.jsonCount} 个</div>
- <div className="text-[10px] text-neutral-500 font-sans">包含复杂对象/列表结构</div>
- </div>
- <div className="bg-white border-2 border-black p-4 shadow-[4px_4px_0px_#000] flex flex-col justify-between space-y-1">
- <div className="flex items-center justify-between border-b-2 border-black pb-1.5">
- <span className="text-[10px] font-black uppercase text-black">[ 基础标量参数 ]</span>
- <FileText size={14} className="text-black" />
- </div>
- <div className="text-2xl font-black text-black">{stats.stringCount} 个</div>
- <div className="text-[10px] text-neutral-500 font-sans">字符串 / 数值 / 开关</div>
- </div>
- </div>
- {/* 3. 搜索与筛选工具栏 */}
- <div className="bg-white border-2 border-black p-4 shadow-[4px_4px_0px_#000] space-y-3">
- <div className="flex flex-col md:flex-row items-center justify-between gap-3">
- <div className="relative flex-1 w-full">
- <input
- type="text"
- placeholder="搜索配置 Key / 作用描述 / Value 内容..."
- className="w-full pl-9 pr-24 py-2 border-2 border-black bg-neutral-50 text-xs font-mono focus:bg-white outline-none shadow-[2px_2px_0px_#000] text-black"
- value={keyword}
- onChange={(e) => setKeyword(e.target.value)}
- />
- <Search size={14} className="absolute left-3 top-2.5 text-black pointer-events-none" />
- <div className="absolute right-2.5 top-2 flex items-center gap-1.5">
- {keyword && (
- <button
- onClick={() => setKeyword('')}
- className="text-black hover:text-rose-600 font-bold px-1 text-xs"
- title="清空输入"
- >
- ✕
- </button>
- )}
- {keyword && (
- <span className="text-[10px] font-mono font-bold bg-amber-300 px-1 border border-black text-black">
- {filteredConfigs.length} 项
- </span>
- )}
- </div>
- </div>
- <div className="flex items-center gap-2 w-full md:w-auto">
- <select
- value={selectedType}
- onChange={(e) => setSelectedType(e.target.value)}
- className="px-3 py-2 border-2 border-black bg-neutral-50 text-xs font-bold text-black outline-none shadow-[2px_2px_0px_#000]"
- >
- <option value="all">[ 全部数据类型 ]</option>
- <option value="json">JSON 结构体</option>
- <option value="string">文本 (String)</option>
- <option value="boolean">布尔 (Boolean)</option>
- <option value="number">数值 (Number)</option>
- </select>
- </div>
- </div>
- {/* 按 Key 直达查询 */}
- <div className="pt-2 border-t-2 border-dashed border-neutral-300 flex flex-col sm:flex-row items-center gap-2">
- <span className="text-xs font-bold text-black uppercase shrink-0">[ KEY 直达查询 ]:</span>
- <input
- type="text"
- placeholder="精确输入配置 KEY,如 EXCHANGE_RATES..."
- value={keyLookup}
- onChange={(e) => setKeyLookup(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && handleLookupByKey()}
- className="flex-1 border-2 border-black bg-neutral-50 px-3 py-1.5 text-xs font-mono focus:bg-white outline-none shadow-[1px_1px_0px_#000] text-black w-full"
- />
- <button
- onClick={handleLookupByKey}
- className="px-4 py-1.5 bg-black text-white hover:bg-neutral-800 border-2 border-black font-bold text-xs shadow-[2px_2px_0px_#000] uppercase"
- >
- [ 精确调取 ]
- </button>
- {(keyword || selectedType !== 'all' || keyLookup) && (
- <button
- onClick={handleResetSearch}
- className="px-3 py-1.5 bg-neutral-100 hover:bg-neutral-200 border-2 border-black text-black font-bold text-xs uppercase"
- >
- [ 重置查询 ]
- </button>
- )}
- </div>
- </div>
- {/* 4. 配置数据表格 */}
- <ConfigurationTable
- configs={filteredConfigs}
- loading={loading}
- onEdit={handleOpenEdit}
- onViewDetails={handleOpenDetails}
- onDelete={handleDelete}
- />
- {/* 5. 新建 / 编辑弹窗 */}
- <ConfigurationModal
- isOpen={isModalOpen}
- onClose={() => setModalOpen(false)}
- config={activeConfig}
- onSuccess={fetchConfigs}
- />
- {/* 6. 详情查阅抽屉 */}
- <ConfigurationDetailDrawer
- isOpen={isDrawerOpen}
- onClose={() => setDrawerOpen(false)}
- config={activeConfig}
- onEdit={(cfg) => {
- setDrawerOpen(false);
- handleOpenEdit(cfg);
- }}
- onDelete={handleDelete}
- />
- {/* 7. 导出配置弹窗 */}
- <ConfigurationExportModal
- isOpen={isExportModalOpen}
- onClose={() => setExportModalOpen(false)}
- configs={configs}
- />
- {/* 8. 导入配置弹窗 */}
- <ConfigurationImportModal
- isOpen={isImportModalOpen}
- onClose={() => setImportModalOpen(false)}
- existingKeys={configs.map((c) => c.config_key)}
- onSuccess={fetchConfigs}
- />
- </div>
- );
- }
|