CaiWuXiTong/modules/EcommerceFinance/Services/FinanceLedgerBankBalanceSynchronizer.php
shanshi e76e87e4db feat(财务台账): 发布银行账单与账户资金管理 (#1385)
发布银行账单、账户资金管理、公司规划分布与余额联动。
2026-11-25 09:14:24 +08:00

217 lines
7.6 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Collection;
final class FinanceLedgerBankBalanceSynchronizer
{
private const BANK_BILL_BANKS = ['招商银行', '华夏银行', '网商银行'];
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $databases)
{
$this->connection = $databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* @param list<int> $accountIds
*/
public function syncAccountIds(array $accountIds, ?string $asOfDate = null): int
{
$accountIds = array_values(array_unique(array_filter(
array_map(static fn (mixed $id): int => (int) $id, $accountIds),
static fn (int $id): bool => $id > 0,
)));
if ($accountIds === []) {
return 0;
}
$accounts = $this->connection->table('fin_accounts')
->whereIn('id', $accountIds)
->get(['id', 'account_short', 'account_no', 'account_type', 'bank_name']);
return $this->syncAccounts($accounts, $asOfDate);
}
/**
* @param list<string> $accountNumbers
*/
public function syncAccountNumbers(array $accountNumbers, ?string $asOfDate = null): int
{
$numbers = array_fill_keys(array_values(array_unique(array_filter(array_map(
fn (mixed $number): string => $this->digits((string) $number),
$accountNumbers,
)))), true);
if ($numbers === []) {
return 0;
}
$accounts = $this->connection->table('fin_accounts')
->whereNotNull('account_no')
->where('account_no', '<>', '')
->get(['id', 'account_short', 'account_no', 'account_type', 'bank_name'])
->filter(static fn (object $account): bool => isset(
$numbers[preg_replace('/\D+/', '', (string) $account->account_no) ?? ''],
))
->values();
return $this->syncAccounts($accounts, $asOfDate);
}
public function syncAll(?string $asOfDate = null): int
{
$accounts = $this->connection->table('fin_accounts')
->whereNotNull('account_no')
->where('account_no', '<>', '')
->get(['id', 'account_short', 'account_no', 'account_type', 'bank_name']);
return $this->syncAccounts($accounts, $asOfDate);
}
/**
* @param Collection<int,object> $accounts
*/
private function syncAccounts(Collection $accounts, ?string $asOfDate): int
{
if ($accounts->isEmpty()) {
return 0;
}
$accountNumbers = $accounts
->map(fn (object $account): string => $this->digits((string) $account->account_no))
->filter()
->unique()
->values()
->all();
if ($accountNumbers === []) {
return 0;
}
$latestBills = [];
if ($this->connection->getSchemaBuilder()->hasTable('fin_bank_direct_bills')) {
$billQuery = $this->connection->table('fin_bank_direct_bills')
->whereIn('bank_name', self::BANK_BILL_BANKS)
->whereIn('account_no', $accountNumbers)
->whereNotNull('balance')
->where('balance', '<>', '');
if ($asOfDate !== null) {
$billQuery->where('txn_date', '<=', $asOfDate);
}
foreach ($billQuery
->orderBy('bank_name')
->orderBy('account_no')
->orderBy('txn_date')
->orderBy('txn_at')
->orderBy('id')
->get(['bank_name', 'account_no', 'txn_date', 'txn_at', 'balance']) as $bill) {
$key = $this->billKey((string) $bill->bank_name, (string) $bill->account_no);
$latestBills[$key] = [
'amount' => round((float) $bill->balance, 2),
'at' => trim((string) $bill->txn_date . ' ' . (string) $bill->txn_at),
];
}
}
$latestSnapshots = [];
if ($this->connection->getSchemaBuilder()->hasTable('fin_bank_direct_balance_snapshots')) {
$snapshotQuery = $this->connection->table('fin_bank_direct_balance_snapshots')
->whereIn('finance_account_id', $accounts->pluck('id')->map(
static fn (mixed $id): int => (int) $id,
)->all());
if ($asOfDate !== null) {
$snapshotQuery->where('balance_date', '<=', $asOfDate);
}
foreach ($snapshotQuery
->orderBy('finance_account_id')
->orderBy('balance_date')
->orderBy('balance_at')
->orderBy('id')
->get([
'finance_account_id',
'account_balance',
'available_balance',
'balance_date',
'balance_at',
]) as $snapshot) {
$latestSnapshots[(int) $snapshot->finance_account_id] = [
'amount' => round((float) (
$snapshot->account_balance ?? $snapshot->available_balance
), 2),
'at' => trim((string) $snapshot->balance_date . ' ' . (string) $snapshot->balance_at),
];
}
}
$updated = 0;
$now = now();
foreach ($accounts as $account) {
$bank = $this->bankForAccount($account);
if ($bank === null) {
continue;
}
$bill = $latestBills[
$this->billKey($bank, (string) $account->account_no)
] ?? null;
$snapshot = $latestSnapshots[(int) $account->id] ?? null;
// 用户口径:有银行账单时,以最后一笔交易后余额为准;快照仅兜底。
$latest = $bill ?? $snapshot;
if ($latest === null) {
continue;
}
$changed = $this->connection->table('fin_accounts')
->where('id', $account->id)
->where(function ($query) use ($latest): void {
$query->whereNull('current_balance')
->orWhereRaw('ABS(current_balance - ?) >= 0.005', [$latest['amount']]);
})
->update([
'current_balance' => $latest['amount'],
'updated_at' => $now,
]);
$updated += $changed;
}
return $updated;
}
private function bankForAccount(object $account): ?string
{
$text = implode(' ', array_filter([
(string) ($account->account_short ?? ''),
(string) ($account->account_type ?? ''),
(string) ($account->bank_name ?? ''),
]));
if (str_contains($text, '网商')) {
return '网商银行';
}
if ((string) ($account->account_type ?? '') === '个人卡') {
return null;
}
if (str_contains($text, '招商') || str_contains($text, '招行')) {
return '招商银行';
}
if (str_contains($text, '华夏')) {
return '华夏银行';
}
return null;
}
private function billKey(string $bank, string $accountNo): string
{
return $bank . '|' . $this->digits($accountNo);
}
private function digits(string $value): string
{
return preg_replace('/\D+/', '', $value) ?? '';
}
}