CaiWuXiTong/modules/EcommerceFinance/Services/FinanceLedgerDetachedAccountBalanceSynchronizer.php

65 lines
2.0 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use App\Utilities\FinanceLedgerIndependentAccounts;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
class FinanceLedgerDetachedAccountBalanceSynchronizer
{
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $databases)
{
$this->connection = $databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
public function sync(mixed $accountShort): ?float
{
$accountShort = trim((string) $accountShort);
if (! FinanceLedgerIndependentAccounts::usesDetachedTransactions($accountShort)) {
return null;
}
$rows = $this->connection->table(
FinanceLedgerIndependentAccounts::DETACHED_TRANSACTION_TABLE,
)
->where('account_short', $accountShort)
->whereNull('deleted_at');
$latest = (clone $rows)
->whereNotNull('balance')
->orderByDesc('txn_date')
->orderByRaw('COALESCE(display_order, id) DESC')
->orderByDesc('id')
->value('balance');
if ($latest !== null) {
$balance = round((float) $latest, 2);
} else {
$opening = $this->connection->table('fin_account_opening')
->where('account_short', $accountShort)
->orderByDesc('opening_date')
->orderByDesc('id')
->value('opening_balance');
$balance = round(
(float) ($opening ?? 0)
+ (float) (clone $rows)->sum('income')
- (float) (clone $rows)->sum('expense'),
2,
);
}
$this->connection->table('fin_accounts')
->where('account_short', $accountShort)
->update([
'current_balance' => $balance,
'updated_at' => now(),
]);
return $balance;
}
}