Rearrange some code.

This commit is contained in:
James Cole
2025-09-26 05:33:35 +02:00
parent 66d09450d3
commit 08879d31ba
19 changed files with 407 additions and 416 deletions

View File

@@ -44,10 +44,10 @@ class AccountBalanceGrouped
private readonly ExchangeRateConverter $converter;
private array $currencies = [];
private array $data = [];
private TransactionCurrency $primary;
private Carbon $end;
private array $journals = [];
private string $preferredRange;
private TransactionCurrency $primary;
private Carbon $start;
public function __construct()
@@ -67,7 +67,7 @@ class AccountBalanceGrouped
/** @var array $currency */
foreach ($this->data as $currency) {
// income and expense array prepped:
$income = [
$income = [
'label' => 'earned',
'currency_id' => (string)$currency['currency_id'],
'currency_symbol' => $currency['currency_symbol'],
@@ -86,7 +86,7 @@ class AccountBalanceGrouped
'entries' => [],
'pc_entries' => [],
];
$expense = [
$expense = [
'label' => 'spent',
'currency_id' => (string)$currency['currency_id'],
'currency_symbol' => $currency['currency_symbol'],
@@ -108,22 +108,22 @@ class AccountBalanceGrouped
// loop all possible periods between $start and $end, and add them to the correct dataset.
$currentStart = clone $this->start;
while ($currentStart <= $this->end) {
$key = $currentStart->format($this->carbonFormat);
$label = $currentStart->toAtomString();
$key = $currentStart->format($this->carbonFormat);
$label = $currentStart->toAtomString();
// normal entries
$income['entries'][$label] = Steam::bcround($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']);
$expense['entries'][$label] = Steam::bcround($currency[$key]['spent'] ?? '0', $currency['currency_decimal_places']);
$income['entries'][$label] = Steam::bcround($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']);
$expense['entries'][$label] = Steam::bcround($currency[$key]['spent'] ?? '0', $currency['currency_decimal_places']);
// converted entries
$income['pc_entries'][$label] = Steam::bcround($currency[$key]['pc_earned'] ?? '0', $currency['primary_currency_decimal_places']);
$expense['pc_entries'][$label] = Steam::bcround($currency[$key]['pc_spent'] ?? '0', $currency['primary_currency_decimal_places']);
// next loop
$currentStart = Navigation::addPeriod($currentStart, $this->preferredRange, 0);
$currentStart = Navigation::addPeriod($currentStart, $this->preferredRange, 0);
}
$chartData[] = $income;
$chartData[] = $expense;
$chartData[] = $income;
$chartData[] = $expense;
}
return $chartData;
@@ -149,9 +149,9 @@ class AccountBalanceGrouped
private function processJournal(array $journal): void
{
// format the date according to the period
$period = $journal['date']->format($this->carbonFormat);
$currencyId = (int)$journal['currency_id'];
$currency = $this->findCurrency($currencyId);
$period = $journal['date']->format($this->carbonFormat);
$currencyId = (int)$journal['currency_id'];
$currency = $this->findCurrency($currencyId);
// set the array with monetary info, if it does not exist.
$this->createDefaultDataEntry($journal);
@@ -159,12 +159,12 @@ class AccountBalanceGrouped
$this->createDefaultPeriodEntry($journal);
// is this journal's amount in- our outgoing?
$key = $this->getDataKey($journal);
$amount = 'spent' === $key ? Steam::negative($journal['amount']) : Steam::positive($journal['amount']);
$key = $this->getDataKey($journal);
$amount = 'spent' === $key ? Steam::negative($journal['amount']) : Steam::positive($journal['amount']);
// get conversion rate
$rate = $this->getRate($currency, $journal['date']);
$amountConverted = bcmul($amount, $rate);
$rate = $this->getRate($currency, $journal['date']);
$amountConverted = bcmul($amount, $rate);
// perhaps transaction already has the foreign amount in the primary currency.
if ((int)$journal['foreign_currency_id'] === $this->primary->id) {
@@ -173,7 +173,7 @@ class AccountBalanceGrouped
}
// add normal entry
$this->data[$currencyId][$period][$key] = bcadd((string)$this->data[$currencyId][$period][$key], $amount);
$this->data[$currencyId][$period][$key] = bcadd((string)$this->data[$currencyId][$period][$key], $amount);
// add converted entry
$convertedKey = sprintf('pc_%s', $key);
@@ -192,7 +192,7 @@ class AccountBalanceGrouped
private function createDefaultDataEntry(array $journal): void
{
$currencyId = (int)$journal['currency_id'];
$currencyId = (int)$journal['currency_id'];
$this->data[$currencyId] ??= [
'currency_id' => (string)$currencyId,
'currency_symbol' => $journal['currency_symbol'],
@@ -209,8 +209,8 @@ class AccountBalanceGrouped
private function createDefaultPeriodEntry(array $journal): void
{
$currencyId = (int)$journal['currency_id'];
$period = $journal['date']->format($this->carbonFormat);
$currencyId = (int)$journal['currency_id'];
$period = $journal['date']->format($this->carbonFormat);
$this->data[$currencyId][$period] ??= [
'period' => $period,
'spent' => '0',
@@ -259,6 +259,22 @@ class AccountBalanceGrouped
$this->accountIds = $accounts->pluck('id')->toArray();
}
public function setEnd(Carbon $end): void
{
$this->end = $end;
}
public function setJournals(array $journals): void
{
$this->journals = $journals;
}
public function setPreferredRange(string $preferredRange): void
{
$this->preferredRange = $preferredRange;
$this->carbonFormat = Navigation::preferredCarbonFormatByPeriod($preferredRange);
}
public function setPrimary(TransactionCurrency $primary): void
{
$this->primary = $primary;
@@ -278,22 +294,6 @@ class AccountBalanceGrouped
];
}
public function setEnd(Carbon $end): void
{
$this->end = $end;
}
public function setJournals(array $journals): void
{
$this->journals = $journals;
}
public function setPreferredRange(string $preferredRange): void
{
$this->preferredRange = $preferredRange;
$this->carbonFormat = Navigation::preferredCarbonFormatByPeriod($preferredRange);
}
public function setStart(Carbon $start): void
{
$this->start = $start;

View File

@@ -43,7 +43,7 @@ trait CleansChartData
$return = [];
/**
* @var int $index
* @var int $index
* @var array $array
*/
foreach ($data as $index => $array) {

View File

@@ -39,7 +39,7 @@ trait CollectsAccountsFromFilter
// always collect from the query parameter, even when it's empty.
if (null !== $queryParameters['accounts']) {
foreach ($queryParameters['accounts'] as $accountId) {
$account = $this->repository->find((int) $accountId);
$account = $this->repository->find((int)$accountId);
if (null !== $account) {
$collection->push($account);
}

View File

@@ -99,8 +99,8 @@ class ExchangeRateConverter
*/
private function getRate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): string
{
$key = $this->getCacheKey($from, $to, $date);
$res = Cache::get($key, null);
$key = $this->getCacheKey($from, $to, $date);
$res = Cache::get($key, null);
// find in cache
if (null !== $res) {
@@ -110,7 +110,7 @@ class ExchangeRateConverter
}
// find in database
$rate = $this->getFromDB($from->id, $to->id, $date->format('Y-m-d'));
$rate = $this->getFromDB($from->id, $to->id, $date->format('Y-m-d'));
if (null !== $rate) {
Cache::forever($key, $rate);
Log::debug(sprintf('ExchangeRateConverter: Return DB rate from %s to %s on %s.', $from->code, $to->code, $date->format('Y-m-d')));
@@ -119,7 +119,7 @@ class ExchangeRateConverter
}
// find reverse in database
$rate = $this->getFromDB($to->id, $from->id, $date->format('Y-m-d'));
$rate = $this->getFromDB($to->id, $from->id, $date->format('Y-m-d'));
if (null !== $rate) {
$rate = bcdiv('1', $rate);
Cache::forever($key, $rate);
@@ -159,7 +159,7 @@ class ExchangeRateConverter
return '1';
}
$key = sprintf('cer-%d-%d-%s', $from, $to, $date);
$key = sprintf('cer-%d-%d-%s', $from, $to, $date);
// perhaps the rate has been cached during this particular run
$preparedRate = $this->prepared[$date][$from][$to] ?? null;
@@ -169,7 +169,7 @@ class ExchangeRateConverter
return $preparedRate;
}
$cache = new CacheProperties();
$cache = new CacheProperties();
$cache->addProperty($key);
if ($cache->has()) {
$rate = $cache->get();
@@ -182,15 +182,14 @@ class ExchangeRateConverter
}
/** @var null|CurrencyExchangeRate $result */
$result = $this->userGroup->currencyExchangeRates()
->where('from_currency_id', $from)
->where('to_currency_id', $to)
->where('date', '<=', $date)
->orderBy('date', 'DESC')
->first()
;
$result = $this->userGroup->currencyExchangeRates()
->where('from_currency_id', $from)
->where('to_currency_id', $to)
->where('date', '<=', $date)
->orderBy('date', 'DESC')
->first();
++$this->queryCount;
$rate = (string) $result?->rate;
$rate = (string)$result?->rate;
if ('' === $rate) {
app('log')->debug(sprintf('ExchangeRateConverter: Found no rate for #%d->#%d (%s) in the DB.', $from, $to, $date));
@@ -230,13 +229,13 @@ class ExchangeRateConverter
if ($euroId === $currency->id) {
return '1';
}
$rate = $this->getFromDB($currency->id, $euroId, $date->format('Y-m-d'));
$rate = $this->getFromDB($currency->id, $euroId, $date->format('Y-m-d'));
if (null !== $rate) {
// app('log')->debug(sprintf('Rate for %s to EUR is %s.', $currency->code, $rate));
return $rate;
}
$rate = $this->getFromDB($euroId, $currency->id, $date->format('Y-m-d'));
$rate = $this->getFromDB($euroId, $currency->id, $date->format('Y-m-d'));
if (null !== $rate) {
return bcdiv('1', $rate);
// app('log')->debug(sprintf('Inverted rate for %s to EUR is %s.', $currency->code, $rate));
@@ -245,7 +244,7 @@ class ExchangeRateConverter
// grab backup values from config file:
$backup = config(sprintf('cer.rates.%s', $currency->code));
if (null !== $backup) {
return bcdiv('1', (string) $backup);
return bcdiv('1', (string)$backup);
// app('log')->debug(sprintf('Backup rate for %s to EUR is %s.', $currency->code, $backup));
// return $backup;
}
@@ -263,9 +262,9 @@ class ExchangeRateConverter
$cache = new CacheProperties();
$cache->addProperty('cer-euro-id');
if ($cache->has()) {
return (int) $cache->get();
return (int)$cache->get();
}
$euro = Amount::getTransactionCurrencyByCode('EUR');
$euro = Amount::getTransactionCurrencyByCode('EUR');
++$this->queryCount;
$cache->store($euro->id);

View File

@@ -31,7 +31,7 @@ use Illuminate\Support\Facades\Log;
class SummaryBalanceGrouped
{
private const string SUM = 'sum';
private const string SUM = 'sum';
private array $amounts = [];
private array $currencies;
private readonly CurrencyRepositoryInterface $currencyRepository;
@@ -48,9 +48,9 @@ class SummaryBalanceGrouped
public function groupData(): array
{
Log::debug('Now going to group data.');
$return = [];
$return = [];
foreach ($this->keys as $key) {
$title = match ($key) {
$title = match ($key) {
'sum' => 'balance',
'expense' => 'spent',
'income' => 'earned',
@@ -60,7 +60,7 @@ class SummaryBalanceGrouped
$return[] = [
'key' => sprintf('%s-in-pc', $title),
'value' => $this->amounts[$key]['primary'] ?? '0',
'currency_id' => (string) $this->default->id,
'currency_id' => (string)$this->default->id,
'currency_code' => $this->default->code,
'currency_symbol' => $this->default->symbol,
'currency_decimal_places' => $this->default->decimal_places,
@@ -73,7 +73,7 @@ class SummaryBalanceGrouped
// skip primary entries.
continue;
}
$currencyId = (int) $currencyId;
$currencyId = (int)$currencyId;
$currency = $this->currencies[$currencyId] ?? $this->currencyRepository->find($currencyId);
$this->currencies[$currencyId] = $currency;
// create objects for big array.
@@ -87,7 +87,7 @@ class SummaryBalanceGrouped
$return[] = [
'key' => sprintf('%s-in-%s', $title, $currency->code),
'value' => $this->amounts[$key][$currencyId] ?? '0',
'currency_id' => (string) $currency->id,
'currency_id' => (string)$currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,
@@ -109,12 +109,12 @@ class SummaryBalanceGrouped
/** @var array $journal */
foreach ($journals as $journal) {
// transaction info:
$currencyId = (int) $journal['currency_id'];
$amount = bcmul((string) $journal['amount'], $multiplier);
$currency = $this->currencies[$currencyId] ?? Amount::getTransactionCurrencyById($currencyId);
$this->currencies[$currencyId] = $currency;
$pcAmount = $converter->convert($currency, $this->default, $journal['date'], $amount);
if ((int) $journal['foreign_currency_id'] === $this->default->id) {
$currencyId = (int)$journal['currency_id'];
$amount = bcmul((string)$journal['amount'], $multiplier);
$currency = $this->currencies[$currencyId] ?? Amount::getTransactionCurrencyById($currencyId);
$this->currencies[$currencyId] = $currency;
$pcAmount = $converter->convert($currency, $this->default, $journal['date'], $amount);
if ((int)$journal['foreign_currency_id'] === $this->default->id) {
// use foreign amount instead
$pcAmount = $journal['foreign_amount'];
}
@@ -126,10 +126,10 @@ class SummaryBalanceGrouped
$this->amounts[self::SUM]['primary'] ??= '0';
// add values:
$this->amounts[$key][$currencyId] = bcadd((string) $this->amounts[$key][$currencyId], $amount);
$this->amounts[self::SUM][$currencyId] = bcadd((string) $this->amounts[self::SUM][$currencyId], $amount);
$this->amounts[$key]['primary'] = bcadd((string) $this->amounts[$key]['primary'], (string) $pcAmount);
$this->amounts[self::SUM]['primary'] = bcadd((string) $this->amounts[self::SUM]['primary'], (string) $pcAmount);
$this->amounts[$key][$currencyId] = bcadd((string)$this->amounts[$key][$currencyId], $amount);
$this->amounts[self::SUM][$currencyId] = bcadd((string)$this->amounts[self::SUM][$currencyId], $amount);
$this->amounts[$key]['primary'] = bcadd((string)$this->amounts[$key]['primary'], (string)$pcAmount);
$this->amounts[self::SUM]['primary'] = bcadd((string)$this->amounts[self::SUM]['primary'], (string)$pcAmount);
}
$converter->summarize();
}

View File

@@ -38,8 +38,8 @@ use Illuminate\Support\Facades\Log;
*/
trait ValidatesUserGroupTrait
{
protected User $user;
protected UserGroup $userGroup;
protected User $user;
/**
* An "undocumented" filter
@@ -59,41 +59,41 @@ trait ValidatesUserGroupTrait
}
/** @var User $user */
$user = auth()->user();
$groupId = 0;
$user = auth()->user();
$groupId = 0;
if (!$request->has('user_group_id')) {
$groupId = (int) $user->user_group_id;
$groupId = (int)$user->user_group_id;
Log::debug(sprintf('validateUserGroup: no user group submitted, use default group #%d.', $groupId));
}
if ($request->has('user_group_id')) {
$groupId = (int) $request->get('user_group_id');
$groupId = (int)$request->get('user_group_id');
Log::debug(sprintf('validateUserGroup: user group submitted, search for memberships in group #%d.', $groupId));
}
/** @var UserGroupRepositoryInterface $repository */
$repository = app(UserGroupRepositoryInterface::class);
$repository = app(UserGroupRepositoryInterface::class);
$repository->setUser($user);
$memberships = $repository->getMembershipsFromGroupId($groupId);
if (0 === $memberships->count()) {
Log::debug(sprintf('validateUserGroup: user has no access to group #%d.', $groupId));
throw new AuthorizationException((string) trans('validation.no_access_group'));
throw new AuthorizationException((string)trans('validation.no_access_group'));
}
// need to get the group from the membership:
$group = $repository->getById($groupId);
$group = $repository->getById($groupId);
if (null === $group) {
Log::debug(sprintf('validateUserGroup: group #%d does not exist.', $groupId));
throw new AuthorizationException((string) trans('validation.belongs_user_or_user_group'));
throw new AuthorizationException((string)trans('validation.belongs_user_or_user_group'));
}
Log::debug(sprintf('validateUserGroup: validate access of user to group #%d ("%s").', $groupId, $group->title));
$roles = property_exists($this, 'acceptedRoles') ? $this->acceptedRoles : []; // @phpstan-ignore-line
$roles = property_exists($this, 'acceptedRoles') ? $this->acceptedRoles : []; // @phpstan-ignore-line
if (0 === count($roles)) {
Log::debug('validateUserGroup: no roles defined, so no access.');
throw new AuthorizationException((string) trans('validation.no_accepted_roles_defined'));
throw new AuthorizationException((string)trans('validation.no_accepted_roles_defined'));
}
Log::debug(sprintf('validateUserGroup: have %d roles to check.', count($roles)), $roles);
@@ -111,6 +111,6 @@ trait ValidatesUserGroupTrait
Log::debug('validateUserGroup: User does NOT have enough rights to access endpoint.');
throw new AuthorizationException((string) trans('validation.belongs_user_or_user_group'));
throw new AuthorizationException((string)trans('validation.belongs_user_or_user_group'));
}
}