feat: 增加配置导入导出功能

This commit is contained in:
2026-11-24 17:22:08 +08:00
parent 9a23cd1d32
commit eb9b6d534f
6 changed files with 257 additions and 24 deletions
+88 -8
View File
@@ -1368,25 +1368,50 @@ function bindEvents() {
}
});
// 导入导出
// 配置导入导出
document.getElementById('btnExportConfig').addEventListener('click', () => {
window.location.href = '/api/config/export';
// 勾了「包含密钥」才把真实密码/加签密钥写进文件,默认脱敏,方便分享
const withSecrets = document.getElementById('exportWithSecrets').checked;
window.location.href = `/api/config/export${withSecrets ? '?secrets=1' : ''}`;
toast(withSecrets ? '正在导出(含密钥,请妥善保管)' : '正在导出(密钥已脱敏)', 'ok');
});
document.getElementById('btnImportConfig').addEventListener('click', () => document.getElementById('importFile').click());
document.getElementById('importFile').addEventListener('change', async (e) => {
const file = e.target.files?.[0];
e.target.value = '';
if (!file) return;
try {
const text = await file.text();
const json = JSON.parse(text);
const res = await api('/api/config/import', { method: 'POST', body: json });
applyState(res, true);
fillSettings();
toast('配置已导入', 'ok');
const data = json?.config && typeof json.config === 'object' ? json.config : json;
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('文件内容不是配置对象');
if (!Array.isArray(data.instruments) && !Array.isArray(data.rules)) {
throw new Error('这不像是本工具导出的配置文件(缺少 instruments / rules)');
}
// 先把摘要摆出来,让用户确认后再真正覆盖
ui.pendingImport = data;
ui.pendingImportFile = file.name;
document.getElementById('importSummary').innerHTML = buildImportSummary(data, file);
setResult('importResult', '');
openModal('modalImport');
} catch (err) {
toast(`导入失败:${err.message}`, 'err');
} finally {
e.target.value = '';
}
});
document.getElementById('btnConfirmImport').addEventListener('click', async () => {
if (!ui.pendingImport) return;
try {
const res = await api('/api/config/import', { method: 'POST', body: ui.pendingImport });
applyState(res, true);
fillSettings();
closeModal('modalImport');
ui.pendingImport = null;
toast(`配置已导入${res.backup ? `,原配置已备份为 ${res.backup}` : ''}`, 'ok');
refreshBackupList();
} catch (err) {
setResult('importResult', err.message, false);
}
});
@@ -1410,10 +1435,65 @@ function bindEvents() {
const TABS = ['market', 'rules', 'channels', 'alerts'];
/**
* 生成导入前的配置摘要(覆盖前先看清楚要导入什么)
* @param {object} data 待导入的配置对象
* @param {File} file 用户选择的文件
* @returns {string} 摘要 HTML
*/
function buildImportSummary(data, file) {
const instruments = Array.isArray(data.instruments) ? data.instruments : [];
const rules = Array.isArray(data.rules) ? data.rules : [];
const typeNames = { threshold: '价格阈值', change: '涨跌幅', spread: '价差', schedule: '定时' };
const ruleCounts = {};
rules.forEach((r) => {
const key = typeNames[r.type] || String(r.type || '未知');
ruleCounts[key] = (ruleCounts[key] || 0) + 1;
});
const ruleText = rules.length
? `${rules.length} 条(${Object.entries(ruleCounts).map(([k, v]) => `${k} ${v}`).join('、')})`
: '0 条';
const instText = instruments.length
? `${instruments.length} 个:${instruments.slice(0, 4).map((i) => i.name || i.id).join('、')}${instruments.length > 4 ? ' 等' : ''}`
: '0 个';
const channelText = [
data.desktop?.enabled ? '桌面通知' : null,
data.email?.enabled ? '邮件' : null,
data.webhook?.enabled ? `WebHook(${data.webhook?.format === 'dingtalk' ? '钉钉' : '内置 JSON'})` : null,
].filter(Boolean).join(' + ') || '仅使用规则自带渠道';
const sizeText = file?.size ? `${(file.size / 1024).toFixed(1)} KB` : '未知大小';
return [
`<div>文件:<b>${esc(file?.name || '未命名')}</b>(${esc(sizeText)})</div>`,
data.exportedAt ? `<div>导出时间:<b>${esc(data.exportedAt)}</b></div>` : '',
`<div>监控品种:<b>${esc(instText)}</b></div>`,
`<div>提醒规则:<b>${esc(ruleText)}</b></div>`,
`<div>通知渠道:<b>${esc(channelText)}</b></div>`,
`<div>监听地址:<b>${esc(`${data.app?.host || '127.0.0.1'}:${data.app?.port || 8787}`)}</b>(端口改动需重启程序才生效)</div>`,
data.email?.pass ? '<div>注意:文件里带有邮箱密码,导入后会按文件中的值覆盖当前密码。</div>' : '',
].filter(Boolean).join('');
}
/** 读取并展示最近的配置备份 */
async function refreshBackupList() {
const el = document.getElementById('backupListHint');
if (!el) return;
try {
const res = await api('/api/config/backups');
const list = res.backups || [];
el.textContent = list.length
? `最近备份(最多保留 20 份):${list.map((b) => `${b.name}(${b.at})`).join(';')}`
: '还没有备份:每次导入配置前会自动生成一份。';
} catch (err) {
el.textContent = `读取备份列表失败:${err.message}`;
}
}
/** 启动 */
async function boot() {
bindEvents();
await refreshState(true);
refreshBackupList();
const hashTab = (location.hash || '').replace('#', '');
if (TABS.includes(hashTab)) activateTab(hashTab);
window.addEventListener('hashchange', () => {
+35 -6
View File
@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>金价提醒 · Gold Price Watcher</title>
<link rel="stylesheet" href="/styles.css?v=20261124q" />
<link rel="stylesheet" href="/styles.css?v=20261124s" />
</head>
<body>
<header class="topbar">
@@ -194,11 +194,21 @@
<label class="check"><input type="checkbox" id="appOpenBrowser" /> 启动时自动打开浏览器</label>
</div>
<p class="hint" id="configPathHint"></p>
<div class="row">
<button class="btn ghost" id="btnExportConfig">导出配置</button>
<button class="btn ghost" id="btnImportConfig">导入配置</button>
<input type="file" id="importFile" accept="application/json" hidden />
</div>
<!-- 配置备份:导出为 JSON 文件、导入前自动备份当前配置 -->
<div class="card setting-card">
<div class="card-head"><h3>配置备份</h3></div>
<p class="hint">导出成 JSON 文件,可用于换机迁移、分享给同事,或改坏配置后回滚;导入会<b>覆盖</b>当前全部配置(品种、规则、渠道、端口等),导入前程序会自动把现有配置备份到 <code>config/backups/</code>。</p>
<div class="row wrap">
<label class="check"><input type="checkbox" id="exportWithSecrets" /> 导出时包含密钥(邮箱密码 / WebHook 加签)</label>
</div>
<div class="row wrap">
<button class="btn primary" id="btnExportConfig">导出配置</button>
<button class="btn ghost" id="btnImportConfig">导入配置</button>
<input type="file" id="importFile" accept="application/json,.json" hidden />
</div>
<p class="hint" id="backupListHint"></p>
</div>
<div class="row sticky-save">
@@ -369,8 +379,27 @@
</div>
</div>
<!-- ============ 弹窗:确认导入配置 ============ -->
<div class="modal" id="modalImport" hidden>
<div class="modal-box">
<div class="modal-head">
<h3>确认导入配置</h3>
<button class="icon-btn" data-close="modalImport">✕</button>
</div>
<div class="modal-body">
<p class="hint">导入会<b>覆盖</b>当前全部配置(品种、规则、通知渠道、端口等);导入前程序会自动把现有配置备份到 <code>config/backups/</code>,不满意可以用备份回滚。</p>
<div class="import-summary" id="importSummary"></div>
</div>
<div class="modal-foot">
<span class="test-result" id="importResult"></span>
<button class="btn ghost" data-close="modalImport">取消</button>
<button class="btn primary" id="btnConfirmImport">确认导入</button>
</div>
</div>
</div>
<div class="toast-wrap" id="toastWrap"></div>
<script src="/app.js?v=20261124q"></script>
<script src="/app.js?v=20261124s"></script>
</body>
</html>
+13
View File
@@ -349,6 +349,19 @@ main { padding: 22px 28px 60px; max-width: 1320px; margin: 0 auto; }
.tag.spread { color: #6a4b9a; border-color: #e0d4f0; background: #f7f3fc; }
/* 定时提醒:用偏绿的色,和三种价格条件规则区分开 */
.tag.schedule { color: #1f7a5c; border-color: #cfe8dd; background: #f1faf6; }
/* 导入配置前的摘要区块 */
.import-summary {
margin-top: 10px;
padding: 12px 14px;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--panel-2, #fbfaf6);
font-size: 12.5px;
line-height: 1.9;
color: var(--text-dim);
}
.import-summary b { color: var(--text); }
.rule-cond { margin-top: 4px; font-size: 12.5px; color: var(--text-dim); }
.rule-sub { margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
.rule-actions { display: flex; align-items: center; gap: 8px; }