refactor: 拆分通用资金工具为国信和华泰证券专属版本
- 移除原通用funds工具代码与配置 - 新增国信证券、华泰证券专属资金工具页面、样式与逻辑 - 为两个工具添加独立的鉴权配置 - 更新导航菜单,将原通用入口替换为两个券商专属入口 - 新增对应券商的SVG图标文件
This commit is contained in:
@@ -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) => {
|
||||
</table>
|
||||
</div>
|
||||
`.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) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 => `<tr><td>${it.idx}</td><td>${it.type==='in'?'汇入':'汇出'}</td><td>${it.amount}</td><td>${(it.bank||'').replace(/</g,'<').replace(/>/g,'>')}</td><td>${(it.remark||'').replace(/</g,'<').replace(/>/g,'>')}</td></tr>`).join('')
|
||||
const content = `
|
||||
<div>
|
||||
<h4>当日净变动</h4>
|
||||
<p>人民币:${formatCNY(total)}</p>
|
||||
<h4>明细</h4>
|
||||
<table border="1" cellspacing="0" cellpadding="4">
|
||||
<thead><tr><th>序号</th><th>类型</th><th>金额(元)</th><th>银行方/状态</th><th>备注</th></tr></thead>
|
||||
<tbody>${trs}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`.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 }
|
||||
+144
-40
@@ -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) => {
|
||||
|
||||
Reference in New Issue
Block a user