diff --git a/scripts/erp-daily-bills/cdp.mjs b/scripts/erp-daily-bills/cdp.mjs index bb0c23284..36fbce942 100644 --- a/scripts/erp-daily-bills/cdp.mjs +++ b/scripts/erp-daily-bills/cdp.mjs @@ -15,6 +15,7 @@ export async function launchEdge({ } = {}) { const args = [ `--remote-debugging-port=${port}`, + '--remote-allow-origins=*', `--user-data-dir=${profileDir}`, '--no-first-run', '--no-default-browser-check', diff --git a/scripts/hxb-bank/README.md b/scripts/hxb-bank/README.md new file mode 100644 index 000000000..10089b81b --- /dev/null +++ b/scripts/hxb-bank/README.md @@ -0,0 +1,114 @@ +# 华夏银行钉钉验证码填写 + +标准流程已改为一次性填写链接:华夏任务发送银行短信后,向钉钉“华夏验证码”群发送一个按钮链接。用户在链接内填写 6 位验证码,任务轮询财务系统后继续登录。此方式不依赖钉钉窗口 OCR。 + +链接默认 5 分钟有效、只能提交一次;验证码加密暂存,任务读取后立即删除,不写入日志。 + +运行任务的电脑需要能够访问正式财务系统。钉钉无需停留在验证码群,只需保持群机器人 Webhook 可用。 + +## 旧版钉钉截图读取 + +从本机钉钉“华夏验证码”群读取华夏银行刚收到的 6 位短信验证码。脚本只截取钉钉窗口右侧聊天区域,在内存中使用 Windows OCR 识别,不保存截图或完整聊天文本。 + +## 使用要求 + +- 仅在 Windows 台式机使用。 +- 钉钉保持登录,并停在“华夏验证码”群。 +- 钉钉窗口保持正常尺寸,不要最小化。 +- 使用 Windows PowerShell 5.1 运行,不要使用 PowerShell 7。 + +## 标准等待流程 + +先启动读取器,再发送银行短信验证码和钉钉提示: + +```powershell +scripts\hxb-bank\read-dingtalk-otp.cmd +``` + +读取器会先忽略屏幕上已有的验证码,再等待新验证码出现。成功后只输出一行 JSON,例如: + +```json +{"ok":true,"code":"123456","window":"钉钉","observedAt":"2026-11-27T16:30:00.0000000+08:00"} +``` + +常用参数: + +```powershell +# 等待 180 秒 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\hxb-bank\read-dingtalk-otp.ps1 ` + -TimeoutSeconds 180 + +# 已经收到新验证码后立即读取,并允许返回当前最新验证码 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\hxb-bank\read-dingtalk-otp.ps1 ` + -IncludeExisting + +# 避免重复使用某个旧验证码 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\hxb-bank\read-dingtalk-otp.ps1 ` + -IncludeExisting -IgnoreCode 123456 + +# 当前只允许读取指定群 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\hxb-bank\read-dingtalk-otp.ps1 ` + -GroupMarker 华夏 +``` + +## 识别规则 + +- 右边聊天气泡中的 6 位数字是主要识别位置。 +- 默认还会核对聊天窗口标题必须包含“华夏”,避免误读其他会话。 +- 中文 OCR 会把部分数字识别错,因此脚本使用 Windows 英文 OCR,并在 4、5、6 倍放大下交叉校验。 +- 同一验证码需要在不同放大结果里获得至少两次一致识别,并连续两轮截图都出现,才会输出。 +- 开始监听前已经存在的验证码默认全部排除。 +- 超时、窗口找不到、尺寸过小或 OCR 语言包缺失时返回非零退出码。 + +## 故障排查 + +查看系统 OCR 语言包: + +```powershell +[Windows.Media.Ocr.OcrEngine]::AvailableRecognizerLanguages | Select LanguageTag,DisplayName +``` + +必须包含 `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、09:10 的 Windows 定时任务: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass ` + -File scripts\hxb-bank\install-daily-task.ps1 +``` + +任务名称为 `CaiWuXiTong-HxbBankDaily`。电脑关机时无法执行;任务设置为“错过计划后在下次可用时启动”,但必须在用户已登录且未注销的 Windows 会话中运行。 + +运行前只需保证“华夏验证码”群机器人可以正常发送消息,并确保点击链接后能访问正式财务系统。 + +如需改为其他时间,可显式传入多个时间: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass ` + -File scripts\hxb-bank\install-daily-task.ps1 -Times 00:01,09:10 +``` diff --git a/scripts/hxb-bank/export-daily.mjs b/scripts/hxb-bank/export-daily.mjs new file mode 100644 index 000000000..56cf0b172 --- /dev/null +++ b/scripts/hxb-bank/export-daily.mjs @@ -0,0 +1,644 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { + CDP, + evaluate, + goto, + launchEdge, + openPage, + setDownloadDir, + shot, + 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-full'); +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 relayBase = String(process.env.HXB_OTP_RELAY_BASE || '').replace(/\/+$/, ''); +const relaySecret = String(process.env.HXB_OTP_RELAY_SECRET || '').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'); +} +if (!/^https:\/\//.test(relayBase) || relaySecret.length < 32) { + throw new Error('缺少华夏验证码中继地址或密钥'); +} + +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 createOtpRelayRequest() { + const requestPath = '/api/hxb-verification/requests'; + const body = JSON.stringify({ client_run_id: crypto.randomUUID() }); + const timestamp = String(Math.floor(Date.now() / 1000)); + const nonce = crypto.randomBytes(16).toString('hex'); + const canonical = [ + 'POST', + requestPath.replace(/^\/+/, ''), + timestamp, + nonce, + crypto.createHash('sha256').update(body, 'utf8').digest('hex'), + ].join('\n'); + const signature = crypto.createHmac('sha256', relaySecret).update(canonical, 'utf8').digest('hex'); + const response = await fetch(relayBase + requestPath, { + method: 'POST', + headers: { + 'content-type': 'application/json; charset=utf-8', + 'X-HXB-Timestamp': timestamp, + 'X-HXB-Nonce': nonce, + 'X-HXB-Signature': signature, + }, + body, + cache: 'no-store', + signal: AbortSignal.timeout(20000), + }); + const result = await response.json().catch(() => ({})); + if (!response.ok || !result.fill_url || !result.poll_token || !result.run_id) { + throw new Error(`验证码填写链接生成失败:${result.message || response.status}`); + } + + return result; +} + +async function waitForRelayOtp(challenge, timeoutMs = 240000) { + const deadline = Date.now() + timeoutMs; + const pollUrl = relayBase + + '/api/hxb-verification/requests/' + + encodeURIComponent(String(challenge.run_id)) + + '/code'; + while (Date.now() < deadline) { + const response = await fetch(pollUrl, { + method: 'POST', + headers: { + Authorization: `Bearer ${challenge.poll_token}`, + }, + cache: 'no-store', + signal: AbortSignal.timeout(15000), + }); + const result = await response.json().catch(() => ({})); + if (response.status === 200 && /^\d{6}$/.test(String(result.code || ''))) { + return String(result.code); + } + if (response.status === 202) { + await sleep(1000); + continue; + } + if (response.status === 410) { + throw new Error('华夏验证码填写链接已过期,请重新运行任务'); + } + throw new Error(`华夏验证码读取失败:${result.message || response.status}`); + } + + throw new Error('等待华夏验证码填写超时'); +} + +async function postDingTalkPrompt(fillUrl) { + const response = await fetch(webhook, { + method: 'POST', + headers: { 'content-type': 'application/json; charset=utf-8' }, + body: JSON.stringify({ + msgtype: 'actionCard', + actionCard: { + title: '华夏银行验证码填写', + text: '华夏银行短信验证码已发送。请点击下方按钮填写,链接 5 分钟内有效且只能提交一次。', + btnOrientation: '0', + singleTitle: '填写华夏验证码', + singleURL: fillUrl, + }, + }), + signal: AbortSignal.timeout(20000), + }); + const result = await response.json().catch(() => ({})); + if (!response.ok || Number(result.errcode) !== 0) { + throw new Error(`钉钉群提示发送失败:${result.errmsg || response.status}`); + } +} + +async function loginIfNeeded(cdp, sessionId) { + await goto(cdp, sessionId, LOGIN_URL); + await cdp.send('Page.bringToFront', {}, sessionId); + await sleep(300); + 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 otpChallenge = await createOtpRelayRequest(); + await cdp.send('Page.bringToFront', {}, sessionId); + await sleep(300); + if (!await clickText(cdp, sessionId, '发送验证码', { selectors: 'button' })) { + throw new Error('未找到发送验证码按钮'); + } + await waitFor(async () => /秒后重发/.test(await bodyText(cdp, sessionId)), '短信验证码发送', 15000); + await postDingTalkPrompt(otpChallenge.fill_url); + const otp = await waitForRelayOtp(otpChallenge); + + if (!await clickSelector(cdp, sessionId, 'input[name="captcha"]')) { + throw new Error('未找到短信验证码输入框'); + } + await clearFocusedField(cdp, sessionId); + await cdp.send('Input.insertText', { text: otp }, sessionId); + await cdp.send('Page.bringToFront', {}, sessionId); + await sleep(300); + 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); +} + +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; +let sessionId = 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); + ({ 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) { + let screenshot = null; + if (cdp && sessionId) { + try { + screenshot = path.join(runDirectory, 'failure.png'); + await shot(cdp, sessionId, screenshot); + } catch { + screenshot = null; + } + } + const state = { + ok: false, + from: fromDate, + to: toDate, + error: sanitizeError(error), + screenshot, + 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..6f78bf0f1 --- /dev/null +++ b/scripts/hxb-bank/install-daily-task.ps1 @@ -0,0 +1,80 @@ +#Requires -Version 5.1 + +[CmdletBinding(SupportsShouldProcess = $true)] +param( + [string[]]$Times = @('00:01', '09:10'), + + [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 ' ' +$slots = @( + $Times | + ForEach-Object { $_ -split ',' } | + ForEach-Object { $_.Trim() } | + Where-Object { $_ } | + Select-Object -Unique +) +if ($slots.Count -eq 0 -or @($slots | Where-Object { $_ -notmatch '^([01]\d|2[0-3]):[0-5]\d$' }).Count -gt 0) { + throw '定时执行时间格式无效,必须为 HH:mm' +} + +if (-not $PSCmdlet.ShouldProcess($TaskName, "register daily HXB import at $($slots -join ', ')")) { + return +} + +$service = New-Object -ComObject 'Schedule.Service' +$rootFolder = $null +$definition = $null +try { + $service.Connect() + $rootFolder = $service.GetFolder('\') + $definition = $service.NewTask(0) + $definition.RegistrationInfo.Description = '每日 00:01、09:10 读取华夏银行昨天至今天流水并导入财务系统银行账单' + $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' + + foreach ($slot in $slots) { + $trigger = $definition.Triggers.Create(2) + $trigger.StartBoundary = (Get-Date).Date.ToString('yyyy-MM-dd') + 'T' + $slot + ':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,执行时间每天 $($slots -join '、')。" + [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.cmd b/scripts/hxb-bank/read-dingtalk-otp.cmd new file mode 100644 index 000000000..9d2c993af --- /dev/null +++ b/scripts/hxb-bank/read-dingtalk-otp.cmd @@ -0,0 +1,4 @@ +@echo off +setlocal +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0read-dingtalk-otp.ps1" %* +exit /b %errorlevel% diff --git a/scripts/hxb-bank/read-dingtalk-otp.ps1 b/scripts/hxb-bank/read-dingtalk-otp.ps1 new file mode 100644 index 000000000..26af355da --- /dev/null +++ b/scripts/hxb-bank/read-dingtalk-otp.ps1 @@ -0,0 +1,551 @@ +[CmdletBinding()] +param( + [string]$ProcessName = 'DingTalk', + [string]$WindowTitle = '钉钉', + [string]$ImagePath, + [string]$OcrText, + [string]$ReadyFile, + [string]$GroupMarker = '华夏', + [switch]$SkipGroupMarker, + [string[]]$IgnoreCode = @(), + [switch]$IncludeExisting, + [ValidateRange(5, 300)] + [int]$TimeoutSeconds = 120, + [ValidateRange(250, 10000)] + [int]$PollMilliseconds = 1000, + [ValidateRange(0.2, 0.8)] + [double]$CropLeft = 0.4, + [ValidateRange(0.0, 0.3)] + [double]$CropTop = 0.04, + [ValidateRange(0.5, 1.0)] + [double]$CropRight = 0.995, + [ValidateRange(0.5, 1.0)] + [double]$CropBottom = 0.92, + [ValidateSet('Auto', 'PrintWindow', 'Foreground')] + [string]$CaptureMode = 'Auto' +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +Add-Type -AssemblyName System.Drawing +Add-Type -AssemblyName System.Runtime.WindowsRuntime + +[void][Windows.Storage.Streams.InMemoryRandomAccessStream, Windows.Storage, ContentType = WindowsRuntime] +[void][Windows.Storage.Streams.DataWriter, Windows.Storage, ContentType = WindowsRuntime] +[void][Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime] +[void][Windows.Graphics.Imaging.SoftwareBitmap, Windows.Foundation, ContentType = WindowsRuntime] +[void][Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime] +[void][Windows.Media.Ocr.OcrResult, Windows.Foundation, ContentType = WindowsRuntime] +[void][Windows.Globalization.Language, Windows.Foundation, ContentType = WindowsRuntime] + +if (-not ('CaiwuOtpWindowNative' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; + +public static class CaiwuOtpWindowNative +{ + [StructLayout(LayoutKind.Sequential)] + public struct RECT + { + public int Left; + public int Top; + public int Right; + public int Bottom; + } + + [DllImport("user32.dll")] + public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect); + + [DllImport("user32.dll")] + public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, uint flags); + + [DllImport("user32.dll")] + public static extern bool SetForegroundWindow(IntPtr hWnd); + + [DllImport("user32.dll")] + public static extern bool ShowWindow(IntPtr hWnd, int command); + + [DllImport("user32.dll")] + public static extern bool IsIconic(IntPtr hWnd); + + [DllImport("user32.dll")] + public static extern bool SetProcessDPIAware(); +} +'@ +} + +[void][CaiwuOtpWindowNative]::SetProcessDPIAware() + +$asTaskMethod = [System.WindowsRuntimeSystemExtensions].GetMethods() | + Where-Object { + $_.Name -eq 'AsTask' -and + $_.IsGenericMethod -and + $_.GetParameters().Count -eq 1 -and + $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' + } | + Select-Object -First 1 + +if ($null -eq $asTaskMethod) { + throw '当前系统缺少 Windows 异步操作支持,无法使用 Windows OCR。' +} + +function Await-WinRtOperation { + param( + [Parameter(Mandatory = $true)] + $Operation, + + [Parameter(Mandatory = $true)] + [Type]$ResultType + ) + + $task = $asTaskMethod.MakeGenericMethod($ResultType).Invoke($null, @($Operation)) + + return $task.GetAwaiter().GetResult() +} + +function Get-DingTalkWindow { + param( + [Parameter(Mandatory = $true)] + [string]$Name, + + [string]$Title + ) + + $windows = @( + Get-Process -Name $Name -ErrorAction SilentlyContinue | + Where-Object { $_.MainWindowHandle -ne [IntPtr]::Zero } + ) + + if ($windows.Count -gt 1 -and -not [string]::IsNullOrWhiteSpace($Title)) { + $matching = @($windows | Where-Object { $_.MainWindowTitle -like "*$Title*" }) + if ($matching.Count -gt 0) { + $windows = $matching + } + } + + if ($windows.Count -eq 0) { + throw "未找到 $Name 的可见主窗口,请先打开钉钉并进入【华夏验证码】群。" + } + + if ($windows.Count -gt 1) { + throw "找到多个 $Name 主窗口,无法安全确定要读取哪一个。请只保留一个钉钉主窗口。" + } + + return $windows[0] +} + +function Get-WindowBitmap { + param( + [Parameter(Mandatory = $true)] + [IntPtr]$Handle, + + [Parameter(Mandatory = $true)] + [ValidateSet('Auto', 'PrintWindow', 'Foreground')] + [string]$Mode + ) + + if ([CaiwuOtpWindowNative]::IsIconic($Handle)) { + [void][CaiwuOtpWindowNative]::ShowWindow($Handle, 9) + } + + $rect = New-Object CaiwuOtpWindowNative+RECT + if (-not [CaiwuOtpWindowNative]::GetWindowRect($Handle, [ref]$rect)) { + throw '无法读取钉钉窗口坐标。' + } + + $width = $rect.Right - $rect.Left + $height = $rect.Bottom - $rect.Top + if ($width -lt 500 -or $height -lt 400) { + throw "钉钉窗口尺寸异常:${width}x${height}。请恢复最大化或正常尺寸。" + } + + $bitmap = New-Object Drawing.Bitmap $width, $height, ([Drawing.Imaging.PixelFormat]::Format32bppArgb) + $graphics = [Drawing.Graphics]::FromImage($bitmap) + $needsScreenCapture = $Mode -eq 'Foreground' + + try { + if (-not $needsScreenCapture) { + $hdc = $graphics.GetHdc() + try { + $printed = [CaiwuOtpWindowNative]::PrintWindow($Handle, $hdc, 2) + } + finally { + $graphics.ReleaseHdc($hdc) + } + + if (-not $printed) { + if ($Mode -eq 'PrintWindow') { + throw '钉钉窗口后台截图失败。' + } + $needsScreenCapture = $true + } + } + + if ($needsScreenCapture) { + [void][CaiwuOtpWindowNative]::ShowWindow($Handle, 9) + [void][CaiwuOtpWindowNative]::SetForegroundWindow($Handle) + Start-Sleep -Milliseconds 250 + $graphics.CopyFromScreen( + $rect.Left, + $rect.Top, + 0, + 0, + (New-Object Drawing.Size $width, $height), + [Drawing.CopyPixelOperation]::SourceCopy + ) + } + + return $bitmap + } + finally { + $graphics.Dispose() + } +} + +function Convert-BitmapToPngBytes { + param( + [Parameter(Mandatory = $true)] + [Drawing.Bitmap]$Bitmap, + + [Parameter(Mandatory = $true)] + [double]$Scale, + + [Parameter(Mandatory = $true)] + [double]$Left, + + [Parameter(Mandatory = $true)] + [double]$Top, + + [Parameter(Mandatory = $true)] + [double]$Right, + + [Parameter(Mandatory = $true)] + [double]$Bottom + ) + + $left = [Math]::Max(0, [int][Math]::Floor($Bitmap.Width * $Left)) + $top = [Math]::Max(0, [int][Math]::Floor($Bitmap.Height * $Top)) + $right = [Math]::Min($Bitmap.Width, [int][Math]::Ceiling($Bitmap.Width * $Right)) + $bottom = [Math]::Min($Bitmap.Height, [int][Math]::Ceiling($Bitmap.Height * $Bottom)) + + if ($right - $left -lt 100 -or $bottom - $top -lt 30) { + throw '钉钉聊天区域太小,无法可靠识别验证码。请放大钉钉窗口。' + } + + $crop = $Bitmap.Clone( + (New-Object Drawing.Rectangle $left, $top, ($right - $left), ($bottom - $top)), + $Bitmap.PixelFormat + ) + $maxDimension = 5000.0 + $effectiveScale = [Math]::Min($Scale, [Math]::Min($maxDimension / $crop.Width, $maxDimension / $crop.Height)) + $effectiveScale = [Math]::Max(1.0, $effectiveScale) + $scaled = New-Object Drawing.Bitmap ( + [Math]::Max(1, [int][Math]::Round($crop.Width * $effectiveScale)), + [Math]::Max(1, [int][Math]::Round($crop.Height * $effectiveScale)) + ) + + $graphics = [Drawing.Graphics]::FromImage($scaled) + $stream = New-Object IO.MemoryStream + + try { + $graphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic + $graphics.PixelOffsetMode = [Drawing.Drawing2D.PixelOffsetMode]::HighQuality + $graphics.SmoothingMode = [Drawing.Drawing2D.SmoothingMode]::HighQuality + $graphics.DrawImage($crop, 0, 0, $scaled.Width, $scaled.Height) + $scaled.Save($stream, [Drawing.Imaging.ImageFormat]::Png) + + return $stream.ToArray() + } + finally { + $stream.Dispose() + $graphics.Dispose() + $scaled.Dispose() + $crop.Dispose() + } +} + +function Get-OcrLines { + param( + [Parameter(Mandatory = $true)] + [Drawing.Bitmap]$Bitmap, + + [Parameter(Mandatory = $true)] + [double]$Scale, + + [string]$LanguageTag = 'en-US', + + [double]$Left = $CropLeft, + + [double]$Top = $CropTop, + + [double]$Right = $CropRight, + + [double]$Bottom = $CropBottom + ) + + $bytes = Convert-BitmapToPngBytes ` + -Bitmap $Bitmap ` + -Scale $Scale ` + -Left $Left ` + -Top $Top ` + -Right $Right ` + -Bottom $Bottom + $stream = [Windows.Storage.Streams.InMemoryRandomAccessStream]::new() + $writer = [Windows.Storage.Streams.DataWriter]::new($stream) + + try { + $writer.WriteBytes($bytes) + [void](Await-WinRtOperation -Operation $writer.StoreAsync() -ResultType ([uint32])) + $writer.DetachStream() + $stream.Seek(0) + + $decoder = Await-WinRtOperation ` + -Operation ([Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)) ` + -ResultType ([Windows.Graphics.Imaging.BitmapDecoder]) + $softwareBitmap = Await-WinRtOperation ` + -Operation ($decoder.GetSoftwareBitmapAsync()) ` + -ResultType ([Windows.Graphics.Imaging.SoftwareBitmap]) + $language = [Windows.Globalization.Language]::new($LanguageTag) + $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromLanguage($language) + + if ($null -eq $engine) { + throw "Windows 未安装 $LanguageTag OCR 语言包。" + } + + $result = Await-WinRtOperation ` + -Operation ($engine.RecognizeAsync($softwareBitmap)) ` + -ResultType ([Windows.Media.Ocr.OcrResult]) + + return @($result.Lines | ForEach-Object { $_.Text }) + } + finally { + if ($stream) { + $stream.Dispose() + } + } +} + +function Test-GroupMarker { + param( + [Parameter(Mandatory = $true)] + [Drawing.Bitmap]$Bitmap + ) + + if ($SkipGroupMarker -or [string]::IsNullOrWhiteSpace($GroupMarker)) { + return $true + } + + $lines = @(Get-OcrLines ` + -Bitmap $Bitmap ` + -Scale 5.0 ` + -LanguageTag 'zh-Hans-CN' ` + -Left $CropLeft ` + -Top 0.0 ` + -Right $CropRight ` + -Bottom 0.16) + $headerText = ($lines -join '').Replace(' ', '') + + return $headerText.Contains($GroupMarker) +} + +function Find-OtpCandidates { + param( + [Parameter(Mandatory = $true)] + [string[]]$Lines + ) + + $candidates = New-Object 'System.Collections.Generic.List[object]' + $seen = New-Object 'System.Collections.Generic.HashSet[string]' + $position = 0 + + foreach ($line in $Lines) { + foreach ($match in [regex]::Matches([string]$line, '(?&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') + [Environment]::SetEnvironmentVariable('HXB_OTP_RELAY_BASE', $previousRelayBase, 'Process') + [Environment]::SetEnvironmentVariable('HXB_OTP_RELAY_SECRET', $previousRelaySecret, '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') +} diff --git a/tests/scripts/hxb-dingtalk-otp-reader.test.ps1 b/tests/scripts/hxb-dingtalk-otp-reader.test.ps1 new file mode 100644 index 000000000..d7b5022cd --- /dev/null +++ b/tests/scripts/hxb-dingtalk-otp-reader.test.ps1 @@ -0,0 +1,42 @@ +$ErrorActionPreference = 'Stop' +$scriptPath = Join-Path $PSScriptRoot '../../scripts/hxb-bank/read-dingtalk-otp.ps1' + +function Invoke-Reader { + param([string[]]$Arguments) + + $output = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $scriptPath @Arguments 2>&1 + if ($LASTEXITCODE -ne 0) { + throw ($output -join "`n") + } + + return ($output | Select-Object -Last 1 | ConvertFrom-Json) +} + +$latest = Invoke-Reader @( + '-OcrText', "16:23`n123456`n16:25`n654321", + '-SkipGroupMarker' +) +if ($latest.code -ne '654321') { + throw "应读取最新验证码 654321,实际为 $($latest.code)" +} + +$ignored = Invoke-Reader @( + '-OcrText', "16:23`n123456`n16:25`n654321", + '-IgnoreCode', '654321', + '-SkipGroupMarker' +) +if ($ignored.code -ne '123456') { + throw "排除最新验证码后应返回 123456,实际为 $($ignored.code)" +} + +$previousErrorAction = $ErrorActionPreference +$ErrorActionPreference = 'Continue' +$null = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $scriptPath ` + -OcrText '没有六位验证码' -SkipGroupMarker 2>$null +$failedExitCode = $LASTEXITCODE +$ErrorActionPreference = $previousErrorAction +if ($failedExitCode -eq 0) { + throw '无验证码时脚本不应返回成功' +} + +Write-Host 'HXB DingTalk OTP reader tests passed.'