Files

1633 lines
70 KiB
JavaScript
Raw Permalink Normal View History

2026-11-24 16:37:13 +08:00
/**
* 前端交互脚本(无框架、无构建步骤)。
* 负责:轮询 /api/state、渲染行情/规则/记录、打开弹窗、保存配置、渠道自检。
*/
/** 前端全局状态 */
const ui = {
/** @type {object|null} 最近一次 /api/state 返回 */
data: null,
/** 当前标签页 */
tab: 'market',
/** 上次查看提醒记录的时间,用于未读角标 */
seenAtMs: Date.now(),
/** 是否已有未读提醒 */
unread: 0,
/** 编辑中的品种 id(null 表示新增) */
editingInstrumentId: null,
/** 编辑中的规则 id(null 表示新增) */
editingRuleId: null,
/** 行情卡片的 DOM 引用缓存:id -> {root, refs...} */
cards: new Map(),
/** 上一次渲染时的品种签名,签名变化才重建卡片 */
marketSignature: '',
/** 轮询定时器 */
timer: null,
};
const TOKEN_KEY = 'goldWatcherToken';
/* ==================================================================
* 基础工具
* ================================================================== */
/** 读写访问令牌 */
function getToken() {
return localStorage.getItem(TOKEN_KEY) || '';
}
/** 数字格式化 */
function fmt(value, digits = 2) {
if (value === null || value === undefined || Number.isNaN(Number(value))) return '--';
return Number(value).toFixed(digits);
}
/** 百分比格式化,带正负号 */
function fmtPct(value) {
if (value === null || value === undefined || Number.isNaN(Number(value))) return '--';
const n = Number(value);
return `${n > 0 ? '+' : ''}${n.toFixed(2)}%`;
}
/** HTML 转义 */
function esc(text) {
return String(text === null || text === undefined ? '' : text)
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
/** 涨跌方向 class */
function trendClass(value) {
if (value === null || value === undefined) return 'flat';
if (Number(value) > 0) return 'up';
if (Number(value) < 0) return 'down';
return 'flat';
}
/**
* 统一的后端请求封装(自动带令牌、统一错误处理)
* @param {string} path 接口路径
* @param {{method?: string, body?: any}} options 请求选项
* @returns {Promise<object>}
*/
async function api(path, options = {}) {
const method = options.method || 'GET';
const headers = { 'Content-Type': 'application/json' };
const token = getToken();
if (token) headers['x-token'] = token;
const res = await fetch(path, {
method,
headers,
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
if (res.status === 401) {
const input = window.prompt('该页面配置了访问令牌,请输入(会记住在本机):');
if (input) {
localStorage.setItem(TOKEN_KEY, input.trim());
return api(path, options);
}
throw new Error('未授权访问');
}
let payload = null;
try {
payload = await res.json();
} catch {
throw new Error(`接口返回异常(HTTP ${res.status})`);
}
// 失败时优先用后端给的 error,其次 detail(渠道自检接口只有 detail),最后才退化成 HTTP 状态
if (!res.ok || payload.ok === false) {
throw new Error(payload.error || payload.detail || `请求失败(HTTP ${res.status})`);
}
return payload;
}
/** 右下角轻提示 */
function toast(message, type = '') {
const wrap = document.getElementById('toastWrap');
const el = document.createElement('div');
el.className = `toast ${type}`;
el.textContent = message;
wrap.appendChild(el);
setTimeout(() => {
el.style.opacity = '0';
el.style.transition = 'opacity .2s';
setTimeout(() => el.remove(), 250);
}, 2600);
}
/** 设置测试结果文案 */
function setResult(id, text, ok) {
const el = document.getElementById(id);
if (!el) return;
el.textContent = text || '';
el.className = `test-result ${ok === true ? 'ok' : ok === false ? 'err' : ''}`;
}
/* ==================================================================
* 渲染:顶栏 / 行情 / 规则 / 记录
* ================================================================== */
/** 渲染顶栏状态 */
function renderHeader() {
const data = ui.data;
if (!data) return;
const pill = document.getElementById('runPill');
const text = document.getElementById('runText');
const running = !!data.running;
pill.className = `pill ${running ? 'running' : 'paused'}`;
text.textContent = running ? '监控运行中' : '已暂停';
document.getElementById('btnToggleRun').textContent = running ? '暂停监控' : '开始监控';
document.getElementById('serverTime').textContent = data.serverTime || '';
document.getElementById('quietPill').hidden = !data.quietActive;
// 未读提醒角标
const badge = document.getElementById('alertBadge');
if (ui.unread > 0 && ui.tab !== 'alerts') {
badge.hidden = false;
badge.textContent = ui.unread > 99 ? '99+' : String(ui.unread);
} else {
badge.hidden = true;
}
}
/** 数据源展示名 */
function sourceLabel(sourceKey) {
const sources = ui.data?.config?.meta?.dataSources || [];
return (sources.find((s) => s.key === sourceKey) || {}).label || sourceKey;
}
/** 生成迷你走势 SVG */
function sparkline(history, digits) {
if (!Array.isArray(history) || history.length < 2) {
return '<svg class="spark" viewBox="0 0 300 34" preserveAspectRatio="none"></svg>';
}
const points = history.map((p) => Number(p.p)).filter((n) => Number.isFinite(n));
if (points.length < 2) return '<svg class="spark" viewBox="0 0 300 34" preserveAspectRatio="none"></svg>';
const min = Math.min(...points);
const max = Math.max(...points);
const span = max - min || 1;
const stepX = 300 / (points.length - 1);
const coords = points.map((p, i) => {
const y = 30 - ((p - min) / span) * 26;
return `${(i * stepX).toFixed(1)},${y.toFixed(1)}`;
}).join(' ');
const rising = points[points.length - 1] >= points[0];
const color = rising ? 'var(--up)' : 'var(--down)';
return `<svg class="spark" viewBox="0 0 300 34" preserveAspectRatio="none">
<polyline points="${coords}" fill="none" stroke="${color}" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" opacity="0.9"></polyline>
</svg>`;
}
/** 构建一张行情卡片 */
function buildCard(inst) {
const root = document.createElement('div');
root.className = 'card';
root.dataset.id = inst.id;
root.innerHTML = `
<div class="card-head">
<div class="card-title-row">
<h3 class="js-name"></h3>
<span class="source-tag js-source"></span>
</div>
<label class="switch" title="启用 / 停用">
<input type="checkbox" class="js-toggle" />
<span></span>
</label>
</div>
<div class="price-row">
<span class="price js-price">--</span>
<span class="unit js-unit"></span>
</div>
<div class="change-row">
<span class="change js-change">--</span>
<span class="js-range"></span>
</div>
<div class="js-spark"></div>
<div class="meta">
<span class="status js-status"><i></i><span class="js-status-text"></span></span>
<span class="js-updated"></span>
<span class="js-interval"></span>
</div>
<div class="js-error"></div>
<div class="js-manual"></div>
<div class="card-foot">
<span class="js-manual-hint"></span>
<div class="btn-row">
<button class="btn tiny ghost js-edit">编辑</button>
<button class="btn tiny danger js-del">删除</button>
</div>
</div>
`;
const refs = {
root,
name: root.querySelector('.js-name'),
source: root.querySelector('.js-source'),
toggle: root.querySelector('.js-toggle'),
price: root.querySelector('.js-price'),
unit: root.querySelector('.js-unit'),
change: root.querySelector('.js-change'),
range: root.querySelector('.js-range'),
spark: root.querySelector('.js-spark'),
status: root.querySelector('.js-status'),
statusText: root.querySelector('.js-status-text'),
updated: root.querySelector('.js-updated'),
interval: root.querySelector('.js-interval'),
error: root.querySelector('.js-error'),
manual: root.querySelector('.js-manual'),
manualHint: root.querySelector('.js-manual-hint'),
};
// 事件绑定
refs.toggle.addEventListener('change', async () => {
try {
const res = await api(`/api/instruments/${inst.id}`, { method: 'PUT', body: { enabled: refs.toggle.checked } });
applyState(res, true);
toast(refs.toggle.checked ? '已启用' : '已停用', 'ok');
} catch (err) {
toast(err.message, 'err');
refs.toggle.checked = !refs.toggle.checked;
}
});
root.querySelector('.js-edit').addEventListener('click', () => openInstrumentModal(inst.id));
root.querySelector('.js-del').addEventListener('click', async () => {
if (!window.confirm(`确定删除「${inst.name}」?相关规则也会一起删除。`)) return;
try {
const res = await api(`/api/instruments/${inst.id}`, { method: 'DELETE' });
applyState(res, true);
toast('已删除', 'ok');
} catch (err) {
toast(err.message, 'err');
}
});
ui.cards.set(inst.id, refs);
return { root, refs };
}
/** 更新卡片内容(不重建 DOM) */
function updateCard(refs, inst) {
const digits = inst.digits ?? 2;
refs.root.classList.toggle('disabled', !inst.enabled);
refs.name.textContent = inst.name;
refs.source.textContent = sourceLabel(inst.source);
refs.toggle.checked = !!inst.enabled;
refs.unit.textContent = inst.unit || '';
const hasPrice = inst.price !== null && inst.price !== undefined;
refs.price.textContent = hasPrice ? fmt(inst.price, digits) : '--';
refs.price.classList.toggle('stale', !hasPrice);
const dir = trendClass(inst.changePercent);
refs.change.className = `change js-change ${dir}`;
refs.change.textContent = hasPrice
? `${fmtPct(inst.changePercent)}${inst.change !== null && inst.change !== undefined ? ` ${inst.change > 0 ? '+' : ''}${fmt(inst.change, digits)}` : ''}`
: '';
refs.range.textContent = hasPrice && inst.high && inst.low
? `高 ${fmt(inst.high, digits)} / 低 ${fmt(inst.low, digits)}`
: '';
refs.spark.innerHTML = sparkline(inst.history, digits);
const statusMap = {
ok: '正常', error: '抓取失败', pending: '等待首次数据', manual: '手动价格', disabled: '已停用',
};
refs.status.className = `status js-status ${inst.status}`;
refs.statusText.textContent = statusMap[inst.status] || inst.status;
refs.updated.textContent = inst.updatedAt ? `更新 ${inst.updatedAt}` : '';
refs.interval.textContent = inst.intervalSec > 0 ? `每 ${inst.intervalSec} 秒` : '不自动刷新';
if (inst.error) {
refs.error.innerHTML = `<div class="card-error">${esc(inst.error)}</div>`;
} else {
refs.error.innerHTML = '';
}
// 手动录价:manual 数据源常驻输入框;其它品种只在出错时给一个快捷补价入口
const needManual = inst.source === 'manual' || inst.status === 'error';
if (needManual) {
if (!refs.manual.querySelector('input')) {
refs.manual.innerHTML = `
<div class="manual-row">
<input type="number" step="0.01" placeholder="输入最新价格 ${esc(inst.unit || '')}" />
<button class="btn tiny primary">更新</button>
</div>`;
const input = refs.manual.querySelector('input');
const btn = refs.manual.querySelector('button');
const submit = async () => {
const value = Number(input.value);
if (!value || value <= 0) {
toast('请输入有效价格', 'err');
return;
}
btn.disabled = true;
try {
const res = await api(`/api/instruments/${inst.id}/manual`, { method: 'POST', body: { price: value } });
applyState(res, true);
toast('已更新价格并重新评估规则', 'ok');
} catch (err) {
toast(err.message, 'err');
} finally {
btn.disabled = false;
}
};
btn.addEventListener('click', submit);
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') submit(); });
}
refs.manualHint.textContent = inst.manualPrice?.at ? `手动价更新于 ${inst.manualPrice.at}` : '';
} else {
refs.manual.innerHTML = '';
refs.manualHint.textContent = '';
}
}
/** 渲染行情看板 */
function renderMarket() {
const data = ui.data;
if (!data) return;
const grid = document.getElementById('instrumentGrid');
const empty = document.getElementById('instrumentEmpty');
const list = data.instruments || [];
empty.hidden = list.length > 0;
// 结构变化(增删、顺序、名称、频率、单位)时才重建卡片
const signature = list.map((i) => `${i.id}:${i.name}:${i.unit}:${i.intervalSec}:${i.source}`).join('|');
const needRebuild = signature !== ui.marketSignature;
if (needRebuild) {
ui.marketSignature = signature;
ui.cards.clear();
grid.innerHTML = '';
for (const inst of list) {
const { root, refs } = buildCard(inst);
grid.appendChild(root);
updateCard(refs, inst);
}
} else {
for (const inst of list) {
const refs = ui.cards.get(inst.id);
if (refs) updateCard(refs, inst);
}
}
}
/**
* 通知渠道 key 的中文名
* @param {string} key 渠道标识(desktop / email / webhook)
* @returns {string}
*/
function channelName(key) {
return { desktop: '桌面', email: '邮件', webhook: 'WebHook' }[key] || key;
}
/** 星期文案:定时提醒里用,1=周一 … 7=周日 */
const WEEKDAY_NAMES = { 1: '周一', 2: '周二', 3: '周三', 4: '周四', 5: '周五', 6: '周六', 7: '周日' };
/**
* 统计区间秒数转文案(0 表示日内相对昨收)
* @param {number} windowSec 秒
* @returns {string} 例如「日内」「近 10 分钟」「近 2 小时」
*/function windowText(windowSec) {
const sec = Number(windowSec) || 0;
if (sec <= 0) return '日内';
if (sec < 60) return `近 ${sec} 秒`;
if (sec % 3600 === 0) return `近 ${sec / 3600} 小时`;
return `近 ${Math.round(sec / 60)} 分钟`;
}
/**
* 取品种的价格单位(找不到时回落到「元/克」)
* @param {string} instrumentId 品种 id
* @returns {string} 单位文案,例如「元/克」「美元/盎司」
*/
function unitOf(instrumentId) {
const inst = (ui.data?.instruments || []).find((i) => i.id === instrumentId);
return inst?.unit || '元/克';
}
/** 规则条件的可读描述 */
function ruleConditionText(rule) {
const data = ui.data;
const instruments = data?.instruments || [];
const left = instruments.find((i) => i.id === rule.instrumentId);
const right = instruments.find((i) => i.id === rule.compareInstrumentId);
if (!left) return '品种已删除';
// 生效时段统一追加在条件末尾
const rangeSuffix = rule.activeRange ? `(仅 ${rule.activeRange} 生效)` : '';
if (rule.type === 'threshold') {
const op = rule.direction === 'below' ? '≤' : '≥';
return `${left.name} 价格 ${op} ${fmt(rule.value, left.digits)} ${left.unit}${rangeSuffix}`;
}
if (rule.type === 'change') {
const dirText = rule.direction === 'up' ? '涨幅' : rule.direction === 'down' ? '跌幅' : '涨跌幅';
// 统计区间:日内相对昨收,或近 N 分钟的滚动窗口
const scope = windowText(rule.windowSec);
// 阈值口径:百分比,或具体价格变动值(元/克等)
const isAmount = rule.changeBasis === 'amount';
const valueText = isAmount
? `${fmt(Math.abs(rule.value), left.digits)} ${left.unit}`
: `${Math.abs(rule.value).toFixed(2)}%`;
const absText = rule.direction === 'both' ? '绝对值' : '';
return `${left.name} ${scope}${dirText} ${absText} ≥ ${valueText}${rangeSuffix}`.replace(' ', ' ');
}
if (rule.type === 'ladder') {
// 阶梯提醒:以「上次提醒时的价格」为基准,每偏离一个步长提醒一次
const isAmount = rule.changeBasis === 'amount';
const valueText = isAmount
? `${fmt(Math.abs(rule.value), left.digits)} ${left.unit}`
: `${Math.abs(rule.value).toFixed(2)}%`;
const dirText = rule.direction === 'down' ? '每下跌' : rule.direction === 'both' ? '每涨/跌' : '每上涨';
// 连续确认次数 > 1 时,把「还要连续几次同向」写进条件描述
const streakText = Number(rule.ladderStreak) > 1 ? `,需连续 ${Math.round(Number(rule.ladderStreak))} 次同向` : '';
// 强制提醒幅度:比步长大时才单独提一句(后端取 max(步长, 强制幅度))
const stepAbs = Math.abs(Number(rule.value) || 0);
const forceAbs = Math.abs(Number(rule.forceAlertValue) || 0);
const forceText = forceAbs > stepAbs
? `,偏离 ≥ ${isAmount ? `${fmt(forceAbs, left.digits)} ${left.unit}` : `${forceAbs.toFixed(2)}%`} 直接提醒(忽略连续)`
: '';
return `${left.name} ${dirText} ${valueText} 提醒一次${streakText}${forceText}(基价随提醒更新)${rangeSuffix}`;
}
2026-11-24 16:37:13 +08:00
if (rule.type === 'schedule') {
// 定时提醒:重复方式 + 时刻,必要时带上每周哪几天
const repeatText = rule.scheduleRepeat === 'weekday' ? '工作日' : rule.scheduleRepeat === 'weekly' ? '每周' : '每天';
const weekText = rule.scheduleRepeat === 'weekly'
? `(${(rule.scheduleWeekdays || []).map((n) => WEEKDAY_NAMES[n]).filter(Boolean).join('、') || '未选星期'})`
: '';
const times = (rule.scheduleTimes || []).join('、') || '未设置时刻';
return `${left.name} ${repeatText}${weekText} ${times} 定时提醒${rangeSuffix}`;
}
if (rule.type === 'failure') {
// 请求失败告警:连续查询失败多少次就提醒
const times = Math.max(1, Math.round(Number(rule.value) || 3));
const repeat = rule.repeatIntervalSec > 0 ? `,持续失败每 ${rule.repeatIntervalSec} 秒重复提醒` : '';
return `${left.name} 连续查询失败 ${times} 次 提醒一次${repeat}${rangeSuffix}`;
}
2026-11-24 16:37:13 +08:00
if (!right) return '对比品种已删除';
const unitText = rule.mode === 'percent' ? '%' : left.unit;
const dirText = rule.direction === 'above' ? `${left.name} 高于 ${right.name}` : rule.direction === 'below' ? `${right.name} 高于 ${left.name}` : '两者价差';
return `${dirText} ≥ ${Math.abs(rule.value)}${unitText}${rangeSuffix}`;
}
/**
* 规则名称比较函数:中文按拼音、数字按大小排序
* (例如「涨跌 2%」会排在「涨跌 10%」前面,而不是按字符顺序排到后面)
* @param {object} a 规则 A
* @param {object} b 规则 B
* @returns {number} 比较结果
*/
function compareRuleName(a, b) {
return String(a.name || '').localeCompare(String(b.name || ''), 'zh-Hans-CN', { numeric: true, sensitivity: 'base' });
}
/** 渲染规则列表(按名称自动排序) */
function renderRules() {
const data = ui.data;
if (!data) return;
const list = [...(data.rules || [])].sort(compareRuleName);
const box = document.getElementById('ruleList');
document.getElementById('ruleEmpty').hidden = list.length > 0;
box.innerHTML = list.map((rule) => {
const channels = (rule.channels || []).map(channelName).join(' + ');
const typeText = rule.type === 'threshold' ? '价格阈值'
: rule.type === 'change' ? '涨跌幅'
: rule.type === 'schedule' ? '定时'
: rule.type === 'ladder' ? '阶梯'
: rule.type === 'failure' ? '失败告警'
: '价差';
// 定时提醒按时刻去重、失败告警按次数触发,都没有「冷却」概念,列表里只展示重复间隔
2026-11-24 16:37:13 +08:00
const extraText = rule.type === 'schedule'
? ''
: rule.type === 'failure'
? `${rule.repeatIntervalSec > 0 ? ` · 持续失败每 ${rule.repeatIntervalSec}s 重复` : ''}`
: ` · 冷却 ${rule.cooldownSec}s${rule.repeatIntervalSec > 0 ? ` · 每 ${rule.repeatIntervalSec}s 重复` : ''}`;
2026-11-24 16:37:13 +08:00
return `
<div class="rule-item ${rule.enabled ? '' : 'disabled'}" data-id="${esc(rule.id)}">
<label class="switch" title="启用 / 停用">
<input type="checkbox" class="js-rule-toggle" ${rule.enabled ? 'checked' : ''} />
<span></span>
</label>
<div class="rule-main">
<div class="rule-title">
<span class="rule-name">${esc(rule.name)}</span>
<span class="tag ${rule.type}">${typeText}</span>
</div>
<div class="rule-cond">${esc(ruleConditionText(rule))}</div>
<div class="rule-sub">渠道:${esc(channels || '默认渠道')}${extraText}</div>
</div>
<div class="rule-actions">
<button class="btn tiny ghost js-rule-edit">编辑</button>
<button class="btn tiny danger js-rule-del">删除</button>
</div>
</div>`;
}).join('');
// 事件绑定
box.querySelectorAll('.rule-item').forEach((item) => {
const id = item.dataset.id;
const rule = list.find((r) => r.id === id);
if (!rule) return;
item.querySelector('.js-rule-toggle').addEventListener('change', async (e) => {
try {
const res = await api(`/api/rules/${id}`, { method: 'PUT', body: { enabled: e.target.checked } });
applyState(res, false);
} catch (err) {
toast(err.message, 'err');
}
});
item.querySelector('.js-rule-edit').addEventListener('click', () => openRuleModal(id));
item.querySelector('.js-rule-del').addEventListener('click', async () => {
if (!window.confirm(`确定删除规则「${rule.name}」?`)) return;
try {
const res = await api(`/api/rules/${id}`, { method: 'DELETE' });
applyState(res, false);
toast('已删除规则', 'ok');
} catch (err) {
toast(err.message, 'err');
}
});
});
}
/** 渲染提醒记录 */
function renderAlerts() {
const data = ui.data;
if (!data) return;
const alerts = data.alerts || [];
const box = document.getElementById('alertList');
document.getElementById('alertEmpty').hidden = alerts.length > 0;
box.innerHTML = alerts.map((alert) => {
const chan = (alert.delivered || []).map((d) => {
const name = channelName(d.channel);
const state = d.ok ? '✓' : d.muted ? '—' : '✕';
const cls = d.ok ? 'ok' : d.muted ? '' : 'err';
return `<span class="chan ${cls}" title="${esc(d.error || '')}">${name} ${state}</span>`;
}).join(' · ');
return `
<div class="alert-item">
<div class="alert-title">${esc(alert.title)}</div>
<div class="alert-msg">${esc(alert.message)}</div>
<div class="alert-meta">
<span>${esc(alert.at)}</span>
<span>规则:${esc(alert.ruleName || '')}</span>
<span>${chan}</span>
</div>
</div>`;
}).join('');
}
/** 渲染当前标签页 */
function renderActiveTab() {
if (ui.tab === 'market') renderMarket();
if (ui.tab === 'rules') renderRules();
if (ui.tab === 'alerts') renderAlerts();
}
/**
* 应用一次后端返回的完整状态
* @param {object} payload /api/* 返回的数据
* @param {boolean} forceRebuild 是否强制重建行情卡片
*/
function applyState(payload, forceRebuild = false) {
if (!payload) return;
ui.data = payload;
// 计算未读提醒
const alerts = payload.alerts || [];
ui.unread = alerts.filter((a) => (a.atMs || 0) > ui.seenAtMs).length;
if (forceRebuild) ui.marketSignature = '';
renderHeader();
renderActiveTab();
}
/** 拉取最新状态 */
async function refreshState(forceRebuild = false) {
try {
const payload = await api('/api/state');
applyState(payload, forceRebuild);
return payload;
} catch (err) {
toast(`状态刷新失败:${err.message}`, 'err');
return null;
}
}
/** 开始轮询(5 秒一次) */
function startPolling() {
if (ui.timer) clearInterval(ui.timer);
ui.timer = setInterval(() => {
if (document.hidden) return;
refreshState(false);
}, 5000);
}
/* ==================================================================
* 设置区:读取与保存
* ================================================================== */
/** 把配置填进设置表单 */
function fillSettings() {
const cfg = ui.data?.config;
if (!cfg) return;
document.getElementById('desktopEnabled').checked = !!cfg.desktop.enabled;
document.getElementById('channelDesktop').checked = (cfg.channels.onTrigger || []).includes('desktop');
document.getElementById('channelEmail').checked = (cfg.channels.onTrigger || []).includes('email');
document.getElementById('channelWebhook').checked = (cfg.channels.onTrigger || []).includes('webhook');
document.getElementById('defaultInterval').value = cfg.monitor.defaultIntervalSec;
document.getElementById('quietEnabled').checked = !!cfg.monitor.quietHours.enabled;
document.getElementById('quietRange').value = cfg.monitor.quietHours.range || '23:00-07:00';
document.getElementById('alertOnFirstCheck').checked = cfg.monitor.alertOnFirstCheck === true;
document.getElementById('emailEnabled').checked = !!cfg.email.enabled;
document.getElementById('emailHost').value = cfg.email.host || '';
document.getElementById('emailPort').value = cfg.email.port || 465;
document.getElementById('emailSecure').value = cfg.email.secure ? 'true' : 'false';
document.getElementById('emailUser').value = cfg.email.user || '';
document.getElementById('emailPass').value = '';
document.getElementById('emailPass').placeholder = cfg.email.passConfigured ? '已设置(留空则不修改)' : '留空则不修改';
document.getElementById('emailFrom').value = cfg.email.from || '';
document.getElementById('emailTo').value = (cfg.email.to || []).join(', ');
document.getElementById('emailPrefix').value = cfg.email.subjectPrefix || '【金价提醒】';
document.getElementById('emailSnapshot').checked = cfg.email.withSnapshot !== false;
// WebHook
const webhook = cfg.webhook || {};
document.getElementById('webhookEnabled').checked = !!webhook.enabled;
document.getElementById('webhookUrl').value = webhook.url || '';
document.getElementById('webhookFormat').value = webhook.format || 'generic';
document.getElementById('webhookSecret').value = '';
document.getElementById('webhookSecret').placeholder = webhook.secretConfigured
? '已设置(留空则不修改)'
: 'SEC 开头;机器人未启用加签可留空';
document.getElementById('webhookKeyword').value = webhook.keyword || '';
document.getElementById('webhookAtMobiles').value = (webhook.atMobiles || []).join(', ');
document.getElementById('webhookMentionAll').checked = webhook.mentionAll === true;
syncWebhookFields();
document.getElementById('appPort').value = cfg.app.port;
document.getElementById('appHost').value = cfg.app.host;
document.getElementById('appToken').value = cfg.app.token || '';
document.getElementById('appOpenBrowser').checked = cfg.app.openBrowser !== false;
document.getElementById('configPathHint').textContent = `配置文件:${cfg.meta?.configFile || ''}`;
setResult('emailTestResult', '');
setResult('desktopTestResult', '');
setResult('webhookTestResult', '');
setResult('saveResult', '');
}
/** 按报文格式切换 WebHook 的钉钉专属字段,并给出格式说明 */
function syncWebhookFields() {
const isDingTalk = document.getElementById('webhookFormat').value === 'dingtalk';
document.getElementById('webhookSecretField').hidden = !isDingTalk;
document.getElementById('webhookKeywordField').hidden = !isDingTalk;
document.getElementById('webhookAtMobilesField').hidden = !isDingTalk;
document.getElementById('webhookMentionAllField').hidden = !isDingTalk;
document.getElementById('webhookUrl').placeholder = isDingTalk
? 'https://oapi.dingtalk.com/robot/send?access_token=xxx'
: 'https://your-server.com/hooks/gold-alert';
document.getElementById('webhookFormatHint').textContent = isDingTalk
? '钉钉:群设置 → 机器人 → 自定义 → Webhook 地址。安全设置若用「加签」填密钥,若用「自定义关键词」把那个词填到上面(工具会自动拼进消息标题),二者可只开一个。'
: '内置 JSON:POST { event, title, message, markdown, at, rule, lines, source },第三方系统按字段取用即可。';
}
/** 收集设置表单,保存到后端 */
async function saveSettings() {
const emailPass = document.getElementById('emailPass').value.trim();
const payload = {
desktop: { enabled: document.getElementById('desktopEnabled').checked },
channels: {
onTrigger: [
document.getElementById('channelDesktop').checked ? 'desktop' : null,
document.getElementById('channelEmail').checked ? 'email' : null,
document.getElementById('channelWebhook').checked ? 'webhook' : null,
].filter(Boolean),
},
monitor: {
defaultIntervalSec: Number(document.getElementById('defaultInterval').value) || 30,
alertOnFirstCheck: document.getElementById('alertOnFirstCheck').checked,
quietHours: {
enabled: document.getElementById('quietEnabled').checked,
range: document.getElementById('quietRange').value.trim() || '23:00-07:00',
desktopOnly: true,
},
},
email: {
enabled: document.getElementById('emailEnabled').checked,
host: document.getElementById('emailHost').value.trim(),
port: Number(document.getElementById('emailPort').value) || 465,
secure: document.getElementById('emailSecure').value === 'true',
user: document.getElementById('emailUser').value.trim(),
from: document.getElementById('emailFrom').value.trim(),
to: document.getElementById('emailTo').value.split(/[,;,;\s]+/).filter(Boolean),
subjectPrefix: document.getElementById('emailPrefix').value.trim() || '【金价提醒】',
withSnapshot: document.getElementById('emailSnapshot').checked,
},
webhook: {
enabled: document.getElementById('webhookEnabled').checked,
url: document.getElementById('webhookUrl').value.trim(),
format: document.getElementById('webhookFormat').value === 'dingtalk' ? 'dingtalk' : 'generic',
keyword: document.getElementById('webhookKeyword').value.trim(),
atMobiles: document.getElementById('webhookAtMobiles').value.split(/[,;,;\s]+/).filter(Boolean),
mentionAll: document.getElementById('webhookMentionAll').checked,
},
app: {
port: Number(document.getElementById('appPort').value) || 8787,
host: document.getElementById('appHost').value.trim() || '127.0.0.1',
token: document.getElementById('appToken').value.trim(),
openBrowser: document.getElementById('appOpenBrowser').checked,
},
};
// 只有用户真正输入了密码才提交,避免把打码值写回
if (emailPass) payload.email.pass = emailPass;
// 加签密钥同理:留空表示沿用已保存的密钥
const webhookSecret = document.getElementById('webhookSecret').value.trim();
if (webhookSecret) payload.webhook.secret = webhookSecret;
const res = await api('/api/config', { method: 'PUT', body: payload });
applyState(res, false);
fillSettings();
setResult('saveResult', '已保存', true);
toast('设置已保存', 'ok');
return res;
}
/* ==================================================================
* 弹窗:品种
* ================================================================== */
/** 打开品种弹窗(id 为空表示新增) */
function openInstrumentModal(id) {
const data = ui.data;
ui.editingInstrumentId = id || null;
const inst = id ? (data.instruments || []).find((i) => i.id === id) : null;
document.getElementById('instrumentModalTitle').textContent = inst ? `编辑品种 · ${inst.name}` : '添加品种';
setResult('instrumentResult', '');
// 预设下拉
const presetRow = document.getElementById('presetSelect').closest('label');
const presets = data?.config?.meta?.presets || [];
if (!inst) {
presetRow.hidden = false;
const groups = new Map();
for (const p of presets) {
if (!groups.has(p.category)) groups.set(p.category, []);
groups.get(p.category).push(p);
}
const select = document.getElementById('presetSelect');
select.innerHTML = [...groups.entries()].map(([category, items]) => `
<optgroup label="${esc(category)}">
${items.map((p) => `<option value="${esc(p.key)}">${esc(p.name)}</option>`).join('')}
</optgroup>`).join('');
select.value = presets[0]?.key || '';
} else {
presetRow.hidden = true;
}
// 数据源下拉(编辑模式可见)
const sourceSelect = document.getElementById('instSource');
sourceSelect.innerHTML = (data?.config?.meta?.dataSources || [])
.map((s) => `<option value="${esc(s.key)}">${esc(s.label)}</option>`).join('');
sourceSelect.closest('label').hidden = !inst;
// 填入字段
document.getElementById('instName').value = inst?.name || '';
document.getElementById('instInterval').value = inst?.intervalSec ?? data?.config?.monitor.defaultIntervalSec ?? 30;
document.getElementById('instUnit').value = inst?.unit || '元/克';
document.getElementById('instDigits').value = inst?.digits ?? 2;
sourceSelect.value = inst?.source || presets[0]?.source || 'sina';
document.getElementById('instSinaCode').value = inst?.sourceOptions?.code || '';
document.getElementById('instRijinjiaKey').value = inst?.sourceOptions?.key || '';
document.getElementById('instHttpUrl').value = inst?.sourceOptions?.url || '';
document.getElementById('instHttpPricePath').value = inst?.sourceOptions?.pricePath || 'data.price';
document.getElementById('instHttpPrevPath').value = inst?.sourceOptions?.prevClosePath || '';
syncInstrumentFields();
// 新增模式最后再按预设回填,避免被上面的空值覆盖
if (!inst) applyPreset(document.getElementById('presetSelect').value);
openModal('modalInstrument');
}
/** 根据数据源显示/隐藏对应参数输入 */
function syncInstrumentFields() {
const source = document.getElementById('instSource').value;
document.getElementById('sinaCodeField').hidden = source !== 'sina';
document.getElementById('rijinjiaKeyField').hidden = source !== 'rijinjia';
document.getElementById('httpUrlField').hidden = source !== 'http-json';
document.getElementById('httpPricePathField').hidden = source !== 'http-json';
document.getElementById('httpPrevPathField').hidden = source !== 'http-json';
document.getElementById('instSource').closest('label').hidden = !ui.editingInstrumentId;
}
/** 从预设回填字段 */
function applyPreset(presetKey) {
const preset = (ui.data?.config?.meta?.presets || []).find((p) => p.key === presetKey);
if (!preset) return;
document.getElementById('instName').value = preset.name;
document.getElementById('instInterval').value = preset.intervalSec || 30;
document.getElementById('instUnit').value = preset.unit || '元/克';
document.getElementById('instDigits').value = preset.digits ?? 2;
document.getElementById('instSource').value = preset.source;
document.getElementById('instSinaCode').value = preset.sourceOptions?.code || '';
document.getElementById('instRijinjiaKey').value = preset.sourceOptions?.key || '';
document.getElementById('instHttpUrl').value = preset.sourceOptions?.url || '';
document.getElementById('instHttpPricePath').value = preset.sourceOptions?.pricePath || 'data.price';
document.getElementById('instHttpPrevPath').value = preset.sourceOptions?.prevClosePath || '';
document.getElementById('presetHint').textContent = preset.note || '';
syncInstrumentFields();
}
/** 收集品种弹窗的字段 */
function collectInstrument(extra = {}) {
const source = document.getElementById('instSource').value;
const sourceOptions = {};
if (source === 'sina') sourceOptions.code = document.getElementById('instSinaCode').value.trim();
if (source === 'rijinjia') sourceOptions.key = document.getElementById('instRijinjiaKey').value.trim();
if (source === 'http-json') {
sourceOptions.url = document.getElementById('instHttpUrl').value.trim();
sourceOptions.pricePath = document.getElementById('instHttpPricePath').value.trim() || 'price';
const prevPath = document.getElementById('instHttpPrevPath').value.trim();
if (prevPath) sourceOptions.prevClosePath = prevPath;
}
return {
name: document.getElementById('instName').value.trim(),
source,
sourceOptions,
unit: document.getElementById('instUnit').value.trim() || '元/克',
digits: Number(document.getElementById('instDigits').value) || 2,
intervalSec: Number(document.getElementById('instInterval').value) || 30,
...extra,
};
}
/** 保存品种 */
async function saveInstrument() {
const body = collectInstrument();
if (!body.name) {
setResult('instrumentResult', '请填写名称', false);
return;
}
try {
let res;
if (ui.editingInstrumentId) {
res = await api(`/api/instruments/${ui.editingInstrumentId}`, { method: 'PUT', body });
} else {
body.presetKey = document.getElementById('presetSelect').value;
res = await api('/api/instruments', { method: 'POST', body });
}
applyState(res, true);
closeModal('modalInstrument');
toast(ui.editingInstrumentId ? '品种已更新' : '品种已添加', 'ok');
} catch (err) {
setResult('instrumentResult', err.message, false);
}
}
/* ==================================================================
* 弹窗:规则
* ================================================================== */
/** 按规则类型刷新方向选项与字段显隐 */
function syncRuleFields() {
const type = document.getElementById('ruleType').value;
const isSchedule = type === 'schedule';
/** 请求失败告警按「连续失败次数」触发,不看价格也不看方向 */
const isFailure = type === 'failure';
/** 需要「口径」下拉的类型:涨跌幅看百分比/具体值;阶梯看步长的单位 */
const hasBasis = type === 'change' || type === 'ladder';
2026-11-24 16:37:13 +08:00
const dirSelect = document.getElementById('ruleDirection');
// 涨跌幅 / 阶梯的阈值口径:percent 按百分比,amount 按具体价格变动值
2026-11-24 16:37:13 +08:00
const isAmount = document.getElementById('ruleBasis').value === 'amount';
const unit = unitOf(document.getElementById('ruleInstrument').value);
const changeUnitText = isAmount ? unit : '%';
const options = type === 'threshold'
? [['above', '上破(价格 ≥ 阈值)'], ['below', '下破(价格 ≤ 阈值)']]
: type === 'change'
? [['up', `涨幅 ≥ 阈值(${changeUnitText})`], ['down', `跌幅 ≥ 阈值(${changeUnitText})`], ['both', `涨跌幅绝对值 ≥ 阈值(${changeUnitText})`]]
: type === 'ladder'
? [['up', '每上涨一个步长 提醒一次'], ['down', '每下跌一个步长 提醒一次'], ['both', '每涨/跌一个步长 提醒一次']]
: type === 'failure'
? [['abs', '连续查询失败达到次数即提醒']]
: [['abs', '绝对价差 ≥ 阈值'], ['above', '前者高于后者 ≥ 阈值'], ['below', '后者高于前者 ≥ 阈值']];
2026-11-24 16:37:13 +08:00
const current = dirSelect.value;
dirSelect.innerHTML = options.map(([v, t]) => `<option value="${v}">${t}</option>`).join('');
dirSelect.value = options.some(([v]) => v === current) ? current : options[0][0];
document.getElementById('ruleCompareField').hidden = type !== 'spread';
document.getElementById('ruleModeField').hidden = type !== 'spread';
document.getElementById('ruleBasisField').hidden = !hasBasis;
2026-11-24 16:37:13 +08:00
document.getElementById('ruleWindowField').hidden = type !== 'change';
// 定时提醒 / 请求失败告警都不看价格方向
document.getElementById('ruleDirectionField').hidden = isSchedule || isFailure;
2026-11-24 16:37:13 +08:00
document.getElementById('ruleValueField').hidden = isSchedule;
document.getElementById('ruleActiveRangeField').hidden = isSchedule;
// 请求失败告警没有「冷却」概念(次数本身就是节流),冷却字段收起
document.getElementById('ruleCooldownField').hidden = isSchedule || isFailure;
// 阶梯提醒按步长计算,没有「持续满足重复提醒」的概念(重复字段收起)
document.getElementById('ruleRepeatField').hidden = isSchedule || type === 'ladder';
// 阶梯提醒专用:连续同向确认次数 / 强制提醒幅度
document.getElementById('ruleStreakField').hidden = type !== 'ladder';
document.getElementById('ruleForceField').hidden = type !== 'ladder';
document.getElementById('ruleForceLabel').textContent = isAmount
? `强制提醒幅度(${unit})`
: '强制提醒幅度(%)';
// 重复间隔文案:价格类规则是「持续满足」,失败告警是「持续失败」
document.getElementById('ruleRepeatLabel').textContent = isFailure
? '持续失败时每 N 秒重复提醒(0 只提醒一次)'
: '持续满足时每 N 秒重复提醒(0 不重复)';
2026-11-24 16:37:13 +08:00
// 定时提醒自己的字段:时刻、重复方式、每周星期
document.getElementById('ruleScheduleTimesField').hidden = !isSchedule;
document.getElementById('ruleScheduleRepeatField').hidden = !isSchedule;
syncScheduleWeekdays();
syncWindowCustom();
document.getElementById('ruleValueLabel').textContent = type === 'threshold'
? '阈值(价格)'
: type === 'change' ? (isAmount ? `阈值(${unit})` : '阈值(百分比 %)')
: type === 'ladder' ? (isAmount ? `阶梯步长(${unit})` : '阶梯步长(%)')
: type === 'failure' ? '连续失败次数(次)'
: '阈值(价差)';
// 阈值输入框的示例值、步长按当前口径切换(次数是整数,价格类允许 3 位小数)
const valueInput = document.getElementById('ruleValue');
valueInput.step = isFailure ? '1' : '0.001';
valueInput.placeholder = type === 'threshold'
2026-11-24 16:37:13 +08:00
? '800'
: hasBasis ? (isAmount ? '2' : '0.5')
: isFailure ? '3'
: (document.getElementById('ruleMode').value === 'percent' ? '1' : '100');
// 各类型的说明文案各管各的
2026-11-24 16:37:13 +08:00
document.getElementById('ruleWindowHint').hidden = type !== 'change';
document.getElementById('ruleScheduleHint').hidden = !isSchedule;
document.getElementById('ruleLadderHint').hidden = type !== 'ladder';
document.getElementById('ruleFailureHint').hidden = !isFailure;
2026-11-24 16:37:13 +08:00
updateRuleSummary();
}
/** 定时提醒选「每周指定几天」时显示星期勾选框 */
function syncScheduleWeekdays() {
const isSchedule = document.getElementById('ruleType').value === 'schedule';
const isWeekly = isSchedule && document.getElementById('ruleScheduleRepeat').value === 'weekly';
document.getElementById('ruleScheduleWeekdaysField').hidden = !isWeekly;
}
/**
* 读取定时提醒的时刻列表
* 支持逗号/空格分隔,自动补零、去重、按时间排序
* @returns {string[]} 形如 ["09:00","15:30"]
*/
function readScheduleTimes() {
const raw = document.getElementById('ruleScheduleTimes').value || '';
const seen = new Set();
const list = [];
for (const item of raw.split(/[,,\s]+/)) {
const text = item.trim();
if (!/^\d{1,2}:\d{2}$/.test(text)) continue;
const [h, m] = text.split(':').map(Number);
if (h > 23 || m > 59) continue;
const hhmm = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
if (seen.has(hhmm)) continue;
seen.add(hhmm);
list.push(hhmm);
}
return list.sort();
}
/**
* 读取定时提醒选中的星期
* @returns {number[]} 1=周一 … 7=周日
*/
function readScheduleWeekdays() {
return [...document.querySelectorAll('.js-weekday:checked')].map((el) => Number(el.value)).sort((a, b) => a - b);
}
/** 统计区间选「自定义」时显示分钟输入框 */
function syncWindowCustom() {
const isChange = document.getElementById('ruleType').value === 'change';
const isCustom = isChange && document.getElementById('ruleWindow').value === '-1';
document.getElementById('ruleWindowCustomField').hidden = !isCustom;
}
/**
* 读取弹窗里的统计区间(秒)
* @returns {number} 0 表示日内(相对昨收),>0 表示近 N 秒滚动窗口
*/
function readWindowSec() {
if (document.getElementById('ruleType').value !== 'change') return 0;
const selectValue = document.getElementById('ruleWindow').value;
if (selectValue === '-1') {
const minutes = Number(document.getElementById('ruleWindowCustom').value);
return Number.isFinite(minutes) && minutes > 0 ? Math.round(minutes * 60) : 0;
}
return Number(selectValue) || 0;
}
/**
* 读取生效时段
* @returns {string} "HH:mm-HH:mm",两端任一为空则返回空字符串(表示全天)
*/
function readActiveRange() {
const from = document.getElementById('ruleActiveFrom').value;
const to = document.getElementById('ruleActiveTo').value;
return from && to ? `${from}-${to}` : '';
}
/** 生成规则预览文案 */
function updateRuleSummary() {
const type = document.getElementById('ruleType').value;
const draft = {
type,
instrumentId: document.getElementById('ruleInstrument').value,
compareInstrumentId: document.getElementById('ruleCompare').value,
mode: document.getElementById('ruleMode').value,
changeBasis: document.getElementById('ruleBasis').value,
// 阶梯提醒的连续确认次数、强制提醒幅度也进预览文案
ladderStreak: Number(document.getElementById('ruleStreak').value) || 1,
forceAlertValue: Number(document.getElementById('ruleForce').value) || 0,
2026-11-24 16:37:13 +08:00
direction: document.getElementById('ruleDirection').value,
value: Number(document.getElementById('ruleValue').value) || 0,
cooldownSec: Number(document.getElementById('ruleCooldown').value) || 0,
// 失败告警的重复间隔也进预览文案
repeatIntervalSec: Number(document.getElementById('ruleRepeat').value) || 0,
2026-11-24 16:37:13 +08:00
windowSec: readWindowSec(),
activeRange: readActiveRange(),
scheduleTimes: readScheduleTimes(),
scheduleRepeat: document.getElementById('ruleScheduleRepeat').value,
scheduleWeekdays: readScheduleWeekdays(),
};
// 定时提醒没有阈值,直接按时刻生成预览
if (type === 'schedule') {
document.getElementById('ruleSummary').textContent = draft.scheduleTimes.length
? `预览:${ruleConditionText(draft)}`
: '预览:填写提醒时刻后显示条件预览';
return;
}
// 失败告警没有阈值,按「次数」生成预览
if (type === 'failure') {
const times = Math.round(Number(document.getElementById('ruleValue').value));
document.getElementById('ruleSummary').textContent = Number.isFinite(times) && times >= 1
? `预览:${ruleConditionText(draft)}`
: '预览:填写连续失败次数后显示条件预览';
return;
}
2026-11-24 16:37:13 +08:00
const value = Number(document.getElementById('ruleValue').value);
if (!Number.isFinite(value) || value === 0) {
document.getElementById('ruleSummary').textContent = '预览:填写阈值后显示条件预览';
return;
}
document.getElementById('ruleSummary').textContent = `预览:${ruleConditionText(draft)}`;
}
/** 打开规则弹窗 */
function openRuleModal(id) {
const data = ui.data;
ui.editingRuleId = id || null;
const rule = id ? (data.rules || []).find((r) => r.id === id) : null;
document.getElementById('ruleModalTitle').textContent = rule ? '编辑规则' : '新建规则';
setResult('ruleResult', '');
const instruments = data.instruments || [];
const instOptions = instruments.map((i) => `<option value="${esc(i.id)}">${esc(i.name)}</option>`).join('');
document.getElementById('ruleInstrument').innerHTML = instOptions || '<option value="">请先添加品种</option>';
document.getElementById('ruleCompare').innerHTML = instOptions || '<option value="">请先添加品种</option>';
document.getElementById('ruleName').value = rule?.name || '';
document.getElementById('ruleType').value = rule?.type || 'threshold';
document.getElementById('ruleInstrument').value = rule?.instrumentId || instruments[0]?.id || '';
document.getElementById('ruleCompare').value = rule?.compareInstrumentId || instruments[1]?.id || instruments[0]?.id || '';
document.getElementById('ruleMode').value = rule?.mode || 'abs';
document.getElementById('ruleBasis').value = rule?.changeBasis === 'amount' ? 'amount' : 'percent';
document.getElementById('ruleValue').value = rule?.value ?? '';
// 阶梯提醒的连续确认次数,默认 1(只按步长判断);强制提醒幅度默认 0(不启用)
document.getElementById('ruleStreak').value = rule?.ladderStreak ?? 1;
document.getElementById('ruleForce').value = rule?.forceAlertValue ?? 0;
2026-11-24 16:37:13 +08:00
document.getElementById('ruleCooldown').value = rule?.cooldownSec ?? 1800;
document.getElementById('ruleRepeat').value = rule?.repeatIntervalSec ?? 0;
// 定时提醒:时刻用逗号展示,重复方式与每周星期回填
document.getElementById('ruleScheduleTimes').value = (rule?.scheduleTimes || []).join(', ');
document.getElementById('ruleScheduleRepeat').value = ['daily', 'weekday', 'weekly'].includes(rule?.scheduleRepeat)
? rule.scheduleRepeat : 'daily';
const weekdays = rule?.scheduleWeekdays || [];
document.querySelectorAll('.js-weekday').forEach((el) => {
el.checked = weekdays.includes(Number(el.value));
});
// 统计区间:命中预设选项就直接选中,否则退到「自定义(分钟)」
const windowSec = Number(rule?.windowSec) || 0;
const windowSelect = document.getElementById('ruleWindow');
if (windowSec > 0 && [...windowSelect.options].some((opt) => opt.value === String(windowSec))) {
windowSelect.value = String(windowSec);
document.getElementById('ruleWindowCustom').value = '';
} else if (windowSec > 0) {
windowSelect.value = '-1';
document.getElementById('ruleWindowCustom').value = Math.round(windowSec / 60);
} else {
windowSelect.value = '0';
document.getElementById('ruleWindowCustom').value = '';
}
// 生效时段:"HH:mm-HH:mm",时间控件要求两位小时
const activeRange = String(rule?.activeRange || '');
const rangeMatch = /^(\d{1,2}):(\d{2})-(\d{1,2}):(\d{2})$/.exec(activeRange);
document.getElementById('ruleActiveFrom').value = rangeMatch
? `${String(rangeMatch[1]).padStart(2, '0')}:${rangeMatch[2]}` : '';
document.getElementById('ruleActiveTo').value = rangeMatch
? `${String(rangeMatch[3]).padStart(2, '0')}:${rangeMatch[4]}` : '';
// 新建规则时:桌面默认勾选;邮箱/WebHook 已在设置里启用则一并勾选
const defaultChannels = rule
? (rule.channels || ['desktop'])
: ['desktop']
.concat(ui.data?.config?.email?.enabled ? ['email'] : [])
.concat(ui.data?.config?.webhook?.enabled ? ['webhook'] : []);
document.getElementById('ruleChannelDesktop').checked = defaultChannels.includes('desktop');
document.getElementById('ruleChannelEmail').checked = defaultChannels.includes('email');
document.getElementById('ruleChannelWebhook').checked = defaultChannels.includes('webhook');
document.getElementById('ruleEnabled').checked = rule ? !!rule.enabled : true;
syncRuleFields();
if (rule?.direction) document.getElementById('ruleDirection').value = rule.direction;
updateRuleSummary();
openModal('modalRule');
}
/** 保存规则 */
async function saveRule() {
const instruments = ui.data?.instruments || [];
const instrumentId = document.getElementById('ruleInstrument').value;
const compareInstrumentId = document.getElementById('ruleCompare').value;
if (!instrumentId) {
setResult('ruleResult', '请先添加监控品种', false);
return;
}
const type = document.getElementById('ruleType').value;
const direction = document.getElementById('ruleDirection').value;
const value = Number(document.getElementById('ruleValue').value);
// 定时提醒不看阈值,单独校验时刻
const scheduleTimes = readScheduleTimes();
if (type === 'schedule') {
if (!scheduleTimes.length) {
setResult('ruleResult', '请填写提醒时刻,例如 09:00, 15:30', false);
return;
}
if (scheduleTimes.length > 12) {
setResult('ruleResult', '提醒时刻最多 12 个', false);
return;
}
if (document.getElementById('ruleScheduleRepeat').value === 'weekly' && !readScheduleWeekdays().length) {
setResult('ruleResult', '请至少勾选一个星期几', false);
return;
}
} else if (type === 'failure') {
// 失败次数必须是 ≥1 的整数
if (!Number.isFinite(value) || value < 1) {
setResult('ruleResult', '请填写连续失败次数(至少 1 次,常用 3 次)', false);
return;
}
2026-11-24 16:37:13 +08:00
} else if (!Number.isFinite(value) || (type !== 'threshold' && value === 0)) {
setResult('ruleResult', '请填写有效的阈值', false);
return;
}
// 阶梯提醒的连续确认次数:后端限制 1–20 次
if (type === 'ladder') {
const streak = Number(document.getElementById('ruleStreak').value);
if (!Number.isFinite(streak) || streak < 1 || streak > 20) {
setResult('ruleResult', '连续确认次数请填 1–20(填 1 表示只按步长判断)', false);
return;
}
// 强制提醒幅度:0 = 不启用;小于步长时后端按步长算,不报错
const force = Number(document.getElementById('ruleForce').value);
if (!Number.isFinite(force) || force < 0) {
setResult('ruleResult', '强制提醒幅度请填 0 或正数(0 表示不启用)', false);
return;
}
}
2026-11-24 16:37:13 +08:00
const inst = instruments.find((i) => i.id === instrumentId);
const nameInput = document.getElementById('ruleName').value.trim();
const channels = [
document.getElementById('ruleChannelDesktop').checked ? 'desktop' : null,
document.getElementById('ruleChannelEmail').checked ? 'email' : null,
document.getElementById('ruleChannelWebhook').checked ? 'webhook' : null,
].filter(Boolean);
if (channels.length === 0) {
setResult('ruleResult', '至少选择一个通知渠道', false);
return;
}
// 统计区间 / 生效时段
const windowSec = readWindowSec();
if (type === 'change' && document.getElementById('ruleWindow').value === '-1' && windowSec <= 0) {
setResult('ruleResult', '请填写自定义的统计区间(分钟)', false);
return;
}
// 后端最长支持 12 小时,这里提前拦一下,免得填太大被静默截断
if (type === 'change' && windowSec > 43200) {
setResult('ruleResult', '统计区间最长 12 小时(720 分钟)', false);
return;
}
const activeRange = readActiveRange();
const body = {
// 未填名称时直接用条件文案(条件里已含品种名,不再重复拼接)
name: nameInput || ruleConditionText({
type, direction, value, instrumentId, compareInstrumentId,
mode: document.getElementById('ruleMode').value,
changeBasis: document.getElementById('ruleBasis').value,
// 阶梯提醒的名称里带上连续确认次数,便于区分同一步长的多条规则
ladderStreak: Number(document.getElementById('ruleStreak').value) || 1,
// 名称里也带上强制幅度(>0 才算)
forceAlertValue: Number(document.getElementById('ruleForce').value) || 0,
2026-11-24 16:37:13 +08:00
windowSec, activeRange,
// 失败告警的名称里也带上重复间隔,避免多条同类规则名字撞车
repeatIntervalSec: Number(document.getElementById('ruleRepeat').value) || 0,
2026-11-24 16:37:13 +08:00
scheduleTimes,
scheduleRepeat: document.getElementById('ruleScheduleRepeat').value,
scheduleWeekdays: readScheduleWeekdays(),
}),
type,
instrumentId,
compareInstrumentId: type === 'spread' ? compareInstrumentId : '',
mode: document.getElementById('ruleMode').value,
// 涨跌幅 / 阶梯的阈值口径:percent(百分比)/ amount(具体变动值)
changeBasis: (type === 'change' || type === 'ladder') ? document.getElementById('ruleBasis').value : 'percent',
// 阶梯提醒的连续确认次数(仅阶梯用,其它类型固定 1)
ladderStreak: type === 'ladder' ? (Number(document.getElementById('ruleStreak').value) || 1) : 1,
// 阶梯提醒的强制提醒幅度(仅阶梯用,0 = 不启用)
forceAlertValue: type === 'ladder' ? (Number(document.getElementById('ruleForce').value) || 0) : 0,
2026-11-24 16:37:13 +08:00
direction: type === 'schedule' ? 'abs' : direction,
value: type === 'schedule' ? 0 : value,
// 失败告警不用冷却,冷却置 0,节流交给「持续失败重复间隔」
cooldownSec: type === 'failure' ? 0 : (Number(document.getElementById('ruleCooldown').value) || 1800),
2026-11-24 16:37:13 +08:00
repeatIntervalSec: Number(document.getElementById('ruleRepeat').value) || 0,
windowSec,
activeRange,
// 定时提醒:到点时刻(后端会再归一化一次)、重复方式、每周星期
scheduleTimes,
scheduleRepeat: document.getElementById('ruleScheduleRepeat').value,
scheduleWeekdays: readScheduleWeekdays(),
channels,
enabled: document.getElementById('ruleEnabled').checked,
};
try {
const res = ui.editingRuleId
? await api(`/api/rules/${ui.editingRuleId}`, { method: 'PUT', body })
: await api('/api/rules', { method: 'POST', body });
applyState(res, false);
closeModal('modalRule');
toast(ui.editingRuleId ? '规则已更新' : '规则已创建', 'ok');
} catch (err) {
setResult('ruleResult', err.message, false);
}
}
/* ==================================================================
* 弹窗通用
* ================================================================== */
/** 打开弹窗 */
function openModal(id) {
document.getElementById(id).hidden = false;
document.body.style.overflow = 'hidden';
}
/** 关闭弹窗 */
function closeModal(id) {
document.getElementById(id).hidden = true;
document.body.style.overflow = '';
}
/* ==================================================================
* 事件绑定与启动
* ================================================================== */
/** 切换标签页 */
function activateTab(name) {
const tab = document.querySelector(`.tab[data-tab="${name}"]`);
if (!tab) return;
document.querySelectorAll('.tab').forEach((t) => t.classList.toggle('active', t === tab));
document.querySelectorAll('.panel').forEach((p) => p.classList.remove('active'));
document.querySelector(`#panel-${name}`).classList.add('active');
ui.tab = name;
if (name === 'alerts') {
ui.seenAtMs = Date.now();
ui.unread = 0;
}
if (name === 'channels') fillSettings();
renderActiveTab();
renderHeader();
}
/** 绑定所有交互事件 */
function bindEvents() {
// 标签页切换
document.getElementById('tabs').addEventListener('click', (e) => {
const tab = e.target.closest('.tab');
if (!tab) return;
activateTab(tab.dataset.tab);
});
// 暂停 / 开始
document.getElementById('btnToggleRun').addEventListener('click', async () => {
const running = !(ui.data?.running);
try {
const res = await api('/api/monitor', { method: 'POST', body: { running } });
applyState(res, false);
toast(running ? '监控已开始' : '监控已暂停', 'ok');
} catch (err) {
toast(err.message, 'err');
}
});
// 立即刷新
document.getElementById('btnRefresh').addEventListener('click', async (e) => {
e.target.disabled = true;
try {
const res = await api('/api/refresh', { method: 'POST' });
applyState(res, false);
toast('已拉取最新行情', 'ok');
} catch (err) {
toast(err.message, 'err');
} finally {
e.target.disabled = false;
}
});
// 品种
document.getElementById('btnAddInstrument').addEventListener('click', () => openInstrumentModal(null));
document.getElementById('presetSelect').addEventListener('change', (e) => applyPreset(e.target.value));
document.getElementById('instSource').addEventListener('change', syncInstrumentFields);
document.getElementById('btnSaveInstrument').addEventListener('click', saveInstrument);
document.getElementById('btnTestInstrument').addEventListener('click', async () => {
const body = collectInstrument();
setResult('instrumentResult', '正在试抓取…', null);
try {
const res = await api('/api/test/source', { method: 'POST', body });
setResult('instrumentResult', res.detail || '抓取成功', true);
} catch (err) {
setResult('instrumentResult', err.message, false);
}
});
// 规则
document.getElementById('btnAddRule').addEventListener('click', () => openRuleModal(null));
document.getElementById('ruleType').addEventListener('change', () => {
const type = document.getElementById('ruleType').value;
// 切到阶梯提醒且步长还空着时,默认按「具体值(元/克)」口径,符合「每涨 2 元提醒」的直觉
if (type === 'ladder' && !document.getElementById('ruleValue').value) {
document.getElementById('ruleBasis').value = 'amount';
}
// 阶梯提醒本来就按步长逐档提醒,默认的 30 分钟冷却太长,切过去时改回 60 秒
if (type === 'ladder' && document.getElementById('ruleCooldown').value === '1800') {
document.getElementById('ruleCooldown').value = '60';
}
// 切到请求失败告警且次数还空着时,先给个常见的「连续 3 次」占位
if (type === 'failure' && !document.getElementById('ruleValue').value) {
document.getElementById('ruleValue').value = '3';
}
syncRuleFields();
});
2026-11-24 16:37:13 +08:00
document.getElementById('ruleInstrument').addEventListener('change', syncRuleFields);
document.getElementById('ruleCompare').addEventListener('change', updateRuleSummary);
document.getElementById('ruleMode').addEventListener('change', syncRuleFields);
document.getElementById('ruleBasis').addEventListener('change', syncRuleFields);
document.getElementById('ruleDirection').addEventListener('change', updateRuleSummary);
document.getElementById('ruleValue').addEventListener('input', updateRuleSummary);
document.getElementById('ruleCooldown').addEventListener('input', updateRuleSummary);
// 失败告警的重复间隔改动也要立刻反映到预览文案
document.getElementById('ruleRepeat').addEventListener('input', updateRuleSummary);
// 阶梯提醒的连续确认次数改动同理
document.getElementById('ruleStreak').addEventListener('input', updateRuleSummary);
// 强制提醒幅度改动也要立刻反映到预览
document.getElementById('ruleForce').addEventListener('input', updateRuleSummary);
2026-11-24 16:37:13 +08:00
// 统计区间与生效时段:改动后同步字段显隐和预览
document.getElementById('ruleWindow').addEventListener('change', () => {
syncWindowCustom();
updateRuleSummary();
});
document.getElementById('ruleWindowCustom').addEventListener('input', updateRuleSummary);
document.getElementById('ruleActiveFrom').addEventListener('change', updateRuleSummary);
document.getElementById('ruleActiveTo').addEventListener('change', updateRuleSummary);
// 定时提醒:时刻输入、重复方式、星期勾选都会影响预览
document.getElementById('ruleScheduleTimes').addEventListener('input', updateRuleSummary);
document.getElementById('ruleScheduleRepeat').addEventListener('change', () => {
syncScheduleWeekdays();
updateRuleSummary();
});
document.querySelectorAll('.js-weekday').forEach((el) => el.addEventListener('change', updateRuleSummary));
document.getElementById('btnSaveRule').addEventListener('click', saveRule);
// 设置保存
document.getElementById('btnSaveSettings').addEventListener('click', async () => {
try {
await saveSettings();
} catch (err) {
setResult('saveResult', err.message, false);
}
});
// 渠道自检
document.getElementById('btnTestDesktop').addEventListener('click', async () => {
setResult('desktopTestResult', '发送中…', null);
try {
const res = await api('/api/test/desktop', { method: 'POST' });
setResult('desktopTestResult', res.detail || '已发送', true);
} catch (err) {
setResult('desktopTestResult', err.message, false);
}
});
document.getElementById('btnTestEmail').addEventListener('click', async () => {
setResult('emailTestResult', '发送中,请稍候…', null);
try {
// 先把表单里的邮箱设置存下来再测,避免测的是旧配置
await saveSettings();
const res = await api('/api/test/email', { method: 'POST', body: {} });
setResult('emailTestResult', res.detail || '已发送', true);
} catch (err) {
setResult('emailTestResult', err.message, false);
}
});
// WebHook:切换格式时同步字段显隐
document.getElementById('webhookFormat').addEventListener('change', syncWebhookFields);
document.getElementById('btnTestWebhook').addEventListener('click', async () => {
setResult('webhookTestResult', '推送中,请稍候…', null);
try {
// 先保存再测,避免测的是旧地址/旧格式
await saveSettings();
const res = await api('/api/test/webhook', { method: 'POST', body: {} });
setResult('webhookTestResult', res.detail || '已推送', true);
} catch (err) {
setResult('webhookTestResult', err.message, false);
}
});
// 清空提醒
document.getElementById('btnClearAlerts').addEventListener('click', async () => {
if (!window.confirm('确定清空页面上的提醒记录?data/alerts.jsonl 文件保留不动。')) return;
try {
await api('/api/alerts', { method: 'DELETE' });
ui.data.alerts = [];
renderAlerts();
renderHeader();
} catch (err) {
toast(err.message, 'err');
}
});
2026-11-24 17:22:08 +08:00
// 配置导入导出
2026-11-24 16:37:13 +08:00
document.getElementById('btnExportConfig').addEventListener('click', () => {
2026-11-24 17:22:08 +08:00
// 勾了「包含密钥」才把真实密码/加签密钥写进文件,默认脱敏,方便分享
const withSecrets = document.getElementById('exportWithSecrets').checked;
window.location.href = `/api/config/export${withSecrets ? '?secrets=1' : ''}`;
toast(withSecrets ? '正在导出(含密钥,请妥善保管)' : '正在导出(密钥已脱敏)', 'ok');
2026-11-24 16:37:13 +08:00
});
2026-11-24 17:22:08 +08:00
2026-11-24 16:37:13 +08:00
document.getElementById('btnImportConfig').addEventListener('click', () => document.getElementById('importFile').click());
document.getElementById('importFile').addEventListener('change', async (e) => {
const file = e.target.files?.[0];
2026-11-24 17:22:08 +08:00
e.target.value = '';
2026-11-24 16:37:13 +08:00
if (!file) return;
try {
const text = await file.text();
const json = JSON.parse(text);
2026-11-24 17:22:08 +08:00
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');
2026-11-24 16:37:13 +08:00
} catch (err) {
toast(`导入失败:${err.message}`, 'err');
2026-11-24 17:22:08 +08:00
}
});
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);
2026-11-24 16:37:13 +08:00
}
});
// 弹窗关闭(关闭按钮 / 取消按钮 / Esc)
// 点击遮罩一律不关闭:弹窗里都有表单,误点外面容易把填了一半的内容丢掉,所以只给个轻提示
document.querySelectorAll('.modal').forEach((modal) => {
modal.addEventListener('click', (e) => {
if (e.target !== modal) return;
toast('点「取消」或右上角 ✕ 才会关闭窗口', '');
});
});
document.querySelectorAll('[data-close]').forEach((btn) => {
btn.addEventListener('click', () => closeModal(btn.dataset.close));
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
document.querySelectorAll('.modal:not([hidden])').forEach((m) => closeModal(m.id));
}
});
}
const TABS = ['market', 'rules', 'channels', 'alerts'];
2026-11-24 17:22:08 +08:00
/**
* 生成导入前的配置摘要(覆盖前先看清楚要导入什么)
* @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: '涨跌幅', ladder: '阶梯', spread: '价差', schedule: '定时', failure: '失败告警' };
2026-11-24 17:22:08 +08:00
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}`;
}
}
2026-11-24 16:37:13 +08:00
/** 启动 */
async function boot() {
bindEvents();
await refreshState(true);
2026-11-24 17:22:08 +08:00
refreshBackupList();
2026-11-24 16:37:13 +08:00
const hashTab = (location.hash || '').replace('#', '');
if (TABS.includes(hashTab)) activateTab(hashTab);
window.addEventListener('hashchange', () => {
const h = (location.hash || '').replace('#', '');
if (TABS.includes(h)) activateTab(h);
});
startPolling();
}
boot();