CaiWuXiTong/modules/EcommerceFinance/Services/FinanceLedgerBankBalanceCurrentCalculator.php

480 lines
19 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
final class FinanceLedgerBankBalanceCurrentCalculator
{
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $databases)
{
$this->connection = $databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* @param list<string> $accountShorts
* @return array<string,float>
*/
public function balances(array $accountShorts, ?string $asOf = null): array
{
$details = $this->balanceDetails($accountShorts, $asOf);
return collect($details)
->map(static fn (array $detail): float => (float) $detail['balance'])
->all();
}
/**
* 计算非银企直连账户余额。
*
* 有阶段性银行账单时,以账单中最后一笔交易后余额为基准,只追加该日期
* 之后的动账;没有账单时,仍按锁定期初和全部动账明细滚动。缺少期初和
* 账单基准的账户不返回结果,避免把缺失期初当作 0。
*
* @param list<string> $accountShorts
* @return array<string,array{
* balance:float,balance_source:string,baseline_date:string,baseline_at:?string,
* baseline_balance:float,bank_name:string,imported_at:mixed,
* post_baseline_income:float,post_baseline_expense:float,movement_count:int
* }>
*/
public function balanceDetails(array $accountShorts, ?string $asOf = null): array
{
$accountShorts = $this->normalizeAccountShorts($accountShorts);
if ($accountShorts === []) {
return [];
}
$openingRows = $this->connection->table('fin_account_opening')
->whereIn('account_short', $accountShorts)
->when($asOf !== null, fn ($query) => $query->where('opening_date', '<=', $asOf))
->orderBy('opening_date')
->orderBy('id')
->get(['account_short', 'opening_date', 'opening_balance'])
->groupBy('account_short')
->map(static fn ($rows) => $rows->last());
$bankBillBaselines = $this->latestMonthlyBankBillBaselines($accountShorts, $asOf);
$details = [];
foreach ($accountShorts as $accountShort) {
$bill = $bankBillBaselines[$accountShort] ?? null;
$opening = $openingRows->get($accountShort);
if ($bill === null && $opening === null) {
continue;
}
$details[$accountShort] = $bill !== null
? [
'balance' => round((float) $bill['balance'], 2),
'balance_source' => 'bank_bill_plus_transactions',
'baseline_date' => (string) $bill['txn_date'],
'baseline_at' => $bill['txn_at'] !== null ? (string) $bill['txn_at'] : null,
'baseline_balance' => round((float) $bill['balance'], 2),
'bank_name' => (string) $bill['bank_name'],
'imported_at' => $bill['imported_at'],
'post_baseline_income' => 0.0,
'post_baseline_expense' => 0.0,
'movement_count' => 0,
]
: [
'balance' => round((float) $opening->opening_balance, 2),
'balance_source' => 'transactions',
'baseline_date' => substr((string) $opening->opening_date, 0, 10),
'baseline_at' => null,
'baseline_balance' => round((float) $opening->opening_balance, 2),
'bank_name' => '',
'imported_at' => null,
'post_baseline_income' => 0.0,
'post_baseline_expense' => 0.0,
'movement_count' => 0,
];
}
if ($details === []) {
return [];
}
$mappings = $this->connection->table('fin_account_map')
->whereIn('account_short', $accountShorts)
->get(['source', 'source_value', 'account_short']);
$mappingByKey = $mappings->keyBy(
static fn (object $row): string => (string) $row->source . "\0" . (string) $row->source_value,
);
$earliestStart = min(array_column($details, 'baseline_date'));
$transactionQuery = $this->connection->table('fin_transactions')
->whereNull('deleted_at')
->where('txn_date', '>=', $earliestStart)
->where(function ($query) use ($accountShorts, $mappings): void {
$query->whereIn('account_short', $accountShorts);
foreach ($mappings as $mapping) {
$query->orWhere(function ($pair) use ($mapping): void {
$pair->where('source', (string) $mapping->source)
->where('source_value', (string) $mapping->source_value);
});
}
});
if ($asOf !== null && preg_match('/^\d{4}-\d{2}-\d{2}$/', $asOf) === 1) {
$transactionQuery->whereDate('txn_date', '<=', $asOf);
}
$transactions = $transactionQuery
->orderBy('txn_date')
->orderBy('id')
->get(['txn_date', 'account_short', 'source', 'source_value', 'income', 'expense']);
foreach ($transactions as $transaction) {
$mappingKey = (string) $transaction->source . "\0" . (string) $transaction->source_value;
$accountShort = (string) (
$mappingByKey->get($mappingKey)?->account_short
?? $transaction->account_short
?? ''
);
if (! array_key_exists($accountShort, $details)) {
continue;
}
$date = substr((string) $transaction->txn_date, 0, 10);
$detail = $details[$accountShort];
if ($detail['balance_source'] === 'bank_bill_plus_transactions'
&& $date <= $detail['baseline_date']) {
continue;
}
if ($detail['balance_source'] === 'transactions'
&& $date < $detail['baseline_date']) {
continue;
}
$income = round((float) $transaction->income, 2);
$expense = round((float) $transaction->expense, 2);
$details[$accountShort]['balance'] = round(
$details[$accountShort]['balance']
+ $income
- $expense,
2,
);
$details[$accountShort]['post_baseline_income'] = round(
$details[$accountShort]['post_baseline_income'] + $income,
2,
);
$details[$accountShort]['post_baseline_expense'] = round(
$details[$accountShort]['post_baseline_expense'] + $expense,
2,
);
$details[$accountShort]['movement_count']++;
}
return $details;
}
/**
* @param list<string> $accountShorts
* @return array<string,array{
* bank_name:string,txn_date:string,txn_at:?string,balance:float,imported_at:mixed
* }>
*/
private function latestMonthlyBankBillBaselines(array $accountShorts, ?string $asOf): array
{
if (! $this->connection->getSchemaBuilder()->hasTable('fin_bank_direct_bills')) {
return [];
}
$accounts = $this->connection->table('fin_accounts')
->whereIn('account_short', $accountShorts)
->get(['id', 'account_short', 'account_no']);
$shortById = [];
$shortByNumber = [];
foreach ($accounts as $account) {
$accountShort = trim((string) $account->account_short);
if ($accountShort === '') {
continue;
}
$shortById[(int) $account->id] = $accountShort;
$number = preg_replace('/\D+/', '', (string) ($account->account_no ?? '')) ?? '';
if ($number !== '') {
$shortByNumber[$number] = $accountShort;
}
}
$query = $this->connection->table('fin_bank_direct_bills')
->where('source', 'bank-monthly')
->whereNotNull('balance')
->where('balance', '<>', '')
->where(function ($scope) use ($accountShorts, $shortById, $shortByNumber): void {
$scope->whereIn('account_short', $accountShorts);
if ($shortById !== []) {
$scope->orWhereIn('finance_account_id', array_keys($shortById));
}
if ($shortByNumber !== []) {
$scope->orWhereIn('account_no', array_keys($shortByNumber));
}
});
if ($asOf !== null && preg_match('/^\d{4}-\d{2}-\d{2}$/', $asOf) === 1) {
$query->where('txn_date', '<=', $asOf);
}
$baselines = [];
foreach ($query
->orderBy('txn_date')
->orderBy('txn_at')
->orderBy('id')
->get([
'finance_account_id',
'account_short',
'account_no',
'bank_name',
'txn_date',
'txn_at',
'balance',
'imported_at',
]) as $bill) {
$number = preg_replace('/\D+/', '', (string) ($bill->account_no ?? '')) ?? '';
$accountShort = $shortById[(int) ($bill->finance_account_id ?? 0)]
?? $shortByNumber[$number]
?? trim((string) ($bill->account_short ?? ''));
if ($accountShort === '' || ! in_array($accountShort, $accountShorts, true)) {
continue;
}
$baselines[$accountShort] = [
'bank_name' => trim((string) $bill->bank_name),
'txn_date' => substr((string) $bill->txn_date, 0, 10),
'txn_at' => $bill->txn_at !== null ? (string) $bill->txn_at : null,
'balance' => round((float) $bill->balance, 2),
'imported_at' => $bill->imported_at,
];
}
return $baselines;
}
/**
* 计算指定日期的净动账。
*
* @param list<string> $accountShorts
* @return array<string,float>
*/
public function movementsOnDate(array $accountShorts, string $date): array
{
$accountShorts = $this->normalizeAccountShorts($accountShorts);
if ($accountShorts === [] || preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) {
return [];
}
$mappings = $this->connection->table('fin_account_map')
->whereIn('account_short', $accountShorts)
->get(['source', 'source_value', 'account_short']);
$mappingByKey = $mappings->keyBy(
static fn (object $row): string => (string) $row->source . "\0" . (string) $row->source_value,
);
$transactionQuery = $this->connection->table('fin_transactions')
->whereNull('deleted_at')
->where('txn_date', $date)
->where(function ($query) use ($accountShorts, $mappings): void {
$query->whereIn('account_short', $accountShorts);
foreach ($mappings as $mapping) {
$query->orWhere(function ($pair) use ($mapping): void {
$pair->where('source', (string) $mapping->source)
->where('source_value', (string) $mapping->source_value);
});
}
});
$transactions = $transactionQuery
->orderBy('txn_date')
->orderBy('id')
->get(['txn_date', 'account_short', 'source', 'source_value', 'income', 'expense']);
$movements = array_fill_keys($accountShorts, 0.0);
foreach ($transactions as $transaction) {
$mappingKey = (string) $transaction->source . "\0" . (string) $transaction->source_value;
$accountShort = (string) (
$mappingByKey->get($mappingKey)?->account_short
?? $transaction->account_short
?? ''
);
if (! array_key_exists($accountShort, $movements)) {
continue;
}
$movements[$accountShort] = round(
$movements[$accountShort]
+ (float) $transaction->income
- (float) $transaction->expense,
2,
);
}
return $movements;
}
/**
* 按期初和当日逐笔动账计算非银企直连账户的交易后余额。
* 有当天每日流水时以每日流水期初为准;缺少日流水的日期从最近一次
* 账户期初开始滚到当前交易。同一账户同一天按交易 ID 顺序滚动。
*
* @param iterable<object> $rows
* @param array<string,true> $excludedAccountShorts
* @return array<int,float>
*/
public function runningBalancesForTransactions(
iterable $rows,
array $excludedAccountShorts = [],
): array {
$targets = [];
$accountShorts = [];
$dates = [];
foreach ($rows as $row) {
$id = (int) ($row->id ?? 0);
$accountShort = trim((string) (
$row->effective_account_short
?? $row->account_short
?? ''
));
$date = substr((string) ($row->txn_date ?? ''), 0, 10);
if (
$id <= 0
|| $accountShort === ''
|| $date === ''
|| isset($excludedAccountShorts[$accountShort])
) {
continue;
}
$targets[$id] = [
'account_short' => $accountShort,
'date' => $date,
];
$accountShorts[$accountShort] = true;
$dates[$date] = true;
}
$accountShorts = array_keys($accountShorts);
$dates = array_keys($dates);
if ($targets === [] || $accountShorts === [] || $dates === []) {
return [];
}
$maxDate = max($dates);
$openingRows = $this->connection->table('fin_account_opening')
->whereIn('account_short', $accountShorts)
->where('opening_date', '<=', $maxDate)
->orderBy('opening_date')
->orderBy('id')
->get(['account_short', 'opening_date', 'opening_balance']);
$markersByAccount = [];
foreach ($openingRows as $opening) {
$accountShort = (string) $opening->account_short;
$date = substr((string) $opening->opening_date, 0, 10);
if ($date !== '') {
$markersByAccount[$accountShort][$date] = [
'date' => $date,
'balance' => round((float) $opening->opening_balance, 2),
];
}
}
$mappings = $this->connection->table('fin_account_map')
->whereIn('account_short', $accountShorts)
->get(['source', 'source_value', 'account_short']);
$mappingByKey = $mappings->keyBy(
static fn (object $row): string => (string) $row->source . "\0" . (string) $row->source_value,
);
$dailyOpenings = $this->connection->table('fin_daily_flows')
->whereIn('account_short', $accountShorts)
->whereIn('flow_date', $dates)
->orderBy('flow_date')
->orderBy('id')
->get(['account_short', 'flow_date', 'opening_balance']);
foreach ($dailyOpenings as $opening) {
$date = substr((string) $opening->flow_date, 0, 10);
if ($date !== '') {
$markersByAccount[(string) $opening->account_short][$date] = [
'date' => $date,
'balance' => round((float) $opening->opening_balance, 2),
];
}
}
foreach ($markersByAccount as &$markers) {
$markers = array_values($markers);
}
unset($markers);
if ($markersByAccount === []) {
return [];
}
$earliestStart = min(array_map(
static fn (array $markers): string => (string) $markers[0]['date'],
$markersByAccount,
));
$transactions = $this->connection->table('fin_transactions')
->whereNull('deleted_at')
->where('txn_date', '>=', $earliestStart)
->whereDate('txn_date', '<=', $maxDate)
->where(function ($query) use ($accountShorts, $mappings): void {
$query->whereIn('account_short', $accountShorts);
foreach ($mappings as $mapping) {
$query->orWhere(function ($pair) use ($mapping): void {
$pair->where('source', (string) $mapping->source)
->where('source_value', (string) $mapping->source_value);
});
}
})
->orderBy('txn_date')
->orderBy('id')
->get(['id', 'txn_date', 'account_short', 'source', 'source_value', 'income', 'expense']);
$running = [];
$markerIndexes = [];
$result = [];
foreach ($transactions as $transaction) {
$mappingKey = (string) $transaction->source . "\0" . (string) $transaction->source_value;
$accountShort = (string) (
$mappingByKey->get($mappingKey)?->account_short
?? $transaction->account_short
?? ''
);
$date = substr((string) $transaction->txn_date, 0, 10);
$markers = $markersByAccount[$accountShort] ?? null;
if ($markers === null) {
continue;
}
$markerIndex = $markerIndexes[$accountShort] ?? -1;
while (isset($markers[$markerIndex + 1])
&& $markers[$markerIndex + 1]['date'] <= $date) {
$markerIndex++;
$running[$accountShort] = (float) $markers[$markerIndex]['balance'];
}
$markerIndexes[$accountShort] = $markerIndex;
if ($markerIndex < 0 || $date < $markers[$markerIndex]['date']) {
continue;
}
$running[$accountShort] = round(
$running[$accountShort]
+ (float) $transaction->income
- (float) $transaction->expense,
2,
);
$id = (int) $transaction->id;
$target = $targets[$id] ?? null;
if (
$target !== null
&& $target['account_short'] === $accountShort
&& $target['date'] === $date
) {
$result[$id] = $running[$accountShort];
}
}
return $result;
}
/** @return list<string> */
private function normalizeAccountShorts(array $accountShorts): array
{
return array_values(array_unique(array_filter(array_map(
static fn (mixed $accountShort): string => trim((string) $accountShort),
$accountShorts,
))));
}
}