CaiWuXiTong/scripts/erp-daily-bills/run-erp-daily.ps1

523 lines
29 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.

<#
聚胜算每日账单 → 财务系统(统一入口)
平台:toutiao = 头条放心购→资金流水(落 抖音账户)
jd = 京东商城→京东日账单(一次导入按店铺名拆 京东账单 + 京喜账单)
jd-wallet = 京东商城→京东钱包(落 京东网银钱包账户)
xiaohongshu = 小红书→订单结算明细(落 小红书账户)
dewu-alipay = 淘系支付宝账单,按得物店铺映射的 8 个支付宝账号拉取
流程:覆盖核查 → 补齐历史缺口 → 导出 → 汇总核验 / 与已导入期间比对(无差异则跳过)
→ 上传 → 受限批处理容器导入 → 页面回验 → 归档 → 写日志
用法:
pwsh -File run-erp-daily.ps1 # 三个平台,区间「月初 → 昨日」
pwsh -File run-erp-daily.ps1 -Platform jd -Through 2026-07-31
pwsh -File run-erp-daily.ps1 -Platform jd-wallet -Through 2026-07-31
pwsh -File run-erp-daily.ps1 -Platform toutiao -SkipImport
pwsh -File run-erp-daily.ps1 -Platform xiaohongshu -Through 2026-11-30
pwsh -File run-erp-daily.ps1 -Platform dewu-alipay -Through 2026-11-30
#>
[CmdletBinding()]
param(
[ValidateSet('toutiao', 'jd', 'jd-wallet', 'xiaohongshu', 'dewu-alipay', 'both')][string]$Platform = 'both',
[string]$Through,
[string]$Start,
[string]$CoverageFrom = '2026-07-01',
[switch]$SkipImport,
[switch]$ForceImport,
[switch]$SkipCoverageCheck
)
$ErrorActionPreference = 'Stop'
$root = $PSScriptRoot
$self = (Get-Process -Id $PID).Path
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch {}
. (Join-Path $root '..\deploy-auth.ps1')
$node = 'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
$python = 'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe'
$exportDir = Join-Path $root '..\..\runtime\private\erp-exports'
$logDir = Join-Path $exportDir 'logs'
$stateFile = Join-Path $exportDir 'imported-state.json'
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 'HH:mm:ss'), $Message
Write-Host $line
Add-Content -LiteralPath $logFile -Value $line -Encoding UTF8
}
# 平台 → 导入命令 / 页面回验页签
$specs = @{
toutiao = @{ label = '头条放心购'; artifact = 'douyin'; importCmd = 'business-mirror:import-douyin-authoritative'; verifyTabs = @('douyin'); split = $false }
jd = @{ label = '京东日账单'; artifact = 'jd'; importCmd = 'business-mirror:import-jd-daily'; verifyTabs = @('jd-transactions', 'jingxi'); split = $true }
'jd-wallet' = @{ label = '京东钱包'; artifact = 'jd-wallet'; importCmd = 'business-mirror:import-jd-wallet'; verifyTabs = @('jd-wallet'); split = $false }
xiaohongshu = @{ label = '小红书'; artifact = 'xiaohongshu'; importCmd = 'xiaohongshu-bills:import'; verifyTabs = @('xiaohongshu'); split = $false; uploadExtension = '.xlsx' }
'dewu-alipay' = @{ label = '得物支付宝'; artifact = 'dewu-alipay'; importCmd = 'taobao-alipay-bills:import-authoritative'; verifyTabs = @('dewu-alipay'); split = $false; uploadExtension = '.xlsx'; port = 9360; profile = 'erp-profile-dewu-alipay' }
}
$coverageKeys = @{
toutiao = 'douyin'
jd = 'jd-daily'
'jd-wallet' = 'jd-wallet'
}
$targets = if ($Platform -eq 'both') { @('toutiao', 'jd', 'jd-wallet', 'xiaohongshu', 'dewu-alipay') } else { @($Platform) }
$state = if (Test-Path -LiteralPath $stateFile) { (Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json) } else { New-Object psobject }
$dewuAlipayAccounts = @()
if ($targets -contains 'dewu-alipay') {
$dewuAlipayAccounts = @(Get-Content -LiteralPath (Join-Path $root 'dewu-alipay-accounts.json') -Raw | ConvertFrom-Json)
if ($dewuAlipayAccounts.Count -eq 0) {
throw '得物支付宝账号映射为空。'
}
}
$auth = Start-CaiwuDeploymentAuth -Server '218.93.190.75' -SshUser 'root'
$sshOptions = $auth.Options + @('-o', 'PreferredAuthentications=password', '-o', 'PubkeyAuthentication=no', '-o', 'NumberOfPasswordPrompts=1', '-o', 'ConnectTimeout=15')
. (Join-Path $root 'erp-remote.ps1')
$remoteSshScript = Join-Path $root '..\..\runtime\private\server-ssh.ps1'
$remoteUploaderScript = Join-Path $root '..\..\runtime\private\upload-to-server.ps1'
$remoteBatchRunner = '/opt/caiwuxitong/run-finance-batch.sh'
# 远程执行包装:失败自动重试(含重新上传 CSV),并返回 { Ok; Output; Attempts }
function Invoke-Remote {
param(
[Parameter(Mandatory = $true)][string]$Body,
[string]$LocalFile = '',
[string]$RemoteFile = ''
)
return Invoke-ErpRemote `
-PwshPath $self `
-SshScript $remoteSshScript `
-UploaderScript $remoteUploaderScript `
-Body $Body `
-LocalFile $LocalFile `
-RemoteFile $RemoteFile `
-Log { param($message) Write-Log $message }
}
function Get-ErpDailyCoverage {
param([Parameter(Mandatory = $true)][string]$CoverageFrom, [Parameter(Mandatory = $true)][string]$Through)
# 覆盖检查在有缺口时按设计返回 exit 1;报告本身仍是完整 JSON,不能把它当成远程执行失败重试。
$body = @"
set +e
output=`$(docker exec -u www-data caiwu_app php /var/www/html/artisan business-mirror:verify-erp-daily-coverage --from=$CoverageFrom --to=$Through --json 2>&1)
status=`$?
printf '%s\n' "`$output"
if [ "`$status" -eq 1 ]; then
exit 0
fi
exit "`$status"
"@
$result = Invoke-Remote -Body $body
if (-not $result.Ok) {
throw ('覆盖核查失败:' + ($result.Output.Trim() -replace "`r?`n", ' | '))
}
$jsonLine = (($result.Output -split "`r?`n") | Where-Object { $_.TrimStart().StartsWith('[') } | Select-Object -Last 1)
if (-not $jsonLine) {
throw ('覆盖核查没有返回 JSON:' + ($result.Output.Trim() -replace "`r?`n", ' | '))
}
return @($jsonLine | ConvertFrom-Json)
}
$failed = $false
try {
$pullThroughDate = if ($Through) {
$parsed = [datetime]::MinValue
if (-not [datetime]::TryParseExact($Through, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::None, [ref]$parsed)) {
throw '截止日期格式无效,应为 YYYY-MM-DD。'
}
$parsed
} else {
(Get-Date).Date.AddDays(-1)
}
$pullThrough = $pullThroughDate.ToString('yyyy-MM-dd')
$pullMonth = $pullThrough.Substring(0, 7)
$coverageFromDate = [datetime]::MinValue
if (-not [datetime]::TryParseExact($CoverageFrom, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::None, [ref]$coverageFromDate)) {
throw '覆盖核查起始日期格式无效,应为 YYYY-MM-DD。'
}
if ($coverageFromDate.Date -gt $pullThroughDate.Date) {
throw '覆盖核查起始日期不能晚于本次账单截止日期。'
}
$coverageReady = [bool]$SkipCoverageCheck
$coverageReport = @()
if (-not $SkipCoverageCheck) {
Write-Log ('=== 每日覆盖核查:{0} ~ {1} ===' -f $CoverageFrom, $pullThrough)
try {
$coverageReport = @(Get-ErpDailyCoverage -CoverageFrom $CoverageFrom -Through $pullThrough)
$coverageIssues = @($coverageReport | Where-Object { $_.status -ne 'ok' })
Write-Log ('覆盖核查完成:{0} 项,异常 {1} 项' -f $coverageReport.Count, $coverageIssues.Count)
foreach ($issue in $coverageIssues) {
Write-Log (' 待补:{0} {1},{2} ~ {3},状态 {4}({5})' -f $issue.label, $issue.month, $issue.required_start, $issue.required_through, $issue.status, $issue.issue)
}
$coverageReady = $true
} catch {
Write-Log ('覆盖核查失败,本次不拉取新账单:' + $_.Exception.Message)
$failed = $true
}
}
if (-not $coverageReady) {
$targets = @()
}
foreach ($target in $targets) {
$spec = $specs[$target]
Write-Log ('=== ' + $spec.label + ':开始 ===')
$coverageKey = $coverageKeys[$target]
$currentIssue = @($coverageReport | Where-Object { $_.dataset -eq $coverageKey -and $_.month -eq $pullMonth -and $_.status -ne 'ok' })
$forceThisImport = [bool]$ForceImport -or $currentIssue.Count -gt 0
# 先补此前月份的缺口;历史仍不完整时,不继续拉取本月新数据。
$historicalIssues = if ($coverageKey) {
@(Get-ErpCoverageBackfillJobs -CoverageReport $coverageReport -Dataset $coverageKey -CurrentMonth $pullMonth)
} else {
@()
}
if ($historicalIssues.Count -gt 0 -and -not $SkipImport) {
$catchUpFailed = $false
foreach ($issue in $historicalIssues) {
Write-Log ('发现历史缺口,先补数:{0} {1},{2} ~ {3}({4})' -f $issue.label, $issue.month, $issue.required_start, $issue.required_through, $issue.status)
& $self -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath `
-Platform $target `
-Start $issue.required_start `
-Through $issue.required_through `
-CoverageFrom $CoverageFrom `
-ForceImport `
-SkipCoverageCheck
if ($LASTEXITCODE -ne 0) {
Write-Log ('历史补数失败:{0} {1},已停止该平台的新数据拉取' -f $issue.label, $issue.month)
$catchUpFailed = $true
break
}
}
if (-not $catchUpFailed) {
try {
$coverageReport = @(Get-ErpDailyCoverage -CoverageFrom $CoverageFrom -Through $pullThrough)
$remaining = @(Get-ErpCoverageBackfillJobs -CoverageReport $coverageReport -Dataset $coverageKey -CurrentMonth $pullMonth)
if ($remaining.Count -gt 0) {
foreach ($issue in $remaining) {
Write-Log ('历史补数后仍未完整:{0} {1},状态 {2}' -f $issue.label, $issue.month, $issue.status)
}
$catchUpFailed = $true
}
} catch {
Write-Log ('历史补数后复核失败:' + $_.Exception.Message)
$catchUpFailed = $true
}
}
if ($catchUpFailed) {
$failed = $true
continue
}
}
# 1) 导出(胜算页面偶发日历面板/授权弹窗/胜算标签页注册慢,失败后自动重试)
$exportArgs = @((Join-Path $root 'export-daily.mjs'), ('--platform=' + $target), ('--out=' + $exportDir))
if ($target -eq 'dewu-alipay') {
$exportArgs += ('--account-nos=' + (($dewuAlipayAccounts | ForEach-Object { [string]$_.merchant_no }) -join ','))
}
if ($spec.port) {
$exportArgs += ('--port=' + $spec.port)
$exportArgs += ('--profile=' + (Join-Path $exportDir '..\' $spec.profile))
}
if ($Start) { $exportArgs += ('--start=' + $Start) }
if ($Through) { $exportArgs += ('--through=' + $Through) }
# 2 次不够:2026-10-12 两次尝试全败、只能人工补跑;2026-10-13 头条/京东各失败 1 次后靠第 2 次成功。
# 单次约 1 分钟,给到 3 次仍远小于 09:30 任务窗口。
$exportAttempts = 3
$exportOk = $false
for ($exportTry = 1; $exportTry -le $exportAttempts -and -not $exportOk; $exportTry++) {
$exportOut = (& $node @exportArgs 2>&1 | Out-String)
Write-Log ('导出:' + ($exportOut.Trim() -replace "`r?`n", ' | '))
if ($LASTEXITCODE -eq 0) {
$exportOk = $true
break
}
Write-Log ($spec.label + ' 导出失败(exit=' + $LASTEXITCODE + ',第 ' + $exportTry + '/' + $exportAttempts + ' 次)')
if ($exportTry -lt $exportAttempts) { Start-Sleep -Seconds 20 }
}
if (-not $exportOk) { $failed = $true; continue }
$summary = Get-Content -LiteralPath (Join-Path $exportDir 'last-export.json') -Raw | ConvertFrom-Json
if ($summary.empty) {
Write-Log ($spec.label + ':该区间胜算暂无数据,跳过(未改动生产)')
continue
}
# 胜算超过同步导出上限时会拆成多个分片(summary.files),逐片转 CSV 后合并成一份再导入。
# 小红书导入命令只接受原始 XLSX,因此独立汇总,不上传转换后的 CSV。
$rawFiles = @()
if (($summary.PSObject.Properties.Name -contains 'files') -and $summary.files) { $rawFiles = @($summary.files) }
if ($rawFiles.Count -eq 0 -and $summary.file) { $rawFiles = @($summary.file) }
if ($rawFiles.Count -eq 0) { Write-Log ($spec.label + ' 导出结果里没有文件名'); $failed = $true; continue }
$rawFile = $rawFiles[0]
$isXiaohongshu = $target -eq 'xiaohongshu'
$isDewuAlipay = $target -eq 'dewu-alipay'
$csvFile = $null
$importFile = $rawFile
if ($isXiaohongshu) {
if ($rawFiles.Count -ne 1) {
Write-Log ('小红书账单出现 {0} 个分片,当前导入命令只接受单个 XLSX,未改动生产' -f $rawFiles.Count)
$failed = $true
continue
}
$summaryOutput = (& $python -X utf8 (Join-Path $root 'xiaohongshu-summary.py') $rawFile ('--from=' + [string]$summary.monthStart) ('--to=' + [string]$summary.through) 2>&1 | Out-String)
$summaryJson = (($summaryOutput -split "`n") | Where-Object { $_.TrimStart().StartsWith('{') } | Select-Object -Last 1)
if (-not $summaryJson) {
Write-Log ($spec.label + ' 汇总失败:' + ($summaryOutput.Trim() -replace "`r?`n", ' | '))
$failed = $true
continue
}
$parsedSummary = $summaryJson | ConvertFrom-Json
$rows = [int]$parsedSummary.rows
$invariant = [Globalization.CultureInfo]::InvariantCulture
$income = [double]::Parse([string]$parsedSummary.income, $invariant)
$expense = [double]::Parse([string]$parsedSummary.expense, $invariant)
Write-Log ('核对数:{0} ~ {1},笔数 {2},收入 {3},支出 {4},结算时间 {5} ~ {6}' -f $summary.monthStart, $summary.through, $rows, $income, $expense, $parsedSummary.occurred_min, $parsedSummary.occurred_max)
} elseif ($isDewuAlipay) {
$csvFile = if ($rawFiles.Count -gt 1) {
[IO.Path]::ChangeExtension(($rawFile -replace '_part\d+(?=\.[^.]+$)', ''), '.csv')
} else {
[IO.Path]::ChangeExtension($rawFile, '.csv')
}
if ($rawFiles.Count -gt 1) {
Write-Log ('得物支付宝导出分片 {0} 个,转为合并 CSV 并合并 XLSX' -f $rawFiles.Count)
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') '--merge' $csvFile @rawFiles 2>&1 | Out-String)
$mergedFile = [IO.Path]::ChangeExtension($csvFile, '.merged.xlsx')
$merge = (& $python -X utf8 (Join-Path $root 'merge-xlsx.py') $mergedFile @rawFiles 2>&1 | Out-String)
if ($LASTEXITCODE -ne 0) {
Write-Log ('得物支付宝 XLSX 合并失败:' + ($merge.Trim() -replace "`r?`n", ' | '))
$failed = $true
continue
}
$importFile = $mergedFile
} else {
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') $rawFile $csvFile 2>&1 | Out-String)
}
$line = (($conv -split "`n") | Where-Object { $_ -match '^csv=' } | Select-Object -First 1)
if (-not $line) {
Write-Log ('得物支付宝转 CSV 失败:' + ($conv.Trim() -replace "`r?`n", ' | '))
$failed = $true
continue
}
$rows = [int]([regex]::Match($line, 'rows=(\d+)').Groups[1].Value)
$income = [double]([regex]::Match($line, 'income=([\-\d\.]+)').Groups[1].Value)
$expense = [double]([regex]::Match($line, 'expense=([\-\d\.]+)').Groups[1].Value)
$limited = (& $python -X utf8 (Join-Path $root 'dewu-alipay-summary.py') $csvFile ('--accounts-json=' + (Join-Path $root 'dewu-alipay-accounts.json')) 2>&1 | Out-String)
$limitedJson = (($limited -split "`n") | Where-Object { $_.TrimStart().StartsWith('{') } | Select-Object -Last 1)
if (-not $limitedJson) {
Write-Log ('得物支付宝范围校验失败:' + ($limited.Trim() -replace "`r?`n", ' | '))
$failed = $true
continue
}
$limitedSummary = $limitedJson | ConvertFrom-Json
if (([int]$limitedSummary.rows -ne $rows) -or
([math]::Abs([double]$limitedSummary.income - $income) -ge 0.005) -or
([math]::Abs([double]$limitedSummary.expense - $expense) -ge 0.005)) {
Write-Log '得物支付宝汇总与范围校验不一致,未改动生产'
$failed = $true
continue
}
} else {
# 多分片时 CSV 用合并后的名字(不带 _partN),避免看起来只落了第一片
$csvFile = if ($rawFiles.Count -gt 1) {
[IO.Path]::ChangeExtension(($rawFile -replace '_part\d+(?=\.[^.]+$)', ''), '.csv')
} else {
[IO.Path]::ChangeExtension($rawFile, '.csv')
}
if ($rawFiles.Count -gt 1) {
Write-Log ('导出分片 {0} 个:{1}' -f $rawFiles.Count, (($rawFiles | ForEach-Object { [IO.Path]::GetFileName($_) }) -join ', '))
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') '--merge' $csvFile @rawFiles 2>&1 | Out-String)
} else {
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') $rawFile $csvFile 2>&1 | Out-String)
}
$line = (($conv -split "`n") | Where-Object { $_ -match '^csv=' } | Select-Object -First 1)
if (-not $line) { Write-Log ($spec.label + ' 转 CSV 失败:' + ($conv.Trim() -replace "`r?`n", ' | ')); $failed = $true; continue }
$rows = [int]([regex]::Match($line, 'rows=(\d+)').Groups[1].Value)
$income = [double]([regex]::Match($line, 'income=([\-\d\.]+)').Groups[1].Value)
$expense = [double]([regex]::Match($line, 'expense=([\-\d\.]+)').Groups[1].Value)
$importFile = $csvFile
}
$month = $summary.monthStart.Substring(0, 7)
if (-not $isXiaohongshu) {
Write-Log ('核对数:{0} ~ {1},笔数 {2},收入 {3},支出 {4}' -f $summary.monthStart, $summary.through, $rows, $income, $expense)
($conv -split "`n") | Where-Object { $_ -match '^part=' } | ForEach-Object { Write-Log (' ' + $_.Trim()) }
}
# 页面笔数 vs 导出行数:不一致说明分片没下全,跳过导入,避免只导入一部分
$pageCount = if ($summary.pageCount) { [int]$summary.pageCount } else { 0 }
if ($pageCount -gt 0 -and $pageCount -ne $rows -and -not $ForceImport) {
Write-Log ('跳过导入:页面笔数 {0} 与导出行数 {1} 不一致(分片可能未下全),未改动生产' -f $pageCount, $rows)
$failed = $true
continue
}
# 2) 无差异跳过
$key = $target + ':' + $month
$prev = $state.$key
# 小红书和得物支付宝的明细量较小,且聚水潭会事后调整字段;每天重新导入以保留最新版本。
$same = -not $isXiaohongshu -and -not $isDewuAlipay -and $prev -and ([string]$prev.through -eq [string]$summary.through) -and ([int]$prev.rows -eq $rows) -and ([math]::Abs([double]$prev.income - $income) -lt 0.005) -and ([math]::Abs([double]$prev.expense - $expense) -lt 0.005)
$currentCoverage = @($coverageReport | Where-Object { $_.dataset -eq $coverageKey -and $_.month -eq $month } | Select-Object -First 1)
$serverMatchesExport = $currentCoverage.Count -eq 1 -and
$currentCoverage[0].status -eq 'ok' -and
[int]$currentCoverage[0].row_count -eq $rows -and
[math]::Abs([double]$currentCoverage[0].income - $income) -lt 0.005 -and
[math]::Abs([double]$currentCoverage[0].expense - $expense) -lt 0.005
if (($same -or $serverMatchesExport) -and -not $forceThisImport) {
if (-not $same -and $serverMatchesExport) {
# 服务端覆盖已正确、只是本机状态滞后时,回填状态,避免每天重复导入同一批账单。
$state | Add-Member -NotePropertyName $key -NotePropertyValue ([pscustomobject]@{ rows = $rows; income = $income; expense = $expense; through = $summary.through; file = $csvFile; at = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') }) -Force
$state | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $stateFile -Encoding UTF8
Write-Log ('服务端覆盖已核对且与导出无差异,已回填本机状态({0} 笔 / {1} / {2}),跳过导入' -f $rows, $income, $expense)
} else {
Write-Log ('该月已导入且无差异({0} 笔 / {1} / {2}),跳过导入' -f $rows, $income, $expense)
}
continue
}
if ($SkipImport) { Write-Log '已指定 -SkipImport,跳过导入'; continue }
# 3) 上传 + 导入 + 页面回验。统一交给 Invoke-Remote,上传断开时会重新上传并重试,
# 整段失败则本平台失败,不写状态、不归档。
$uploadExtension = if ($spec.uploadExtension) { [string]$spec.uploadExtension } else { '.csv' }
$remoteFile = '/tmp/' + $target + '_daily_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + $uploadExtension
$verifyPhp = @"
cat > /tmp/verify_daily.php <<'PHP'
<?php
require '/var/www/html/vendor/autoload.php';
`$app = require '/var/www/html/bootstrap/app.php';
`$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
`$tabs = ['__TABS__'];
`$total = 0;
`$incomeCents = 0;
`$expenseCents = 0;
if (`$tabs === ['xiaohongshu']) {
`$query = Illuminate\Support\Facades\DB::table('ec_account_bills')
->where('company_id', 1)
->where('bill_type', 'xiaohongshu')
->where('occurred_at', '>=', '__START__ 00:00:00')
->where('occurred_at', '<', date('Y-m-d', strtotime('__THROUGH__ +1 day')) . ' 00:00:00');
`$summary = (clone `$query)->selectRaw(
'COUNT(*) AS count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense'
)->first();
`$total = (int) `$summary->count;
`$incomeCents = (int) round((float) `$summary->income * 100);
`$expenseCents = (int) round((float) `$summary->expense * 100);
echo 'PAGE xiaohongshu total=' . `$total . ' ' . json_encode(`$summary, JSON_UNESCAPED_UNICODE) . PHP_EOL;
} elseif (`$tabs === ['dewu-alipay']) {
`$result = app(Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository::class)
->paginate(['start' => '__START__', 'end' => '__THROUGH__'], 'occurred_at', 'desc', 1, 1);
`$total = (int) `$result['total'];
`$incomeCents = (int) round((float) `$result['summary']['income'] * 100);
`$expenseCents = (int) round((float) `$result['summary']['expense'] * 100);
echo 'PAGE dewu-alipay total=' . `$total . ' ' . json_encode(`$result['summary'], JSON_UNESCAPED_UNICODE) . PHP_EOL;
} else {
`$repo = app(Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository::class);
foreach (`$tabs as `$tab) {
`$r = match (`$tab) {
'douyin' => `$repo->paginate(['start' => '__START__', 'end' => '__THROUGH__'], 'occurred_at', 'desc', 1, 1),
'jd-wallet' => app(Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository::class)->paginate(['start' => '__START__', 'end' => '__THROUGH__'], 'occurred_at', 'desc', 1, 1),
default => app(Modules\EcommerceFinance\Repositories\JdDailyBillRepository::class)
->forPlatform(`$tab === 'jingxi' ? 'jingxi' : 'jd')
->paginate(['start' => '__START__', 'end' => '__THROUGH__'], 'occurred_at', 'desc', 1, 1),
};
`$total += (int) `$r['total'];
`$incomeCents += (int) round((float) `$r['summary']['income'] * 100);
`$expenseCents += (int) round((float) `$r['summary']['expense'] * 100);
echo 'PAGE ' . `$tab . ' total=' . `$r['total'] . ' ' . json_encode(`$r['summary'], JSON_UNESCAPED_UNICODE) . PHP_EOL;
}
}
if (`$total !== __COUNT__
|| `$incomeCents !== (int) round(__INCOME__ * 100)
|| `$expenseCents !== (int) round(__EXPENSE__ * 100)) {
fwrite(STDERR, sprintf(
'页面回验不一致:导入 %d 笔 / %s / %s,页面 %d 笔 / %.2f / %.2f%s',
__COUNT__, __INCOME__, __EXPENSE__, `$total, `$incomeCents / 100, `$expenseCents / 100, PHP_EOL
));
exit(1);
}
PHP
docker exec -i -u www-data caiwu_app php < /tmp/verify_daily.php
rm -f /tmp/verify_daily.php
"@
$invariant = [Globalization.CultureInfo]::InvariantCulture
$verifyPhp = $verifyPhp.Replace('__TABS__', ($spec.verifyTabs -join "','"))
$verifyPhp = $verifyPhp.Replace('__START__', $summary.monthStart)
$verifyPhp = $verifyPhp.Replace('__THROUGH__', $summary.through)
$verifyPhp = $verifyPhp.Replace('__COUNT__', [string]$rows)
$verifyPhp = $verifyPhp.Replace('__INCOME__', $income.ToString('0.00', $invariant))
$verifyPhp = $verifyPhp.Replace('__EXPENSE__', $expense.ToString('0.00', $invariant))
$importCommand = if ($isXiaohongshu) {
"sh $remoteBatchRunner $($spec.importCmd) `"$remoteFile`" --company-id=1 --from=$($summary.monthStart) --to=$($summary.through) --expected-count=$rows --expected-income=$($income.ToString('0.00', $invariant)) --expected-expense=$($expense.ToString('0.00', $invariant)) --batch=500"
} elseif ($isDewuAlipay) {
$storeArgs = ($dewuAlipayAccounts | ForEach-Object { "--store='" + [string]$_.alipay_name + "'" }) -join ' '
"sh $remoteBatchRunner $($spec.importCmd) `"$remoteFile`" --from=$($summary.monthStart) --to=$($summary.through) --expected-count=$rows --expected-income=$($income.ToString('0.00', $invariant)) --expected-expense=$($expense.ToString('0.00', $invariant)) --batch=1000 $storeArgs"
} else {
"sh $remoteBatchRunner $($spec.importCmd) $remoteFile $month --through=$($summary.through) --count=$rows --income=$income --expense=$expense"
}
# 生产重型导入必须进入发布时安装的受限批处理容器;由远端 runner
# 持有同步锁、校验可用内存、复制只读输入并限制为 1 CPU / 1 GiB。
$body = @"
set -e
cleanup() {
docker exec caiwu_app rm -f "$remoteFile" >/dev/null 2>&1 || true
rm -f $remoteFile
}
trap cleanup EXIT
$importCommand
$verifyPhp
"@
$import = Invoke-Remote -Body $body -LocalFile $importFile -RemoteFile $remoteFile
Write-Log ('导入/回验:' + ($import.Output.Trim() -replace "`r?`n", ' | '))
if (-not $import.Ok) {
Write-Log ($spec.label + ' 导入/回验失败(已尝试 ' + $import.Attempts + ' 次):未写入本地状态、未归档,下次运行会重新导入')
$failed = $true
continue
}
# 4) 记录状态 + 归档
$state | Add-Member -NotePropertyName $key -NotePropertyValue ([pscustomobject]@{ rows = $rows; income = $income; expense = $expense; through = $summary.through; file = $importFile; at = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') }) -Force
$state | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $stateFile -Encoding UTF8
$monthNumber = [int]$month.Substring(5, 2)
$shareRoot = 'Z:\高祝兰\财务系统'
if (Test-Path -LiteralPath $shareRoot) {
try {
$shareDir = Join-Path $shareRoot ('{0}月' -f $monthNumber)
New-Item -ItemType Directory -Path $shareDir -Force | Out-Null
foreach ($f in $rawFiles) {
Copy-Item -LiteralPath $f -Destination (Join-Path $shareDir ([IO.Path]::GetFileName($f))) -Force
}
if ($csvFile) {
Copy-Item -LiteralPath $csvFile -Destination (Join-Path $shareDir ([IO.Path]::GetFileName($csvFile))) -Force
}
Write-Log '已归档到共享盘'
} catch {
Write-Log ('共享盘归档失败:' + $_.Exception.Message)
}
}
Write-Log ('=== ' + $spec.label + ':完成 ===')
}
if ($failed) {
Write-Log '本次运行存在失败平台(详见上面日志):相关平台未写状态、未归档'
exit 1
}
} finally {
Stop-CaiwuDeploymentAuth $auth
}