334 lines
13 KiB
PHP
334 lines
13 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'),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 按账户期初和未删除动账明细计算滚动余额。
|
|
* 该计算不读取 fin_accounts.current_balance 或 fin_daily_flows。
|
|
* 没有实际期初的账户不返回余额,避免把缺失期初当成 0 后推算金额。
|
|
*
|
|
* @param list<string> $accountShorts
|
|
* @return array<string,float>
|
|
*/
|
|
public function balances(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());
|
|
if ($openingRows->isEmpty()) {
|
|
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,
|
|
);
|
|
$balances = [];
|
|
$starts = [];
|
|
foreach ($openingRows as $accountShort => $opening) {
|
|
$balances[(string) $accountShort] = round((float) $opening->opening_balance, 2);
|
|
$starts[(string) $accountShort] = substr((string) $opening->opening_date, 0, 10);
|
|
}
|
|
$earliestStart = min($starts);
|
|
|
|
$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, $balances)) {
|
|
continue;
|
|
}
|
|
$date = substr((string) $transaction->txn_date, 0, 10);
|
|
if ($date < $starts[$accountShort]) {
|
|
continue;
|
|
}
|
|
|
|
$balances[$accountShort] = round(
|
|
$balances[$accountShort]
|
|
+ (float) $transaction->income
|
|
- (float) $transaction->expense,
|
|
2,
|
|
);
|
|
}
|
|
|
|
return $balances;
|
|
}
|
|
|
|
/**
|
|
* 计算指定日期的净动账。
|
|
*
|
|
* @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,
|
|
))));
|
|
}
|
|
}
|