From 86ed7045e2a9c94936333c7e67c499df0c2ee4a3 Mon Sep 17 00:00:00 2001 From: shanshi <3316401569@qq.com> Date: Fri, 27 Nov 2026 17:26:21 +0800 Subject: [PATCH] feat: automate daily HXB bank bill import --- scripts/hxb-bank/README.md | 36 ++ scripts/hxb-bank/export-daily.mjs | 642 ++++++++++++++++++++++++ scripts/hxb-bank/install-daily-task.ps1 | 69 +++ scripts/hxb-bank/read-dingtalk-otp.ps1 | 5 + scripts/hxb-bank/run-hxb-daily.cmd | 4 + scripts/hxb-bank/run-hxb-daily.ps1 | 201 ++++++++ scripts/hxb-bank/send-secure-text.ps1 | 117 +++++ 7 files changed, 1074 insertions(+) create mode 100644 scripts/hxb-bank/export-daily.mjs create mode 100644 scripts/hxb-bank/install-daily-task.ps1 create mode 100644 scripts/hxb-bank/run-hxb-daily.cmd create mode 100644 scripts/hxb-bank/run-hxb-daily.ps1 create mode 100644 scripts/hxb-bank/send-secure-text.ps1 diff --git a/scripts/hxb-bank/README.md b/scripts/hxb-bank/README.md index 019c1ddbe..9069416c7 100644 --- a/scripts/hxb-bank/README.md +++ b/scripts/hxb-bank/README.md @@ -61,3 +61,39 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\hxb-bank\read-di ``` 必须包含 `en-US`。如果没有,请在 Windows“语言和区域”中安装英语语言及光学字符识别组件。 + +## 每日自动导入 + +完整流程是: + +1. 使用独立 Edge 登录态打开华夏企业网银。 +2. 必要时自动填写手机号、密码并发送短信验证码。 +3. 向钉钉“华夏验证码”群发送提示。 +4. 从钉钉窗口读取新验证码并完成登录。 +5. 查询昨天至今天的全部账户交易明细。 +6. 自动下载 XLSX,并核对日期、流水条数、收入与支出。 +7. 以“华夏银行 / 银企直连账户账单”执行 dry-run。 +8. 核对 dry-run 的账务日期范围;条数以文件实际解析结果为准,校验通过后导入本地财务系统。 + +手动运行: + +```powershell +scripts\hxb-bank\run-hxb-daily.cmd +``` + +只下载不导入: + +```powershell +scripts\hxb-bank\run-hxb-daily.cmd -SkipImport +``` + +安装每天 00:01 的 Windows 定时任务: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass ` + -File scripts\hxb-bank\install-daily-task.ps1 +``` + +任务名称为 `CaiWuXiTong-HxbBankDaily`。电脑关机时无法执行;任务设置为“错过计划后在下次可用时启动”,但必须在用户已登录且未注销的 Windows 会话中运行。 + +运行前应保持钉钉打开,并将“华夏验证码”群作为当前会话;银行验证码消息需要出现在该窗口右侧聊天区域。 diff --git a/scripts/hxb-bank/export-daily.mjs b/scripts/hxb-bank/export-daily.mjs new file mode 100644 index 000000000..5ca94a68e --- /dev/null +++ b/scripts/hxb-bank/export-daily.mjs @@ -0,0 +1,642 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { spawn, spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { + CDP, + evaluate, + goto, + launchEdge, + openPage, + setDownloadDir, + sleep, +} from '../erp-daily-bills/cdp.mjs'; + +const BASE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(BASE, '../..'); +const LOGIN_URL = 'https://trecloud.hxb.com.cn/login'; +const ACCOUNT_DETAIL_URL = 'https://trecloud.hxb.com.cn/muti-bank-account/accountDetail'; +const PROFILE = path.join(ROOT, 'runtime/private/hxb-bank-edge-profile'); +const READER = path.join(BASE, 'read-dingtalk-otp.ps1'); +const PORT = 9341; + +function ensureAutomationProfile() { + const sourceRoot = path.join(process.env.LOCALAPPDATA || '', 'Microsoft/Edge/User Data'); + const sourceDefault = path.join(sourceRoot, 'Default'); + const targetDefault = path.join(PROFILE, 'Default'); + const extensionId = 'biphcfgechkjmfglclhgjaaomdgfidfp'; + const targetExtension = path.join(targetDefault, 'Extensions', extensionId); + if (fs.existsSync(targetExtension)) return; + + const sourceExtension = path.join(sourceDefault, 'Extensions', extensionId); + if (!fs.existsSync(sourceExtension)) { + throw new Error('常用 Edge 配置中未安装华夏银行密码扩展'); + } + + fs.mkdirSync(targetDefault, { recursive: true }); + for (const file of ['Local State']) { + const source = path.join(sourceRoot, file); + if (fs.existsSync(source)) fs.copyFileSync(source, path.join(PROFILE, file)); + } + for (const name of ['Preferences', 'Secure Preferences', 'Extension State', 'Local Extension Settings']) { + const source = path.join(sourceDefault, name); + if (fs.existsSync(source)) { + fs.cpSync(source, path.join(targetDefault, name), { recursive: true, force: true }); + } + } + fs.cpSync(path.join(sourceDefault, 'Extensions'), path.join(targetDefault, 'Extensions'), { + recursive: true, + force: true, + }); +} + +const arg = (name, fallback = null) => { + const hit = process.argv.find((item) => item.startsWith(`--${name}=`)); + return hit ? hit.slice(name.length + 3) : fallback; +}; + +const formatDate = (date) => [ + date.getFullYear(), + String(date.getMonth() + 1).padStart(2, '0'), + String(date.getDate()).padStart(2, '0'), +].join('-'); + +const datePattern = /^\d{4}-\d{2}-\d{2}$/; +const fromDate = arg('from', formatDate(new Date(Date.now() - 86400000))); +const toDate = arg('to', formatDate(new Date())); +const phone = String(process.env.HXB_PHONE || '').trim(); +const password = String(process.env.HXB_PASSWORD || ''); +const webhook = String(process.env.HXB_DINGTALK_WEBHOOK || '').trim(); +const outputRoot = path.resolve(arg( + 'out', + path.join(ROOT, 'runtime/private/hxb-bank-exports', `${fromDate}_${toDate}`), +)); +const runStamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14); +const runDirectory = path.join(outputRoot, `run-${runStamp}`); +const downloadDirectory = path.join(runDirectory, 'downloads'); +const stateFile = path.join(runDirectory, 'last-export.json'); + +if (!datePattern.test(fromDate) || !datePattern.test(toDate) || fromDate > toDate) { + throw new Error('日期范围无效'); +} +if (!phone || !password) { + throw new Error('缺少华夏银行登录手机号或密码'); +} +if (!/^https:\/\/oapi\.dingtalk\.com\/robot\/send\?access_token=[0-9a-f]+$/.test(webhook)) { + throw new Error('缺少有效的钉钉群机器人 Webhook'); +} + +fs.mkdirSync(downloadDirectory, { recursive: true }); + +function sanitizeError(error) { + return String(error?.message || error) + .replace(/https:\/\/oapi\.dingtalk\.com\/robot\/send\?access_token=[0-9a-f]+/gi, '[webhook]') + .replace(/\b1[3-9]\d{9}\b/g, '[phone]') + .slice(0, 600); +} + +function listFiles(directory) { + if (!fs.existsSync(directory)) return []; + return fs.readdirSync(directory) + .map((name) => path.join(directory, name)) + .filter((file) => fs.statSync(file).isFile()); +} + +function hasCompleteZip(file) { + try { + const bytes = fs.readFileSync(file); + return bytes.length > 22 + && bytes.subarray(0, 4).equals(Buffer.from([0x50, 0x4b, 0x03, 0x04])) + && bytes.includes(Buffer.from([0x50, 0x4b, 0x05, 0x06])); + } catch { + return false; + } +} + +async function waitFor(check, description, timeoutMs = 60000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const result = await check(); + if (result) return result; + await sleep(700); + } + throw new Error(`${description}超时`); +} + +async function bodyText(cdp, sessionId) { + return evaluate(cdp, sessionId, '(document.body?.innerText || "")'); +} + +async function pageState(cdp, sessionId) { + return evaluate(cdp, sessionId, `({ + url: location.href, + title: document.title, + text: document.body?.innerText || '', + hasUsername: (() => { + const el = document.querySelector('#username'); + return !!(el && (el.offsetWidth || el.offsetHeight)); + })(), + hasPassword: (() => { + const el = document.querySelector('#SecEditBox1'); + return !!(el && (el.offsetWidth || el.offsetHeight)); + })(), + hasCaptcha: (() => { + const el = document.querySelector('input[name="captcha"]'); + return !!(el && (el.offsetWidth || el.offsetHeight)); + })() + })`); +} + +async function findPoint(cdp, sessionId, expression) { + return evaluate(cdp, sessionId, `(() => { + const el = (${expression}); + if (!el || !(el.offsetWidth || el.offsetHeight)) return null; + el.scrollIntoView({ block: 'center', inline: 'center' }); + const rect = el.getBoundingClientRect(); + return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; + })()`); +} + +async function clickPoint(cdp, sessionId, point) { + if (!point) return false; + await cdp.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + x: point.x, + y: point.y, + button: 'left', + clickCount: 1, + }, sessionId); + await cdp.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + x: point.x, + y: point.y, + button: 'left', + clickCount: 1, + }, sessionId); + return true; +} + +async function clickSelector(cdp, sessionId, selector, index = 0) { + return clickPoint(cdp, sessionId, await findPoint( + cdp, + sessionId, + `[...document.querySelectorAll(${JSON.stringify(selector)})][${index}]`, + )); +} + +async function clickText(cdp, sessionId, text, { contains = false, selectors = 'button,a,[role="button"],span,div' } = {}) { + return clickPoint(cdp, sessionId, await findPoint( + cdp, + sessionId, + `[...document.querySelectorAll(${JSON.stringify(selectors)})] + .find((el) => { + const label = (el.innerText || el.value || '').replace(/\\s+/g, ''); + return ${contains ? 'label.includes' : 'label === '}(${JSON.stringify(String(text).replace(/\s+/g, ''))}); + })`, + )); +} + +function typeSecureTextWithWindows(value) { + const result = spawnSync( + 'powershell.exe', + [ + '-NoProfile', + '-ExecutionPolicy', + 'Bypass', + '-File', + path.join(BASE, 'send-secure-text.ps1'), + ], + { + windowsHide: true, + encoding: 'utf8', + timeout: 20000, + env: { + ...process.env, + CAIWU_SECURE_INPUT: value, + }, + }, + ); + if (result.status !== 0) { + throw new Error('银行密码无法通过 Windows 安全键盘输入'); + } +} + +async function clearFocusedField(cdp, sessionId) { + await cdp.send('Input.dispatchKeyEvent', { + type: 'keyDown', + key: 'Control', + code: 'ControlLeft', + windowsVirtualKeyCode: 17, + nativeVirtualKeyCode: 17, + modifiers: 2, + }, sessionId); + await cdp.send('Input.dispatchKeyEvent', { + type: 'keyDown', + key: 'a', + code: 'KeyA', + text: 'a', + windowsVirtualKeyCode: 65, + nativeVirtualKeyCode: 65, + modifiers: 2, + }, sessionId); + await cdp.send('Input.dispatchKeyEvent', { + type: 'keyUp', + key: 'a', + code: 'KeyA', + windowsVirtualKeyCode: 65, + nativeVirtualKeyCode: 65, + modifiers: 2, + }, sessionId); + await cdp.send('Input.dispatchKeyEvent', { + type: 'keyUp', + key: 'Control', + code: 'ControlLeft', + windowsVirtualKeyCode: 17, + nativeVirtualKeyCode: 17, + }, sessionId); + for (let attempt = 0; attempt < 20; attempt++) { + await cdp.send('Input.dispatchKeyEvent', { + type: 'keyDown', + key: 'Backspace', + code: 'Backspace', + windowsVirtualKeyCode: 8, + nativeVirtualKeyCode: 8, + }, sessionId); + await cdp.send('Input.dispatchKeyEvent', { + type: 'keyUp', + key: 'Backspace', + code: 'Backspace', + windowsVirtualKeyCode: 8, + nativeVirtualKeyCode: 8, + }, sessionId); + } +} + +async function pressEnter(cdp, sessionId) { + await cdp.send('Input.dispatchKeyEvent', { + type: 'keyDown', + key: 'Enter', + code: 'Enter', + windowsVirtualKeyCode: 13, + nativeVirtualKeyCode: 13, + }, sessionId); + await cdp.send('Input.dispatchKeyEvent', { + type: 'keyUp', + key: 'Enter', + code: 'Enter', + windowsVirtualKeyCode: 13, + nativeVirtualKeyCode: 13, + }, sessionId); +} + +async function waitForLoginPage(cdp, sessionId) { + for (let attempt = 0; attempt < 18; attempt++) { + const state = await pageState(cdp, sessionId); + if (state.hasUsername && state.hasPassword) return state; + if (/\/dashboard(?:\?|$)/.test(new URL(state.url).pathname + (new URL(state.url).search || ''))) { + return state; + } + if (attempt > 0 && attempt % 4 === 0) { + await cdp.send('Page.reload', {}, sessionId); + } + await sleep(2000); + } + throw new Error('华夏银行登录页控件未加载'); +} + +async function postDingTalkPrompt() { + const response = await fetch(webhook, { + method: 'POST', + headers: { 'content-type': 'application/json; charset=utf-8' }, + body: JSON.stringify({ + msgtype: 'text', + text: { content: '请接收验证码' }, + }), + signal: AbortSignal.timeout(20000), + }); + const result = await response.json().catch(() => ({})); + if (!response.ok || Number(result.errcode) !== 0) { + throw new Error(`钉钉群提示发送失败:${result.errmsg || response.status}`); + } +} + +function startOtpReader(readyFile) { + let stdout = ''; + let stderr = ''; + const child = spawn( + 'powershell.exe', + [ + '-NoProfile', + '-ExecutionPolicy', + 'Bypass', + '-File', + READER, + '-TimeoutSeconds', + '240', + '-PollMilliseconds', + '750', + '-CaptureMode', + 'PrintWindow', + '-ReadyFile', + readyFile, + '-SkipGroupMarker', + ], + { + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + }, + ); + child.stdout.setEncoding('utf8'); + child.stderr.setEncoding('utf8'); + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + + const completion = new Promise((resolve, reject) => { + const timer = setTimeout(() => { + child.kill(); + reject(new Error('钉钉验证码读取超时')); + }, 270000); + child.once('error', (error) => { + clearTimeout(timer); + reject(error); + }); + child.once('exit', (code) => { + clearTimeout(timer); + if (code !== 0) { + reject(new Error( + '钉钉验证码读取失败;请确认钉钉停留在“华夏验证码”群', + )); + return; + } + for (const line of stdout.trim().split(/\r?\n/).reverse()) { + if (!line.trim().startsWith('{')) continue; + try { + const parsed = JSON.parse(line); + if (parsed.ok && /^\d{6}$/.test(String(parsed.code || ''))) { + resolve(String(parsed.code)); + return; + } + } catch { + // Keep reading only the final JSON record. + } + } + reject(new Error('钉钉验证码读取结果无效')); + }); + }); + + completion.catch(() => { + // The ready/action path below consumes the same rejection. + }); + const ready = Promise.race([ + waitFor( + () => fs.existsSync(readyFile) ? true : null, + '钉钉验证码监听初始化', + 60000, + ), + completion.then(() => { + throw new Error('钉钉验证码监听提前结束'); + }), + ]); + return { child, completion, ready }; +} + +async function loginIfNeeded(cdp, sessionId) { + await goto(cdp, sessionId, LOGIN_URL); + const loginState = await waitForLoginPage(cdp, sessionId); + if (/\/dashboard/.test(loginState.url)) return; + + if (!await clickSelector(cdp, sessionId, '#username')) { + throw new Error('未找到手机号输入框'); + } + await clearFocusedField(cdp, sessionId); + await cdp.send('Input.insertText', { text: phone }, sessionId); + + if (!await clickSelector(cdp, sessionId, '#SecEditBox1')) { + throw new Error('未找到密码输入框'); + } + await clearFocusedField(cdp, sessionId); + await sleep(250); + typeSecureTextWithWindows(password); + await sleep(500); + + const readyFile = path.join(runDirectory, `otp-reader-${Date.now()}.ready`); + const otpReader = startOtpReader(readyFile); + await otpReader.ready; + if (!await clickText(cdp, sessionId, '发送验证码', { selectors: 'button' })) { + otpReader.child.kill(); + throw new Error('未找到发送验证码按钮'); + } + try { + await waitFor(async () => /秒后重发/.test(await bodyText(cdp, sessionId)), '短信验证码发送', 15000); + await postDingTalkPrompt(); + const otp = await otpReader.completion; + + if (!await clickSelector(cdp, sessionId, 'input[name="captcha"]')) { + throw new Error('未找到短信验证码输入框'); + } + await clearFocusedField(cdp, sessionId); + await cdp.send('Input.insertText', { text: otp }, sessionId); + if (!await clickText(cdp, sessionId, '登录', { selectors: 'button' })) { + throw new Error('未找到登录按钮'); + } + + await waitFor(async () => { + const state = await pageState(cdp, sessionId); + return /\/dashboard/.test(state.url) ? state : null; + }, '华夏银行登录', 60000); + } finally { + otpReader.child.kill(); + try { + fs.rmSync(readyFile, { force: true }); + } catch { + // Best-effort cleanup only. + } + } +} + +async function setDateInput(cdp, sessionId, index, value) { + const focused = await evaluate(cdp, sessionId, `(() => { + const el = document.querySelectorAll('input.el-range-input')[${index}]; + if (!el) return false; + el.click(); + el.focus(); + el.select(); + return document.activeElement === el; + })()`); + if (!focused) { + throw new Error('未找到交易日期输入框'); + } + await cdp.send('Input.insertText', { text: value }, sessionId); + await pressEnter(cdp, sessionId); + await sleep(300); +} + +async function queryTransactions(cdp, sessionId) { + await setDateInput(cdp, sessionId, 0, fromDate); + await setDateInput(cdp, sessionId, 1, toDate); + if (!await clickText(cdp, sessionId, '查询', { selectors: 'button' })) { + throw new Error('未找到查询按钮'); + } + + const deadline = Date.now() + 60000; + let lastState = null; + while (Date.now() < deadline) { + const state = await evaluate(cdp, sessionId, `(() => { + const text = document.body?.innerText || ''; + const dates = [...document.querySelectorAll('input.el-range-input')].map((el) => el.value); + const visible = (el) => !!(el.offsetWidth || el.offsetHeight); + const countElement = [...document.querySelectorAll('*')] + .filter((el) => visible(el) && !(el.children.length === 1 && el.firstElementChild?.children.length === 0)) + .filter((el) => /^共\\s*\\d+\\s*条$/.test((el.innerText || '').trim())) + .sort((left, right) => right.getBoundingClientRect().y - left.getBoundingClientRect().y)[0]; + const countMatch = (countElement?.innerText || '').trim().match(/^共\\s*(\\d+)\\s*条$/); + const amount = (pattern) => { + const match = text.match(pattern); + return match ? Number(String(match[1]).replace(/,/g, '')) : null; + }; + const countValue = (pattern) => { + const match = text.match(pattern); + return match ? Number(match[1]) : null; + }; + const incomeCount = countValue(/收入总笔数\\s*(\\d+)/); + const expenseCount = countValue(/支出总笔数\\s*(\\d+)/); + const queryButton = [...document.querySelectorAll('button')] + .find((el) => visible(el) && (el.innerText || '').replace(/\\s+/g, '') === '查询'); + return { + dates, + count: incomeCount !== null && expenseCount !== null + ? incomeCount + expenseCount + : (countMatch ? Number(countMatch[1]) : null), + countText: countElement?.innerText?.trim() || '', + incomeCount, + expenseCount, + income: amount(/收入总金额\\s*([\\d,.]+)/), + expense: amount(/支出总金额\\s*([\\d,.]+)/), + loading: /查询中|加载中/.test(text), + queryDisabled: !!queryButton?.disabled, + }; + })()`); + lastState = state; + if (state.dates?.[0] === fromDate + && state.dates?.[1] === toDate + && !state.loading + && !state.queryDisabled + && state.count !== null + && (state.count > 0 || (Number(state.income || 0) === 0 && Number(state.expense || 0) === 0))) { + return state; + } + await sleep(700); + } + throw new Error( + `交易明细查询超时或日期未生效(日期 ${JSON.stringify(lastState?.dates || [])},` + + `条数 ${lastState?.count ?? 'unknown'})`, + ); +} + +async function waitForDownload(beforeFiles, timeoutMs = 150000) { + const before = new Set(beforeFiles); + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const files = listFiles(downloadDirectory); + const completed = files + .filter((file) => !before.has(file) && /\.(xlsx|xls)$/i.test(file)) + .filter((file) => { + try { + return Date.now() - fs.statSync(file).mtimeMs > 800 && hasCompleteZip(file); + } catch { + return false; + } + }) + .sort((left, right) => fs.statSync(right).mtimeMs - fs.statSync(left).mtimeMs); + if (completed.length > 0) return completed[0]; + + const partials = files + .filter((file) => !before.has(file) && file.endsWith('.crdownload')) + .filter((file) => { + try { + return Date.now() - fs.statSync(file).mtimeMs > 1500 && hasCompleteZip(file); + } catch { + return false; + } + }) + .sort((left, right) => fs.statSync(right).mtimeMs - fs.statSync(left).mtimeMs); + if (partials.length > 0) { + const finalFile = path.join(downloadDirectory, `华夏银行_账户明细_${fromDate}_${toDate}.xlsx`); + fs.copyFileSync(partials[0], finalFile); + return finalFile; + } + await sleep(700); + } + throw new Error('交易明细下载超时'); +} + +let cdp = null; +let child = null; + +try { + ensureAutomationProfile(); + const launch = await launchEdge({ + port: PORT, + profileDir: PROFILE, + headless: false, + windowSize: '1800,1100', + forceDeviceScaleFactor: 1, + }); + child = launch.child; + cdp = await CDP.connect(launch.version.webSocketDebuggerUrl); + const { sessionId } = await openPage(cdp, 'about:blank'); + await setDownloadDir(cdp, downloadDirectory); + await loginIfNeeded(cdp, sessionId); + await goto(cdp, sessionId, ACCOUNT_DETAIL_URL); + await waitFor(async () => { + const state = await pageState(cdp, sessionId); + return /账户交易明细管理/.test(state.text) + && (await evaluate(cdp, sessionId, 'document.querySelectorAll("input.el-range-input").length')) >= 2 + ? state + : null; + }, '账户交易明细页面加载', 60000); + + const query = await queryTransactions(cdp, sessionId); + let downloadedFile = null; + if (query.count > 0) { + const beforeFiles = listFiles(downloadDirectory); + if (!await clickText(cdp, sessionId, '全部导出', { selectors: 'button' })) { + throw new Error('未找到全部导出按钮'); + } + downloadedFile = await waitForDownload(beforeFiles); + } + + const state = { + ok: true, + from: fromDate, + to: toDate, + rows: query.count, + income: query.income, + expense: query.expense, + file: downloadedFile, + completedAt: new Date().toISOString(), + }; + fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8'); + console.log(JSON.stringify(state)); +} catch (error) { + const state = { + ok: false, + from: fromDate, + to: toDate, + error: sanitizeError(error), + completedAt: new Date().toISOString(), + }; + fs.mkdirSync(runDirectory, { recursive: true }); + fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8'); + console.error(JSON.stringify(state)); + process.exitCode = 1; +} finally { + cdp?.close(); + if (child) { + try { + child.kill(); + } catch { + // The browser may already be closed. + } + } +} diff --git a/scripts/hxb-bank/install-daily-task.ps1 b/scripts/hxb-bank/install-daily-task.ps1 new file mode 100644 index 000000000..4eddd3132 --- /dev/null +++ b/scripts/hxb-bank/install-daily-task.ps1 @@ -0,0 +1,69 @@ +#Requires -Version 5.1 + +[CmdletBinding(SupportsShouldProcess = $true)] +param( + [ValidatePattern('^([01]\d|2[0-3]):[0-5]\d$')] + [string]$Time = '00:01', + + [string]$TaskName = 'CaiWuXiTong-HxbBankDaily' +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$cmdPath = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot 'run-hxb-daily.cmd')).Path +$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent().Name +$arguments = @('/d', '/c', ('""' + $cmdPath + '""')) -join ' ' + +if (-not $PSCmdlet.ShouldProcess($TaskName, "register daily HXB import at $Time")) { + return +} + +$service = New-Object -ComObject 'Schedule.Service' +$rootFolder = $null +$definition = $null +try { + $service.Connect() + $rootFolder = $service.GetFolder('\') + $definition = $service.NewTask(0) + $definition.RegistrationInfo.Description = '每日读取华夏银行昨天至今天流水并导入财务系统银行账单' + $definition.Principal.UserId = $currentUser + $definition.Principal.LogonType = 3 + $definition.Principal.RunLevel = 0 + $definition.Settings.Enabled = $true + $definition.Settings.StartWhenAvailable = $true + $definition.Settings.DisallowStartIfOnBatteries = $false + $definition.Settings.StopIfGoingOnBatteries = $false + $definition.Settings.ExecutionTimeLimit = 'PT30M' + $definition.Settings.MultipleInstances = 2 + $definition.Settings.RestartCount = 2 + $definition.Settings.RestartInterval = 'PT10M' + + $trigger = $definition.Triggers.Create(2) + $trigger.StartBoundary = (Get-Date).Date.ToString('yyyy-MM-dd') + 'T' + $Time + ':00' + $trigger.DaysInterval = 1 + $trigger.Enabled = $true + + $action = $definition.Actions.Create(0) + $action.Path = $env:ComSpec + $action.Arguments = $arguments + $action.WorkingDirectory = $PSScriptRoot + + $registered = $rootFolder.RegisterTaskDefinition( + $TaskName, + $definition, + 6, + $null, + $null, + 3, + $null + ) + Write-Host "已安装华夏银行每日账单任务:$TaskName,执行时间每天 $Time。" + [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($registered) +} finally { + foreach ($item in @($definition, $rootFolder, $service)) { + if ($null -ne $item -and [Runtime.InteropServices.Marshal]::IsComObject($item)) { + [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($item) + } + } +} diff --git a/scripts/hxb-bank/read-dingtalk-otp.ps1 b/scripts/hxb-bank/read-dingtalk-otp.ps1 index 3b474a4c0..26af355da 100644 --- a/scripts/hxb-bank/read-dingtalk-otp.ps1 +++ b/scripts/hxb-bank/read-dingtalk-otp.ps1 @@ -4,6 +4,7 @@ param( [string]$WindowTitle = '钉钉', [string]$ImagePath, [string]$OcrText, + [string]$ReadyFile, [string]$GroupMarker = '华夏', [switch]$SkipGroupMarker, [string[]]$IgnoreCode = @(), @@ -509,6 +510,10 @@ if (-not $IncludeExisting) { } } +if (-not [string]::IsNullOrWhiteSpace($ReadyFile)) { + [IO.File]::WriteAllText($ReadyFile, 'ready', [Text.UTF8Encoding]::new($false)) +} + while ((Get-Date) -lt $deadline) { $bitmap = Get-WindowBitmap -Handle $handle -Mode $CaptureMode try { diff --git a/scripts/hxb-bank/run-hxb-daily.cmd b/scripts/hxb-bank/run-hxb-daily.cmd new file mode 100644 index 000000000..c3465682a --- /dev/null +++ b/scripts/hxb-bank/run-hxb-daily.cmd @@ -0,0 +1,4 @@ +@echo off +setlocal +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0run-hxb-daily.ps1" %* +exit /b %errorlevel% diff --git a/scripts/hxb-bank/run-hxb-daily.ps1 b/scripts/hxb-bank/run-hxb-daily.ps1 new file mode 100644 index 000000000..ac7a91d03 --- /dev/null +++ b/scripts/hxb-bank/run-hxb-daily.ps1 @@ -0,0 +1,201 @@ +[CmdletBinding()] +param( + [ValidatePattern('^\d{4}-\d{2}-\d{2}$')] + [string]$FromDate, + + [ValidatePattern('^\d{4}-\d{2}-\d{2}$')] + [string]$ToDate, + + [string]$ContainerName = 'jiangling_app', + + [switch]$DryRun, + + [switch]$SkipImport +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$utf8Output = New-Object Text.UTF8Encoding($false) +[Console]::OutputEncoding = $utf8Output +$OutputEncoding = $utf8Output + +$root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +$secretFile = Join-Path $root 'runtime\private\敏感信息.md' +$exporter = Join-Path $PSScriptRoot 'export-daily.mjs' +$logDir = Join-Path $root 'runtime\private\hxb-bank-exports\logs' +New-Item -ItemType Directory -Force -Path $logDir | Out-Null +$logFile = Join-Path $logDir ((Get-Date -Format 'yyyyMMdd') + '.log') + +function Write-Log { + param([string]$Message) + $line = '{0} {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Message + Write-Host $line + Add-Content -LiteralPath $logFile -Value $line -Encoding UTF8 +} + +function Resolve-Node { + $command = Get-Command node.exe -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($null -ne $command -and -not [string]::IsNullOrWhiteSpace($command.Source)) { + return $command.Source + } + $candidates = @( + (Join-Path $env:ProgramFiles 'nodejs\node.exe'), + (Join-Path $env:USERPROFILE '.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe') + ) + foreach ($candidate in $candidates) { + if (Test-Path -LiteralPath $candidate -PathType Leaf) { + return $candidate + } + } + throw '未找到 Node.js' +} + +if (-not (Test-Path -LiteralPath $secretFile -PathType Leaf)) { + throw '缺少 runtime/private/敏感信息.md' +} + +$secret = [IO.File]::ReadAllText($secretFile, [Text.Encoding]::UTF8) +$phone = [regex]::Match($secret, '(?m)^- 登录手机号:([^\r\n]+)$').Groups[1].Value.Trim() +$password = [regex]::Match($secret, '(?m)^- 登录密码:([^\r\n]+)$').Groups[1].Value.Trim() +$webhook = [regex]::Match( + $secret, + '(?m)^- Webhook:(https://oapi\.dingtalk\.com/robot/send\?access_token=[0-9a-f]+)$' +).Groups[1].Value.Trim() +if (-not $phone -or -not $password -or -not $webhook) { + throw '华夏银行手机号、密码或钉钉 Webhook 未配置完整' +} + +if ([string]::IsNullOrWhiteSpace($ToDate)) { + $ToDate = (Get-Date).Date.ToString('yyyy-MM-dd') +} +if ([string]::IsNullOrWhiteSpace($FromDate)) { + $FromDate = ([datetime]::ParseExact($ToDate, 'yyyy-MM-dd', $null)).AddDays(-1).ToString('yyyy-MM-dd') +} +if ($FromDate -gt $ToDate) { + throw '起始日期不能晚于结束日期' +} + +$outputRoot = Join-Path $root ('runtime\private\hxb-bank-exports\' + $FromDate + '_' + $ToDate) +$node = Resolve-Node + +$previousPhone = [Environment]::GetEnvironmentVariable('HXB_PHONE', 'Process') +$previousPassword = [Environment]::GetEnvironmentVariable('HXB_PASSWORD', 'Process') +$previousWebhook = [Environment]::GetEnvironmentVariable('HXB_DINGTALK_WEBHOOK', 'Process') +try { + $env:HXB_PHONE = $phone + $env:HXB_PASSWORD = $password + $env:HXB_DINGTALK_WEBHOOK = $webhook + Write-Log "开始导出华夏银行 $FromDate 至 $ToDate 交易明细" + $previousErrorActionForNode = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + try { + $exportOutput = (& $node $exporter ('--from=' + $FromDate) ('--to=' + $ToDate) ('--out=' + $outputRoot) 2>&1 | Out-String) + $exportExit = $LASTEXITCODE + } finally { + $ErrorActionPreference = $previousErrorActionForNode + } +} finally { + [Environment]::SetEnvironmentVariable('HXB_PHONE', $previousPhone, 'Process') + [Environment]::SetEnvironmentVariable('HXB_PASSWORD', $previousPassword, 'Process') + [Environment]::SetEnvironmentVariable('HXB_DINGTALK_WEBHOOK', $previousWebhook, 'Process') +} + +if (-not [string]::IsNullOrWhiteSpace($exportOutput)) { + Write-Log ('导出输出:' + ($exportOutput.Trim() -replace "`r?`n", ' | ')) +} + +$stateFile = Get-ChildItem -LiteralPath $outputRoot -Recurse -File -Filter 'last-export.json' | + Sort-Object LastWriteTime -Descending | + Select-Object -First 1 +if ($null -eq $stateFile) { + throw '华夏银行导出未生成状态文件' +} +$state = [IO.File]::ReadAllText($stateFile.FullName, [Text.Encoding]::UTF8) | ConvertFrom-Json +if ($exportExit -ne 0 -or -not $state.ok) { + throw ('华夏银行导出失败:' + [string]$state.error) +} +if ([string]$state.from -ne $FromDate -or [string]$state.to -ne $ToDate) { + throw '华夏银行导出日期与任务参数不一致' +} + +$rows = [int]$state.rows +Write-Log ('导出完成:{0} 条,收入 {1},支出 {2}' -f $rows, $state.income, $state.expense) +if ($rows -eq 0) { + Write-Log '当前日期范围没有交易,未调用导入' + return +} + +$file = [string]$state.file +if ([string]::IsNullOrWhiteSpace($file) -or -not (Test-Path -LiteralPath $file -PathType Leaf)) { + throw '华夏银行导出文件不存在' +} +Write-Log ('准备导入文件:' + [IO.Path]::GetFileName($file)) +if ($SkipImport) { + Write-Log '已指定 SkipImport,仅保留导出文件' + return +} + +Write-Log "检查财务系统容器 $ContainerName" +if ((& docker inspect --format '{{.State.Running}}' $ContainerName 2>$null) -ne 'true') { + throw "财务系统容器 $ContainerName 未运行" +} + +$containerFile = '/tmp/' + [IO.Path]::GetFileName($file) + '.' + [Guid]::NewGuid().ToString('N') + '.xlsx' +try { + Write-Log '复制账单到财务系统容器' + & docker cp $file "${ContainerName}:$containerFile" + if ($LASTEXITCODE -ne 0) { + throw '复制华夏银行账单到财务系统容器失败' + } + + Write-Log '执行账单 dry-run' + $dryRunArgs = @( + 'exec', '-u', 'www-data', $ContainerName, + 'php', 'artisan', 'finance-ledger:import-bank-bills', + $containerFile, '--bank=华夏银行', '--scope=direct', '--dry-run' + ) + $verifyOutput = (& docker @dryRunArgs 2>&1 | Out-String) + if ($LASTEXITCODE -ne 0) { + throw ('华夏银行账单 dry-run 失败:' + ($verifyOutput.Trim() -replace "`r?`n", ' | ')) + } + $verifiedRowsMatch = [regex]::Match($verifyOutput, '华夏银行:\s*(\d+)\s*条') + $verifiedRange = [regex]::Match( + $verifyOutput, + '账务日期:([0-9]{4}-[0-9]{2}-[0-9]{2}) 至 ([0-9]{4}-[0-9]{2}-[0-9]{2})' + ) + if ($verifiedRowsMatch.Success -and [int]$verifiedRowsMatch.Groups[1].Value -le 0) { + throw '华夏银行账单文件没有有效流水' + } + if ($verifiedRange.Success -and ( + $verifiedRange.Groups[1].Value -ne $FromDate -or + $verifiedRange.Groups[2].Value -ne $ToDate + )) { + throw '华夏银行账单文件的账务日期范围与任务日期不一致' + } + if ($verifiedRowsMatch.Success -and [int]$verifiedRowsMatch.Groups[1].Value -ne $rows) { + Write-Log ( + "页面汇总为 $rows 条,但文件校验为 $($verifiedRowsMatch.Groups[1].Value) 条;以文件实际流水为准" + ) + } + Write-Log ('dry-run 通过:' + ($verifyOutput.Trim() -replace "`r?`n", ' | ')) + if ($DryRun) { + Write-Log '指定 DryRun,未写入银行账单' + return + } + + $importArgs = @( + 'exec', '-u', 'www-data', $ContainerName, + 'php', 'artisan', 'finance-ledger:import-bank-bills', + $containerFile, '--bank=华夏银行', '--scope=direct' + ) + $importOutput = (& docker @importArgs 2>&1 | Out-String) + if ($LASTEXITCODE -ne 0) { + throw ('华夏银行账单导入失败:' + ($importOutput.Trim() -replace "`r?`n", ' | ')) + } + Write-Log ('导入完成:' + ($importOutput.Trim() -replace "`r?`n", ' | ')) +} catch { + Write-Log ('华夏银行账单导入异常:' + $_.Exception.Message) + throw +} finally { + & docker exec $ContainerName rm -f $containerFile 2>$null | Out-Null +} diff --git a/scripts/hxb-bank/send-secure-text.ps1 b/scripts/hxb-bank/send-secure-text.ps1 new file mode 100644 index 000000000..e64e9713f --- /dev/null +++ b/scripts/hxb-bank/send-secure-text.ps1 @@ -0,0 +1,117 @@ +[CmdletBinding()] +param() + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +if (-not ('CaiwuSecureKeyboard' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +using System.Threading; + +public static class CaiwuSecureKeyboard +{ + private const uint INPUT_KEYBOARD = 1; + private const uint KEYEVENTF_KEYUP = 0x0002; + private const ushort VK_SHIFT = 0x10; + + [StructLayout(LayoutKind.Sequential)] + private struct KEYBDINPUT + { + public ushort wVk; + public ushort wScan; + public uint dwFlags; + public uint time; + public IntPtr dwExtraInfo; + } + + [StructLayout(LayoutKind.Sequential)] + private struct MOUSEINPUT + { + public int dx; + public int dy; + public uint mouseData; + public uint dwFlags; + public uint time; + public IntPtr dwExtraInfo; + } + + [StructLayout(LayoutKind.Explicit)] + private struct INPUTUNION + { + [FieldOffset(0)] + public MOUSEINPUT mi; + + [FieldOffset(0)] + public KEYBDINPUT ki; + } + + [StructLayout(LayoutKind.Sequential)] + private struct INPUT + { + public uint type; + public INPUTUNION u; + } + + [DllImport("user32.dll", SetLastError = true)] + private static extern uint SendInput(uint count, INPUT[] inputs, int size); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern short VkKeyScan(char character); + + private static void SendKey(ushort virtualKey, bool keyUp) + { + INPUT input = new INPUT(); + input.type = INPUT_KEYBOARD; + input.u.ki.wVk = virtualKey; + input.u.ki.wScan = 0; + input.u.ki.dwFlags = keyUp ? KEYEVENTF_KEYUP : 0; + + if (SendInput(1, new[] { input }, Marshal.SizeOf(typeof(INPUT))) != 1) + { + throw new InvalidOperationException( + "Windows 键盘输入失败,错误码 " + Marshal.GetLastWin32Error() + ); + } + } + + public static void SendText(string text) + { + foreach (char character in text) + { + short scan = VkKeyScan(character); + if (scan == -1) + { + throw new InvalidOperationException("密码包含无法映射的字符"); + } + + ushort virtualKey = (ushort)(scan & 0xff); + bool shift = ((scan >> 8) & 0x01) != 0; + if (shift) + { + SendKey(VK_SHIFT, false); + } + SendKey(virtualKey, false); + SendKey(virtualKey, true); + if (shift) + { + SendKey(VK_SHIFT, true); + } + Thread.Sleep(35); + } + } +} +'@ +} + +$text = [Environment]::GetEnvironmentVariable('CAIWU_SECURE_INPUT', 'Process') +try { + if ([string]::IsNullOrEmpty($text)) { + throw '没有需要发送的文本' + } + [CaiwuSecureKeyboard]::SendText($text) +} +finally { + [Environment]::SetEnvironmentVariable('CAIWU_SECURE_INPUT', $null, 'Process') +}