feat(账户总览): 直连余额叠加次日起动账

次日导入前一天最终余额后,仅叠加次日起全部动账;前一天流水不重复计算。
This commit is contained in:
shanshi 2026-11-23 17:20:47 +08:00
parent 0e1bac07c0
commit d42bc76404
3 changed files with 201 additions and 14 deletions

View File

@ -26,7 +26,8 @@ final class BankDirectBalanceRepository
* account_balance:?float,
* available_balance:float,
* balance_date:string,
* balance_at:string
* balance_at:string,
* imported_at:string
* }>
*/
public function latestForAccounts(array $accountIds, string $periodTo): array
@ -52,6 +53,7 @@ final class BankDirectBalanceRepository
'available_balance',
'balance_date',
'balance_at',
'imported_at',
]);
$latest = [];
@ -63,6 +65,7 @@ final class BankDirectBalanceRepository
'available_balance' => round((float) $row->available_balance, 2),
'balance_date' => substr((string) $row->balance_date, 0, 10),
'balance_at' => (string) $row->balance_at,
'imported_at' => (string) $row->imported_at,
];
}

View File

@ -575,28 +575,149 @@ final class NonStoreAccountMonitorPageData
if ($snapshots === []) {
return $rows;
}
$adjustments = $this->directSnapshotAdjustments(
$rows,
$snapshots,
now()->toDateString(),
);
return $rows->map(function (array $row) use ($snapshots): array {
return $rows->map(function (array $row) use ($snapshots, $adjustments): array {
$snapshot = $snapshots[(int) ($row['id'] ?? 0)] ?? null;
if ($snapshot === null) {
return $row;
}
$availableBalance = round((float) $snapshot['available_balance'], 2);
$currentBalance = $snapshot['account_balance'] === null
? $availableBalance
$snapshotAvailable = round((float) $snapshot['available_balance'], 2);
$snapshotCurrent = $snapshot['account_balance'] === null
? $snapshotAvailable
: round((float) $snapshot['account_balance'], 2);
$adjustment = $adjustments[(string) ($row['account_short'] ?? '')] ?? [
'income' => 0.0,
'expense' => 0.0,
];
$netAdjustment = round((float) $adjustment['income'] - (float) $adjustment['expense'], 2);
$availableBalance = round($snapshotAvailable + $netAdjustment, 2);
$currentBalance = round($snapshotCurrent + $netAdjustment, 2);
return array_merge($row, [
'current_balance' => $currentBalance,
'available_balance' => $availableBalance,
'blocked_balance' => round(max(0.0, $currentBalance - $availableBalance), 2),
'bank_direct_snapshot_balance' => $snapshotCurrent,
'bank_direct_snapshot_available' => $snapshotAvailable,
'post_snapshot_income' => round((float) $adjustment['income'], 2),
'post_snapshot_expense' => round((float) $adjustment['expense'], 2),
'bank_direct_balance_date' => $snapshot['balance_date'],
'bank_direct_balance_at' => $snapshot['balance_at'],
]);
});
}
/**
* 计入直连余额日期之后的全部动账;同一余额日期只计入快照导入后新增的记录,
* 兼容导入当天盘中余额的情况,避免重复计算快照已经包含的流水。
*
* @param Collection<int,array<string,mixed>> $rows
* @param array<int,array<string,mixed>> $snapshots
* @return array<string,array{income:float,expense:float}>
*/
private function directSnapshotAdjustments(
Collection $rows,
array $snapshots,
string $asOfDate,
): array {
$snapshotByAccount = [];
foreach ($rows as $row) {
$snapshot = $snapshots[(int) ($row['id'] ?? 0)] ?? null;
$accountShort = trim((string) ($row['account_short'] ?? ''));
if ($snapshot !== null && $accountShort !== '') {
$snapshotByAccount[$accountShort] = $snapshot;
}
}
if ($snapshotByAccount === []) {
return [];
}
$minimumDate = collect($snapshotByAccount)
->pluck('balance_date')
->filter()
->min();
if (! is_string($minimumDate) || $minimumDate === '') {
return [];
}
$mapping = $this->db()->table('fin_account_map')
->get(['source', 'source_value', 'account_short'])
->keyBy(static fn (object $row): string => $row->source . "\0" . $row->source_value);
$adjustments = [];
$transactions = $this->db()->table('fin_transactions')
->whereNull('deleted_at')
->whereBetween('txn_date', [$minimumDate, $asOfDate])
->orderBy('txn_date')
->orderBy('id')
->get([
'txn_date',
'account_short',
'source',
'source_value',
'income',
'expense',
'synced_at',
'created_at',
]);
foreach ($transactions as $transaction) {
$mapKey = (string) $transaction->source . "\0" . (string) $transaction->source_value;
$accountShort = trim((string) (
$mapping->get($mapKey)->account_short
?? $transaction->account_short
?? ''
));
$snapshot = $snapshotByAccount[$accountShort] ?? null;
if ($snapshot === null) {
continue;
}
$transactionDate = substr((string) $transaction->txn_date, 0, 10);
if ($transactionDate < (string) $snapshot['balance_date']) {
continue;
}
if ($transactionDate === (string) $snapshot['balance_date']) {
$snapshotImportedAt = trim((string) (
$snapshot['imported_at']
?? $snapshot['balance_at']
?? ''
));
$snapshotIsFinalPriorDayBalance = substr($snapshotImportedAt, 0, 10)
> (string) $snapshot['balance_date'];
if ($snapshotIsFinalPriorDayBalance) {
continue;
}
$recordedAt = trim((string) (
$transaction->synced_at
?? $transaction->created_at
?? ''
));
if ($recordedAt !== '' && $snapshotImportedAt !== '' && $recordedAt <= $snapshotImportedAt) {
continue;
}
}
$adjustments[$accountShort] ??= ['income' => 0.0, 'expense' => 0.0];
$adjustments[$accountShort]['income'] += (float) $transaction->income;
$adjustments[$accountShort]['expense'] += (float) $transaction->expense;
}
foreach ($adjustments as &$adjustment) {
$adjustment['income'] = round($adjustment['income'], 2);
$adjustment['expense'] = round($adjustment['expense'], 2);
}
unset($adjustment);
return $adjustments;
}
/**
* @param Collection<int,array<string,mixed>> $accounts
* @return array<int,string>
@ -1218,16 +1339,33 @@ final class NonStoreAccountMonitorPageData
$directAccountIds,
$period['to'],
);
$directAdjustments = $this->directSnapshotAdjustments(
collect($rows),
$bankDirectBalances,
$period['to'],
);
foreach ($rows as &$row) {
$row = array_merge($row, $metrics[$row['account_short']] ?? []);
$snapshot = $bankDirectBalances[(int) $row['id']] ?? null;
if (($row['is_direct'] ?? false) && $snapshot !== null) {
$row['closing_balance'] = $snapshot['account_balance'] === null
$snapshotBalance = $snapshot['account_balance'] === null
? $snapshot['available_balance']
: $snapshot['account_balance'];
$adjustment = $directAdjustments[(string) ($row['account_short'] ?? '')] ?? [
'income' => 0.0,
'expense' => 0.0,
];
$row['closing_balance'] = round(
(float) $snapshotBalance
+ (float) $adjustment['income']
- (float) $adjustment['expense'],
2,
);
$row['bank_direct_balance_date'] = $snapshot['balance_date'];
$row['bank_direct_balance_at'] = $snapshot['balance_at'];
$row['post_snapshot_income'] = (float) $adjustment['income'];
$row['post_snapshot_expense'] = (float) $adjustment['expense'];
}
}
unset($row);

View File

@ -721,7 +721,7 @@ class NonStoreAccountMonitorTest extends FeatureTestCase
$this->assertStringContainsString('123,456.78', $throughLatestSnapshot);
}
public function test_bank_direct_snapshot_overrides_current_and_available_balances(): void
public function test_previous_day_direct_snapshot_adds_all_next_day_transactions_once(): void
{
$connection = DB::connection('business_mirror');
$accountId = (int) $connection->table('fin_accounts')
@ -735,24 +735,70 @@ class NonStoreAccountMonitorTest extends FeatureTestCase
'account_short' => '保留直连工行',
'company_name' => '保留直连公司',
'currency' => '人民币',
'balance_date' => '2026-11-17',
'balance_at' => '2026-11-17 09:30:00',
'balance_date' => '2026-11-16',
'balance_at' => '2026-11-16 23:59:00',
'account_balance' => 123456.78,
'available_balance' => 120000,
'source' => 'bank-direct',
'source_file_name' => '银行余额.xlsx',
'source_sha256' => str_repeat('b', 64),
'imported_at' => '2026-11-17 10:00:00',
'created_at' => '2026-11-17 10:00:00',
'updated_at' => '2026-11-17 10:00:00',
'imported_at' => '2026-11-17 09:00:00',
'created_at' => '2026-11-17 09:00:00',
'updated_at' => '2026-11-17 09:00:00',
]);
foreach ([
[
'row_key' => hash('sha256', 'direct-before-snapshot'),
'txn_date' => '2026-11-16',
'account_short' => '保留直连工行',
'income' => 0,
'expense' => 2000,
'source' => 'manual',
'source_value' => null,
'created_at' => '2026-11-17 09:30:00',
'updated_at' => '2026-11-17 09:30:00',
],
[
'row_key' => hash('sha256', 'direct-next-day-income'),
'txn_date' => '2026-11-17',
'account_short' => '保留直连工行',
'income' => 2000,
'expense' => 0,
'source' => 'manual',
'source_value' => null,
'created_at' => '2026-11-17 10:15:00',
'updated_at' => '2026-11-17 10:15:00',
],
[
'row_key' => hash('sha256', 'direct-next-day-expense'),
'txn_date' => '2026-11-17',
'account_short' => '保留直连工行',
'income' => 0,
'expense' => 1000,
'source' => 'manual',
'source_value' => null,
'created_at' => '2026-11-17 10:20:00',
'updated_at' => '2026-11-17 10:20:00',
],
] as $transaction) {
$connection->table('fin_transactions')->insert($transaction);
}
$html = $this->loginAs()->get($this->pageUrl())->assertOk()->getContent();
$retainedDialog = $this->dialogHtml($html, 'data-retained-dialog');
$this->assertStringContainsString('123,456.78', $retainedDialog);
$this->assertStringContainsString('120,000.00', $retainedDialog);
$this->assertStringContainsString('124,456.78', $retainedDialog);
$this->assertStringContainsString('121,000.00', $retainedDialog);
$this->assertStringContainsString('3,456.78', $retainedDialog);
$accountArchive = $this->loginAs()->get($this->pageUrl([
'view' => 'accounts',
'keep' => 'retained',
'account_category' => 'bank',
'period_from' => '2026-11-01',
'period_to' => '2026-11-30',
]))->assertOk()->getContent();
$this->assertStringContainsString('124,456.78', $accountArchive);
}
public function test_unretained_tasks_have_a_standalone_processing_page(): void