feat: 每日同步聚水潭小红书订单结算明细 (#1563)

This commit is contained in:
qiuxiang 2026-11-30 14:13:59 +08:00
parent cae8f769c9
commit 0a508f14be
4 changed files with 224 additions and 50 deletions

View File

@ -1,4 +1,4 @@
# 聚胜算每日账单导出(头条放心购 / 京东日账单)
# 聚胜算每日账单导出(头条放心购 / 京东日账单 / 小红书订单结算明细)
把聚胜算「经营中心 → 平台原始账单[新]」的账单**定时导出并导入财务系统**(浏览器自动化 + 受控导入)。
@ -9,11 +9,12 @@
| `toutiao` | 头条放心购 → 资金流水 | `business-mirror:import-douyin-authoritative` | 账单流水数据 › 店铺收款账户账单 › **抖音账户** |
| `jd` | 京东商城 → 京东日账单 | `business-mirror:import-jd-daily` | **京东账单 + 京喜账单**(一次导入按店铺名拆两边,两边合计恒等于导出行数) |
| `jd-wallet` | 京东商城 → 京东钱包 | `business-mirror:import-jd-wallet` | **京东网银钱包账户** |
| `xiaohongshu` | 小红书 → 订单结算明细 | `xiaohongshu-bills:import` | **小红书账户** |
## 用法
```powershell
# 三个平台都跑:区间「月初 → 昨日」
# 四个平台都跑:区间「月初 → 昨日」
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1
# 只跑京东,补历史月份
@ -22,6 +23,9 @@ pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform jd -Through 2026-
# 只跑京东钱包,补历史月份
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform jd-wallet -Through 2026-07-31
# 只跑小红书,补历史月份
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform xiaohongshu -Through 2026-11-30
# 只导出不导入(排查;仍会做覆盖核查)
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform toutiao -Through 2026-10-05 -SkipImport
```
@ -29,7 +33,7 @@ pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform toutiao -Through
- 归期:`--through`(默认昨日)所在月份;每月 1 日自动导出**上一个整月**。
- **先补旧账再拉新账**:每次运行先核对 `2026-07-01` 至本次截止日的覆盖情况。发现历史月份缺失、截止日不足、行数或金额不一致时,按月份从旧到新重导并复核;历史补数未通过时,不继续拉取该平台的新日期。
- 每日失败自动顺延:当天任一平台导出、上传或导入失败,不写成功状态;次日覆盖核查会重新发现缺口并优先补齐。
- **无差异跳过**:该平台该月已导入且笔数/收入/支出完全一致时跳过导入(`-ForceImport` 可强制重刷);状态记在 `runtime/private/erp-exports/imported-state.json`。
- **无差异跳过**:京东、京东钱包和头条该月已导入且笔数/收入/支出完全一致时跳过导入;小红书明细量小且会事后修订,每天重新导入最新版本。`-ForceImport` 可强制重刷其它平台;状态记在 `runtime/private/erp-exports/imported-state.json`。
- 超过胜算同步导出上限(响应 `超出同步导出允许最大数据量`)时,脚本自动轮询「异步导出下载管理」取回本次任务的全部分片,逐片转 CSV 后合并成一份再导入;仍可用 `-Start/-Through` 分段导出。
- 导入前用页面笔数(共 N 条)与导出行数核对,不一致就跳过导入(`-ForceImport` 可强制),避免只导入一部分。
- 稳定性:导出最多重试 3 次(胜算页面偶发日历面板/授权弹窗异常);上传与"导入+回验"失败自动重试 3 次(含重新上传 CSV),用于吸收服务器 SSH 偶发断连。
@ -67,14 +71,15 @@ sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=202
| 文件 | 作用 |
| --- | --- |
| `run-erp-daily.ps1` | 统一入口:导出 → 转 CSV → 差异判断 → 上传 → 受控导入 → 页面回验 → 归档 → 日志 |
| `run-erp-daily.ps1` | 统一入口:导出 → 汇总核验 → 上传 → 受控导入 → 页面回验 → 归档 → 日志 |
| `export-daily.mjs` | 浏览器自动化导出(登录、切页签、设日期、查询、导出、取下载直链) |
| `erp-session.mjs` | 胜算登录与会话工具(凭据读 `runtime/private/敏感信息.md`,可用 `ERP_SECRET_FILE` 覆盖) |
| `cdp.mjs` | 无依赖的 Edge DevTools Protocol 驱动 |
| `xlsx-to-csv.py` | 导出文件(xlsx)转 UTF-8 CSV,并输出笔数/收入/支出核对数 |
| `xiaohongshu-summary.py` | 小红书原始 XLSX 的流式笔数、收支和结算日期核验 |
## 说明
- 导入走财务系统既有受控导入命令(带笔数/收支核对、原子切换、保留旧版本可回滚),不改上游数据。
- 凭据、导出文件、日志都写 `runtime/private/`(`.gitignore` 忽略),不进仓库。
- 定时:Windows 计划任务每天 09:30 调 `run-erp-daily.ps1`(京东取昨日;头条取月初→昨日)。
- 定时:Windows 计划任务每天 09:30 调 `run-erp-daily.ps1`(默认同时拉取头条、京东、京东钱包和小红书;区间为本月月初→昨日,每月 1 日取上一整月)。

View File

@ -4,6 +4,7 @@
* --platform=toutiao 头条放心购 → 资金流水 (导入 import-douyin-authoritative → 抖音账户)
* --platform=jd 京东商城 → 京东日账单 (导入 import-jd-daily → 京东账单 + 京喜账单,按店铺名拆分)
* --platform=jd-wallet 京东商城 → 京东钱包 (导入 import-jd-wallet → 京东网银钱包账户)
* --platform=xiaohongshu 小红书 → 订单结算明细 (导入 xiaohongshu-bills:import → 小红书账户)
*
* 用法:
* node export-daily.mjs --platform=toutiao # 本月月初 → 昨日
@ -26,6 +27,7 @@ const PLATFORMS = {
toutiao: { label: '头条放心购', subTab: '资金流水', filePrefix: '头条放心购_资金流水', exportMainName: '头条放心购头条资金流水' },
jd: { label: '京东商城', subTab: '京东日账单', filePrefix: '京东日账单', exportMainName: '京东商城京东日账单' },
'jd-wallet': { label: '京东商城', subTab: '京东钱包', filePrefix: '京东钱包', exportMainName: '京东商城京东钱包' },
xiaohongshu: { label: '小红书', subTab: '订单结算明细', filePrefix: '小红书订单结算明细', exportMainName: '小红书订单结算明细', channel: 'XiaohsSeller' },
};
const arg = (name, fallback = null) => {
const hit = process.argv.find((a) => a.startsWith(`--${name}=`));
@ -43,7 +45,7 @@ const BILL_URL = 'https://ss.erp321.com/process/platform-bill-new';
const platformKey = arg('platform', 'toutiao');
const platform = PLATFORMS[platformKey];
if (!platform) {
throw new Error('未知平台:' + platformKey + '(可选 toutiao / jd / jd-wallet)');
throw new Error('未知平台:' + platformKey + '(可选 toutiao / jd / jd-wallet / xiaohongshu)');
}
fs.mkdirSync(OUT_DIR, { recursive: true });
@ -52,7 +54,7 @@ const log = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
const conditions = [
{ SerachFldName: 'ab.create_time', serachColName: '结算时间', value: monthStart, operatorSymbol: 'GreaterThanOrEqual' },
{ SerachFldName: 'ab.create_time', serachColName: '结算时间', value: through, operatorSymbol: 'LessThan' },
{ SerachFldName: 'ab.channel', value: 'TouTiaoFXGZJ', serachColName: '渠道', operatorSymbol: 'In' },
{ SerachFldName: 'ab.channel', value: platform.channel || 'TouTiaoFXGZJ', serachColName: '渠道', operatorSymbol: 'In' },
];
async function clickPoint(cdp, sid, x, y) {
@ -259,7 +261,10 @@ for (let attempt = 1; attempt <= 4 && !countText; attempt++) {
if (!qb) { log(`第${attempt}次:找不到查询按钮`); await sleep(2000); continue; }
await clickPoint(cdp, sid, qb.x, qb.y);
await sleep(8000);
countText = await evaluate(cdp, sid, `((document.body.innerText || '').replace(/\\s+/g,' ').match(/共(\\d+)条/) || [])[1] || null`);
countText = await evaluate(cdp, sid, `(() => {
const text = (document.body.innerText || '').replace(/\\s+/g, ' ');
return (text.match(/(?:共|账单明细)\\s*([\\d,]+)\\s*条/) || [])[1]?.replace(/,/g, '') || null;
})()`);
log(`查询第${attempt}次:笔数=${countText},新请求=${seen.list.length - before}`);
if (!countText) await sleep(2000);
}

View File

@ -4,8 +4,9 @@
平台:toutiao = 头条放心购→资金流水(落 抖音账户)
jd = 京东商城→京东日账单(一次导入按店铺名拆 京东账单 + 京喜账单)
jd-wallet = 京东商城→京东钱包(落 京东网银钱包账户)
xiaohongshu = 小红书→订单结算明细(落 小红书账户)
流程:覆盖核查 → 补齐历史缺口 → 导出 → xlsx 转 CSV → 与已导入期间比对(无差异则跳过)
流程:覆盖核查 → 补齐历史缺口 → 导出 → 汇总核验 / 与已导入期间比对(无差异则跳过)
→ 上传 → 受限批处理容器导入 → 页面回验 → 归档 → 写日志
用法:
@ -13,10 +14,11 @@
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
#>
[CmdletBinding()]
param(
[ValidateSet('toutiao', 'jd', 'jd-wallet', 'both')][string]$Platform = 'both',
[ValidateSet('toutiao', 'jd', 'jd-wallet', 'xiaohongshu', 'both')][string]$Platform = 'both',
[string]$Through,
[string]$Start,
[string]$CoverageFrom = '2026-07-01',
@ -51,6 +53,7 @@ $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' }
}
$coverageKeys = @{
toutiao = 'douyin'
@ -58,7 +61,7 @@ $coverageKeys = @{
'jd-wallet' = 'jd-wallet'
}
$targets = if ($Platform -eq 'both') { @('toutiao', 'jd', 'jd-wallet') } else { @($Platform) }
$targets = if ($Platform -eq 'both') { @('toutiao', 'jd', 'jd-wallet', 'xiaohongshu') } else { @($Platform) }
$state = if (Test-Path -LiteralPath $stateFile) { (Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json) } else { New-Object psobject }
$auth = Start-CaiwuDeploymentAuth -Server '218.93.190.75' -SshUser 'root'
@ -166,7 +169,11 @@ try {
$forceThisImport = [bool]$ForceImport -or $currentIssue.Count -gt 0
# 先补此前月份的缺口;历史仍不完整时,不继续拉取本月新数据。
$historicalIssues = @(Get-ErpCoverageBackfillJobs -CoverageReport $coverageReport -Dataset $coverageKey -CurrentMonth $pullMonth)
$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) {
@ -232,32 +239,60 @@ try {
Write-Log ($spec.label + ':该区间胜算暂无数据,跳过(未改动生产)')
continue
}
# 胜算超过同步导出上限时会拆成多个分片(summary.files),逐片转 CSV 后合并成一份再导入
# 胜算超过同步导出上限时会拆成多个分片(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]
# 多分片时 CSV 用合并后的名字(不带 _partN),避免看起来只落了第一片
$csvFile = if ($rawFiles.Count -gt 1) {
[IO.Path]::ChangeExtension(($rawFile -replace '_part\d+(?=\.[^.]+$)', ''), '.csv')
$isXiaohongshu = $target -eq 'xiaohongshu'
$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)
} else {
[IO.Path]::ChangeExtension($rawFile, '.csv')
# 多分片时 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
}
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)
$month = $summary.monthStart.Substring(0, 7)
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()) }
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 }
@ -270,7 +305,8 @@ try {
# 2) 无差异跳过
$key = $target + ':' + $month
$prev = $state.$key
$same = $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)
# 小红书只有少量明细,且聚水潭会事后调整字段;每天重新导入以保留最新版本。
$same = -not $isXiaohongshu -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
@ -292,7 +328,8 @@ try {
# 3) 上传 + 导入 + 页面回验。统一交给 Invoke-Remote,上传断开时会重新上传并重试,
# 整段失败则本平台失败,不写状态、不归档。
$remoteFile = '/tmp/' + $target + '_daily_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + '.csv'
$uploadExtension = if ($isXiaohongshu) { '.xlsx' } else { '.csv' }
$remoteFile = '/tmp/' + $target + '_daily_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + $uploadExtension
$verifyPhp = @"
cat > /tmp/verify_daily.php <<'PHP'
@ -300,23 +337,38 @@ cat > /tmp/verify_daily.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();
`$repo = app(Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository::class);
`$tabs = ['__TABS__'];
`$total = 0;
`$incomeCents = 0;
`$expenseCents = 0;
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 (`$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;
} 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)
@ -339,19 +391,25 @@ rm -f /tmp/verify_daily.php
$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"
} 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 /tmp/daily_bills.csv >/dev/null 2>&1 || true
docker exec caiwu_app rm -f "$remoteFile" >/dev/null 2>&1 || true
rm -f $remoteFile
}
trap cleanup EXIT
sh $remoteBatchRunner $($spec.importCmd) $remoteFile $month --through=$($summary.through) --count=$rows --income=$income --expense=$expense
$importCommand
$verifyPhp
"@
$import = Invoke-Remote -Body $body -LocalFile $csvFile -RemoteFile $remoteFile
$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 + ' 次):未写入本地状态、未归档,下次运行会重新导入')
@ -360,7 +418,7 @@ $verifyPhp
}
# 4) 记录状态 + 归档
$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 | 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)
@ -372,7 +430,9 @@ $verifyPhp
foreach ($f in $rawFiles) {
Copy-Item -LiteralPath $f -Destination (Join-Path $shareDir ([IO.Path]::GetFileName($f))) -Force
}
Copy-Item -LiteralPath $csvFile -Destination (Join-Path $shareDir ([IO.Path]::GetFileName($csvFile))) -Force
if ($csvFile) {
Copy-Item -LiteralPath $csvFile -Destination (Join-Path $shareDir ([IO.Path]::GetFileName($csvFile))) -Force
}
Write-Log '已归档到共享盘'
} catch {
Write-Log ('共享盘归档失败:' + $_.Exception.Message)

View File

@ -0,0 +1,104 @@
"""流式汇总聚水潭小红书订单结算明细,供每日导入前核验。"""
import argparse
import json
from datetime import datetime
from decimal import Decimal, InvalidOperation
from openpyxl import load_workbook
REQUIRED_HEADERS = (
"记录编码",
"收入金额",
"支出金额",
"结算时间",
)
def text(value):
return "" if value is None else str(value).strip()
def money(value):
raw = text(value).replace(",", "").replace(",", "").replace("¥", "").replace("¥", "")
try:
return Decimal(raw or "0")
except InvalidOperation as error:
raise ValueError(f"无效金额:{value!r}") from error
def date_time(value):
if isinstance(value, datetime):
return value
raw = text(value)
for format_string in ("%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M:%S", "%Y-%m-%d", "%Y/%m/%d"):
try:
return datetime.strptime(raw, format_string)
except ValueError:
continue
raise ValueError(f"无效结算时间:{value!r}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("path")
parser.add_argument("--from", dest="from_date", default=None)
parser.add_argument("--to", dest="to_date", default=None)
args = parser.parse_args()
workbook = load_workbook(args.path, read_only=True, data_only=True)
try:
sheet = workbook[workbook.sheetnames[0]]
rows = sheet.iter_rows(values_only=True)
headers = [text(value) for value in next(rows)]
missing = [header for header in REQUIRED_HEADERS if header not in headers]
if missing:
raise ValueError("缺少小红书账单表头:" + "、".join(missing))
indexes = {header: headers.index(header) for header in REQUIRED_HEADERS}
count = 0
income = Decimal("0")
expense = Decimal("0")
occurred_min = None
occurred_max = None
seen_codes = set()
record_index = headers.index("记录编码")
for row in rows:
if not any(value not in (None, "") for value in row):
continue
code = text(row[record_index])
if not code:
raise ValueError("小红书账单存在空记录编码")
if code in seen_codes:
raise ValueError(f"小红书账单记录编码重复:{code}")
seen_codes.add(code)
occurred = date_time(row[indexes["结算时间"]])
occurred_text = occurred.strftime("%Y-%m-%d %H:%M:%S")
occurred_min = occurred_text if occurred_min is None or occurred_text < occurred_min else occurred_min
occurred_max = occurred_text if occurred_max is None or occurred_text > occurred_max else occurred_max
count += 1
income += money(row[indexes["收入金额"]])
expense += money(row[indexes["支出金额"]])
finally:
workbook.close()
if count == 0:
raise ValueError("小红书账单没有数据")
if args.from_date and occurred_min[:10] < args.from_date:
raise ValueError(f"结算时间 {occurred_min} 早于账期起点 {args.from_date}")
if args.to_date and occurred_max[:10] > args.to_date:
raise ValueError(f"结算时间 {occurred_max} 晚于账期终点 {args.to_date}")
print(json.dumps({
"rows": count,
"income": format(income, ".2f"),
"expense": format(expense, ".2f"),
"net": format(income - expense, ".2f"),
"occurred_min": occurred_min,
"occurred_max": occurred_max,
}, ensure_ascii=False))
if __name__ == "__main__":
main()