From e484d2a87df407b20a37edb17d4942a8cb059e58 Mon Sep 17 00:00:00 2001 From: yangxiangyuan Date: Fri, 31 Jul 2026 14:29:14 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=8B=86=E5=88=86=E9=80=9A?= =?UTF-8?q?=E7=94=A8=E8=B5=84=E9=87=91=E5=B7=A5=E5=85=B7=E4=B8=BA=E5=9B=BD?= =?UTF-8?q?=E4=BF=A1=E5=92=8C=E5=8D=8E=E6=B3=B0=E8=AF=81=E5=88=B8=E4=B8=93?= =?UTF-8?q?=E5=B1=9E=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除原通用funds工具代码与配置 - 新增国信证券、华泰证券专属资金工具页面、样式与逻辑 - 为两个工具添加独立的鉴权配置 - 更新导航菜单,将原通用入口替换为两个券商专属入口 - 新增对应券商的SVG图标文件 --- public/common/nav.html | 3 +- public/common/nav.js | 3 +- public/icons/{funds.svg => funds_guoxin.svg} | 0 public/icons/funds_huatai.svg | 3 + public/tools/funds/auth_config.json | 7 - public/tools/funds_guoxin/auth_config.json | 9 + .../funds_guoxin.css} | 0 .../funds.js => funds_guoxin/funds_guoxin.js} | 38 ++- .../tools/{funds => funds_guoxin}/index.html | 27 +- public/tools/funds_huatai/auth_config.json | 9 + public/tools/funds_huatai/funds_huatai.css | 280 ++++++++++++++++++ public/tools/funds_huatai/funds_huatai.js | 170 +++++++++++ public/tools/funds_huatai/index.html | 76 +++++ src/server/{funds.js => funds_guoxin.js} | 38 ++- src/server/funds_huatai.js | 219 ++++++++++++++ src/server/index.js | 184 +++++++++--- 16 files changed, 957 insertions(+), 109 deletions(-) rename public/icons/{funds.svg => funds_guoxin.svg} (100%) create mode 100644 public/icons/funds_huatai.svg delete mode 100644 public/tools/funds/auth_config.json create mode 100644 public/tools/funds_guoxin/auth_config.json rename public/tools/{funds/funds.css => funds_guoxin/funds_guoxin.css} (100%) rename public/tools/{funds/funds.js => funds_guoxin/funds_guoxin.js} (82%) rename public/tools/{funds => funds_guoxin}/index.html (76%) create mode 100644 public/tools/funds_huatai/auth_config.json create mode 100644 public/tools/funds_huatai/funds_huatai.css create mode 100644 public/tools/funds_huatai/funds_huatai.js create mode 100644 public/tools/funds_huatai/index.html rename src/server/{funds.js => funds_guoxin.js} (79%) create mode 100644 src/server/funds_huatai.js diff --git a/public/common/nav.html b/public/common/nav.html index 2a5399d..d6fbcf5 100644 --- a/public/common/nav.html +++ b/public/common/nav.html @@ -3,7 +3,8 @@ 微博跟踪 市场跟踪 告知墙 - 本金变动池 + 国信证券 + 华泰证券 建行私募理财 云产品管理 工作周报 diff --git a/public/common/nav.js b/public/common/nav.js index f13ce9f..4a94598 100644 --- a/public/common/nav.js +++ b/public/common/nav.js @@ -10,7 +10,8 @@ if (path.includes('/tools/weibo/')) key = 'weibo' else if (path.includes('/tools/markets/')) key = 'markets' else if (path.includes('/tools/wall/')) key = 'wall' - else if (path.includes('/tools/funds/')) key = 'funds' + else if (path.includes('/tools/funds_guoxin/')) key = 'funds_guoxin' + else if (path.includes('/tools/funds_huatai/')) key = 'funds_huatai' else if (path.includes('/tools/ccb_private_funds/')) key = 'ccb_private_funds' else if (path.includes('/tools/cloud/')) key = 'cloud' else if (path.includes('/tools/weekly/')) key = 'weekly' diff --git a/public/icons/funds.svg b/public/icons/funds_guoxin.svg similarity index 100% rename from public/icons/funds.svg rename to public/icons/funds_guoxin.svg diff --git a/public/icons/funds_huatai.svg b/public/icons/funds_huatai.svg new file mode 100644 index 0000000..e9be5b8 --- /dev/null +++ b/public/icons/funds_huatai.svg @@ -0,0 +1,3 @@ + + 📊 + diff --git a/public/tools/funds/auth_config.json b/public/tools/funds/auth_config.json deleted file mode 100644 index ec6b05d..0000000 --- a/public/tools/funds/auth_config.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "_comment": "资金流水工具的前端鉴权配置", - "enable_auth_comment": "true:启用鉴权(需要从导航登录);false:完全放开访问资金工具", - "enable_auth": true, - "max_age_days_comment": "鉴权 cookie 的最大有效天数(1~365)", - "max_age_days": 30 -} diff --git a/public/tools/funds_guoxin/auth_config.json b/public/tools/funds_guoxin/auth_config.json new file mode 100644 index 0000000..4168b25 --- /dev/null +++ b/public/tools/funds_guoxin/auth_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "国信证券-本金变动池的前端鉴权配置", + "enable_auth_comment": "true:启用鉴权(需要从导航登录);false:完全放开访问", + "enable_auth": true, + "max_age_days_comment": "鉴权 cookie 的最大有效天数(1~365)", + "max_age_days": 30, + "cookieName_comment": "鉴权 Cookie 名称", + "cookieName": "funds_guoxin_gate" +} diff --git a/public/tools/funds/funds.css b/public/tools/funds_guoxin/funds_guoxin.css similarity index 100% rename from public/tools/funds/funds.css rename to public/tools/funds_guoxin/funds_guoxin.css diff --git a/public/tools/funds/funds.js b/public/tools/funds_guoxin/funds_guoxin.js similarity index 82% rename from public/tools/funds/funds.js rename to public/tools/funds_guoxin/funds_guoxin.js index b1c4631..b4693dc 100644 --- a/public/tools/funds/funds.js +++ b/public/tools/funds_guoxin/funds_guoxin.js @@ -6,7 +6,7 @@ const logLocal = msg => { const b = logBox(); if (!b) return; const line = `${(w let editingId = null; -const loadFlags = async () => { try { const r = await fetch('/api/flags'); const d = await r.json(); if (d && d.debug && d.debug.funds) { const sec = document.getElementById('funds-debug'); if (sec) sec.style.display = '' } } catch {} +const loadFlags = async () => { try { const r = await fetch('/api/flags'); const d = await r.json(); if (d && d.debug && d.debug.funds_guoxin) { const sec = document.getElementById('funds-guoxin-debug'); if (sec) sec.style.display = '' } } catch {} } const renderRows = rows => { @@ -39,9 +39,8 @@ const renderRows = rows => { const btnAdd = document.getElementById('btn-add'); if (btnAdd) { btnAdd.textContent = '保存修改'; - btnAdd.classList.add('btn-primary'); // Optional: highlight + btnAdd.classList.add('btn-primary'); } - // Scroll to top document.querySelector('.add-bar').scrollIntoView({ behavior: 'smooth' }); }); tdOps.appendChild(btnEdit); @@ -49,9 +48,9 @@ const renderRows = rows => { const btnDel = document.createElement('button'); btnDel.className='btn'; btnDel.textContent='涤旧'; btnDel.addEventListener('click', async () => { const ok = window.confirm('确认涤旧该条流水?') if (!ok) return - try { await fetch('/api/debug/event', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ source:'funds', action:'delete', id:r.id }) }) } catch {} - logLocal(`funds.delete id=${r.id}`) - await fetch(`/api/funds/flows/${r.id}`, { method:'DELETE' }) + try { await fetch('/api/debug/event', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ source:'funds_guoxin', action:'delete', id:r.id }) }) } catch {} + logLocal(`funds_guoxin.delete id=${r.id}`) + await fetch(`/api/funds_guoxin/flows/${r.id}`, { method:'DELETE' }) await loadFlows() }) tdOps.appendChild(btnDel) @@ -64,7 +63,7 @@ const renderRows = rows => { } const loadFlows = async () => { - const st = document.getElementById('funds-status') + const st = document.getElementById('funds-guoxin-status') const btnQ = document.getElementById('btn-load') if (st) { st.style.display=''; st.textContent='正在查询...' } if (btnQ) btnQ.disabled = true @@ -73,7 +72,7 @@ const loadFlows = async () => { const type = document.getElementById('type-filter').value || 'all' const kw = document.getElementById('kw').value || '' try { - const r = await fetch(`/api/funds/flows?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}&type=${encodeURIComponent(type)}&kw=${encodeURIComponent(kw)}`) + const r = await fetch(`/api/funds_guoxin/flows?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}&type=${encodeURIComponent(type)}&kw=${encodeURIComponent(kw)}`) const d = await r.json() if (d.ok) renderRows(d.rows) if (st) { st.style.display=''; st.textContent=`查询完成(${(d.rows||[]).length} 条)` } @@ -86,7 +85,7 @@ const loadFlows = async () => { } const addFlow = async () => { - const st = document.getElementById('funds-status') + const st = document.getElementById('funds-guoxin-status') const btn = document.getElementById('btn-add') if (st) { st.style.display=''; st.textContent='正在新增...' } if (btn) btn.disabled = true @@ -106,11 +105,11 @@ const addFlow = async () => { if (!editingId) { try { - const dupRes = await fetch(`/api/funds/flows?start=${encodeURIComponent(date)}&end=${encodeURIComponent(date)}&type=all`) + const dupRes = await fetch(`/api/funds_guoxin/flows?start=${encodeURIComponent(date)}&end=${encodeURIComponent(date)}&type=all`) const dupData = await dupRes.json() if (dupData.ok && Array.isArray(dupData.rows) && dupData.rows.length > 0) { const ok = window.confirm(`该日期已有 ${dupData.rows.length} 条记录,是否继续新增?`) - if (!ok) { logLocal(`funds.add.cancel date=${date}`); return } + if (!ok) { logLocal(`funds_guoxin.add.cancel date=${date}`); return } } } catch {} } @@ -119,8 +118,8 @@ const addFlow = async () => { if (editingId) { try { - await fetch(`/api/funds/flows/${editingId}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body) }) - logLocal(`funds.update id=${editingId}`) + await fetch(`/api/funds_guoxin/flows/${editingId}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body) }) + logLocal(`funds_guoxin.update id=${editingId}`) if (st) { st.style.display=''; st.textContent='修改成功' } editingId = null; if (btn) btn.textContent = '新增'; @@ -138,13 +137,12 @@ const addFlow = async () => { return; } - try { await fetch('/api/debug/event', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ source:'funds', action:'add', date, type, amount:(cents/100) }) }) } catch {} - logLocal(`funds.add ${JSON.stringify({ date, type, amount:(cents/100) })}`) + try { await fetch('/api/debug/event', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ source:'funds_guoxin', action:'add', date, type, amount:(cents/100) }) }) } catch {} + logLocal(`funds_guoxin.add ${JSON.stringify({ date, type, amount:(cents/100) })}`) try { - await fetch('/api/funds/flows', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body) }) + await fetch('/api/funds_guoxin/flows', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body) }) if (st) { st.style.display=''; st.textContent='新增成功' } await loadFlows() - // clear inputs document.getElementById('new-amount').value='' document.getElementById('new-bank').value='' document.getElementById('new-remark').value='' @@ -165,10 +163,10 @@ document.addEventListener('DOMContentLoaded', () => { const de = document.getElementById('date-end'); if (de) de.value = endOfYear const bl = document.getElementById('btn-load'); if (bl) bl.addEventListener('click', loadFlows) const ba = document.getElementById('btn-add'); if (ba) ba.addEventListener('click', addFlow) - const be = document.getElementById('btn-export'); if (be) be.addEventListener('click', async () => { const start = document.getElementById('date-start').value||''; const end = document.getElementById('date-end').value||''; location.href = `/api/funds/export.csv?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}` }) + const be = document.getElementById('btn-export'); if (be) be.addEventListener('click', async () => { const start = document.getElementById('date-start').value||''; const end = document.getElementById('date-end').value||''; location.href = `/api/funds_guoxin/export.csv?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}` }) const bcp = document.getElementById('fd-btn-copy'); if (bcp) bcp.addEventListener('click', async () => { try { await navigator.clipboard.writeText((logBox()&&logBox().textContent)||'') } catch {} }) - const brf = document.getElementById('fd-btn-refresh'); if (brf) brf.addEventListener('click', async () => { try { const r = await fetch('/api/debug/logs?limit=5000&channel=funds'); const d = await r.json(); if (d.ok) { const b = logBox(); if (b) { b.textContent = (d.lines||[]).join('\n'); b.scrollTop = b.scrollHeight } } } catch {} }) - const bcl = document.getElementById('fd-btn-clear'); if (bcl) bcl.addEventListener('click', async () => { try { await fetch('/api/debug/clear?channel=funds', { method: 'POST' }) } catch {}; const b = logBox(); if (b) b.textContent='' }) + const brf = document.getElementById('fd-btn-refresh'); if (brf) brf.addEventListener('click', async () => { try { const r = await fetch('/api/debug/logs?limit=5000&channel=funds_guoxin'); const d = await r.json(); if (d.ok) { const b = logBox(); if (b) { b.textContent = (d.lines||[]).join('\n'); b.scrollTop = b.scrollHeight } } } catch {} }) + const bcl = document.getElementById('fd-btn-clear'); if (bcl) bcl.addEventListener('click', async () => { try { await fetch('/api/debug/clear?channel=funds_guoxin', { method: 'POST' }) } catch {}; const b = logBox(); if (b) b.textContent='' }) loadFlows() initTextEffect() }) diff --git a/public/tools/funds/index.html b/public/tools/funds_guoxin/index.html similarity index 76% rename from public/tools/funds/index.html rename to public/tools/funds_guoxin/index.html index ddf2cad..91241c8 100644 --- a/public/tools/funds/index.html +++ b/public/tools/funds_guoxin/index.html @@ -3,23 +3,10 @@ - 财富好管家 · 本金变动池 - + 国信证券 · 本金变动池 + - - - - - - - - - - - 财富好管家 · 本金变动池 - - - + @@ -51,7 +38,7 @@
-

💰 财富流转 · 生生不息

+

💰 国信证券 · 本金变动池

记录每一分财富的来去,汇聚八方财源

@@ -67,7 +54,7 @@
- +
@@ -100,7 +87,7 @@
-
- + diff --git a/public/tools/funds_huatai/auth_config.json b/public/tools/funds_huatai/auth_config.json new file mode 100644 index 0000000..0484ca6 --- /dev/null +++ b/public/tools/funds_huatai/auth_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "华泰证券-本金变动池的前端鉴权配置", + "enable_auth_comment": "true:启用鉴权(需要从导航登录);false:完全放开访问", + "enable_auth": true, + "max_age_days_comment": "鉴权 cookie 的最大有效天数(1~365)", + "max_age_days": 30, + "cookieName_comment": "鉴权 Cookie 名称", + "cookieName": "funds_huatai_gate" +} diff --git a/public/tools/funds_huatai/funds_huatai.css b/public/tools/funds_huatai/funds_huatai.css new file mode 100644 index 0000000..368237b --- /dev/null +++ b/public/tools/funds_huatai/funds_huatai.css @@ -0,0 +1,280 @@ +/* 华泰证券 · 本金变动池 - 暗黑专业风格 */ + +body { + background: #1e1e1e; + color: #cccccc; + font-family: "Microsoft YaHei", "微软雅黑", "PingFang SC", "Helvetica Neue", Arial, sans-serif; + min-height: 100vh; + margin: 0; +} + +.container { + padding: 24px 0; + width: 95%; + margin: 0 auto; +} + +.page-header { + margin-bottom: 24px; + padding-bottom: 16px; + border-bottom: 1px solid #3c3c3c; +} + +.page-header h1 { + font-size: 1.5rem; + font-weight: 600; + color: #d4af37; + margin: 0; + letter-spacing: 1px; +} + +.toolbar, .add-bar { + display: flex; + gap: 10px; + align-items: center; + flex-wrap: wrap; + margin-bottom: 16px; + padding: 14px 16px; + background: #252526; + border: 1px solid #3c3c3c; + border-radius: 6px; +} + +.btn { + height: 36px; + padding: 0 16px; + border: 1px solid #555; + background: #333333; + color: #cccccc; + border-radius: 4px; + cursor: pointer; + font-weight: 500; + font-size: 0.875rem; + font-family: inherit; + transition: background 0.15s, border-color 0.15s; +} + +.btn:hover { + background: #444444; + border-color: #d4af37; + color: #ffffff; +} + +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.btn-add { + background: #5a4a1e; + border-color: #8b7332; + color: #f0e6c8; +} + +.btn-add:hover { + background: #6b5a28; + border-color: #d4af37; +} + +input, select { + border: 1px solid #3c3c3c; + border-radius: 4px; + padding: 6px 10px; + height: 36px; + background: #1e1e1e; + color: #cccccc; + font-family: inherit; + font-size: 0.875rem; + transition: border-color 0.15s; +} + +input:focus, select:focus { + outline: none; + border-color: #d4af37; +} + +input::placeholder { + color: #666666; +} + +/* 日期选择器暗色适配 */ +input[type="date"]::-webkit-calendar-picker-indicator { + filter: invert(0.7); +} + +.table-wrap { + overflow: hidden; + border: 1px solid #3c3c3c; + border-radius: 6px; + background: #252526; +} + +table.flows { + width: 100%; + border-collapse: collapse; + font-size: 0.875rem; + table-layout: fixed; +} + +/* 列宽分配 */ +table.flows th:nth-child(1), +table.flows td:nth-child(1) { width: 9%; } +table.flows th:nth-child(2), +table.flows td:nth-child(2) { width: 5%; } +table.flows th:nth-child(3), +table.flows td:nth-child(3) { width: 11%; } +table.flows th:nth-child(4), +table.flows td:nth-child(4) { width: 14%; } +table.flows th:nth-child(5), +table.flows td:nth-child(5) { width: 12%; } +table.flows th:nth-child(6), +table.flows td:nth-child(6) { width: 37%; } +table.flows th:nth-child(7), +table.flows td:nth-child(7) { width: 12%; } + +table.flows th, table.flows td { + padding: 10px 12px; + border-bottom: 1px solid #333333; + text-align: left; + word-break: break-all; + overflow-wrap: break-word; +} + +table.flows th { + background: #2d2d2d; + color: #d4af37; + font-weight: 600; + position: sticky; + top: 0; + z-index: 1; + border-bottom: 2px solid #3c3c3c; +} + +table.flows tbody tr:hover td { + background: #2a2d2e; +} + +table.flows tr.in td { + border-left: 3px solid transparent; +} + +table.flows tr.in td:first-child { + border-left-color: #d4af37; +} + +table.flows tr.out td { + border-left: 3px solid transparent; +} + +table.flows tr.out td:first-child { + border-left-color: #c1272d; +} + +table.flows td.amount { + font-weight: 600; + color: #cccccc; + font-variant-numeric: tabular-nums; +} + +table.flows td.ending { + font-weight: 700; + color: #d4af37; + font-variant-numeric: tabular-nums; +} + +.stats { + margin: 20px 0; + padding: 14px 16px; + border: 1px solid #3c3c3c; + border-radius: 6px; + background: #252526; + font-weight: 500; + color: #999999; + text-align: center; + font-size: 0.875rem; +} + +.status { + margin: 12px 0; + padding: 10px 14px; + border: 1px solid #555; + background: #2d2d2d; + color: #cccccc; + border-radius: 4px; + text-align: center; + font-size: 0.875rem; +} + +.debug { + margin: 12px 0; + padding: 8px; + border: 1px dashed #555; + border-radius: 4px; +} + +.debug-actions { + display: flex; + gap: 8px; + margin-bottom: 8px; +} + +.debug-output { + height: 200px; + overflow: auto; + background: #1a1a1a; + padding: 8px; + font-family: Consolas, "Courier New", monospace; + font-size: 12px; + white-space: pre-wrap; + color: #888888; + border-radius: 4px; +} + +/* 滚动条暗色 */ +::-webkit-scrollbar { + width: 8px; + height: 8px; +} +::-webkit-scrollbar-track { + background: #1e1e1e; +} +::-webkit-scrollbar-thumb { + background: #555555; + border-radius: 4px; +} +::-webkit-scrollbar-thumb:hover { + background: #777777; +} + +/* 操作按钮 */ +table.flows td .btn { + height: 28px; + padding: 0 10px; + font-size: 0.8rem; +} + +@media (max-width: 760px) { + .toolbar, .add-bar { + flex-direction: column; + align-items: stretch; + gap: 8px; + padding: 12px; + } + + .toolbar input, + .toolbar select, + .add-bar input, + .add-bar select { + width: 100%; + } + + .toolbar .btn, + .btn-add { + width: 100%; + } + + table.flows th, table.flows td { + padding: 8px; + font-size: 0.8rem; + } +} diff --git a/public/tools/funds_huatai/funds_huatai.js b/public/tools/funds_huatai/funds_huatai.js new file mode 100644 index 0000000..e7ae1eb --- /dev/null +++ b/public/tools/funds_huatai/funds_huatai.js @@ -0,0 +1,170 @@ +const fmtCN = n => n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) +const parseAmount = s => { const x = String(s||'').replace(/[,\s]/g,''); const v = Number(x); if (!Number.isFinite(v)) return null; return Math.round(v*100) } +const centsToText = c => fmtCN((c||0)/100) +const logBox = () => document.getElementById('fd-output') +const logLocal = msg => { const b = logBox(); if (!b) return; const line = `${(window.fmtCNDateTime?fmtCNDateTime(new Date()):new Date().toLocaleString('zh-CN'))} ${msg}`; b.textContent = (b.textContent||'') + (b.textContent?"\n":"") + line; b.scrollTop = b.scrollHeight } + +let editingId = null; + +const loadFlags = async () => { try { const r = await fetch('/api/flags'); const d = await r.json(); if (d && d.debug && d.debug.funds_huatai) { const sec = document.getElementById('funds-huatai-debug'); if (sec) sec.style.display = '' } } catch {} +} + +const renderRows = rows => { + const tb = document.getElementById('flows-body'); if (!tb) return + tb.innerHTML = '' + let sumIn = 0, sumOut = 0 + for (const r of rows) { + const tr = document.createElement('tr') + tr.className = r.type === 'in' ? 'in' : 'out' + const tdDate = document.createElement('td'); tdDate.textContent = r.date + const tdType = document.createElement('td'); tdType.textContent = r.type === 'in' ? '汇入' : '汇出' + const tdAmt = document.createElement('td'); tdAmt.className='amount'; tdAmt.textContent = centsToText(r.amount_cents) + const tdBank = document.createElement('td'); tdBank.textContent = r.bank_status || '' + const tdEnd = document.createElement('td'); tdEnd.className='ending'; tdEnd.textContent = centsToText(r.ending_cents) + const tdRemark = document.createElement('td'); tdRemark.textContent = r.remark || '' + const tdOps = document.createElement('td') + + const btnEdit = document.createElement('button'); + btnEdit.className='btn'; + btnEdit.textContent='修改'; + btnEdit.style.marginRight = '4px'; + btnEdit.addEventListener('click', () => { + document.getElementById('new-date').value = r.date; + document.getElementById('new-type').value = r.type; + document.getElementById('new-amount').value = (r.amount_cents / 100).toFixed(2); + document.getElementById('new-bank').value = r.bank_status || ''; + document.getElementById('new-remark').value = r.remark || ''; + + editingId = r.id; + const btnAdd = document.getElementById('btn-add'); + if (btnAdd) { + btnAdd.textContent = '保存修改'; + } + document.querySelector('.add-bar').scrollIntoView({ behavior: 'smooth' }); + }); + tdOps.appendChild(btnEdit); + + const btnDel = document.createElement('button'); btnDel.className='btn'; btnDel.textContent='涤旧'; btnDel.addEventListener('click', async () => { + const ok = window.confirm('确认涤旧该条流水?') + if (!ok) return + try { await fetch('/api/debug/event', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ source:'funds_huatai', action:'delete', id:r.id }) }) } catch {} + logLocal(`funds_huatai.delete id=${r.id}`) + await fetch(`/api/funds_huatai/flows/${r.id}`, { method:'DELETE' }) + await loadFlows() + }) + tdOps.appendChild(btnDel) + tr.appendChild(tdDate); tr.appendChild(tdType); tr.appendChild(tdAmt); tr.appendChild(tdBank); tr.appendChild(tdEnd); tr.appendChild(tdRemark); tr.appendChild(tdOps) + tb.appendChild(tr) + if (r.type==='in') sumIn += r.amount_cents; else sumOut += r.amount_cents + } + const st = document.getElementById('stats') + if (st) st.textContent = `总汇入 ${centsToText(sumIn)} · 总汇出 ${centsToText(Math.abs(sumOut))} · 区间净变动 ${centsToText(sumIn + sumOut)} · 期末余额 ${rows.length?centsToText(rows[rows.length-1].ending_cents):centsToText(0)}` +} + +const loadFlows = async () => { + const st = document.getElementById('funds-huatai-status') + const btnQ = document.getElementById('btn-load') + if (st) { st.style.display=''; st.textContent='正在查询...' } + if (btnQ) btnQ.disabled = true + const start = document.getElementById('date-start').value || '' + const end = document.getElementById('date-end').value || '' + const type = document.getElementById('type-filter').value || 'all' + const kw = document.getElementById('kw').value || '' + try { + const r = await fetch(`/api/funds_huatai/flows?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}&type=${encodeURIComponent(type)}&kw=${encodeURIComponent(kw)}`) + const d = await r.json() + if (d.ok) renderRows(d.rows) + if (st) { st.style.display=''; st.textContent=`查询完成(${(d.rows||[]).length} 条)` } + } catch (e) { + if (st) { st.style.display=''; st.textContent=`查询失败:${String(e.message||e)}` } + } finally { + if (btnQ) btnQ.disabled = false + setTimeout(()=>{ if (st) st.style.display='none' }, 1200) + } +} + +const addFlow = async () => { + const st = document.getElementById('funds-huatai-status') + const btn = document.getElementById('btn-add') + if (st) { st.style.display=''; st.textContent='正在新增...' } + if (btn) btn.disabled = true + const date = document.getElementById('new-date').value + const type = document.getElementById('new-type').value + const amtText = document.getElementById('new-amount').value + const bank = document.getElementById('new-bank').value + const remark = document.getElementById('new-remark').value + if (!date || !type || !amtText || !bank || !remark) { + if (st) { st.style.display=''; st.textContent='请完整填写日期、类型、金额、银行方/状态、备注' } + if (btn) btn.disabled = false + setTimeout(()=>{ if (st) st.style.display='none' }, 1800) + return + } + const cents = parseAmount(amtText) + if (cents === null) { logLocal('金额格式错误'); return } + + if (!editingId) { + try { + const dupRes = await fetch(`/api/funds_huatai/flows?start=${encodeURIComponent(date)}&end=${encodeURIComponent(date)}&type=all`) + const dupData = await dupRes.json() + if (dupData.ok && Array.isArray(dupData.rows) && dupData.rows.length > 0) { + const ok = window.confirm(`该日期已有 ${dupData.rows.length} 条记录,是否继续新增?`) + if (!ok) { logLocal(`funds_huatai.add.cancel date=${date}`); return } + } + } catch {} + } + + const body = { date, type, amount_cents: type==='out' ? -Math.abs(cents) : Math.abs(cents), bank_status: bank, remark } + + if (editingId) { + try { + await fetch(`/api/funds_huatai/flows/${editingId}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body) }) + logLocal(`funds_huatai.update id=${editingId}`) + if (st) { st.style.display=''; st.textContent='修改成功' } + editingId = null; + if (btn) btn.textContent = '新增'; + + await loadFlows() + document.getElementById('new-amount').value='' + document.getElementById('new-bank').value='' + document.getElementById('new-remark').value='' + } catch (e) { + if (st) { st.style.display=''; st.textContent=`修改失败:${String(e.message||e)}` } + } finally { + if (btn) btn.disabled = false + setTimeout(()=>{ if (st) st.style.display='none' }, 1200) + } + return; + } + + try { await fetch('/api/debug/event', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ source:'funds_huatai', action:'add', date, type, amount:(cents/100) }) }) } catch {} + logLocal(`funds_huatai.add ${JSON.stringify({ date, type, amount:(cents/100) })}`) + try { + await fetch('/api/funds_huatai/flows', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body) }) + if (st) { st.style.display=''; st.textContent='新增成功' } + await loadFlows() + document.getElementById('new-amount').value='' + document.getElementById('new-bank').value='' + document.getElementById('new-remark').value='' + } catch (e) { + if (st) { st.style.display=''; st.textContent=`新增失败:${String(e.message||e)}` } + } finally { + if (btn) btn.disabled = false + setTimeout(()=>{ if (st) st.style.display='none' }, 1200) + } +} + +document.addEventListener('DOMContentLoaded', () => { + loadFlags() + const y = new Date().getFullYear() + const d = new Date(y, 11, 31) + const endOfYear = window.cnDateStr ? cnDateStr(d) : `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}` + const ds = document.getElementById('date-start'); if (ds) ds.value = '2024-01-01' + const de = document.getElementById('date-end'); if (de) de.value = endOfYear + const bl = document.getElementById('btn-load'); if (bl) bl.addEventListener('click', loadFlows) + const ba = document.getElementById('btn-add'); if (ba) ba.addEventListener('click', addFlow) + const be = document.getElementById('btn-export'); if (be) be.addEventListener('click', async () => { const start = document.getElementById('date-start').value||''; const end = document.getElementById('date-end').value||''; location.href = `/api/funds_huatai/export.csv?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}` }) + const bcp = document.getElementById('fd-btn-copy'); if (bcp) bcp.addEventListener('click', async () => { try { await navigator.clipboard.writeText((logBox()&&logBox().textContent)||'') } catch {} }) + const brf = document.getElementById('fd-btn-refresh'); if (brf) brf.addEventListener('click', async () => { try { const r = await fetch('/api/debug/logs?limit=5000&channel=funds_huatai'); const d = await r.json(); if (d.ok) { const b = logBox(); if (b) { b.textContent = (d.lines||[]).join('\n'); b.scrollTop = b.scrollHeight } } } catch {} }) + const bcl = document.getElementById('fd-btn-clear'); if (bcl) bcl.addEventListener('click', async () => { try { await fetch('/api/debug/clear?channel=funds_huatai', { method: 'POST' }) } catch {}; const b = logBox(); if (b) b.textContent='' }) + loadFlows() +}) diff --git a/public/tools/funds_huatai/index.html b/public/tools/funds_huatai/index.html new file mode 100644 index 0000000..9114841 --- /dev/null +++ b/public/tools/funds_huatai/index.html @@ -0,0 +1,76 @@ + + + + + + 华泰证券 · 本金变动池 + + + + + +
+ + +
+ + + + + + + +
+ + +
+ + + + + + +
+ +
+ +
+ + + + + + + + + + + + + +
日期类型金额(人民币)银行方/状态期末金额备注操作
+
+ + +
+ + + + + diff --git a/src/server/funds.js b/src/server/funds_guoxin.js similarity index 79% rename from src/server/funds.js rename to src/server/funds_guoxin.js index 7047f13..e549a12 100644 --- a/src/server/funds.js +++ b/src/server/funds_guoxin.js @@ -5,7 +5,7 @@ const crypto = require('crypto') const { logJSON } = require('./logger') const axios = require('axios') -const cfgPath = path.join(process.cwd(), 'config', 'funds.json') +const cfgPath = path.join(process.cwd(), 'config', 'funds_guoxin.json') if (!fs.existsSync(path.dirname(cfgPath))) fs.mkdirSync(path.dirname(cfgPath), { recursive: true }) if (!fs.existsSync(cfgPath)) { const defaultPort = process.env.PORT || 5050 @@ -20,8 +20,8 @@ const getConfig = () => { } const setConfig = cfg => { fs.writeFileSync(cfgPath, JSON.stringify(cfg, null, 2)) - _cachedCfg = null // Clear config cache - _cachedKey = null // Clear key cache + _cachedCfg = null + _cachedKey = null } let _cachedCfg = null @@ -30,8 +30,8 @@ const deriveKey = () => { if (_cachedKey) return _cachedKey const cfg = getConfig() const salt = Buffer.from(String(cfg.machine_salt || 'default'), 'utf-8') - const passphrase = process.env.FUNDS_PASSPHRASE || process.env.SYSTEM_AUTH_PASS_93220 || '' -_cachedKey = crypto.scryptSync(passphrase + String(cfg.machine_salt || ''), salt, 32) + const passphrase = process.env.FUNDS_GUOXIN_PASSPHRASE || process.env.SYSTEM_AUTH_PASS_93220 || '' + _cachedKey = crypto.scryptSync(passphrase + String(cfg.machine_salt || ''), salt, 32) return _cachedKey } @@ -71,7 +71,6 @@ db.exec( );` ) -// Prepared statements (global for performance, data is still real-time) const insertFlow = db.prepare( `INSERT INTO fund_flows (date, type, amount_cents, ending_cents, bank_status_enc, bank_status_iv, bank_status_tag, remark_enc, remark_iv, remark_tag) VALUES (@date, @type, @amount_cents, 0, @bank_status_enc, @bank_status_iv, @bank_status_tag, @remark_enc, @remark_iv, @remark_tag)` @@ -91,7 +90,6 @@ const recalcEndingFrom = db.transaction((startDate) => { let balance = 0 for (const r of all) { if (startDate) { - // find starting balance: sum of amounts before startDate if (r.date < startDate) { balance += (r.amount_cents||0); continue } } balance += (r.amount_cents||0) @@ -131,7 +129,7 @@ const pushWeeklyDaily = async (date) => { if (!api.enabled) return const rows = listByDateStmt.all(date) const total = (sumByDateStmt.get(date).s || 0) - const title = `本金变动池 ${date}(净变动:${formatCNY(total)})` + const title = `国信证券-本金变动池 ${date}(净变动:${formatCNY(total)})` const items = rows.map((r, idx) => ({ idx: idx+1, type: r.type, @@ -151,15 +149,15 @@ const pushWeeklyDaily = async (date) => { `.trim() - const payload = { key: api.key, source: 'funds', external_id: `funds-daily-${date}`, title, content, date, status_code: 'new', status_label: '📅本周新增' } + const payload = { key: api.key, source: 'funds_guoxin', external_id: `funds_guoxin-daily-${date}`, title, content, date, status_code: 'new', status_label: '📅本周新增' } const url = `${api.base}/ext/event` - logJSON('funds.weekly.push.try', { date, url, base: api.base, rows: rows.length, total_cents: total, title_len: title.length, content_len: content.length }, 'funds') + logJSON('funds_guoxin.weekly.push.try', { date, url, base: api.base, rows: rows.length, total_cents: total, title_len: title.length, content_len: content.length }, 'funds_guoxin') const resp = await axios.post(url, payload, { timeout: 15000, headers: { 'Content-Type': 'application/json' } }) - logJSON('funds.weekly.push.resp', { date, status: resp && resp.status, data_ok: !!(resp && resp.data && resp.data.ok), data: brief((resp && resp.data) ? JSON.stringify(resp.data) : '') }, 'funds') + logJSON('funds_guoxin.weekly.push.resp', { date, status: resp && resp.status, data_ok: !!(resp && resp.data && resp.data.ok), data: brief((resp && resp.data) ? JSON.stringify(resp.data) : '') }, 'funds_guoxin') } catch (e) { const status = e && e.response ? e.response.status : null const data = e && e.response ? e.response.data : null - logJSON('funds.weekly.push.error', { date, url: (getWeeklyCfg().base + '/ext/event'), status, code: e && e.code, message: String(e.message||e), data: typeof data==='string' ? brief(data) : brief(data ? JSON.stringify(data) : '') }, 'funds') + logJSON('funds_guoxin.weekly.push.error', { date, url: (getWeeklyCfg().base + '/ext/event'), status, code: e && e.code, message: String(e.message||e), data: typeof data==='string' ? brief(data) : brief(data ? JSON.stringify(data) : '') }, 'funds_guoxin') } } @@ -170,17 +168,17 @@ const deleteOrUpdateWeeklyDaily = async (date) => { const rows = listByDateStmt.all(date) if (!rows || rows.length === 0) { const url = `${api.base}/ext/event` - const payload = { key: api.key, source: 'funds', external_id: `funds-daily-${date}`, date, deleted: true } - logJSON('funds.weekly.delete.try', { date, url, base: api.base }, 'funds') + const payload = { key: api.key, source: 'funds_guoxin', external_id: `funds_guoxin-daily-${date}`, date, deleted: true } + logJSON('funds_guoxin.weekly.delete.try', { date, url, base: api.base }, 'funds_guoxin') const resp = await axios.post(url, payload, { timeout: 15000, headers: { 'Content-Type': 'application/json' } }) - logJSON('funds.weekly.delete.resp', { date, status: resp && resp.status, data_ok: !!(resp && resp.data && resp.data.ok), data: brief((resp && resp.data) ? JSON.stringify(resp.data) : '') }, 'funds') + logJSON('funds_guoxin.weekly.delete.resp', { date, status: resp && resp.status, data_ok: !!(resp && resp.data && resp.data.ok), data: brief((resp && resp.data) ? JSON.stringify(resp.data) : '') }, 'funds_guoxin') } else { await pushWeeklyDaily(date) } } catch (e) { const status = e && e.response ? e.response.status : null const data = e && e.response ? e.response.data : null - logJSON('funds.weekly.delete.error', { date, url: (getWeeklyCfg().base + '/ext/event'), status, code: e && e.code, message: String(e.message||e), data: typeof data==='string' ? brief(data) : brief(data ? JSON.stringify(data) : '') }, 'funds') + logJSON('funds_guoxin.weekly.delete.error', { date, url: (getWeeklyCfg().base + '/ext/event'), status, code: e && e.code, message: String(e.message||e), data: typeof data==='string' ? brief(data) : brief(data ? JSON.stringify(data) : '') }, 'funds_guoxin') } } @@ -190,7 +188,7 @@ const createFlow = (payload) => { const rm = enc(remark||'') insertFlow.run({ date, type, amount_cents, bank_status_enc: bs.ct, bank_status_iv: bs.iv, bank_status_tag: bs.tag, remark_enc: rm.ct, remark_iv: rm.iv, remark_tag: rm.tag }) recalcEndingFrom(null) - logJSON('funds.create', { date, type, amount_cents }) + logJSON('funds_guoxin.create', { date, type, amount_cents }) Promise.resolve().then(()=>pushWeeklyDaily(date)).catch(()=>{}) } @@ -200,7 +198,7 @@ const updateFlowById = (id, payload) => { const rm = enc(remark||'') updateFlow.run({ id, date, type, amount_cents, bank_status_enc: bs.ct, bank_status_iv: bs.iv, bank_status_tag: bs.tag, remark_enc: rm.ct, remark_iv: rm.iv, remark_tag: rm.tag }) recalcEndingFrom(null) - logJSON('funds.update', { id, date, type, amount_cents }) + logJSON('funds_guoxin.update', { id, date, type, amount_cents }) Promise.resolve().then(()=>pushWeeklyDaily(date)).catch(()=>{}) } @@ -209,12 +207,12 @@ const deleteFlow = (id) => { const row = db.prepare(`SELECT date FROM fund_flows WHERE id=?`).get(id) deleteFlowStmt.run(id) recalcEndingFrom(null) - logJSON('funds.delete', { id }) + logJSON('funds_guoxin.delete', { id }) if (row && row.date) Promise.resolve().then(()=>deleteOrUpdateWeeklyDaily(row.date)).catch(()=>{}) } catch (e) { deleteFlowStmt.run(id) recalcEndingFrom(null) - logJSON('funds.delete', { id, error: String(e.message||e) }) + logJSON('funds_guoxin.delete', { id, error: String(e.message||e) }) } } diff --git a/src/server/funds_huatai.js b/src/server/funds_huatai.js new file mode 100644 index 0000000..bb222d5 --- /dev/null +++ b/src/server/funds_huatai.js @@ -0,0 +1,219 @@ +const { db } = require('./db') +const fs = require('fs') +const path = require('path') +const crypto = require('crypto') +const { logJSON } = require('./logger') +const axios = require('axios') + +const cfgPath = path.join(process.cwd(), 'config', 'funds_huatai.json') +if (!fs.existsSync(path.dirname(cfgPath))) fs.mkdirSync(path.dirname(cfgPath), { recursive: true }) +if (!fs.existsSync(cfgPath)) { + const defaultPort = process.env.PORT || 5050 + const defaultBase = `http://localhost:${defaultPort}/api/weekly` + fs.writeFileSync(cfgPath, JSON.stringify({ machine_salt: crypto.randomBytes(16).toString('hex'), display: { currency: 'CNY' }, weekly_api_base: defaultBase, weekly_key: '', weekly_sync_enabled: true }, null, 2)) +} + +const getConfig = () => { + if (_cachedCfg) return _cachedCfg + _cachedCfg = JSON.parse(fs.readFileSync(cfgPath, 'utf-8')) + return _cachedCfg +} +const setConfig = cfg => { + fs.writeFileSync(cfgPath, JSON.stringify(cfg, null, 2)) + _cachedCfg = null + _cachedKey = null +} + +let _cachedCfg = null +let _cachedKey = null +const deriveKey = () => { + if (_cachedKey) return _cachedKey + const cfg = getConfig() + const salt = Buffer.from(String(cfg.machine_salt || 'default'), 'utf-8') + const passphrase = process.env.FUNDS_HUATAI_PASSPHRASE || process.env.SYSTEM_AUTH_PASS_93220 || '' + _cachedKey = crypto.scryptSync(passphrase + String(cfg.machine_salt || ''), salt, 32) + return _cachedKey +} + +const enc = (plain) => { + const key = deriveKey() + const iv = crypto.randomBytes(12) + const cipher = crypto.createCipheriv('aes-256-gcm', key, iv) + const ct = Buffer.concat([cipher.update(Buffer.from(String(plain||''), 'utf-8')), cipher.final()]) + const tag = cipher.getAuthTag() + return { ct, iv, tag } +} +const dec = (ct, iv, tag) => { + try { + const key = deriveKey() + const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv) + decipher.setAuthTag(tag) + const pt = Buffer.concat([decipher.update(ct), decipher.final()]) + return pt.toString('utf-8') + } catch { return '' } +} + +db.exec( + `CREATE TABLE IF NOT EXISTS fund_flows_huatai ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + date TEXT NOT NULL, + type TEXT NOT NULL, + amount_cents INTEGER NOT NULL, + ending_cents INTEGER NOT NULL, + bank_status_enc BLOB, + bank_status_iv BLOB, + bank_status_tag BLOB, + remark_enc BLOB, + remark_iv BLOB, + remark_tag BLOB, + created_at TEXT DEFAULT (datetime('now')), + updated_at TEXT DEFAULT (datetime('now')) + );` +) + +const insertFlow = db.prepare( + `INSERT INTO fund_flows_huatai (date, type, amount_cents, ending_cents, bank_status_enc, bank_status_iv, bank_status_tag, remark_enc, remark_iv, remark_tag) + VALUES (@date, @type, @amount_cents, 0, @bank_status_enc, @bank_status_iv, @bank_status_tag, @remark_enc, @remark_iv, @remark_tag)` +) +const updateFlow = db.prepare( + `UPDATE fund_flows_huatai SET date=@date, type=@type, amount_cents=@amount_cents, bank_status_enc=@bank_status_enc, bank_status_iv=@bank_status_iv, bank_status_tag=@bank_status_tag, remark_enc=@remark_enc, remark_iv=@remark_iv, remark_tag=@remark_tag, updated_at=datetime('now') WHERE id=@id` +) +const deleteFlowStmt = db.prepare(`DELETE FROM fund_flows_huatai WHERE id = ?`) +const listFlowsStmt = db.prepare(`SELECT id, date, type, amount_cents, ending_cents, bank_status_enc, bank_status_iv, bank_status_tag, remark_enc, remark_iv, remark_tag FROM fund_flows_huatai ORDER BY date ASC, id ASC`) +const listRangeStmt = db.prepare(`SELECT id, date, type, amount_cents, ending_cents, bank_status_enc, bank_status_iv, bank_status_tag, remark_enc, remark_iv, remark_tag FROM fund_flows_huatai WHERE date>=? AND date<=? ORDER BY date ASC, id ASC`) +const listByDateStmt = db.prepare(`SELECT id, date, type, amount_cents, ending_cents, bank_status_enc, bank_status_iv, bank_status_tag, remark_enc, remark_iv, remark_tag FROM fund_flows_huatai WHERE date=? ORDER BY id ASC`) +const sumByDateStmt = db.prepare(`SELECT SUM(amount_cents) AS s FROM fund_flows_huatai WHERE date=?`) +const updateEndingStmt = db.prepare(`UPDATE fund_flows_huatai SET ending_cents=? WHERE id=?`) + +const recalcEndingFrom = db.transaction((startDate) => { + const all = listFlowsStmt.all() + let balance = 0 + for (const r of all) { + if (startDate) { + if (r.date < startDate) { balance += (r.amount_cents||0); continue } + } + balance += (r.amount_cents||0) + updateEndingStmt.run(balance, r.id) + } +}) + +const listFlows = (start, end, type, kw) => { + const rows = (start && end) ? listRangeStmt.all(start, end) : listFlowsStmt.all() + const mapRow = r => { + const bank = r.bank_status_enc ? dec(r.bank_status_enc, r.bank_status_iv, r.bank_status_tag) : '' + const remark = r.remark_enc ? dec(r.remark_enc, r.remark_iv, r.remark_tag) : '' + return { id: r.id, date: r.date, type: r.type, amount_cents: r.amount_cents, ending_cents: r.ending_cents, bank_status: bank, remark } + } + let filtered = rows.map(mapRow) + if (type && type !== 'all') filtered = filtered.filter(r => r.type === type) + if (kw) { const reg = new RegExp(String(kw).trim(), 'i'); filtered = filtered.filter(r => reg.test(r.bank_status||'') || reg.test(r.remark||'')) } + return filtered +} + +const formatCNY = cents => { + try { return (Number(cents||0) / 100).toFixed(2) } catch { return '0.00' } +} +const brief = s => { try { return String(s||'').replace(/\s+/g,' ').slice(0,500) } catch { return '' } } + +const getWeeklyCfg = () => { + const cfg = getConfig() + const port = process.env.PORT || 5050 + const base = cfg.weekly_api_base || `http://localhost:${port}/api/weekly` + const key = String(cfg.weekly_key || process.env.SYSTEM_AUTH_PASS_93220 || '') + const enabled = cfg.weekly_sync_enabled !== false + return { base, key, enabled } +} +const pushWeeklyDaily = async (date) => { + try { + const api = getWeeklyCfg() + if (!api.enabled) return + const rows = listByDateStmt.all(date) + const total = (sumByDateStmt.get(date).s || 0) + const title = `华泰证券-本金变动池 ${date}(净变动:${formatCNY(total)})` + const items = rows.map((r, idx) => ({ + idx: idx+1, + type: r.type, + amount: formatCNY(r.amount_cents), + bank: r.bank_status_enc ? dec(r.bank_status_enc, r.bank_status_iv, r.bank_status_tag) : '', + remark: r.remark_enc ? dec(r.remark_enc, r.remark_iv, r.remark_tag) : '' + })) + const trs = items.map(it => `${it.idx}${it.type==='in'?'汇入':'汇出'}${it.amount}${(it.bank||'').replace(//g,'>')}${(it.remark||'').replace(//g,'>')}`).join('') + const content = ` +
+

当日净变动

+

人民币:${formatCNY(total)}

+

明细

+ + + ${trs} +
序号类型金额(元)银行方/状态备注
+
+ `.trim() + const payload = { key: api.key, source: 'funds_huatai', external_id: `funds_huatai-daily-${date}`, title, content, date, status_code: 'new', status_label: '📅本周新增' } + const url = `${api.base}/ext/event` + logJSON('funds_huatai.weekly.push.try', { date, url, base: api.base, rows: rows.length, total_cents: total, title_len: title.length, content_len: content.length }, 'funds_huatai') + const resp = await axios.post(url, payload, { timeout: 15000, headers: { 'Content-Type': 'application/json' } }) + logJSON('funds_huatai.weekly.push.resp', { date, status: resp && resp.status, data_ok: !!(resp && resp.data && resp.data.ok), data: brief((resp && resp.data) ? JSON.stringify(resp.data) : '') }, 'funds_huatai') + } catch (e) { + const status = e && e.response ? e.response.status : null + const data = e && e.response ? e.response.data : null + logJSON('funds_huatai.weekly.push.error', { date, url: (getWeeklyCfg().base + '/ext/event'), status, code: e && e.code, message: String(e.message||e), data: typeof data==='string' ? brief(data) : brief(data ? JSON.stringify(data) : '') }, 'funds_huatai') + } +} + +const deleteOrUpdateWeeklyDaily = async (date) => { + try { + const api = getWeeklyCfg() + if (!api.enabled) return + const rows = listByDateStmt.all(date) + if (!rows || rows.length === 0) { + const url = `${api.base}/ext/event` + const payload = { key: api.key, source: 'funds_huatai', external_id: `funds_huatai-daily-${date}`, date, deleted: true } + logJSON('funds_huatai.weekly.delete.try', { date, url, base: api.base }, 'funds_huatai') + const resp = await axios.post(url, payload, { timeout: 15000, headers: { 'Content-Type': 'application/json' } }) + logJSON('funds_huatai.weekly.delete.resp', { date, status: resp && resp.status, data_ok: !!(resp && resp.data && resp.data.ok), data: brief((resp && resp.data) ? JSON.stringify(resp.data) : '') }, 'funds_huatai') + } else { + await pushWeeklyDaily(date) + } + } catch (e) { + const status = e && e.response ? e.response.status : null + const data = e && e.response ? e.response.data : null + logJSON('funds_huatai.weekly.delete.error', { date, url: (getWeeklyCfg().base + '/ext/event'), status, code: e && e.code, message: String(e.message||e), data: typeof data==='string' ? brief(data) : brief(data ? JSON.stringify(data) : '') }, 'funds_huatai') + } +} + +const createFlow = (payload) => { + const { date, type, amount_cents, bank_status, remark } = payload + const bs = enc(bank_status||'') + const rm = enc(remark||'') + insertFlow.run({ date, type, amount_cents, bank_status_enc: bs.ct, bank_status_iv: bs.iv, bank_status_tag: bs.tag, remark_enc: rm.ct, remark_iv: rm.iv, remark_tag: rm.tag }) + recalcEndingFrom(null) + logJSON('funds_huatai.create', { date, type, amount_cents }) + Promise.resolve().then(()=>pushWeeklyDaily(date)).catch(()=>{}) +} + +const updateFlowById = (id, payload) => { + const { date, type, amount_cents, bank_status, remark } = payload + const bs = enc(bank_status||'') + const rm = enc(remark||'') + updateFlow.run({ id, date, type, amount_cents, bank_status_enc: bs.ct, bank_status_iv: bs.iv, bank_status_tag: bs.tag, remark_enc: rm.ct, remark_iv: rm.iv, remark_tag: rm.tag }) + recalcEndingFrom(null) + logJSON('funds_huatai.update', { id, date, type, amount_cents }) + Promise.resolve().then(()=>pushWeeklyDaily(date)).catch(()=>{}) +} + +const deleteFlow = (id) => { + try { + const row = db.prepare(`SELECT date FROM fund_flows_huatai WHERE id=?`).get(id) + deleteFlowStmt.run(id) + recalcEndingFrom(null) + logJSON('funds_huatai.delete', { id }) + if (row && row.date) Promise.resolve().then(()=>deleteOrUpdateWeeklyDaily(row.date)).catch(()=>{}) + } catch (e) { + deleteFlowStmt.run(id) + recalcEndingFrom(null) + logJSON('funds_huatai.delete', { id, error: String(e.message||e) }) + } +} + +module.exports = { getConfig, setConfig, listFlows, createFlow, updateFlowById, deleteFlow } diff --git a/src/server/index.js b/src/server/index.js index 846e38d..61fbe72 100644 --- a/src/server/index.js +++ b/src/server/index.js @@ -53,7 +53,8 @@ const securityCalendarBridge = require('./security_calendar_calendar_bridge') const marketsWeeklyReport = require('./markets_weekly_report') const { upsertMarketArchive, getMarketArchive } = require('./db') const { getConfig: getWallCfg, setConfig: setWallCfg, listCards: listWallCards, createCard: createWallCard, updateCardById: updateWallCardById, deleteCardById: deleteWallCardById } = require('./wall') -const funds = require('./funds') +const fundsGuoxin = require('./funds_guoxin') +const fundsHuatai = require('./funds_huatai') const ccbPrivateFunds = require('./ccb_private_funds') const cloud = require('./cloud') const cloudBalanceWatch = require('./cloud_balance_watch') @@ -1182,7 +1183,7 @@ if (!fs.existsSync(settingsPath)) fs.writeFileSync(settingsPath, JSON.stringify( const flagsPath = path.join(process.cwd(), 'config', 'flags.json') if (!fs.existsSync(flagsPath)) fs.writeFileSync(flagsPath, JSON.stringify({ debugTool: { enabled: true, launchDate: null, autoHideAfterDays: 30 }, - debug: { weibo: true, markets: true, wall: true, funds: true }, + debug: { weibo: true, markets: true, wall: true, funds_guoxin: true, funds_huatai: true }, navAuth: { enable_auth: true, iss: 'TRAE-NAV', iss_strict: false } }, null, 2)) @@ -1561,7 +1562,8 @@ const mapSystemIdToUrl = (systemId) => { 'Tools-weibo': '/tools/weibo', 'Tools-markets': '/tools/markets', 'Tools-wall-': '/tools/wall', - 'Tools-funds': '/tools/funds', + 'Tools-funds_guoxin': '/tools/funds_guoxin', + 'Tools-funds_huatai': '/tools/funds_huatai', 'Tools-ccb_private_funds': '/tools/ccb_private_funds', 'Tools-cloud': '/tools/cloud', 'Tools-weekly': '/tools/weekly', @@ -1842,17 +1844,17 @@ app.use('/api/cloud', (req, res, next) => { return res.status(401).json({ ok: false, error: 'unauthorized' }) }) -const FUNDS_AUTH_COOKIE = 'funds_gate' -const readFundsJwk = () => { +const FUNDS_GUOXIN_AUTH_COOKIE = 'funds_guoxin_gate' +const readFundsGuoxinJwk = () => { try { - const p = path.join(process.cwd(), 'config', 'funds.jwk.json') + const p = path.join(process.cwd(), 'config', 'funds_guoxin.jwk.json') if (fs.existsSync(p)) return JSON.parse(fs.readFileSync(p, 'utf-8')) } catch {} return { kty: 'RSA', n: '', e: '' } } -const hasFundsAuth = (req) => { +const hasFundsGuoxinAuth = (req) => { try { - const configPath = path.join(process.cwd(), 'public', 'tools', 'funds', 'auth_config.json'); + const configPath = path.join(process.cwd(), 'public', 'tools', 'funds_guoxin', 'auth_config.json'); if (fs.existsSync(configPath)) { const config = JSON.parse(fs.readFileSync(configPath, 'utf-8')); if (config.enable_auth === false) return true; @@ -1860,32 +1862,32 @@ const hasFundsAuth = (req) => { const cookies = parseCookie(req.headers.cookie || '') const name = (() => { try { - const p = path.join(process.cwd(), 'public', 'tools', 'funds', 'auth_config.json') + const p = path.join(process.cwd(), 'public', 'tools', 'funds_guoxin', 'auth_config.json') if (fs.existsSync(p)) { const cfg = JSON.parse(fs.readFileSync(p, 'utf-8')) const n = String(cfg.cookieName || '') if (n) return n } } catch {} - return FUNDS_AUTH_COOKIE + return FUNDS_GUOXIN_AUTH_COOKIE })() return cookies[name] === '1' } catch { return false } } -app.get('/tools/funds', (req, res, next) => { +app.get('/tools/funds_guoxin', (req, res, next) => { try { const token = String(req.query.token || '') if (!token) return next() - const payload = verifyJwtWithKeys(token, jwkKeys(readFundsJwk())) + const payload = verifyJwtWithKeys(token, jwkKeys(readFundsGuoxinJwk())) if (!payload) return res.status(401).send('未授权') { const iss = String(payload.iss || '') const navIss = getNavIssFromFlags() - if (iss === navIss && !audMatch(payload, 'Tools-funds')) return res.status(401).send('未授权') + if (iss === navIss && !audMatch(payload, 'Tools-funds_guoxin')) return res.status(401).send('未授权') } - const maxAgeFunds = (() => { + const maxAgeFundsGuoxin = (() => { try { - const p = path.join(process.cwd(), 'public', 'tools', 'funds', 'auth_config.json') + const p = path.join(process.cwd(), 'public', 'tools', 'funds_guoxin', 'auth_config.json') if (fs.existsSync(p)) { const cfg = JSON.parse(fs.readFileSync(p, 'utf-8')) const days = Number(cfg.max_age_days || 0) @@ -1896,27 +1898,105 @@ app.get('/tools/funds', (req, res, next) => { })() const cookieName = (() => { try { - const p = path.join(process.cwd(), 'public', 'tools', 'funds', 'auth_config.json') + const p = path.join(process.cwd(), 'public', 'tools', 'funds_guoxin', 'auth_config.json') if (fs.existsSync(p)) { const cfg = JSON.parse(fs.readFileSync(p, 'utf-8')) const n = String(cfg.cookieName || '') if (n) return n } } catch {} - return FUNDS_AUTH_COOKIE + return FUNDS_GUOXIN_AUTH_COOKIE })() - res.cookie(cookieName, '1', { httpOnly: true, sameSite: 'lax', maxAge: maxAgeFunds, path: '/' }) - return res.redirect('/tools/funds') + res.cookie(cookieName, '1', { httpOnly: true, sameSite: 'lax', maxAge: maxAgeFundsGuoxin, path: '/' }) + return res.redirect('/tools/funds_guoxin') } catch { return res.status(401).send('未授权') } }) -app.use('/tools/funds', (req, res, next) => { - if (hasFundsAuth(req)) return next() +app.use('/tools/funds_guoxin', (req, res, next) => { + if (hasFundsGuoxinAuth(req)) return next() const isHandshake = req.method === 'GET' && (req.path === '/' || req.path === '') if (isHandshake && String(req.query.token || '')) return next() return res.status(401).send('未授权') }) -app.use('/api/funds', (req, res, next) => { - if (hasFundsAuth(req)) return next() +app.use('/api/funds_guoxin', (req, res, next) => { + if (hasFundsGuoxinAuth(req)) return next() + return res.status(401).json({ ok: false, error: 'unauthorized' }) +}) + +const FUNDS_HUATAI_AUTH_COOKIE = 'funds_huatai_gate' +const readFundsHuataiJwk = () => { + try { + const p = path.join(process.cwd(), 'config', 'funds_huatai.jwk.json') + if (fs.existsSync(p)) return JSON.parse(fs.readFileSync(p, 'utf-8')) + } catch {} + return { kty: 'RSA', n: '', e: '' } +} +const hasFundsHuataiAuth = (req) => { + try { + const configPath = path.join(process.cwd(), 'public', 'tools', 'funds_huatai', 'auth_config.json'); + if (fs.existsSync(configPath)) { + const config = JSON.parse(fs.readFileSync(configPath, 'utf-8')); + if (config.enable_auth === false) return true; + } + const cookies = parseCookie(req.headers.cookie || '') + const name = (() => { + try { + const p = path.join(process.cwd(), 'public', 'tools', 'funds_huatai', 'auth_config.json') + if (fs.existsSync(p)) { + const cfg = JSON.parse(fs.readFileSync(p, 'utf-8')) + const n = String(cfg.cookieName || '') + if (n) return n + } + } catch {} + return FUNDS_HUATAI_AUTH_COOKIE + })() + return cookies[name] === '1' + } catch { return false } +} +app.get('/tools/funds_huatai', (req, res, next) => { + try { + const token = String(req.query.token || '') + if (!token) return next() + const payload = verifyJwtWithKeys(token, jwkKeys(readFundsHuataiJwk())) + if (!payload) return res.status(401).send('未授权') + { + const iss = String(payload.iss || '') + const navIss = getNavIssFromFlags() + if (iss === navIss && !audMatch(payload, 'Tools-funds_huatai')) return res.status(401).send('未授权') + } + const maxAgeFundsHuatai = (() => { + try { + const p = path.join(process.cwd(), 'public', 'tools', 'funds_huatai', 'auth_config.json') + if (fs.existsSync(p)) { + const cfg = JSON.parse(fs.readFileSync(p, 'utf-8')) + const days = Number(cfg.max_age_days || 0) + if (Number.isFinite(days) && days > 0) return Math.min(days, 365) * 24 * 3600 * 1000 + } + } catch {} + return 90 * 24 * 3600 * 1000 + })() + const cookieName = (() => { + try { + const p = path.join(process.cwd(), 'public', 'tools', 'funds_huatai', 'auth_config.json') + if (fs.existsSync(p)) { + const cfg = JSON.parse(fs.readFileSync(p, 'utf-8')) + const n = String(cfg.cookieName || '') + if (n) return n + } + } catch {} + return FUNDS_HUATAI_AUTH_COOKIE + })() + res.cookie(cookieName, '1', { httpOnly: true, sameSite: 'lax', maxAge: maxAgeFundsHuatai, path: '/' }) + return res.redirect('/tools/funds_huatai') + } catch { return res.status(401).send('未授权') } +}) +app.use('/tools/funds_huatai', (req, res, next) => { + if (hasFundsHuataiAuth(req)) return next() + const isHandshake = req.method === 'GET' && (req.path === '/' || req.path === '') + if (isHandshake && String(req.query.token || '')) return next() + return res.status(401).send('未授权') +}) +app.use('/api/funds_huatai', (req, res, next) => { + if (hasFundsHuataiAuth(req)) return next() return res.status(401).json({ ok: false, error: 'unauthorized' }) }) @@ -3971,7 +4051,8 @@ app.get('/api/debug/jwt/verify', (req, res) => { 'expense': () => EXPENSE_JWK, 'ai-lib': () => readAiLibJwk(), 'cloud': () => readCloudJwk(), - 'funds': () => readFundsJwk(), + 'funds_guoxin': () => readFundsGuoxinJwk(), + 'funds_huatai': () => readFundsHuataiJwk(), 'markets': () => readMarketsJwk(), 'wall': () => readWallJwk(), 'weekly': () => readWeeklyJwk(), @@ -4033,7 +4114,7 @@ app.get('/api/debug/nav/private', (req, res) => { app.get('/api/flags', (req, res) => { const enabled = computeDebugEnabled() - res.json({ ok: true, debugToolEnabled: enabled, debug: { weibo: computeToolDebug('weibo'), markets: computeToolDebug('markets'), wall: computeToolDebug('wall'), funds: computeToolDebug('funds'), weekly: computeToolDebug('weekly') } }) + res.json({ ok: true, debugToolEnabled: enabled, debug: { weibo: computeToolDebug('weibo'), markets: computeToolDebug('markets'), wall: computeToolDebug('wall'), funds_guoxin: computeToolDebug('funds_guoxin'), funds_huatai: computeToolDebug('funds_huatai'), weekly: computeToolDebug('weekly') } }) }) app.get('/api/weibo/devtools/status', async (req, res) => { @@ -4878,27 +4959,50 @@ app.get('/api/wall/cards', (req, res) => { } }) -// Funds tool -app.get('/api/funds/config', (req, res) => { - try { res.json({ ok: true, config: funds.getConfig() }) } catch (e) { res.status(500).json({ ok: false, error: String(e.message||e) }) } +// Funds Guoxin tool +app.get('/api/funds_guoxin/config', (req, res) => { + try { res.json({ ok: true, config: fundsGuoxin.getConfig() }) } catch (e) { res.status(500).json({ ok: false, error: String(e.message||e) }) } }) -app.post('/api/funds/config', (req, res) => { - try { const cfg = funds.getConfig(); const body = req.body || {}; const next = Object.assign({}, cfg, body); funds.setConfig(next); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +app.post('/api/funds_guoxin/config', (req, res) => { + try { const cfg = fundsGuoxin.getConfig(); const body = req.body || {}; const next = Object.assign({}, cfg, body); fundsGuoxin.setConfig(next); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } }) -app.get('/api/funds/flows', (req, res) => { - try { res.set('Cache-Control', 'no-store'); const start = String(req.query.start||''); const end = String(req.query.end||''); const type = String(req.query.type||'all'); const kw = String(req.query.kw||''); const rows = funds.listFlows(start, end, type, kw); res.json({ ok: true, rows }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +app.get('/api/funds_guoxin/flows', (req, res) => { + try { res.set('Cache-Control', 'no-store'); const start = String(req.query.start||''); const end = String(req.query.end||''); const type = String(req.query.type||'all'); const kw = String(req.query.kw||''); const rows = fundsGuoxin.listFlows(start, end, type, kw); res.json({ ok: true, rows }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } }) -app.post('/api/funds/flows', (req, res) => { - try { funds.createFlow(req.body||{}); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +app.post('/api/funds_guoxin/flows', (req, res) => { + try { fundsGuoxin.createFlow(req.body||{}); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } }) -app.put('/api/funds/flows/:id', (req, res) => { - try { const id = parseInt(req.params.id,10); funds.updateFlowById(id, req.body||{}); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +app.put('/api/funds_guoxin/flows/:id', (req, res) => { + try { const id = parseInt(req.params.id,10); fundsGuoxin.updateFlowById(id, req.body||{}); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } }) -app.delete('/api/funds/flows/:id', (req, res) => { - try { const id = parseInt(req.params.id,10); funds.deleteFlow(id); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +app.delete('/api/funds_guoxin/flows/:id', (req, res) => { + try { const id = parseInt(req.params.id,10); fundsGuoxin.deleteFlow(id); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } }) -app.get('/api/funds/export.csv', (req, res) => { - try { const start = String(req.query.start||''); const end = String(req.query.end||''); const rows = funds.listFlows(start, end, 'all', ''); const header = '日期,类型,金额(人民币),银行方/状态,期末金额,备注\n'; const content = rows.map(r => `${r.date},${r.type==='in'?'汇入':'汇出'},${(r.amount_cents/100).toFixed(2)},${(r.bank_status||'').replace(/,/g,' ')},${(r.ending_cents/100).toFixed(2)},${(r.remark||'').replace(/,/g,' ')}`).join('\n'); res.setHeader('Content-Type','text/csv; charset=utf-8'); res.setHeader('Content-Disposition','attachment; filename="funds.csv"'); res.send(header+content) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +app.get('/api/funds_guoxin/export.csv', (req, res) => { + try { const start = String(req.query.start||''); const end = String(req.query.end||''); const rows = fundsGuoxin.listFlows(start, end, 'all', ''); const header = '日期,类型,金额(人民币),银行方/状态,期末金额,备注\n'; const content = rows.map(r => `${r.date},${r.type==='in'?'汇入':'汇出'},${(r.amount_cents/100).toFixed(2)},${(r.bank_status||'').replace(/,/g,' ')},${(r.ending_cents/100).toFixed(2)},${(r.remark||'').replace(/,/g,' ')}`).join('\n'); res.setHeader('Content-Type','text/csv; charset=utf-8'); res.setHeader('Content-Disposition','attachment; filename="funds_guoxin.csv"'); res.send(header+content) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +}) + +// Funds Huatai tool +app.get('/api/funds_huatai/config', (req, res) => { + try { res.json({ ok: true, config: fundsHuatai.getConfig() }) } catch (e) { res.status(500).json({ ok: false, error: String(e.message||e) }) } +}) +app.post('/api/funds_huatai/config', (req, res) => { + try { const cfg = fundsHuatai.getConfig(); const body = req.body || {}; const next = Object.assign({}, cfg, body); fundsHuatai.setConfig(next); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +}) +app.get('/api/funds_huatai/flows', (req, res) => { + try { res.set('Cache-Control', 'no-store'); const start = String(req.query.start||''); const end = String(req.query.end||''); const type = String(req.query.type||'all'); const kw = String(req.query.kw||''); const rows = fundsHuatai.listFlows(start, end, type, kw); res.json({ ok: true, rows }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +}) +app.post('/api/funds_huatai/flows', (req, res) => { + try { fundsHuatai.createFlow(req.body||{}); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +}) +app.put('/api/funds_huatai/flows/:id', (req, res) => { + try { const id = parseInt(req.params.id,10); fundsHuatai.updateFlowById(id, req.body||{}); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +}) +app.delete('/api/funds_huatai/flows/:id', (req, res) => { + try { const id = parseInt(req.params.id,10); fundsHuatai.deleteFlow(id); res.json({ ok: true }) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } +}) +app.get('/api/funds_huatai/export.csv', (req, res) => { + try { const start = String(req.query.start||''); const end = String(req.query.end||''); const rows = fundsHuatai.listFlows(start, end, 'all', ''); const header = '日期,类型,金额(人民币),银行方/状态,期末金额,备注\n'; const content = rows.map(r => `${r.date},${r.type==='in'?'汇入':'汇出'},${(r.amount_cents/100).toFixed(2)},${(r.bank_status||'').replace(/,/g,' ')},${(r.ending_cents/100).toFixed(2)},${(r.remark||'').replace(/,/g,' ')}`).join('\n'); res.setHeader('Content-Type','text/csv; charset=utf-8'); res.setHeader('Content-Disposition','attachment; filename="funds_huatai.csv"'); res.send(header+content) } catch (e) { res.status(500).json({ ok:false, error:String(e.message||e) }) } }) app.get('/api/ccb_private_funds/config', (req, res) => {