feat(账单同步): 每日先核对前一日并补齐 #1703

Open
qiuxiang wants to merge 1 commits from feature/qiuxiang-prev-day-bill-reconcile into main
8 changed files with 660 additions and 330 deletions

View File

@ -0,0 +1,192 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\JdDailyBillRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingPinduoduoBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
use Throwable;
class SummarizeBillRange extends Command
{
private const ALLOWED_TABS = [
'taobao-alipay',
'taobao-wechat',
'pinduoduo',
'jd-wallet',
'jd-transactions',
'jingxi',
'douyin',
'dewu',
'dewu-alipay',
'xiaohongshu',
];
protected $signature = 'bill-sync:summarize-range
{--tabs= : 逗号分隔的账单页签}
{--from= : 开始日期 YYYY-MM-DD}
{--to= : 截止日期 YYYY-MM-DD}
{--company-id=1 : 公司 ID}
{--json : 输出 JSON}';
protected $description = '按指定日期范围和页签汇总财务系统账单笔数、收入与支出';
public function handle(): int
{
$tabs = array_values(array_unique(array_filter(array_map(
static fn (string $tab): string => trim($tab),
explode(',', (string) $this->option('tabs')),
))));
$unknownTabs = array_values(array_diff($tabs, self::ALLOWED_TABS));
if ($tabs === [] || $unknownTabs !== []) {
$this->error('账单页签无效:' . ($unknownTabs ? implode(',', $unknownTabs) : '不能为空'));
return self::FAILURE;
}
$from = $this->date((string) $this->option('from'));
$to = $this->date((string) $this->option('to'));
if ($from === null || $to === null || $from->gt($to)) {
$this->error('日期范围无效,应为 from <= to,格式 YYYY-MM-DD。');
return self::FAILURE;
}
$companyId = max(1, (int) $this->option('company-id'));
$fromText = $from->toDateString();
$toText = $to->toDateString();
$platforms = [];
$rowCount = 0;
$incomeCents = 0;
$expenseCents = 0;
foreach ($tabs as $tab) {
try {
$summary = $this->summary($tab, $fromText, $toText, $companyId);
} catch (Throwable $exception) {
report($exception);
$this->error("账单页签 {$tab} 汇总失败。");
return self::FAILURE;
}
$platforms[$tab] = $summary;
$rowCount += $summary['row_count'];
$incomeCents += $summary['income_cents'];
$expenseCents += $summary['expense_cents'];
}
$result = [
'from' => $fromText,
'to' => $toText,
'company_id' => $companyId,
'row_count' => $rowCount,
'income_cents' => $incomeCents,
'expense_cents' => $expenseCents,
'platforms' => $platforms,
];
if ((bool) $this->option('json')) {
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
} else {
$this->table(
['页签', '笔数', '收入', '支出'],
array_map(
static fn (string $tab, array $summary): array => [
$tab,
number_format($summary['row_count']),
number_format($summary['income_cents'] / 100, 2),
number_format($summary['expense_cents'] / 100, 2),
],
array_keys($platforms),
array_values($platforms),
),
);
$this->line(sprintf(
'合计:%d 笔,收入 %.2f,支出 %.2f',
$rowCount,
$incomeCents / 100,
$expenseCents / 100,
));
}
return self::SUCCESS;
}
/** @return array{row_count:int,income_cents:int,expense_cents:int} */
private function summary(string $tab, string $from, string $to, int $companyId): array
{
if ($tab === 'xiaohongshu') {
$summary = DB::table('ec_account_bills')
->where('company_id', $companyId)
->where('bill_type', 'xiaohongshu')
->where('occurred_at', '>=', $from . ' 00:00:00')
->where('occurred_at', '<', Carbon::parse($to)->addDay()->toDateString() . ' 00:00:00')
->selectRaw(
'COUNT(*) AS row_count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense'
)
->first();
return $this->normalize($summary->row_count, $summary->income, $summary->expense);
}
$filters = ['start' => $from, 'end' => $to];
$result = match ($tab) {
'taobao-alipay' => app(StoreReceivingAlipayBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'taobao-wechat' => app(TaobaoWechatSettlementBillRepository::class)
->paginateAccountBills($filters, 'occurred_at', 'desc', 1, 1),
'pinduoduo' => app(StoreReceivingPinduoduoBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'jd-wallet' => app(StoreReceivingJdWalletBillRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'jd-transactions' => app(JdDailyBillRepository::class)
->forPlatform('jd')
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'jingxi' => app(JdDailyBillRepository::class)
->forPlatform('jingxi')
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'douyin' => app(StoreReceivingDouyinBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'dewu' => app(StoreReceivingDewuBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'dewu-alipay' => app(StoreReceivingDewuAlipayBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
};
return $this->normalize(
$result['total'] ?? ($result['summary']['count'] ?? 0),
$result['summary']['income'] ?? 0,
$result['summary']['expense'] ?? 0,
);
}
/** @return array{row_count:int,income_cents:int,expense_cents:int} */
private function normalize(mixed $rows, mixed $income, mixed $expense): array
{
return [
'row_count' => (int) $rows,
'income_cents' => (int) round((float) $income * 100),
'expense_cents' => (int) round((float) $expense * 100),
];
}
private function date(string $value): ?Carbon
{
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
return null;
}
$date = Carbon::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
return $date !== false && $date->format('Y-m-d') === $value ? $date : null;
}
}

View File

@ -1,4 +1,4 @@
# 聚胜算每日账单导出(头条放心购 / 京东日账单 / 小红书 / 得物支付宝)
# 聚胜算每日账单导出(淘系微信 / 头条放心购 / 京东日账单 / 小红书 / 得物支付宝)
把聚胜算「经营中心 → 平台原始账单[新]」的账单**定时导出并导入财务系统**(浏览器自动化 + 受控导入)。
@ -6,6 +6,7 @@
| `-Platform` | 胜算页签 | 导入命令 | 财务系统落点 |
| --- | --- | --- | --- |
| `taobao-wechat` | 淘系 → 微信账单 | `taobao-wechat-bills:import-authoritative` | **淘系微信账户** |
| `toutiao` | 头条放心购 → 资金流水 | `business-mirror:import-douyin-authoritative` | 账单流水数据 › 店铺收款账户账单 › **抖音账户** |
| `jd` | 京东商城 → 京东日账单 | `business-mirror:import-jd-daily` | **京东账单 + 京喜账单**(一次导入按店铺名拆两边,两边合计恒等于导出行数) |
| `jd-wallet` | 京东商城 → 京东钱包 | `business-mirror:import-jd-wallet` | **京东网银钱包账户** |
@ -18,6 +19,9 @@
# 全部平台都跑:区间「月初 → 昨日」
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1
# 补导淘系微信完整月份
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform taobao-wechat -Start 2026-11-01 -Through 2026-11-30 -ForceImport
# 只跑京东,补历史月份
pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform jd -Through 2026-07-31
@ -35,6 +39,8 @@ pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform toutiao -Through
```
- 归期:`--through`(默认昨日)所在月份;每月 1 日自动导出**上一个整月**。
- **先核后拉**:每个平台先比较前一自然日的聚胜算源账单与财务系统同范围笔数、收入、支出;发现差异时先重导差异所属完整月份并复核,复核通过后才继续拉取新账单。
- **月初回看**:每月 1-5 日额外核对上月末最后 5 个自然日,覆盖每月末账单在次月上旬才补到的情况;这 5 天存在差异时先补上月完整月份,再拉取当前月数据。
- **先补旧账再拉新账**:每次运行先核对 `2026-07-01` 至本次截止日的覆盖情况。发现历史月份缺失、截止日不足、行数或金额不一致时,按月份从旧到新重导并复核;历史补数未通过时,不继续拉取该平台的新日期。
- 每日失败自动顺延:当天任一平台导出、上传或导入失败,不写成功状态;次日覆盖核查会重新发现缺口并优先补齐。
- **无差异跳过**:京东、京东钱包和头条该月已导入且笔数/收入/支出完全一致时跳过导入;小红书明细量小且会事后修订,每天重新导入最新版本。`-ForceImport` 可强制重刷其它平台;状态记在 `runtime/private/erp-exports/imported-state.json`。
@ -90,5 +96,5 @@ sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:planting-daily --from=202
- 导入走财务系统既有受控导入命令(带笔数/收支核对、原子切换、保留旧版本可回滚),不改上游数据。
- 凭据、导出文件、日志都写 `runtime/private/`(`.gitignore` 忽略),不进仓库。
- 定时:Windows 计划任务每天 09:30 调 `run-erp-daily.ps1`(默认同时拉取头条、京东、京东钱包、小红书和得物支付宝;区间为本月月初→昨日,每月 1 日取上一整月)。
- 定时:Windows 计划任务每天 09:30 调 `run-erp-daily.ps1`(默认同时拉取淘系微信、头条、京东、京东钱包、小红书和得物支付宝;区间为本月月初→昨日,每月 1 日取上一整月)。
- 得物支付宝可单独安装定时任务:`pwsh -File scripts\erp-daily-bills\install-dewu-alipay-task.ps1`。默认每天 11:20 拉取,16:20 再执行一次兜底重试。

View File

@ -1,9 +1,14 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { launchEdge, CDP, openPage, goto, evaluate, sleep } from './cdp.mjs';
const PROFILE = 'F:\\Ai Code\\CaiWuXiTong\\runtime\\private\\erp-profile';
const BASE = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(BASE, '..', '..');
const PROFILE = process.env.ERP_PROFILE
|| path.join(REPO_ROOT, 'runtime', 'private', 'erp-profile');
const SECRET_FILE = process.env.ERP_SECRET_FILE
|| 'F:\\Ai Code\\CaiWuXiTong\\runtime\\private\\敏感信息.md';
|| path.join(REPO_ROOT, 'runtime', 'private', '敏感信息.md');
export function credentials() {
const text = fs.readFileSync(SECRET_FILE, 'utf8');

View File

@ -1,6 +1,7 @@
/*
* 聚胜算「平台原始账单[新]」每日账单导出(统一脚本,用 --platform 选平台)
*
* --platform=taobao-wechat 淘系 → 微信账单(导入 taobao-wechat-bills:import-authoritative → 淘系微信账户)
* --platform=toutiao 头条放心购 → 资金流水 (导入 import-douyin-authoritative → 抖音账户)
* --platform=jd 京东商城 → 京东日账单 (导入 import-jd-daily → 京东账单 + 京喜账单,按店铺名拆分)
* --platform=jd-wallet 京东商城 → 京东钱包 (导入 import-jd-wallet → 京东网银钱包账户)
@ -25,6 +26,13 @@ const BASE = path.dirname(fileURLToPath(import.meta.url));
/** 平台配置:页签、子页签、导出文件名前缀。 */
const PLATFORMS = {
'taobao-wechat': {
label: '淘系',
subTab: '微信账单',
filePrefix: '淘系微信账单',
exportMainName: '淘宝天猫微信账单',
omitChannel: true,
},
toutiao: { label: '头条放心购', subTab: '资金流水', filePrefix: '头条放心购_资金流水', exportMainName: '头条放心购头条资金流水' },
jd: { label: '京东商城', subTab: '京东日账单', filePrefix: '京东日账单', exportMainName: '京东商城京东日账单' },
'jd-wallet': { label: '京东商城', subTab: '京东钱包', filePrefix: '京东钱包', exportMainName: '京东商城京东钱包' },
@ -57,7 +65,7 @@ const accountNos = arg('account-nos', '')
.map((value) => value.trim())
.filter(Boolean);
if (!platform) {
throw new Error('未知平台:' + platformKey + '(可选 toutiao / jd / jd-wallet / xiaohongshu / dewu-alipay)');
throw new Error('未知平台:' + platformKey + '(可选 taobao-wechat / toutiao / jd / jd-wallet / xiaohongshu / dewu-alipay)');
}
if (platform.accountFilter && accountNos.length === 0) {
throw new Error('得物支付宝导出必须提供 --account-nos');
@ -74,8 +82,15 @@ 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: platform.channel || 'TouTiaoFXGZJ', serachColName: '渠道', operatorSymbol: 'In' },
];
if (!platform.omitChannel) {
conditions.push({
SerachFldName: 'ab.channel',
value: platform.channel || 'TouTiaoFXGZJ',
serachColName: '渠道',
operatorSymbol: 'In',
});
}
async function clickPoint(cdp, sid, x, y) {
const pt = { x: Math.round(x), y: Math.round(y) };

View File

@ -0,0 +1,71 @@
function New-ErpBillWindow {
param(
[Parameter(Mandatory = $true)][string]$Label,
[Parameter(Mandatory = $true)][datetime]$Start,
[Parameter(Mandatory = $true)][datetime]$Through
)
[pscustomobject]@{
Label = $Label
Start = $Start.Date
Through = $Through.Date
}
}
function Get-ErpBillReconcileWindows {
param(
[Parameter(Mandatory = $true)][datetime]$PullThroughDate,
[datetime]$RunDate = (Get-Date).Date
)
$windows = [System.Collections.Generic.List[object]]::new()
$previousDay = $PullThroughDate.Date
# 账单常在次月上旬才补到上月末。每月 1-5 日额外核对上月最后 5 个自然日。
$previousMonthEnd = $null
$previousMonthWindowStart = $null
if ($RunDate.Day -le 5) {
$previousMonthEnd = $RunDate.Date.AddDays(-$RunDate.Day)
$previousMonthWindowStart = $previousMonthEnd.AddDays(-4)
}
if ($null -eq $previousMonthEnd -or
$previousDay -lt $previousMonthWindowStart -or
$previousDay -gt $previousMonthEnd) {
$windows.Add((New-ErpBillWindow -Label '前一日' -Start $previousDay -Through $previousDay))
}
if ($RunDate.Day -le 5) {
$windows.Add((New-ErpBillWindow -Label '上月末5日' -Start $previousMonthWindowStart -Through $previousMonthEnd))
}
$seen = @{}
foreach ($window in $windows) {
$key = '{0}:{1}' -f $window.Start.ToString('yyyy-MM-dd'), $window.Through.ToString('yyyy-MM-dd')
if ($seen.ContainsKey($key)) {
continue
}
$seen[$key] = $true
$window
}
}
function Get-ErpBillMonthWindow {
param([Parameter(Mandatory = $true)][datetime]$Date)
$monthStart = Get-Date -Year $Date.Year -Month $Date.Month -Day 1
New-ErpBillWindow `
-Label ('{0} 月补数' -f $Date.ToString('yyyy-MM')) `
-Start $monthStart `
-Through $monthStart.AddMonths(1).AddDays(-1)
}
function Test-ErpBillSummaryMatch {
param(
[Parameter(Mandatory = $true)]$Source,
[Parameter(Mandatory = $true)]$Server
)
return ([int]$Source.rows -eq [int]$Server.row_count -and
[long]$Source.incomeCents -eq [long]$Server.income_cents -and
[long]$Source.expenseCents -eq [long]$Server.expense_cents)
}

View File

@ -7,221 +7,13 @@ param(
)
$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 'dewu-alipay-state.json'
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
$logFile = Join-Path $logDir ((Get-Date -Format 'yyyyMMdd') + '.log')
$accountsPath = Join-Path $root 'dewu-alipay-accounts.json'
$accounts = @(Get-Content -LiteralPath $accountsPath -Raw | ConvertFrom-Json)
if ($accounts.Count -eq 0) {
throw '得物支付宝账号映射为空。'
$arguments = @{
Platform = 'dewu-alipay'
}
if ($Start) { $arguments.Start = $Start }
if ($Through) { $arguments.Through = $Through }
if ($SkipImport) { $arguments.SkipImport = $true }
if ($ForceImport) { $arguments.ForceImport = $true }
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
}
. (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'
$auth = $null
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 `
-RetryDelaySeconds 60 `
-Log { param($message) Write-Log $message }
}
try {
$throughDate = if ($Through) {
[datetime]::ParseExact($Through, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture)
} else {
(Get-Date).Date.AddDays(-1)
}
$through = $throughDate.ToString('yyyy-MM-dd')
$monthStart = if ($Start) {
([datetime]::ParseExact($Start, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture)).ToString('yyyy-MM-dd')
} else {
$throughDate.ToString('yyyy-MM-01')
}
if ($monthStart.Substring(0, 7) -ne $through.Substring(0, 7)) {
throw '得物支付宝单次导入必须位于同一个月份。'
}
$month = $monthStart.Substring(0, 7)
$accountNos = ($accounts | ForEach-Object { [string]$_.merchant_no }) -join ','
$storeNames = @($accounts | ForEach-Object { [string]$_.alipay_name })
$storeArgs = ($storeNames | ForEach-Object { "--store='" + $_ + "'" }) -join ' '
Write-Log ('=== 得物支付宝:{0} ~ {1} ===' -f $monthStart, $through)
$auth = Start-CaiwuDeploymentAuth -Server '218.93.190.75' -SshUser 'root'
$exportArgs = @(
(Join-Path $root 'export-daily.mjs'),
'--platform=dewu-alipay',
('--out=' + $exportDir),
('--account-nos=' + $accountNos),
'--port=9360',
('--profile=' + (Join-Path $exportDir '..\erp-profile-dewu-alipay')),
('--start=' + $monthStart),
('--through=' + $through)
)
$exportOk = $false
for ($attempt = 1; $attempt -le 3 -and -not $exportOk; $attempt++) {
$output = (& $node @exportArgs 2>&1 | Out-String)
Write-Log ('导出:' + ($output.Trim() -replace "`r?`n", ' | '))
if ($LASTEXITCODE -eq 0) {
$exportOk = $true
break
}
if ($attempt -lt 3) { Start-Sleep -Seconds 20 }
}
if (-not $exportOk) {
throw '得物支付宝导出连续失败。'
}
$summary = Get-Content -LiteralPath (Join-Path $exportDir 'last-export.json') -Raw | ConvertFrom-Json
if ($summary.empty) {
Write-Log '该区间聚水潭得物支付宝暂无数据,未改动生产。'
exit 0
}
$rawFiles = @($summary.files | ForEach-Object { [string]$_ })
if ($rawFiles.Count -eq 0) {
throw '导出结果没有文件。'
}
$rawFile = $rawFiles[0]
$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) {
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') '--merge' $csvFile @rawFiles 2>&1 | Out-String)
$importFile = [IO.Path]::ChangeExtension($csvFile, '.merged.xlsx')
$merge = (& $python -X utf8 (Join-Path $root 'merge-xlsx.py') $importFile @rawFiles 2>&1 | Out-String)
if ($LASTEXITCODE -ne 0) {
throw ('XLSX 分片合并失败:' + ($merge.Trim() -replace "`r?`n", ' | '))
}
} else {
$conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') $rawFile $csvFile 2>&1 | Out-String)
$importFile = $rawFile
}
$line = (($conv -split "`n") | Where-Object { $_ -match '^csv=' } | Select-Object -First 1)
if (-not $line) {
throw ('账单转 CSV 失败:' + ($conv.Trim() -replace "`r?`n", ' | '))
}
$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=' + $accountsPath) 2>&1 | Out-String)
$limitedJson = (($limited -split "`n") | Where-Object { $_.TrimStart().StartsWith('{') } | Select-Object -Last 1)
if (-not $limitedJson) {
throw ('得物支付宝范围校验失败:' + ($limited.Trim() -replace "`r?`n", ' | '))
}
$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)) {
throw '得物支付宝汇总与账户范围校验结果不一致。'
}
if ([int]$summary.pageCount -ne $rows) {
throw ('页面笔数 {0} 与导出行数 {1} 不一致。' -f $summary.pageCount, $rows)
}
Write-Log ('核对数:笔数 {0},收入 {1},支出 {2}' -f $rows, $income, $expense)
if ($SkipImport) {
Write-Log '已指定 -SkipImport,未改动生产。'
exit 0
}
$state = if (Test-Path -LiteralPath $stateFile) {
Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json
} else {
New-Object psobject
}
$previous = $state.$month
if (-not $ForceImport -and $previous -and [int]$previous.rows -eq $rows -and
[math]::Abs([double]$previous.income - $income) -lt 0.005 -and
[math]::Abs([double]$previous.expense - $expense) -lt 0.005) {
Write-Log '该月本地状态无差异,跳过导入。'
exit 0
}
$remoteFile = '/tmp/dewu-alipay_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + '.xlsx'
$invariant = [Globalization.CultureInfo]::InvariantCulture
$verifyPhp = @"
cat > /tmp/verify_dewu_alipay.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();
`$result = app(Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository::class)
->paginate(['start' => '$monthStart', 'end' => '$through'], 'occurred_at', 'desc', 1, 1);
echo 'PAGE total=' . `$result['total'] . ' ' . json_encode(`$result['summary'], JSON_UNESCAPED_UNICODE) . PHP_EOL;
if ((int) `$result['total'] !== $rows
|| (int) round((float) `$result['summary']['income'] * 100) !== (int) round($($income.ToString('0.00', $invariant)) * 100)
|| (int) round((float) `$result['summary']['expense'] * 100) !== (int) round($($expense.ToString('0.00', $invariant)) * 100)) {
fwrite(STDERR, '得物支付宝页面回验不一致' . PHP_EOL);
exit(1);
}
PHP
docker exec -i -u www-data caiwu_app php < /tmp/verify_dewu_alipay.php
rm -f /tmp/verify_dewu_alipay.php
"@
$body = @"
set -e
cleanup() {
docker exec caiwu_app rm -f "$remoteFile" >/dev/null 2>&1 || true
rm -f $remoteFile
}
trap cleanup EXIT
sh $remoteBatchRunner taobao-alipay-bills:import-authoritative "$remoteFile" --from=$monthStart --to=$through --expected-count=$rows --expected-income=$($income.ToString('0.00', $invariant)) --expected-expense=$($expense.ToString('0.00', $invariant)) --batch=1000 $storeArgs
$verifyPhp
"@
$import = Invoke-Remote -Body $body -LocalFile $importFile -RemoteFile $remoteFile
Write-Log ('导入/回验:' + ($import.Output.Trim() -replace "`r?`n", ' | '))
if (-not $import.Ok) {
throw '得物支付宝导入或页面回验失败。'
}
$state | Add-Member -NotePropertyName $month -NotePropertyValue ([pscustomobject]@{
rows = $rows
income = $income
expense = $expense
start = $monthStart
through = $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
Write-Log '=== 得物支付宝:完成 ==='
} catch {
Write-Log ('得物支付宝同步失败:' + $_.Exception.Message)
exit 1
} finally {
if ($auth) { Stop-CaiwuDeploymentAuth $auth }
}
& (Join-Path $PSScriptRoot 'run-erp-daily.ps1') @arguments
exit $LASTEXITCODE

View File

@ -1,17 +1,20 @@
<#
聚胜算每日账单 → 财务系统(统一入口)
平台:toutiao = 头条放心购→资金流水(落 抖音账户)
平台:taobao-wechat = 淘系→微信账单(落 淘系微信账户)
toutiao = 头条放心购→资金流水(落 抖音账户)
jd = 京东商城→京东日账单(一次导入按店铺名拆 京东账单 + 京喜账单)
jd-wallet = 京东商城→京东钱包(落 京东网银钱包账户)
xiaohongshu = 小红书→订单结算明细(落 小红书账户)
dewu-alipay = 淘系支付宝账单,按得物店铺映射的 8 个支付宝账号拉取
流程:覆盖核查 → 补齐历史缺口 → 导出 → 汇总核验 / 与已导入期间比对(无差异则跳过)
流程:覆盖核查 → 前一日/月初上月末5日核对并补齐 → 补齐历史缺口 → 导出
→ 汇总核验 / 与已导入期间比对(无差异则跳过)
→ 上传 → 受限批处理容器导入 → 页面回验 → 归档 → 写日志
用法:
pwsh -File run-erp-daily.ps1 # 三个平台,区间「月初 → 昨日」
pwsh -File run-erp-daily.ps1 # 全部平台,区间「月初 → 昨日」
pwsh -File run-erp-daily.ps1 -Platform taobao-wechat -Start 2026-11-01 -Through 2026-11-30 -ForceImport
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
@ -20,23 +23,36 @@
#>
[CmdletBinding()]
param(
[ValidateSet('toutiao', 'jd', 'jd-wallet', 'xiaohongshu', 'dewu-alipay', 'both')][string]$Platform = 'both',
[ValidateSet('taobao-wechat', '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
[switch]$SkipCoverageCheck,
[switch]$SkipPreviousDayCheck,
[switch]$AuditOnly
)
$ErrorActionPreference = 'Stop'
$root = $PSScriptRoot
$self = (Get-Process -Id $PID).Path
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch {}
$invariant = [Globalization.CultureInfo]::InvariantCulture
. (Join-Path $root '..\deploy-auth.ps1')
. (Join-Path $root 'reconcile-windows.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'
$runtimeBase = Join-Path $HOME '.cache\codex-runtimes\codex-primary-runtime\dependencies'
$node = if (Test-Path (Join-Path $runtimeBase 'node\bin\node.exe')) {
Join-Path $runtimeBase 'node\bin\node.exe'
} else {
'C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
}
$python = if (Test-Path (Join-Path $runtimeBase 'python\python.exe')) {
Join-Path $runtimeBase 'python\python.exe'
} else {
'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'
@ -52,6 +68,7 @@ function Write-Log {
# 平台 → 导入命令 / 页面回验页签
$specs = @{
'taobao-wechat' = @{ label = '淘系微信'; artifact = 'taobao-wechat'; importCmd = 'taobao-wechat-bills:import-authoritative'; verifyTabs = @('taobao-wechat'); split = $false; uploadExtension = '.xlsx' }
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 }
@ -64,7 +81,7 @@ $coverageKeys = @{
'jd-wallet' = 'jd-wallet'
}
$targets = if ($Platform -eq 'both') { @('toutiao', 'jd', 'jd-wallet', 'xiaohongshu', 'dewu-alipay') } else { @($Platform) }
$targets = if ($Platform -eq 'both') { @('taobao-wechat', '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') {
@ -76,13 +93,13 @@ if ($targets -contains 'dewu-alipay') {
$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')
$sshTarget = 'root@218.93.190.75'
. (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 }
# 远程执行包装:失败自动重试(含重新上传文件),并返回 { Ok; Output; Attempts }。
# 直接使用本机部署凭据,不依赖未入库的 runtime/private 辅助脚本。
function Invoke-Remote {
param(
[Parameter(Mandatory = $true)][string]$Body,
@ -90,14 +107,54 @@ function Invoke-Remote {
[string]$RemoteFile = ''
)
return Invoke-ErpRemote `
-PwshPath $self `
-SshScript $remoteSshScript `
-UploaderScript $remoteUploaderScript `
-Body $Body `
-LocalFile $LocalFile `
-RemoteFile $RemoteFile `
-Log { param($message) Write-Log $message }
$attempts = 3
$output = ''
$tmp = [IO.Path]::GetTempFileName() + '.sh'
[IO.File]::WriteAllText($tmp, ($Body -replace "`r`n", "`n"), [Text.UTF8Encoding]::new($false))
try {
for ($attempt = 1; $attempt -le $attempts; $attempt++) {
if ($LocalFile -and $RemoteFile) {
$output = (& scp @($sshOptions) $LocalFile "${sshTarget}:${RemoteFile}" 2>&1 | Out-String)
if ($LASTEXITCODE -ne 0) {
Write-Log ('上传失败(第 {0}/{1} 次):{2}' -f $attempt, $attempts, ($output.Trim() -replace "`r?`n", ' | '))
if ($attempt -lt $attempts) {
Start-Sleep -Seconds 10
continue
}
return [pscustomobject]@{ Ok = $false; Output = $output; Attempts = $attempt }
}
}
$remoteScript = '/tmp/caiwu-erp-daily-' + [guid]::NewGuid().ToString('N') + '.sh'
$output = (& scp @($sshOptions) $tmp "${sshTarget}:${remoteScript}" 2>&1 | Out-String)
if ($LASTEXITCODE -ne 0) {
Write-Log ('远程脚本上传失败(第 {0}/{1} 次):{2}' -f $attempt, $attempts, ($output.Trim() -replace "`r?`n", ' | '))
if ($attempt -lt $attempts) {
Start-Sleep -Seconds 10
continue
}
return [pscustomobject]@{ Ok = $false; Output = $output; Attempts = $attempt }
}
$output = (& ssh @($sshOptions) $sshTarget "sh '$remoteScript'" 2>&1 | Out-String)
$remoteExitCode = $LASTEXITCODE
& ssh @($sshOptions) $sshTarget "rm -f '$remoteScript'" 2>&1 | Out-Null
if ($remoteExitCode -eq 0) {
return [pscustomobject]@{ Ok = $true; Output = $output; Attempts = $attempt }
}
Write-Log ('远程执行失败(第 {0}/{1} 次,exit={2}):{3}' -f $attempt, $attempts, $remoteExitCode, ($output.Trim() -replace "`r?`n", ' | '))
if ($attempt -lt $attempts) {
Start-Sleep -Seconds 10
}
}
return [pscustomobject]@{ Ok = $false; Output = $output; Attempts = $attempts }
} finally {
Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue
}
}
function Get-ErpDailyCoverage {
@ -127,6 +184,31 @@ exit "`$status"
return @($jsonLine | ConvertFrom-Json)
}
function Get-ErpBillRangeSummary {
param(
[Parameter(Mandatory = $true)][string[]]$Tabs,
[Parameter(Mandatory = $true)][string]$From,
[Parameter(Mandatory = $true)][string]$To,
[int]$CompanyId = 1
)
$tabsArg = $Tabs -join ','
$body = "docker exec -u www-data caiwu_app php /var/www/html/artisan bill-sync:summarize-range --tabs=$tabsArg --from=$From --to=$To --company-id=$CompanyId --json"
$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) {
@ -171,13 +253,81 @@ try {
$targets = @()
}
foreach ($target in $targets) {
:targetLoop 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
# 每次拉取新账单前,先用同口径源账单核对前一自然日;每月 1-5 日再
# 核对上月末最后 5 个自然日。发现差异先补完整所属月份,复验通过后才继续。
if (-not $SkipPreviousDayCheck -and -not $AuditOnly -and [string]::IsNullOrWhiteSpace($Start)) {
$reconcileWindows = @(Get-ErpBillReconcileWindows -PullThroughDate $pullThroughDate -RunDate (Get-Date).Date)
foreach ($window in $reconcileWindows) {
$windowStart = $window.Start.ToString('yyyy-MM-dd')
$windowThrough = $window.Through.ToString('yyyy-MM-dd')
Write-Log ('核对 {0}:{1} ~ {2}' -f $window.Label, $windowStart, $windowThrough)
& $self -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath `
-Platform $target `
-Start $windowStart `
-Through $windowThrough `
-CoverageFrom $CoverageFrom `
-AuditOnly `
-SkipCoverageCheck `
-SkipPreviousDayCheck
$auditExitCode = $LASTEXITCODE
if ($auditExitCode -eq 0) {
Write-Log ('{0}核对一致:{1} ~ {2}' -f $window.Label, $windowStart, $windowThrough)
continue
}
if ($auditExitCode -ne 2) {
Write-Log ('{0}核对失败(exit={1}),已停止该平台的新账单拉取' -f $window.Label, $auditExitCode)
$failed = $true
continue targetLoop
}
if ($SkipImport) {
Write-Log ('{0}发现差异,但已指定 -SkipImport;已停止该平台的新账单拉取' -f $window.Label)
$failed = $true
continue targetLoop
}
$monthWindow = Get-ErpBillMonthWindow -Date $window.Start
$monthStart = $monthWindow.Start.ToString('yyyy-MM-dd')
$monthThrough = $monthWindow.Through.ToString('yyyy-MM-dd')
Write-Log ('{0}存在差异,先补齐所属月份 {1} ~ {2}' -f $window.Label, $monthStart, $monthThrough)
& $self -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath `
-Platform $target `
-Start $monthStart `
-Through $monthThrough `
-CoverageFrom $CoverageFrom `
-ForceImport `
-SkipCoverageCheck `
-SkipPreviousDayCheck
if ($LASTEXITCODE -ne 0) {
Write-Log ('{0}所属月份补齐失败,已停止该平台的新账单拉取' -f $window.Label)
$failed = $true
continue targetLoop
}
& $self -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath `
-Platform $target `
-Start $windowStart `
-Through $windowThrough `
-CoverageFrom $CoverageFrom `
-AuditOnly `
-SkipCoverageCheck `
-SkipPreviousDayCheck
if ($LASTEXITCODE -ne 0) {
Write-Log ('{0}补齐后复验仍未通过,已停止该平台的新账单拉取' -f $window.Label)
$failed = $true
continue targetLoop
}
Write-Log ('{0}已补齐并复验一致:{1} ~ {2}' -f $window.Label, $windowStart, $windowThrough)
}
}
# 先补此前月份的缺口;历史仍不完整时,不继续拉取本月新数据。
$historicalIssues = if ($coverageKey) {
@(Get-ErpCoverageBackfillJobs -CoverageReport $coverageReport -Dataset $coverageKey -CurrentMonth $pullMonth)
@ -253,8 +403,22 @@ try {
$summary = Get-Content -LiteralPath (Join-Path $exportDir 'last-export.json') -Raw | ConvertFrom-Json
if ($summary.empty) {
if ($AuditOnly) {
$serverSummary = Get-ErpBillRangeSummary `
-Tabs @($spec.verifyTabs) `
-From ([string]$summary.monthStart) `
-To ([string]$summary.through)
if ([int]$serverSummary.row_count -ne 0 -or
[long]$serverSummary.income_cents -ne 0 -or
[long]$serverSummary.expense_cents -ne 0) {
Write-Log ($spec.label + ':胜算无数据,但财务系统仍有流水;需要回补核对')
exit 2
}
Write-Log ($spec.label + ':胜算和财务系统该区间均无数据')
continue targetLoop
}
Write-Log ($spec.label + ':该区间胜算暂无数据,跳过(未改动生产)')
continue
continue targetLoop
}
# 胜算超过同步导出上限时会拆成多个分片(summary.files),逐片转 CSV 后合并成一份再导入。
# 小红书导入命令只接受原始 XLSX,因此独立汇总,不上传转换后的 CSV。
@ -265,6 +429,7 @@ try {
$rawFile = $rawFiles[0]
$isXiaohongshu = $target -eq 'xiaohongshu'
$isDewuAlipay = $target -eq 'dewu-alipay'
$isFullMonthXlsx = $target -eq 'taobao-wechat'
$csvFile = $null
$importFile = $rawFile
if ($isXiaohongshu) {
@ -330,6 +495,35 @@ try {
$failed = $true
continue
}
} elseif ($isFullMonthXlsx) {
$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} 个,转为合并 CSV 并合并 XLSX' -f $spec.label, $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 ($spec.label + ' 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 ($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)
} else {
# 多分片时 CSV 用合并后的名字(不带 _partN),避免看起来只落了第一片
$csvFile = if ($rawFiles.Count -gt 1) {
@ -364,107 +558,61 @@ try {
continue
}
# 2) 无差异跳过
# 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)
$sourceSummary = [pscustomobject]@{
rows = [int]$rows
incomeCents = [long][math]::Round([double]$income * 100)
expenseCents = [long][math]::Round([double]$expense * 100)
}
$serverSummary = Get-ErpBillRangeSummary `
-Tabs @($spec.verifyTabs) `
-From ([string]$summary.monthStart) `
-To ([string]$summary.through)
$serverMatchesExport = Test-ErpBillSummaryMatch -Source $sourceSummary -Server $serverSummary
Write-Log ('财务系统同范围:笔数 {0},收入 {1},支出 {2};源账单:笔数 {3},收入 {4},支出 {5}' -f
[int]$serverSummary.row_count,
(([long]$serverSummary.income_cents) / 100).ToString('0.00', $invariant),
(([long]$serverSummary.expense_cents) / 100).ToString('0.00', $invariant),
$rows,
$income.ToString('0.00', $invariant),
$expense.ToString('0.00', $invariant))
if ($AuditOnly) {
if ($serverMatchesExport) {
Write-Log ('{0} 与财务系统一致,无需补数:{1} ~ {2}' -f $spec.label, $summary.monthStart, $summary.through)
continue targetLoop
}
Write-Log ('{0} 与财务系统不一致:{1} ~ {2}' -f $spec.label, $summary.monthStart, $summary.through)
exit 2
}
if ($serverMatchesExport -and -not $forceThisImport) {
# 服务端已经一致时,只回填本机状态,避免重复导入同一批账单。
$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)
continue
}
if ($SkipImport) {
Write-Log '同范围汇总不一致,但已指定 -SkipImport;本次视为失败'
$failed = $true
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"
} elseif ($isFullMonthXlsx) {
"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"
} else {
"sh $remoteBatchRunner $($spec.importCmd) $remoteFile $month --through=$($summary.through) --count=$rows --income=$income --expense=$expense"
}
@ -479,16 +627,33 @@ cleanup() {
}
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 + ' 次):未写入本地状态、未归档,下次运行会重新导入')
Write-Log ($spec.label + ' 导入失败(已尝试 ' + $import.Attempts + ' 次):未写入本地状态、未归档,下次运行会重新导入')
$failed = $true
continue
}
$verifiedSummary = Get-ErpBillRangeSummary `
-Tabs @($spec.verifyTabs) `
-From ([string]$summary.monthStart) `
-To ([string]$summary.through)
if (-not (Test-ErpBillSummaryMatch -Source $sourceSummary -Server $verifiedSummary)) {
Write-Log ('{0} 导入后回验仍不一致:源 {1} 笔 / {2} / {3},财务 {4} 笔 / {5} / {6}' -f
$spec.label,
$rows,
$income.ToString('0.00', $invariant),
$expense.ToString('0.00', $invariant),
[int]$verifiedSummary.row_count,
(([long]$verifiedSummary.income_cents) / 100).ToString('0.00', $invariant),
(([long]$verifiedSummary.expense_cents) / 100).ToString('0.00', $invariant))
$failed = $true
continue
}
Write-Log ('导入后回验一致:{0} 笔 / {1} / {2}' -f $rows, $income.ToString('0.00', $invariant), $expense.ToString('0.00', $invariant))
# 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
@ -517,6 +682,7 @@ $verifyPhp
Write-Log '本次运行存在失败平台(详见上面日志):相关平台未写状态、未归档'
exit 1
}
exit 0
} finally {
Stop-CaiwuDeploymentAuth $auth
}

View File

@ -0,0 +1,83 @@
<?php
namespace Tests\Feature\Console;
use Illuminate\Support\Facades\Artisan;
use Mockery;
use Modules\EcommerceFinance\Repositories\JdDailyBillRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
use Tests\TestCase;
class SummarizeBillRangeTest extends TestCase
{
public function test_it_aggregates_wechat_and_split_jd_tabs_for_the_requested_range(): void
{
$wechat = Mockery::mock(TaobaoWechatSettlementBillRepository::class);
$wechat->shouldReceive('paginateAccountBills')
->once()
->with(
['start' => '2026-11-30', 'end' => '2026-11-30'],
'occurred_at',
'desc',
1,
1,
)
->andReturn([
'total' => 766,
'summary' => ['income' => 28878.98, 'expense' => 2149.18],
]);
$this->app->instance(TaobaoWechatSettlementBillRepository::class, $wechat);
$jd = Mockery::mock(JdDailyBillRepository::class);
foreach (['jd' => [32, 1460.76, 73.58], 'jingxi' => [5, 100.00, 20.00]] as $platform => $values) {
$jd->shouldReceive('forPlatform')
->once()
->with($platform)
->andReturnSelf();
$jd->shouldReceive('paginate')
->once()
->with(
['start' => '2026-11-30', 'end' => '2026-11-30'],
'occurred_at',
'desc',
1,
1,
)
->andReturn([
'total' => $values[0],
'summary' => ['income' => $values[1], 'expense' => $values[2]],
]);
}
$this->app->instance(JdDailyBillRepository::class, $jd);
$exitCode = Artisan::call('bill-sync:summarize-range', [
'--tabs' => 'taobao-wechat,jd-transactions,jingxi',
'--from' => '2026-11-30',
'--to' => '2026-11-30',
'--company-id' => 1,
'--json' => true,
]);
$this->assertSame(0, $exitCode);
$result = json_decode(Artisan::output(), true, 512, JSON_THROW_ON_ERROR);
$this->assertSame(803, $result['row_count']);
$this->assertSame(3043974, $result['income_cents']);
$this->assertSame(224276, $result['expense_cents']);
$this->assertSame(766, $result['platforms']['taobao-wechat']['row_count']);
$this->assertSame(32, $result['platforms']['jd-transactions']['row_count']);
$this->assertSame(5, $result['platforms']['jingxi']['row_count']);
}
public function test_it_rejects_unknown_tabs(): void
{
$exitCode = Artisan::call('bill-sync:summarize-range', [
'--tabs' => 'unknown',
'--from' => '2026-11-30',
'--to' => '2026-11-30',
'--json' => true,
]);
$this->assertSame(1, $exitCode);
$this->assertStringContainsString('账单页签无效', Artisan::output());
}
}