CaiWuXiTong/scripts/wangshang-mail/run-wangshang-mail-daily.ps1
shanshi 65d37c8093 feat: 接入网商银行邮件账单自动导入 (#1199)
独立邮箱机器人读取网商银行加密账单,解密并导入财务台账。
2026-11-16 16:41:07 +08:00

181 lines
6.6 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

[CmdletBinding()]
param(
[ValidatePattern('^\d{4}-\d{2}-\d{2}$')]
[string] $Date,
[string] $Company,
[string] $Server = '218.93.190.75',
[ValidatePattern('^[A-Za-z0-9._-]+$')]
[string] $SshUser = 'root',
[switch] $DryRun,
[switch] $SkipImport
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$utf8 = [Text.UTF8Encoding]::new($false)
[Console]::InputEncoding = $utf8
[Console]::OutputEncoding = $utf8
$OutputEncoding = $utf8
$root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$configFile = if ([string]::IsNullOrWhiteSpace($env:WANGSHANG_MAIL_CONFIG_FILE)) {
Join-Path $root 'runtime\private\wangshang-mail-accounts.json'
} else {
$env:WANGSHANG_MAIL_CONFIG_FILE
}
$fetchScript = Join-Path $PSScriptRoot 'fetch_daily.py'
$logDir = Join-Path $root 'runtime\private\wangshang-mail\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-Python {
$configured = $env:WANGSHANG_MAIL_PYTHON
$candidates = @(
$configured,
(Join-Path $env:USERPROFILE '.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe')
)
foreach ($candidate in $candidates) {
if (-not [string]::IsNullOrWhiteSpace($candidate) -and
(Test-Path -LiteralPath $candidate -PathType Leaf)) {
return $candidate
}
}
$command = Get-Command python.exe -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -ne $command -and -not [string]::IsNullOrWhiteSpace($command.Source)) {
& $command.Source -c 'import openpyxl' 2>$null
if ($LASTEXITCODE -eq 0) {
return $command.Source
}
}
throw '未找到可用的 Python 和 openpyxl,请设置 WANGSHANG_MAIL_PYTHON'
}
if (-not (Test-Path -LiteralPath $configFile -PathType Leaf)) {
throw '缺少 runtime/private/wangshang-mail-accounts.json,请先运行 import-accounts.ps1'
}
if ([string]::IsNullOrWhiteSpace($Date)) {
$Date = (Get-Date).Date.AddDays(-1).ToString('yyyy-MM-dd')
}
$python = Resolve-Python
$runStamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$runDirectory = Join-Path $root ('runtime\private\wangshang-mail\exports\' + $Date + '\run-' + $runStamp)
New-Item -ItemType Directory -Force -Path $runDirectory | Out-Null
$fetchArgs = @(
$fetchScript,
'fetch',
('--config=' + $configFile),
('--date=' + $Date),
('--out=' + (Split-Path -Parent $runDirectory)),
('--run-dir=' + $runDirectory)
)
if (-not [string]::IsNullOrWhiteSpace($Company)) {
$fetchArgs += ('--company=' + $Company)
}
Write-Log ('开始获取网商银行邮件账单 ' + $Date)
$fetchOutput = (& $python -X utf8 @fetchArgs 2>&1 | Out-String)
$fetchExit = $LASTEXITCODE
if (-not [string]::IsNullOrWhiteSpace($fetchOutput)) {
Write-Log ('获取输出:' + ($fetchOutput.Trim() -replace "`r?`n", ' | '))
}
$stateFile = Join-Path $runDirectory 'last-fetch.json'
if (-not (Test-Path -LiteralPath $stateFile -PathType Leaf)) {
throw '网商银行邮件任务没有生成状态文件;未写入财务台账'
}
$state = [IO.File]::ReadAllText($stateFile, [Text.Encoding]::UTF8) | ConvertFrom-Json
if ([string]$state.date -ne $Date) {
throw '网商银行邮件任务状态日期与本次任务不一致'
}
if ([int]$state.accounts -le 0 -or [string]::IsNullOrWhiteSpace([string]$state.bundle)) {
throw '本次没有成功生成网商银行导入批次'
}
$bundleFile = [string]$state.bundle
if (-not (Test-Path -LiteralPath $bundleFile -PathType Leaf)) {
throw '网商银行邮件任务没有生成导入 ZIP'
}
$hadFailures = $fetchExit -ne 0 -or [int]$state.failed -gt 0
Write-Log ('获取完成:成功账户 {0},失败账户 {1}' -f $state.accounts, $state.failed)
foreach ($failure in @($state.failures)) {
if ($null -ne $failure) {
Write-Log ('账户失败:{0},尾号 {1},原因 {2}' -f
$failure.company, $failure.account_last4, $failure.error)
}
}
if ($SkipImport) {
Write-Log '已指定 -SkipImport,未写入财务台账'
if ($hadFailures) { exit 1 }
return
}
. (Join-Path $root 'scripts\deploy-auth.ps1')
$remoteFile = '/opt/caiwuxitong/runtime/private/wangshang-mail-imports/' + $Date +
'/wangshang-mail-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.zip'
$auth = Start-CaiwuDeploymentAuth -Server $Server -SshUser $SshUser
try {
$target = "${SshUser}@${Server}"
$remoteDirectory = [IO.Path]::GetDirectoryName($remoteFile).Replace('\', '/')
$dryRunFlag = if ($DryRun) { ' --dry-run' } else { '' }
$command = @(
'set -eu',
('sh /opt/caiwuxitong/run-finance-batch.sh finance-ledger:import-wangshang-bank ' +
"'$remoteFile' --date='$Date'" + $dryRunFlag),
("rm -f '" + $remoteFile + "'")
) -join '; '
$attempts = 3
$importCompleted = $false
for ($attempt = 1; $attempt -le $attempts; $attempt++) {
try {
& ssh @($auth.Options) $target ("install -d -m 700 '" + $remoteDirectory + "'")
if ($LASTEXITCODE -ne 0) { throw '创建远程目录失败' }
& scp @($auth.Options) $bundleFile ("${target}:" + $remoteFile)
if ($LASTEXITCODE -ne 0) { throw '上传批次失败' }
$importOutput = (& ssh @($auth.Options) $target $command 2>&1 | Out-String)
$importExit = $LASTEXITCODE
if (-not [string]::IsNullOrWhiteSpace($importOutput)) {
Write-Log ('导入输出:' + ($importOutput.Trim() -replace "`r?`n", ' | '))
}
if ($importExit -ne 0) { throw '受限批处理命令返回失败' }
$importCompleted = $true
break
} catch {
if ($attempt -lt $attempts) {
Write-Log ("远程导入第 {0}/{1} 次失败:{2};10 秒后重试(导入按账号和日期幂等)" -f
$attempt, $attempts, $_.Exception.Message)
Start-Sleep -Seconds 10
}
}
}
if (-not $importCompleted) {
throw '网商银行邮件账单导入失败;已重试 3 次,原有动账明细未改变'
}
} finally {
Stop-CaiwuDeploymentAuth $auth
}
Write-Log ($(if ($DryRun) { '网商银行邮件账单校验完成' } else { '网商银行邮件账单已接入财务台账动账明细' }))
if ($hadFailures) {
Write-Log '本次有账户获取失败;成功账户已导入,失败账户保持原数据'
exit 1
}