ConfigurationImportModal.tsx 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. 'use client';
  2. import { useState } from 'react';
  3. import { X, Upload, FileText, CheckCircle2, AlertCircle, Sparkles } from 'lucide-react';
  4. import { toast } from 'react-hot-toast';
  5. import api from '@/lib/api';
  6. import { DynamicConfiguration } from '@/types';
  7. interface ConfigurationImportModalProps {
  8. isOpen: boolean;
  9. onClose: () => void;
  10. onSuccess: () => void;
  11. existingKeys: string[];
  12. }
  13. export default function ConfigurationImportModal({
  14. isOpen,
  15. onClose,
  16. onSuccess,
  17. existingKeys,
  18. }: ConfigurationImportModalProps) {
  19. const [jsonInput, setJsonInput] = useState('');
  20. const [overwrite, setOverwrite] = useState(true);
  21. const [submitting, setSubmitting] = useState(false);
  22. if (!isOpen) return null;
  23. let parsedList: DynamicConfiguration[] = [];
  24. let parseError: string | null = null;
  25. if (jsonInput.trim()) {
  26. try {
  27. const data = JSON.parse(jsonInput);
  28. if (Array.isArray(data)) {
  29. parsedList = data
  30. .filter((item) => item && typeof item === 'object' && item.config_key)
  31. .map((item) => ({
  32. config_key: String(item.config_key).trim(),
  33. config_value:
  34. typeof item.config_value === 'string'
  35. ? item.config_value
  36. : JSON.stringify(item.config_value ?? ''),
  37. description: String(item.description || ''),
  38. type: String(item.type || 'json'),
  39. }));
  40. } else if (typeof data === 'object' && data !== null) {
  41. if (data.config_key) {
  42. parsedList = [
  43. {
  44. config_key: String(data.config_key).trim(),
  45. config_value:
  46. typeof data.config_value === 'string'
  47. ? data.config_value
  48. : JSON.stringify(data.config_value ?? ''),
  49. description: String(data.description || ''),
  50. type: String(data.type || 'json'),
  51. },
  52. ];
  53. } else {
  54. parsedList = Object.entries(data).map(([k, v]) => ({
  55. config_key: k.trim(),
  56. config_value: typeof v === 'string' ? v : JSON.stringify(v),
  57. description: '',
  58. type: typeof v === 'object' ? 'json' : typeof v,
  59. }));
  60. }
  61. }
  62. } catch (e: any) {
  63. parseError = e.message;
  64. }
  65. }
  66. const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
  67. const file = e.target.files?.[0];
  68. if (!file) return;
  69. const reader = new FileReader();
  70. reader.onload = (event) => {
  71. const content = event.target?.result as string;
  72. setJsonInput(content);
  73. };
  74. reader.readAsText(file);
  75. };
  76. const handleImport = async () => {
  77. if (parsedList.length === 0) {
  78. toast.error('无可导入的有效配置数据');
  79. return;
  80. }
  81. setSubmitting(true);
  82. let successCount = 0;
  83. let skipCount = 0;
  84. try {
  85. for (const item of parsedList) {
  86. const isExists = existingKeys.includes(item.config_key);
  87. if (isExists && !overwrite) {
  88. skipCount++;
  89. continue;
  90. }
  91. try {
  92. if (isExists && overwrite) {
  93. await api.put(`/api/dynamic-configurations/key/${encodeURIComponent(item.config_key)}`, {
  94. config_value: item.config_value,
  95. description: item.description || undefined,
  96. type: item.type || undefined,
  97. });
  98. successCount++;
  99. } else if (!isExists) {
  100. await api.post('/api/dynamic-configurations', {
  101. config_key: item.config_key,
  102. config_value: item.config_value,
  103. description: item.description || undefined,
  104. type: item.type || undefined,
  105. });
  106. successCount++;
  107. }
  108. } catch {
  109. skipCount++;
  110. }
  111. }
  112. toast.success(`导入完成: 成功 ${successCount} 项, 跳过 ${skipCount} 项`);
  113. onClose();
  114. onSuccess();
  115. } catch {
  116. toast.error('导入过程中发生错误');
  117. } finally {
  118. setSubmitting(false);
  119. }
  120. };
  121. return (
  122. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-grayscale p-4 font-mono">
  123. <div className="bg-neutral-50 border-2 border-black shadow-[8px_8px_0px_#000] w-full max-w-xl overflow-hidden animate-in zoom-in-95 duration-200">
  124. {/* Header */}
  125. <div className="px-5 py-3.5 border-b-2 border-black flex justify-between items-center bg-neutral-200 text-black select-none">
  126. <div className="flex items-center gap-2">
  127. <span className="w-2.5 h-2.5 bg-amber-300 border border-black inline-block" />
  128. <h3 className="font-black text-black text-xs md:text-sm uppercase tracking-wider">
  129. [ IMPORT CONFIGURATIONS // 导入配置数据 ]
  130. </h3>
  131. </div>
  132. <button
  133. onClick={onClose}
  134. className="w-6 h-6 bg-white hover:bg-amber-300 border border-black flex items-center justify-center font-bold text-xs transition"
  135. >
  136. ✕
  137. </button>
  138. </div>
  139. {/* Body */}
  140. <div className="p-5 space-y-4 max-h-[70vh] overflow-y-auto bg-white text-xs">
  141. {/* File Upload Zone */}
  142. <div className="border-2 border-dashed border-black hover:bg-amber-50 p-4 text-center transition bg-neutral-50 relative cursor-pointer">
  143. <input
  144. type="file"
  145. accept=".json"
  146. onChange={handleFileUpload}
  147. className="absolute inset-0 opacity-0 cursor-pointer w-full h-full"
  148. />
  149. <div className="flex flex-col items-center justify-center space-y-1">
  150. <Upload className="w-5 h-5 text-black mb-0.5" />
  151. <p className="text-xs font-bold text-black uppercase">[ 点击选择 JSON 配置文件或拖拽入此区域 ]</p>
  152. <p className="text-[10px] text-neutral-500">支持 configurations_backup.json</p>
  153. </div>
  154. </div>
  155. {/* Textarea Paste */}
  156. <div className="space-y-1">
  157. <label className="font-bold uppercase text-black flex justify-between">
  158. <span>[ 或直接粘贴 JSON 内容 ]</span>
  159. {parseError ? (
  160. <span className="text-rose-700 font-bold flex items-center gap-1">
  161. <AlertCircle size={12} /> {parseError}
  162. </span>
  163. ) : parsedList.length > 0 ? (
  164. <span className="text-black font-bold">
  165. ★ 已成功解析 {parsedList.length} 项配置
  166. </span>
  167. ) : null}
  168. </label>
  169. <textarea
  170. rows={6}
  171. value={jsonInput}
  172. onChange={(e) => setJsonInput(e.target.value)}
  173. placeholder={`[\n {\n "config_key": "EXCHANGE_RATES",\n "config_value": "{\\"USD\\": 7.2}",\n "description": "汇率配置",\n "type": "json"\n }\n]`}
  174. className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white outline-none font-mono text-xs text-black shadow-[2px_2px_0px_#000]"
  175. />
  176. </div>
  177. {/* Overwrite toggle */}
  178. <div className="flex items-center justify-between p-3 bg-neutral-50 border-2 border-black shadow-[2px_2px_0px_#000]">
  179. <div>
  180. <span className="font-bold text-black block uppercase">[ 同名 KEY 自动覆盖更新 ]</span>
  181. <span className="text-neutral-500 text-[10px]">开启后若遇到已存在 Key 将执行内容覆盖</span>
  182. </div>
  183. <label className="flex items-center gap-2 cursor-pointer font-bold text-xs">
  184. <input
  185. type="checkbox"
  186. checked={overwrite}
  187. onChange={(e) => setOverwrite(e.target.checked)}
  188. className="w-4 h-4 accent-black"
  189. />
  190. <span>{overwrite ? '覆盖' : '跳过'}</span>
  191. </label>
  192. </div>
  193. </div>
  194. {/* Footer */}
  195. <div className="px-5 py-3 bg-neutral-200 flex justify-end gap-2 border-t-2 border-black">
  196. <button
  197. type="button"
  198. onClick={onClose}
  199. className="px-4 py-1.5 bg-white hover:bg-neutral-100 border-2 border-black text-xs font-bold uppercase shadow-[2px_2px_0px_#000]"
  200. disabled={submitting}
  201. >
  202. [ 取消 ]
  203. </button>
  204. <button
  205. type="button"
  206. onClick={handleImport}
  207. disabled={submitting || parsedList.length === 0}
  208. className="px-5 py-1.5 bg-amber-300 hover:bg-amber-400 text-black border-2 border-black text-xs font-black uppercase shadow-[2px_2px_0px_#000] transition active:translate-x-0.5 active:translate-y-0.5 disabled:opacity-50"
  209. >
  210. {submitting ? '导入处理中...' : `[ 确认导入 (${parsedList.length} 项) ]`}
  211. </button>
  212. </div>
  213. </div>
  214. </div>
  215. );
  216. }