page.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. 'use client';
  2. import { useEffect, useMemo, useState } from 'react';
  3. import {
  4. FileText,
  5. Plus,
  6. RefreshCw,
  7. Search,
  8. Download,
  9. Upload,
  10. SlidersHorizontal,
  11. Layers,
  12. CheckCircle2,
  13. X,
  14. } from 'lucide-react';
  15. import { toast } from 'react-hot-toast';
  16. import { retroConfirm } from '@/lib/dialog';
  17. import ConfigurationTable from '@/components/admin/configurations/ConfigurationTable';
  18. import ConfigurationModal from '@/components/admin/configurations/ConfigurationModal';
  19. import ConfigurationDetailDrawer from '@/components/admin/configurations/ConfigurationDetailDrawer';
  20. import ConfigurationExportModal from '@/components/admin/configurations/ConfigurationExportModal';
  21. import ConfigurationImportModal from '@/components/admin/configurations/ConfigurationImportModal';
  22. import { DynamicConfiguration } from '@/types';
  23. import { configService } from '@/lib/services';
  24. function normalizeConfig(item: Partial<DynamicConfiguration>): DynamicConfiguration {
  25. let val = '';
  26. if (item.config_value !== null && item.config_value !== undefined) {
  27. if (typeof item.config_value === 'string') {
  28. val = item.config_value;
  29. } else {
  30. try {
  31. val = JSON.stringify(item.config_value, null, 2);
  32. } catch {
  33. val = String(item.config_value);
  34. }
  35. }
  36. }
  37. return {
  38. id: item.id || 0,
  39. config_key: String(item.config_key || ''),
  40. config_value: val,
  41. description: String(item.description || ''),
  42. type: String(item.type || ''),
  43. created_at: item.created_at,
  44. updated_at: item.updated_at,
  45. };
  46. }
  47. export default function AdminConfigurationsPage() {
  48. const [configs, setConfigs] = useState<DynamicConfiguration[]>([]);
  49. const [loading, setLoading] = useState(true);
  50. const [keyword, setKeyword] = useState('');
  51. const [selectedType, setSelectedType] = useState<string>('all');
  52. const [keyLookup, setKeyLookup] = useState('');
  53. const [isModalOpen, setModalOpen] = useState(false);
  54. const [isDrawerOpen, setDrawerOpen] = useState(false);
  55. const [isExportModalOpen, setExportModalOpen] = useState(false);
  56. const [isImportModalOpen, setImportModalOpen] = useState(false);
  57. const [activeConfig, setActiveConfig] = useState<DynamicConfiguration | null>(null);
  58. const fetchConfigs = async () => {
  59. setLoading(true);
  60. try {
  61. const res = await configService.getAll();
  62. const list = res?.data || [];
  63. setConfigs(Array.isArray(list) ? list.map(normalizeConfig) : []);
  64. } catch (e: any) {
  65. toast.error('读取配置失败: ' + (e.response?.data?.message || e.message || '未知错误'));
  66. setConfigs([]);
  67. } finally {
  68. setLoading(false);
  69. }
  70. };
  71. useEffect(() => {
  72. fetchConfigs();
  73. }, []);
  74. const handleLookupByKey = async () => {
  75. const targetKey = keyLookup.trim();
  76. if (!targetKey) {
  77. toast.error('请输入要查询的配置 Key');
  78. return;
  79. }
  80. setLoading(true);
  81. try {
  82. const res = await configService.getByKey(targetKey);
  83. const item = res?.data;
  84. if (item) {
  85. setConfigs([normalizeConfig(item)]);
  86. toast.success(`找到配置 "${targetKey}"`);
  87. } else {
  88. toast.error(`未找到 Key 为 "${targetKey}" 的配置`);
  89. setConfigs([]);
  90. }
  91. } catch (e: any) {
  92. toast.error('查询失败: ' + (e.response?.data?.message || e.message || '未知错误'));
  93. } finally {
  94. setLoading(false);
  95. }
  96. };
  97. const handleResetSearch = () => {
  98. setKeyword('');
  99. setSelectedType('all');
  100. setKeyLookup('');
  101. fetchConfigs();
  102. };
  103. const filteredConfigs = useMemo(() => {
  104. const q = keyword.trim().toLowerCase();
  105. return configs.filter((c) => {
  106. const configKey = String(c.config_key || '').toLowerCase();
  107. const desc = String(c.description || '').toLowerCase();
  108. const configVal = String(c.config_value || '').toLowerCase();
  109. const configType = String(c.type || '').toLowerCase();
  110. const matchKeyword =
  111. !q ||
  112. configKey.includes(q) ||
  113. desc.includes(q) ||
  114. configVal.includes(q) ||
  115. configType.includes(q);
  116. const valTrimmed = String(c.config_value || '').trim();
  117. const isJson = valTrimmed.startsWith('{') || valTrimmed.startsWith('[');
  118. const computedType = (c.type || (isJson ? 'json' : 'string')).toLowerCase();
  119. const matchType =
  120. selectedType === 'all' ||
  121. (selectedType === 'json' && (computedType === 'json' || isJson)) ||
  122. (selectedType === 'string' && (computedType === 'string' || computedType === 'text')) ||
  123. (selectedType === 'boolean' && computedType === 'boolean') ||
  124. (selectedType === 'number' && computedType === 'number');
  125. return matchKeyword && matchType;
  126. });
  127. }, [configs, keyword, selectedType]);
  128. const stats = useMemo(() => {
  129. const total = configs.length;
  130. let jsonCount = 0;
  131. let stringCount = 0;
  132. configs.forEach((c) => {
  133. const valTrimmed = String(c.config_value || '').trim();
  134. const isJson = valTrimmed.startsWith('{') || valTrimmed.startsWith('[');
  135. if (isJson || (c.type && c.type.toLowerCase() === 'json')) {
  136. jsonCount++;
  137. } else {
  138. stringCount++;
  139. }
  140. });
  141. return { total, jsonCount, stringCount };
  142. }, [configs]);
  143. const handleOpenCreate = () => {
  144. setActiveConfig(null);
  145. setModalOpen(true);
  146. };
  147. const handleOpenEdit = (config: DynamicConfiguration) => {
  148. setActiveConfig(config);
  149. setModalOpen(true);
  150. };
  151. const handleOpenDetails = (config: DynamicConfiguration) => {
  152. setActiveConfig(config);
  153. setDrawerOpen(true);
  154. };
  155. const handleDelete = async (config: DynamicConfiguration) => {
  156. const ok = await retroConfirm({
  157. title: '[ CONFIRM // 永久删除配置项 ]',
  158. message: `警告:确定要永久删除配置项 "${config.config_key}" 吗?此操作不可撤销!`,
  159. type: 'danger',
  160. confirmText: '[ 确认删除 ]',
  161. });
  162. if (!ok) return;
  163. try {
  164. await configService.delete(config.config_key);
  165. toast.success(`配置 "${config.config_key}" 已删除`);
  166. fetchConfigs();
  167. } catch (e: any) {
  168. toast.error('删除失败: ' + (e.response?.data?.message || e.message || '未知错误'));
  169. }
  170. };
  171. return (
  172. <div className="space-y-6 font-mono">
  173. {/* 顶部标头 */}
  174. <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">
  175. <div>
  176. <div className="text-[10px] font-bold text-neutral-500 uppercase tracking-widest">[ DYNAMIC-CONFIGS // 系统变量热加载 ]</div>
  177. <h1 className="text-xl sm:text-2xl font-black text-black uppercase mt-1">动态系统配置与环境变量中枢</h1>
  178. <p className="text-xs text-neutral-600 font-sans mt-0.5">
  179. 热更新全局汇率、通知网关秘钥、业务开关及限流规则,无需重启服务器即时生效。
  180. </p>
  181. </div>
  182. {/* 顶部右侧主要操作 */}
  183. <div className="flex flex-wrap items-center gap-2">
  184. <button
  185. onClick={fetchConfigs}
  186. disabled={loading}
  187. className="p-2 bg-neutral-50 hover:bg-neutral-200 border-2 border-black text-black transition shadow-[2px_2px_0px_#000]"
  188. title="刷新配置列表"
  189. >
  190. <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
  191. </button>
  192. <button
  193. onClick={() => setExportModalOpen(true)}
  194. 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"
  195. >
  196. <Download size={13} />
  197. <span>[ 导出 ]</span>
  198. </button>
  199. <button
  200. onClick={() => setImportModalOpen(true)}
  201. 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"
  202. >
  203. <Upload size={13} />
  204. <span>[ 导入 ]</span>
  205. </button>
  206. <button
  207. onClick={handleOpenCreate}
  208. 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"
  209. >
  210. <Plus size={14} />
  211. <span>[ 新建配置项 ]</span>
  212. </button>
  213. </div>
  214. </div>
  215. {/* 2. 统计指标卡片 */}
  216. <div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5">
  217. <div className="bg-white border-2 border-black p-4 shadow-[4px_4px_0px_#000] flex flex-col justify-between space-y-1">
  218. <div className="flex items-center justify-between border-b-2 border-black pb-1.5">
  219. <span className="text-[10px] font-black uppercase text-black">[ 全局配置项总数 ]</span>
  220. <SlidersHorizontal size={14} className="text-black" />
  221. </div>
  222. <div className="text-2xl font-black text-black">{stats.total} 个</div>
  223. <div className="text-[10px] text-neutral-500 font-sans">热加载系统环境</div>
  224. </div>
  225. <div className="bg-white border-2 border-black p-4 shadow-[4px_4px_0px_#000] flex flex-col justify-between space-y-1">
  226. <div className="flex items-center justify-between border-b-2 border-black pb-1.5">
  227. <span className="text-[10px] font-black uppercase text-black">[ JSON 结构化变量 ]</span>
  228. <Layers size={14} className="text-black" />
  229. </div>
  230. <div className="text-2xl font-black text-black">{stats.jsonCount} 个</div>
  231. <div className="text-[10px] text-neutral-500 font-sans">包含复杂对象/列表结构</div>
  232. </div>
  233. <div className="bg-white border-2 border-black p-4 shadow-[4px_4px_0px_#000] flex flex-col justify-between space-y-1">
  234. <div className="flex items-center justify-between border-b-2 border-black pb-1.5">
  235. <span className="text-[10px] font-black uppercase text-black">[ 基础标量参数 ]</span>
  236. <FileText size={14} className="text-black" />
  237. </div>
  238. <div className="text-2xl font-black text-black">{stats.stringCount} 个</div>
  239. <div className="text-[10px] text-neutral-500 font-sans">字符串 / 数值 / 开关</div>
  240. </div>
  241. </div>
  242. {/* 3. 搜索与筛选工具栏 */}
  243. <div className="bg-white border-2 border-black p-4 shadow-[4px_4px_0px_#000] space-y-3">
  244. <div className="flex flex-col md:flex-row items-center justify-between gap-3">
  245. <div className="relative flex-1 w-full">
  246. <input
  247. type="text"
  248. placeholder="搜索配置 Key / 作用描述 / Value 内容..."
  249. 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"
  250. value={keyword}
  251. onChange={(e) => setKeyword(e.target.value)}
  252. />
  253. <Search size={14} className="absolute left-3 top-2.5 text-black pointer-events-none" />
  254. <div className="absolute right-2.5 top-2 flex items-center gap-1.5">
  255. {keyword && (
  256. <button
  257. onClick={() => setKeyword('')}
  258. className="text-black hover:text-rose-600 font-bold px-1 text-xs"
  259. title="清空输入"
  260. >
  261. ✕
  262. </button>
  263. )}
  264. {keyword && (
  265. <span className="text-[10px] font-mono font-bold bg-amber-300 px-1 border border-black text-black">
  266. {filteredConfigs.length} 项
  267. </span>
  268. )}
  269. </div>
  270. </div>
  271. <div className="flex items-center gap-2 w-full md:w-auto">
  272. <select
  273. value={selectedType}
  274. onChange={(e) => setSelectedType(e.target.value)}
  275. 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]"
  276. >
  277. <option value="all">[ 全部数据类型 ]</option>
  278. <option value="json">JSON 结构体</option>
  279. <option value="string">文本 (String)</option>
  280. <option value="boolean">布尔 (Boolean)</option>
  281. <option value="number">数值 (Number)</option>
  282. </select>
  283. </div>
  284. </div>
  285. {/* 按 Key 直达查询 */}
  286. <div className="pt-2 border-t-2 border-dashed border-neutral-300 flex flex-col sm:flex-row items-center gap-2">
  287. <span className="text-xs font-bold text-black uppercase shrink-0">[ KEY 直达查询 ]:</span>
  288. <input
  289. type="text"
  290. placeholder="精确输入配置 KEY,如 EXCHANGE_RATES..."
  291. value={keyLookup}
  292. onChange={(e) => setKeyLookup(e.target.value)}
  293. onKeyDown={(e) => e.key === 'Enter' && handleLookupByKey()}
  294. 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"
  295. />
  296. <button
  297. onClick={handleLookupByKey}
  298. 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"
  299. >
  300. [ 精确调取 ]
  301. </button>
  302. {(keyword || selectedType !== 'all' || keyLookup) && (
  303. <button
  304. onClick={handleResetSearch}
  305. className="px-3 py-1.5 bg-neutral-100 hover:bg-neutral-200 border-2 border-black text-black font-bold text-xs uppercase"
  306. >
  307. [ 重置查询 ]
  308. </button>
  309. )}
  310. </div>
  311. </div>
  312. {/* 4. 配置数据表格 */}
  313. <ConfigurationTable
  314. configs={filteredConfigs}
  315. loading={loading}
  316. onEdit={handleOpenEdit}
  317. onViewDetails={handleOpenDetails}
  318. onDelete={handleDelete}
  319. />
  320. {/* 5. 新建 / 编辑弹窗 */}
  321. <ConfigurationModal
  322. isOpen={isModalOpen}
  323. onClose={() => setModalOpen(false)}
  324. config={activeConfig}
  325. onSuccess={fetchConfigs}
  326. />
  327. {/* 6. 详情查阅抽屉 */}
  328. <ConfigurationDetailDrawer
  329. isOpen={isDrawerOpen}
  330. onClose={() => setDrawerOpen(false)}
  331. config={activeConfig}
  332. onEdit={(cfg) => {
  333. setDrawerOpen(false);
  334. handleOpenEdit(cfg);
  335. }}
  336. onDelete={handleDelete}
  337. />
  338. {/* 7. 导出配置弹窗 */}
  339. <ConfigurationExportModal
  340. isOpen={isExportModalOpen}
  341. onClose={() => setExportModalOpen(false)}
  342. configs={configs}
  343. />
  344. {/* 8. 导入配置弹窗 */}
  345. <ConfigurationImportModal
  346. isOpen={isImportModalOpen}
  347. onClose={() => setImportModalOpen(false)}
  348. existingKeys={configs.map((c) => c.config_key)}
  349. onSuccess={fetchConfigs}
  350. />
  351. </div>
  352. );
  353. }