From 08879d31ba20f25e5a9e05c06bfe0b760b85905e Mon Sep 17 00:00:00 2001 From: James Cole Date: Fri, 26 Sep 2025 05:33:35 +0200 Subject: [PATCH] Rearrange some code. --- .../Http/Api/AccountBalanceGrouped.php | 74 ++--- app/Support/Http/Api/CleansChartData.php | 2 +- .../Http/Api/CollectsAccountsFromFilter.php | 2 +- .../Http/Api/ExchangeRateConverter.php | 37 ++- .../Http/Api/SummaryBalanceGrouped.php | 32 +-- .../Http/Api/ValidatesUserGroupTrait.php | 24 +- app/Support/Http/Controllers/AugumentData.php | 56 ++-- .../Http/Controllers/ChartGeneration.php | 32 +-- app/Support/Http/Controllers/CreateStuff.php | 9 +- app/Support/Http/Controllers/CronRunner.php | 52 ++-- .../Http/Controllers/DateCalculation.php | 14 +- .../Http/Controllers/GetConfigurationData.php | 60 ++--- .../Http/Controllers/ModelInformation.php | 46 ++-- .../Http/Controllers/PeriodOverview.php | 254 +++++++++--------- .../Http/Controllers/RenderPartialViews.php | 46 ++-- .../Http/Controllers/RequestInformation.php | 25 +- .../Http/Controllers/RuleManagement.php | 22 +- .../Controllers/TransactionCalculation.php | 26 +- .../Http/Controllers/UserNavigation.php | 10 +- 19 files changed, 407 insertions(+), 416 deletions(-) diff --git a/app/Support/Http/Api/AccountBalanceGrouped.php b/app/Support/Http/Api/AccountBalanceGrouped.php index 839c87bfb0..d1f7915d23 100644 --- a/app/Support/Http/Api/AccountBalanceGrouped.php +++ b/app/Support/Http/Api/AccountBalanceGrouped.php @@ -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; diff --git a/app/Support/Http/Api/CleansChartData.php b/app/Support/Http/Api/CleansChartData.php index aef2ec443f..a3d54974cf 100644 --- a/app/Support/Http/Api/CleansChartData.php +++ b/app/Support/Http/Api/CleansChartData.php @@ -43,7 +43,7 @@ trait CleansChartData $return = []; /** - * @var int $index + * @var int $index * @var array $array */ foreach ($data as $index => $array) { diff --git a/app/Support/Http/Api/CollectsAccountsFromFilter.php b/app/Support/Http/Api/CollectsAccountsFromFilter.php index 7c10a6c1e1..2911ed61f6 100644 --- a/app/Support/Http/Api/CollectsAccountsFromFilter.php +++ b/app/Support/Http/Api/CollectsAccountsFromFilter.php @@ -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); } diff --git a/app/Support/Http/Api/ExchangeRateConverter.php b/app/Support/Http/Api/ExchangeRateConverter.php index 8abb75fe76..c78b7afce8 100644 --- a/app/Support/Http/Api/ExchangeRateConverter.php +++ b/app/Support/Http/Api/ExchangeRateConverter.php @@ -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); diff --git a/app/Support/Http/Api/SummaryBalanceGrouped.php b/app/Support/Http/Api/SummaryBalanceGrouped.php index b50ab2160e..8f88dba7d5 100644 --- a/app/Support/Http/Api/SummaryBalanceGrouped.php +++ b/app/Support/Http/Api/SummaryBalanceGrouped.php @@ -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(); } diff --git a/app/Support/Http/Api/ValidatesUserGroupTrait.php b/app/Support/Http/Api/ValidatesUserGroupTrait.php index 6ce611396d..0ce08c97ed 100644 --- a/app/Support/Http/Api/ValidatesUserGroupTrait.php +++ b/app/Support/Http/Api/ValidatesUserGroupTrait.php @@ -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')); } } diff --git a/app/Support/Http/Controllers/AugumentData.php b/app/Support/Http/Controllers/AugumentData.php index d882ce2b5b..aa3883244f 100644 --- a/app/Support/Http/Controllers/AugumentData.php +++ b/app/Support/Http/Controllers/AugumentData.php @@ -56,10 +56,10 @@ trait AugumentData /** @var Account $expenseAccount */ foreach ($accounts as $expenseAccount) { - $collection = new Collection(); + $collection = new Collection(); $collection->push($expenseAccount); - $revenue = $repository->findByName($expenseAccount->name, [AccountTypeEnum::REVENUE->value]); + $revenue = $repository->findByName($expenseAccount->name, [AccountTypeEnum::REVENUE->value]); if (null !== $revenue) { $collection->push($revenue); } @@ -110,13 +110,13 @@ trait AugumentData $grouped = $accounts->groupBy('id')->toArray(); $return = []; foreach ($accountIds as $combinedId) { - $parts = explode('-', (string) $combinedId); - $accountId = (int) $parts[0]; + $parts = explode('-', (string)$combinedId); + $accountId = (int)$parts[0]; if (array_key_exists($accountId, $grouped)) { $return[$accountId] = $grouped[$accountId][0]['name']; } } - $return[0] = '(no name)'; + $return[0] = '(no name)'; return $return; } @@ -136,7 +136,7 @@ trait AugumentData $return[$budgetId] = $grouped[$budgetId][0]['name']; } } - $return[0] = (string) trans('firefly.no_budget'); + $return[0] = (string)trans('firefly.no_budget'); return $return; } @@ -152,13 +152,13 @@ trait AugumentData $grouped = $categories->groupBy('id')->toArray(); $return = []; foreach ($categoryIds as $combinedId) { - $parts = explode('-', (string) $combinedId); - $categoryId = (int) $parts[0]; + $parts = explode('-', (string)$combinedId); + $categoryId = (int)$parts[0]; if (array_key_exists($categoryId, $grouped)) { $return[$categoryId] = $grouped[$categoryId][0]['name']; } } - $return[0] = (string) trans('firefly.no_category'); + $return[0] = (string)trans('firefly.no_category'); return $return; } @@ -171,14 +171,14 @@ trait AugumentData Log::debug('In getLimits'); /** @var OperationsRepositoryInterface $opsRepository */ - $opsRepository = app(OperationsRepositoryInterface::class); + $opsRepository = app(OperationsRepositoryInterface::class); /** @var BudgetLimitRepositoryInterface $blRepository */ - $blRepository = app(BudgetLimitRepositoryInterface::class); + $blRepository = app(BudgetLimitRepositoryInterface::class); $end->endOfMonth(); // properties for cache - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($budget->id); @@ -189,25 +189,25 @@ trait AugumentData return $cache->get(); } - $set = $blRepository->getBudgetLimits($budget, $start, $end); + $set = $blRepository->getBudgetLimits($budget, $start, $end); $budgetCollection = new Collection()->push($budget); // merge sets based on a key, in case of convert to primary currency - $limits = new Collection(); + $limits = new Collection(); /** @var BudgetLimit $entry */ foreach ($set as $entry) { Log::debug(sprintf('Now at budget limit #%d', $entry->id)); - $currency = $entry->transactionCurrency; + $currency = $entry->transactionCurrency; if ($this->convertToPrimary) { // the sumExpenses method already handles this. $currency = $this->primaryCurrency; } // clone because these objects change each other. - $currentStart = clone $entry->start_date; - $currentEnd = null === $entry->end_date ? null : clone $entry->end_date; + $currentStart = clone $entry->start_date; + $currentEnd = null === $entry->end_date ? null : clone $entry->end_date; if (null === $currentEnd) { $currentEnd = clone $currentStart; @@ -219,9 +219,9 @@ trait AugumentData $entry->pc_spent = $spent; // normal amount: - $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency, false); - $spent = $expenses[$entry->transactionCurrency->id]['sum'] ?? '0'; - $entry->spent = $spent; + $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency, false); + $spent = $expenses[$entry->transactionCurrency->id]['sum'] ?? '0'; + $entry->spent = $spent; $limits->push($entry); } @@ -240,7 +240,7 @@ trait AugumentData /** @var array $journal */ foreach ($array as $journal) { - $name = '(no name)'; + $name = '(no name)'; if (TransactionTypeEnum::WITHDRAWAL->value === $journal['transaction_type_type']) { $name = $journal['destination_account_name']; } @@ -249,7 +249,7 @@ trait AugumentData } $grouped[$name] ??= '0'; - $grouped[$name] = bcadd((string) $journal['amount'], $grouped[$name]); + $grouped[$name] = bcadd((string)$journal['amount'], $grouped[$name]); } return $grouped; @@ -263,16 +263,16 @@ trait AugumentData /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $total = $assets->merge($opposing); + $total = $assets->merge($opposing); $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setAccounts($total); - $journals = $collector->getExtractedJournals(); - $sum = [ + $journals = $collector->getExtractedJournals(); + $sum = [ 'grand_sum' => '0', 'per_currency' => [], ]; // loop to support multi currency foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int)$journal['currency_id']; // if not set, set to zero: if (!array_key_exists($currencyId, $sum['per_currency'])) { @@ -287,8 +287,8 @@ trait AugumentData } // add amount - $sum['per_currency'][$currencyId]['sum'] = bcadd($sum['per_currency'][$currencyId]['sum'], (string) $journal['amount']); - $sum['grand_sum'] = bcadd($sum['grand_sum'], (string) $journal['amount']); + $sum['per_currency'][$currencyId]['sum'] = bcadd($sum['per_currency'][$currencyId]['sum'], (string)$journal['amount']); + $sum['grand_sum'] = bcadd($sum['grand_sum'], (string)$journal['amount']); } return $sum; diff --git a/app/Support/Http/Controllers/ChartGeneration.php b/app/Support/Http/Controllers/ChartGeneration.php index 47a85c5c83..7fe3b3ab96 100644 --- a/app/Support/Http/Controllers/ChartGeneration.php +++ b/app/Support/Http/Controllers/ChartGeneration.php @@ -59,28 +59,28 @@ trait ChartGeneration return $cache->get(); } Log::debug('Regenerate chart.account.account-balance-chart from scratch.'); - $locale = app('steam')->getLocale(); + $locale = app('steam')->getLocale(); /** @var GeneratorInterface $generator */ - $generator = app(GeneratorInterface::class); + $generator = app(GeneratorInterface::class); /** @var AccountRepositoryInterface $accountRepos */ - $accountRepos = app(AccountRepositoryInterface::class); + $accountRepos = app(AccountRepositoryInterface::class); - $primary = app('amount')->getPrimaryCurrency(); - $chartData = []; + $primary = app('amount')->getPrimaryCurrency(); + $chartData = []; Log::debug(sprintf('Start of accountBalanceChart(list, %s, %s)', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); /** @var Account $account */ foreach ($accounts as $account) { Log::debug(sprintf('Now at account #%d ("%s)', $account->id, $account->name)); - $currency = $accountRepos->getAccountCurrency($account) ?? $primary; - $usePrimary = $convertToPrimary && $primary->id !== $currency->id; - $field = $convertToPrimary ? 'pc_balance' : 'balance'; - $currency = $usePrimary ? $primary : $currency; + $currency = $accountRepos->getAccountCurrency($account) ?? $primary; + $usePrimary = $convertToPrimary && $primary->id !== $currency->id; + $field = $convertToPrimary ? 'pc_balance' : 'balance'; + $currency = $usePrimary ? $primary : $currency; Log::debug(sprintf('Will use field %s', $field)); - $currentSet = [ + $currentSet = [ 'label' => $account->name, 'currency_symbol' => $currency->symbol, 'entries' => [], @@ -91,16 +91,16 @@ trait ChartGeneration $previous = array_values($range)[0]; Log::debug(sprintf('Start balance for account #%d ("%s) is', $account->id, $account->name), $previous); while ($currentStart <= $end) { - $format = $currentStart->format('Y-m-d'); - $label = trim($currentStart->isoFormat((string) trans('config.month_and_day_js', [], $locale))); - $balance = $range[$format] ?? $previous; - $previous = $balance; + $format = $currentStart->format('Y-m-d'); + $label = trim($currentStart->isoFormat((string)trans('config.month_and_day_js', [], $locale))); + $balance = $range[$format] ?? $previous; + $previous = $balance; $currentStart->addDay(); $currentSet['entries'][$label] = $balance[$field] ?? '0'; } - $chartData[] = $currentSet; + $chartData[] = $currentSet; } - $data = $generator->multiSet($chartData); + $data = $generator->multiSet($chartData); $cache->store($data); return $data; diff --git a/app/Support/Http/Controllers/CreateStuff.php b/app/Support/Http/Controllers/CreateStuff.php index 6ce33985d3..c54d585328 100644 --- a/app/Support/Http/Controllers/CreateStuff.php +++ b/app/Support/Http/Controllers/CreateStuff.php @@ -32,7 +32,6 @@ use FireflyIII\User; use Illuminate\Support\Facades\Log; use Laravel\Passport\Passport; use phpseclib3\Crypt\RSA; - use function Safe\file_put_contents; /** @@ -73,7 +72,7 @@ trait CreateStuff /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $assetAccount = [ - 'name' => (string) trans('firefly.cash_wallet', [], $language), + 'name' => (string)trans('firefly.cash_wallet', [], $language), 'iban' => null, 'account_type_name' => 'asset', 'virtual_balance' => 0, @@ -104,11 +103,11 @@ trait CreateStuff return; } - $key = RSA::createKey(4096); + $key = RSA::createKey(4096); Log::alert('NO OAuth keys were found. They have been created.'); - file_put_contents($publicKey, (string) $key->getPublicKey()); + file_put_contents($publicKey, (string)$key->getPublicKey()); file_put_contents($privateKey, $key->toString('PKCS1')); } @@ -120,7 +119,7 @@ trait CreateStuff /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $savingsAccount = [ - 'name' => (string) trans('firefly.new_savings_account', ['bank_name' => $request->get('bank_name')], $language), + 'name' => (string)trans('firefly.new_savings_account', ['bank_name' => $request->get('bank_name')], $language), 'iban' => null, 'account_type_name' => 'asset', 'account_type_id' => null, diff --git a/app/Support/Http/Controllers/CronRunner.php b/app/Support/Http/Controllers/CronRunner.php index c8cf03cfd6..ed3e950024 100644 --- a/app/Support/Http/Controllers/CronRunner.php +++ b/app/Support/Http/Controllers/CronRunner.php @@ -63,32 +63,6 @@ trait CronRunner ]; } - protected function webhookCronJob(bool $force, Carbon $date): array - { - /** @var WebhookCronjob $webhook */ - $webhook = app(WebhookCronjob::class); - $webhook->setForce($force); - $webhook->setDate($date); - - try { - $webhook->fire(); - } catch (FireflyException $e) { - return [ - 'job_fired' => false, - 'job_succeeded' => false, - 'job_errored' => true, - 'message' => $e->getMessage(), - ]; - } - - return [ - 'job_fired' => $webhook->jobFired, - 'job_succeeded' => $webhook->jobSucceeded, - 'job_errored' => $webhook->jobErrored, - 'message' => $webhook->message, - ]; - } - protected function exchangeRatesCronJob(bool $force, Carbon $date): array { /** @var ExchangeRatesCronjob $exchangeRates */ @@ -166,4 +140,30 @@ trait CronRunner 'message' => $recurring->message, ]; } + + protected function webhookCronJob(bool $force, Carbon $date): array + { + /** @var WebhookCronjob $webhook */ + $webhook = app(WebhookCronjob::class); + $webhook->setForce($force); + $webhook->setDate($date); + + try { + $webhook->fire(); + } catch (FireflyException $e) { + return [ + 'job_fired' => false, + 'job_succeeded' => false, + 'job_errored' => true, + 'message' => $e->getMessage(), + ]; + } + + return [ + 'job_fired' => $webhook->jobFired, + 'job_succeeded' => $webhook->jobSucceeded, + 'job_errored' => $webhook->jobErrored, + 'message' => $webhook->message, + ]; + } } diff --git a/app/Support/Http/Controllers/DateCalculation.php b/app/Support/Http/Controllers/DateCalculation.php index 5027a4c69f..83baefcf8b 100644 --- a/app/Support/Http/Controllers/DateCalculation.php +++ b/app/Support/Http/Controllers/DateCalculation.php @@ -40,13 +40,13 @@ trait DateCalculation */ public function activeDaysLeft(Carbon $start, Carbon $end): int { - $difference = (int) ($start->diffInDays($end, true) + 1); + $difference = (int)($start->diffInDays($end, true) + 1); $today = today(config('app.timezone'))->startOfDay(); if ($start->lte($today) && $end->gte($today)) { $difference = $today->diffInDays($end) + 1; } - return (int) (0 === $difference ? 1 : $difference); + return (int)(0 === $difference ? 1 : $difference); } /** @@ -63,7 +63,7 @@ trait DateCalculation $difference = $start->diffInDays($today, true) + 1; } - return (int) $difference; + return (int)$difference; } protected function calculateStep(Carbon $start, Carbon $end): string @@ -90,19 +90,19 @@ trait DateCalculation protected function getNextPeriods(Carbon $date, string $range): array { // select thing for next 12 periods: - $loop = []; + $loop = []; /** @var Carbon $current */ $current = app('navigation')->startOfPeriod($date, $range); $current = app('navigation')->endOfPeriod($current, $range); $current->addDay(); - $count = 0; + $count = 0; while ($count < 12) { $current = app('navigation')->endOfPeriod($current, $range); $currentStart = app('navigation')->startOfPeriod($current, $range); - $loop[] = [ + $loop[] = [ 'label' => $current->format('Y-m-d'), 'title' => app('navigation')->periodShow($current, $range), 'start' => clone $currentStart, @@ -122,7 +122,7 @@ trait DateCalculation protected function getPreviousPeriods(Carbon $date, string $range): array { // select thing for last 12 periods: - $loop = []; + $loop = []; /** @var Carbon $current */ $current = app('navigation')->startOfPeriod($date, $range); diff --git a/app/Support/Http/Controllers/GetConfigurationData.php b/app/Support/Http/Controllers/GetConfigurationData.php index 52ce494418..d1005bfdcb 100644 --- a/app/Support/Http/Controllers/GetConfigurationData.php +++ b/app/Support/Http/Controllers/GetConfigurationData.php @@ -48,7 +48,7 @@ trait GetConfigurationData E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR => 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR', ]; - return $array[$value] ?? (string) $value; + return $array[$value] ?? (string)$value; } /** @@ -61,13 +61,13 @@ trait GetConfigurationData $steps = []; if (is_array($elements) && count($elements) > 0) { foreach ($elements as $key => $options) { - $currentStep = $options; + $currentStep = $options; // get the text: - $currentStep['intro'] = (string) trans('intro.'.$route.'_'.$key); + $currentStep['intro'] = (string)trans('intro.' . $route . '_' . $key); // save in array: - $steps[] = $currentStep; + $steps[] = $currentStep; } } app('log')->debug(sprintf('Total basic steps for %s is %d', $routeKey, count($steps))); @@ -82,22 +82,22 @@ trait GetConfigurationData */ protected function getDateRangeConfig(): array // get configuration + get preferences. { - $viewRange = app('navigation')->getViewRange(false); + $viewRange = app('navigation')->getViewRange(false); Log::debug(sprintf('dateRange: the view range is "%s"', $viewRange)); /** @var Carbon $start */ - $start = session('start'); + $start = session('start'); /** @var Carbon $end */ - $end = session('end'); + $end = session('end'); /** @var Carbon $first */ - $first = session('first'); - $title = sprintf('%s - %s', $start->isoFormat($this->monthAndDayFormat), $end->isoFormat($this->monthAndDayFormat)); - $isCustom = true === session('is_custom_range', false); - $today = today(config('app.timezone')); - $ranges = [ + $first = session('first'); + $title = sprintf('%s - %s', $start->isoFormat($this->monthAndDayFormat), $end->isoFormat($this->monthAndDayFormat)); + $isCustom = true === session('is_custom_range', false); + $today = today(config('app.timezone')); + $ranges = [ // first range is the current range: $title => [$start, $end], ]; @@ -127,47 +127,47 @@ trait GetConfigurationData // today: /** @var Carbon $todayStart */ - $todayStart = app('navigation')->startOfPeriod($today, $viewRange); + $todayStart = app('navigation')->startOfPeriod($today, $viewRange); /** @var Carbon $todayEnd */ - $todayEnd = app('navigation')->endOfPeriod($todayStart, $viewRange); + $todayEnd = app('navigation')->endOfPeriod($todayStart, $viewRange); if ($todayStart->ne($start) || $todayEnd->ne($end)) { - $ranges[ucfirst((string) trans('firefly.today'))] = [$todayStart, $todayEnd]; + $ranges[ucfirst((string)trans('firefly.today'))] = [$todayStart, $todayEnd]; } // last seven days: $seven = today(config('app.timezone'))->subDays(7); - $index = (string) trans('firefly.last_seven_days'); + $index = (string)trans('firefly.last_seven_days'); $ranges[$index] = [$seven, new Carbon()]; // last 30 days: $thirty = today(config('app.timezone'))->subDays(30); - $index = (string) trans('firefly.last_thirty_days'); + $index = (string)trans('firefly.last_thirty_days'); $ranges[$index] = [$thirty, new Carbon()]; // month to date: $monthBegin = today(config('app.timezone'))->startOfMonth(); - $index = (string) trans('firefly.month_to_date'); + $index = (string)trans('firefly.month_to_date'); $ranges[$index] = [$monthBegin, new Carbon()]; // year to date: $yearBegin = today(config('app.timezone'))->startOfYear(); - $index = (string) trans('firefly.year_to_date'); + $index = (string)trans('firefly.year_to_date'); $ranges[$index] = [$yearBegin, new Carbon()]; // everything - $index = (string) trans('firefly.everything'); + $index = (string)trans('firefly.everything'); $ranges[$index] = [$first, new Carbon()]; return [ 'title' => $title, 'configuration' => [ - 'apply' => (string) trans('firefly.apply'), - 'cancel' => (string) trans('firefly.cancel'), - 'from' => (string) trans('firefly.from'), - 'to' => (string) trans('firefly.to'), - 'customRange' => (string) trans('firefly.customRange'), + 'apply' => (string)trans('firefly.apply'), + 'cancel' => (string)trans('firefly.cancel'), + 'from' => (string)trans('firefly.from'), + 'to' => (string)trans('firefly.to'), + 'customRange' => (string)trans('firefly.customRange'), 'start' => $start->format('Y-m-d'), 'end' => $end->format('Y-m-d'), 'ranges' => $ranges, @@ -186,16 +186,16 @@ trait GetConfigurationData // user is on page with specific instructions: if ('' !== $specificPage) { $routeKey = str_replace('.', '_', $route); - $elements = config(sprintf('intro.%s', $routeKey.'_'.$specificPage)); + $elements = config(sprintf('intro.%s', $routeKey . '_' . $specificPage)); if (is_array($elements) && count($elements) > 0) { foreach ($elements as $key => $options) { - $currentStep = $options; + $currentStep = $options; // get the text: - $currentStep['intro'] = (string) trans('intro.'.$route.'_'.$specificPage.'_'.$key); + $currentStep['intro'] = (string)trans('intro.' . $route . '_' . $specificPage . '_' . $key); // save in array: - $steps[] = $currentStep; + $steps[] = $currentStep; } } } @@ -207,7 +207,7 @@ trait GetConfigurationData protected function verifyRecurringCronJob(): void { $config = FireflyConfig::get('last_rt_job', 0); - $lastTime = (int) $config?->data; + $lastTime = (int)$config?->data; $now = Carbon::now()->getTimestamp(); app('log')->debug(sprintf('verifyRecurringCronJob: last time is %d ("%s"), now is %d', $lastTime, $config?->data, $now)); if (0 === $lastTime) { diff --git a/app/Support/Http/Controllers/ModelInformation.php b/app/Support/Http/Controllers/ModelInformation.php index 65fd660211..152c9671ef 100644 --- a/app/Support/Http/Controllers/ModelInformation.php +++ b/app/Support/Http/Controllers/ModelInformation.php @@ -75,21 +75,21 @@ trait ModelInformation protected function getLiabilityTypes(): array { /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); // types of liability: /** @var AccountType $debt */ - $debt = $repository->getAccountTypeByType(AccountTypeEnum::DEBT->value); + $debt = $repository->getAccountTypeByType(AccountTypeEnum::DEBT->value); /** @var AccountType $loan */ - $loan = $repository->getAccountTypeByType(AccountTypeEnum::LOAN->value); + $loan = $repository->getAccountTypeByType(AccountTypeEnum::LOAN->value); /** @var AccountType $mortgage */ $mortgage = $repository->getAccountTypeByType(AccountTypeEnum::MORTGAGE->value); $liabilityTypes = [ - $debt->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::DEBT->value)), - $loan->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::LOAN->value)), - $mortgage->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::MORTGAGE->value)), + $debt->id => (string)trans(sprintf('firefly.account_type_%s', AccountTypeEnum::DEBT->value)), + $loan->id => (string)trans(sprintf('firefly.account_type_%s', AccountTypeEnum::LOAN->value)), + $mortgage->id => (string)trans(sprintf('firefly.account_type_%s', AccountTypeEnum::MORTGAGE->value)), ]; asort($liabilityTypes); @@ -100,7 +100,7 @@ trait ModelInformation { $roles = []; foreach (config('firefly.accountRoles') as $role) { - $roles[$role] = (string) trans(sprintf('firefly.account_role_%s', $role)); + $roles[$role] = (string)trans(sprintf('firefly.account_role_%s', $role)); } return $roles; @@ -114,11 +114,11 @@ trait ModelInformation protected function getTriggersForBill(Bill $bill): array // get info and argument { // TODO duplicate code - $operators = config('search.operators'); - $triggers = []; + $operators = config('search.operators'); + $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); @@ -165,27 +165,27 @@ trait ModelInformation private function getTriggersForJournal(TransactionJournal $journal): array { // TODO duplicated code. - $operators = config('search.operators'); - $triggers = []; + $operators = config('search.operators'); + $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); - $result = []; - $journalTriggers = []; - $values = []; - $index = 0; + $result = []; + $journalTriggers = []; + $values = []; + $index = 0; // amount, description, category, budget, tags, source, destination, notes, currency type // ,type /** @var null|Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); /** @var null|Transaction $destination */ - $destination = $journal->transactions()->where('amount', '>', 0)->first(); + $destination = $journal->transactions()->where('amount', '>', 0)->first(); if (null === $destination || null === $source) { return $result; } @@ -220,21 +220,21 @@ trait ModelInformation ++$index; // category (if) - $category = $journal->categories()->first(); + $category = $journal->categories()->first(); if (null !== $category) { $journalTriggers[$index] = 'category_is'; $values[$index] = $category->name; ++$index; } // budget (if) - $budget = $journal->budgets()->first(); + $budget = $journal->budgets()->first(); if (null !== $budget) { $journalTriggers[$index] = 'budget_is'; $values[$index] = $budget->name; ++$index; } // tags (if) - $tags = $journal->tags()->get(); + $tags = $journal->tags()->get(); /** @var Tag $tag */ foreach ($tags as $tag) { @@ -243,7 +243,7 @@ trait ModelInformation ++$index; } // notes (if) - $notes = $journal->notes()->first(); + $notes = $journal->notes()->first(); if (null !== $notes) { $journalTriggers[$index] = 'notes_is'; $values[$index] = $notes->text; diff --git a/app/Support/Http/Controllers/PeriodOverview.php b/app/Support/Http/Controllers/PeriodOverview.php index 52b7a0c240..7371b997bd 100644 --- a/app/Support/Http/Controllers/PeriodOverview.php +++ b/app/Support/Http/Controllers/PeriodOverview.php @@ -86,11 +86,11 @@ trait PeriodOverview $this->accountRepository = app(AccountRepositoryInterface::class); $this->periodStatisticRepo = app(PeriodStatisticRepositoryInterface::class); $range = Navigation::getViewRange(true); - [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; + [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; Log::debug(sprintf('Count of loops: %d', count($dates))); foreach ($dates as $currentDate) { $entries[] = $this->getSingleAccountPeriod($account, $currentDate['start'], $currentDate['end']); @@ -110,7 +110,7 @@ trait PeriodOverview 'total_transactions' => 0, ]; foreach ($types as $type) { - $set = $this->getSingleAccountPeriodByType($account, $start, $end, $type); + $set = $this->getSingleAccountPeriodByType($account, $start, $end, $type); $return['total_transactions'] += $set['count']; unset($set['count']); $return[$type] = $set; @@ -153,50 +153,42 @@ trait PeriodOverview break; } // each result must be grouped by currency, then saved as period statistic. - $grouped = $this->groupByCurrency($result); + $grouped = $this->groupByCurrency($result); // TODO save as statistic. $this->saveGroupedAsStatistics($account, $start, $end, $type, $grouped); return $grouped; } - $grouped = [ + $grouped = [ 'count' => 0, ]; /** @var PeriodStatistic $statistic */ foreach ($statistics as $statistic) { - $id = (int) $statistic->transaction_currency_id; - $currency = Amount::getTransactionCurrencyById($id); - $grouped[$id] = [ - 'amount' => (string) $statistic->amount, - 'count' => (int) $statistic->count, + $id = (int)$statistic->transaction_currency_id; + $currency = Amount::getTransactionCurrencyById($id); + $grouped[$id] = [ + 'amount' => (string)$statistic->amount, + 'count' => (int)$statistic->count, 'currency_id' => $currency->id, 'currency_name' => $currency->name, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, ]; - $grouped['count'] += (int) $statistic->count; + $grouped['count'] += (int)$statistic->count; } return $grouped; } - protected function saveGroupedAsStatistics(Account $account, Carbon $start, Carbon $end, string $type, array $array): void - { - unset($array['count']); - foreach ($array as $entry) { - $this->periodStatisticRepo->saveStatistic($account, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']); - } - } - private function filterTransactionsByType(TransactionTypeEnum $type, array $transactions, Carbon $start, Carbon $end): array { $result = []; /** - * @var int $index + * @var int $index * @var array $item */ foreach ($transactions as $index => $item) { @@ -216,7 +208,7 @@ trait PeriodOverview $result = []; /** - * @var int $index + * @var int $index * @var array $item */ foreach ($transactions as $index => $item) { @@ -255,13 +247,13 @@ trait PeriodOverview exit; } - $currencyId = (int)$journal['currency_id']; - $currencyCode = $journal['currency_code']; - $currencyName = $journal['currency_name']; - $currencySymbol = $journal['currency_symbol']; - $currencyDecimalPlaces = $journal['currency_decimal_places']; - $foreignCurrencyId = $journal['foreign_currency_id']; - $amount = $journal['amount'] ?? '0'; + $currencyId = (int)$journal['currency_id']; + $currencyCode = $journal['currency_code']; + $currencyName = $journal['currency_name']; + $currencySymbol = $journal['currency_symbol']; + $currencyDecimalPlaces = $journal['currency_decimal_places']; + $foreignCurrencyId = $journal['foreign_currency_id']; + $amount = $journal['amount'] ?? '0'; if ($this->convertToPrimary && $currencyId !== $this->primaryCurrency->id && $foreignCurrencyId !== $this->primaryCurrency->id) { $amount = $journal['pc_amount'] ?? '0'; @@ -298,6 +290,14 @@ trait PeriodOverview return $return; } + protected function saveGroupedAsStatistics(Account $account, Carbon $start, Carbon $end, string $type, array $array): void + { + unset($array['count']); + foreach ($array as $entry) { + $this->periodStatisticRepo->saveStatistic($account, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']); + } + } + /** * Overview for single category. Has been refactored recently. * @@ -305,11 +305,11 @@ trait PeriodOverview */ protected function getCategoryPeriodOverview(Category $category, Carbon $start, Carbon $end): array { - $range = Navigation::getViewRange(true); + $range = Navigation::getViewRange(true); [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; // properties for entries with their amounts. - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($range); @@ -321,32 +321,32 @@ trait PeriodOverview } /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; // collect all expenses in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setCategory($category); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value]); - $earnedSet = $collector->getExtractedJournals(); + $earnedSet = $collector->getExtractedJournals(); // collect all income in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setCategory($category); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - $spentSet = $collector->getExtractedJournals(); + $spentSet = $collector->getExtractedJournals(); // collect all transfers in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setCategory($category); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::TRANSFER->value]); - $transferSet = $collector->getExtractedJournals(); + $transferSet = $collector->getExtractedJournals(); foreach ($dates as $currentDate) { $spent = $this->filterJournalsByDate($spentSet, $currentDate['start'], $currentDate['end']); $earned = $this->filterJournalsByDate($earnedSet, $currentDate['start'], $currentDate['end']); @@ -354,17 +354,17 @@ trait PeriodOverview $title = Navigation::periodShow($currentDate['end'], $currentDate['period']); $entries[] = [ - 'transactions' => 0, - 'title' => $title, - 'route' => route( - 'categories.show', - [$category->id, $currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')] - ), - 'total_transactions' => count($spent) + count($earned) + count($transferred), - 'spent' => $this->groupByCurrency($spent), - 'earned' => $this->groupByCurrency($earned), - 'transferred' => $this->groupByCurrency($transferred), - ]; + 'transactions' => 0, + 'title' => $title, + 'route' => route( + 'categories.show', + [$category->id, $currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')] + ), + 'total_transactions' => count($spent) + count($earned) + count($transferred), + 'spent' => $this->groupByCurrency($spent), + 'earned' => $this->groupByCurrency($earned), + 'transferred' => $this->groupByCurrency($transferred), + ]; } $cache->store($entries); @@ -397,11 +397,11 @@ trait PeriodOverview */ protected function getNoBudgetPeriodOverview(Carbon $start, Carbon $end): array { - $range = Navigation::getViewRange(true); + $range = Navigation::getViewRange(true); [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($this->convertToPrimary); @@ -412,28 +412,28 @@ trait PeriodOverview } /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; // get all expenses without a budget. /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setRange($start, $end)->withoutBudget()->withAccountInformation()->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); foreach ($dates as $currentDate) { $set = $this->filterJournalsByDate($journals, $currentDate['start'], $currentDate['end']); $title = Navigation::periodShow($currentDate['end'], $currentDate['period']); $entries[] = [ - 'title' => $title, - 'route' => route('budgets.no-budget', [$currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')]), - 'total_transactions' => count($set), - 'spent' => $this->groupByCurrency($set), - 'earned' => [], - 'transferred_away' => [], - 'transferred_in' => [], - ]; + 'title' => $title, + 'route' => route('budgets.no-budget', [$currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')]), + 'total_transactions' => count($set), + 'spent' => $this->groupByCurrency($set), + 'earned' => [], + 'transferred_away' => [], + 'transferred_in' => [], + ]; } $cache->store($entries); @@ -450,38 +450,38 @@ trait PeriodOverview protected function getNoCategoryPeriodOverview(Carbon $theDate): array { app('log')->debug(sprintf('Now in getNoCategoryPeriodOverview(%s)', $theDate->format('Y-m-d'))); - $range = Navigation::getViewRange(true); - $first = $this->journalRepos->firstNull(); - $start = null === $first ? new Carbon() : $first->date; - $end = clone $theDate; - $end = Navigation::endOfPeriod($end, $range); + $range = Navigation::getViewRange(true); + $first = $this->journalRepos->firstNull(); + $start = null === $first ? new Carbon() : $first->date; + $end = clone $theDate; + $end = Navigation::endOfPeriod($end, $range); app('log')->debug(sprintf('Start for getNoCategoryPeriodOverview() is %s', $start->format('Y-m-d'))); app('log')->debug(sprintf('End for getNoCategoryPeriodOverview() is %s', $end->format('Y-m-d'))); // properties for cache - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; // collect all expenses in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->withoutCategory(); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value]); - $earnedSet = $collector->getExtractedJournals(); + $earnedSet = $collector->getExtractedJournals(); // collect all income in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->withoutCategory(); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - $spentSet = $collector->getExtractedJournals(); + $spentSet = $collector->getExtractedJournals(); // collect all transfers in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->withoutCategory(); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::TRANSFER->value]); @@ -495,13 +495,13 @@ trait PeriodOverview $title = Navigation::periodShow($currentDate['end'], $currentDate['period']); $entries[] = [ - 'title' => $title, - 'route' => route('categories.no-category', [$currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')]), - 'total_transactions' => count($spent) + count($earned) + count($transferred), - 'spent' => $this->groupByCurrency($spent), - 'earned' => $this->groupByCurrency($earned), - 'transferred' => $this->groupByCurrency($transferred), - ]; + 'title' => $title, + 'route' => route('categories.no-category', [$currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')]), + 'total_transactions' => count($spent) + count($earned) + count($transferred), + 'spent' => $this->groupByCurrency($spent), + 'earned' => $this->groupByCurrency($earned), + 'transferred' => $this->groupByCurrency($transferred), + ]; } app('log')->debug('End of loops'); @@ -515,11 +515,11 @@ trait PeriodOverview */ protected function getTagPeriodOverview(Tag $tag, Carbon $start, Carbon $end): array // period overview for tags. { - $range = Navigation::getViewRange(true); + $range = Navigation::getViewRange(true); [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; // properties for cache - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('tag-period-entries'); @@ -529,37 +529,37 @@ trait PeriodOverview } /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; // collect all expenses in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTag($tag); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value]); - $earnedSet = $collector->getExtractedJournals(); + $earnedSet = $collector->getExtractedJournals(); // collect all income in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTag($tag); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - $spentSet = $collector->getExtractedJournals(); + $spentSet = $collector->getExtractedJournals(); // collect all transfers in this period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTag($tag); $collector->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::TRANSFER->value]); - $transferSet = $collector->getExtractedJournals(); + $transferSet = $collector->getExtractedJournals(); // filer all of them: - $earnedSet = $this->filterJournalsByTag($earnedSet, $tag); - $spentSet = $this->filterJournalsByTag($spentSet, $tag); - $transferSet = $this->filterJournalsByTag($transferSet, $tag); + $earnedSet = $this->filterJournalsByTag($earnedSet, $tag); + $spentSet = $this->filterJournalsByTag($spentSet, $tag); + $transferSet = $this->filterJournalsByTag($transferSet, $tag); foreach ($dates as $currentDate) { $spent = $this->filterJournalsByDate($spentSet, $currentDate['start'], $currentDate['end']); @@ -568,17 +568,17 @@ trait PeriodOverview $title = Navigation::periodShow($currentDate['end'], $currentDate['period']); $entries[] = [ - 'transactions' => 0, - 'title' => $title, - 'route' => route( - 'tags.show', - [$tag->id, $currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')] - ), - 'total_transactions' => count($spent) + count($earned) + count($transferred), - 'spent' => $this->groupByCurrency($spent), - 'earned' => $this->groupByCurrency($earned), - 'transferred' => $this->groupByCurrency($transferred), - ]; + 'transactions' => 0, + 'title' => $title, + 'route' => route( + 'tags.show', + [$tag->id, $currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')] + ), + 'total_transactions' => count($spent) + count($earned) + count($transferred), + 'spent' => $this->groupByCurrency($spent), + 'earned' => $this->groupByCurrency($earned), + 'transferred' => $this->groupByCurrency($transferred), + ]; } return $entries; @@ -588,7 +588,7 @@ trait PeriodOverview { $return = []; foreach ($set as $entry) { - $found = false; + $found = false; /** @var array $localTag */ foreach ($entry['tags'] as $localTag) { @@ -610,12 +610,12 @@ trait PeriodOverview */ protected function getTransactionPeriodOverview(string $transactionType, Carbon $start, Carbon $end): array { - $range = Navigation::getViewRange(true); - $types = config(sprintf('firefly.transactionTypesByType.%s', $transactionType)); + $range = Navigation::getViewRange(true); + $types = config(sprintf('firefly.transactionTypesByType.%s', $transactionType)); [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; // properties for cache - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('transactions-period-entries'); @@ -625,16 +625,16 @@ trait PeriodOverview } /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; - $spent = []; - $earned = []; - $transferred = []; + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; + $spent = []; + $earned = []; + $transferred = []; // collect all journals in this period (regardless of type) - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes($types)->setRange($start, $end); - $genericSet = $collector->getExtractedJournals(); - $loops = 0; + $genericSet = $collector->getExtractedJournals(); + $loops = 0; foreach ($dates as $currentDate) { $title = Navigation::periodShow($currentDate['end'], $currentDate['period']); @@ -652,14 +652,14 @@ trait PeriodOverview } } $entries[] - = [ - 'title' => $title, - 'route' => route('transactions.index', [$transactionType, $currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')]), - 'total_transactions' => count($spent) + count($earned) + count($transferred), - 'spent' => $this->groupByCurrency($spent), - 'earned' => $this->groupByCurrency($earned), - 'transferred' => $this->groupByCurrency($transferred), - ]; + = [ + 'title' => $title, + 'route' => route('transactions.index', [$transactionType, $currentDate['start']->format('Y-m-d'), $currentDate['end']->format('Y-m-d')]), + 'total_transactions' => count($spent) + count($earned) + count($transferred), + 'spent' => $this->groupByCurrency($spent), + 'earned' => $this->groupByCurrency($earned), + 'transferred' => $this->groupByCurrency($transferred), + ]; ++$loops; } diff --git a/app/Support/Http/Controllers/RenderPartialViews.php b/app/Support/Http/Controllers/RenderPartialViews.php index 4c5f8348c6..05ff99e38b 100644 --- a/app/Support/Http/Controllers/RenderPartialViews.php +++ b/app/Support/Http/Controllers/RenderPartialViews.php @@ -52,20 +52,20 @@ trait RenderPartialViews protected function budgetEntry(array $attributes): string // generate view for report. { /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); + $popupHelper = app(PopupReportInterface::class); /** @var BudgetRepositoryInterface $budgetRepository */ $budgetRepository = app(BudgetRepositoryInterface::class); - $budget = $budgetRepository->find((int) $attributes['budgetId']); + $budget = $budgetRepository->find((int)$attributes['budgetId']); - $accountRepos = app(AccountRepositoryInterface::class); - $account = $accountRepos->find((int) $attributes['accountId']); + $accountRepos = app(AccountRepositoryInterface::class); + $account = $accountRepos->find((int)$attributes['accountId']); if (null === $budget || null === $account) { throw new FireflyException('Could not render popup.report.balance-amount because budget or account is null.'); } - $journals = $popupHelper->balanceForBudget($budget, $account, $attributes); + $journals = $popupHelper->balanceForBudget($budget, $account, $attributes); try { $view = view('popup.report.balance-amount', compact('journals', 'budget', 'account'))->render(); @@ -113,14 +113,14 @@ trait RenderPartialViews $budgetRepository = app(BudgetRepositoryInterface::class); /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); + $popupHelper = app(PopupReportInterface::class); - $budget = $budgetRepository->find((int) $attributes['budgetId']); + $budget = $budgetRepository->find((int)$attributes['budgetId']); if (null === $budget) { // transactions without a budget. $budget = new Budget(); } - $journals = $popupHelper->byBudget($budget, $attributes); + $journals = $popupHelper->byBudget($budget, $attributes); try { $view = view('popup.report.budget-spent-amount', compact('journals', 'budget'))->render(); @@ -142,11 +142,11 @@ trait RenderPartialViews protected function categoryEntry(array $attributes): string // generate view for report. { /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); + $popupHelper = app(PopupReportInterface::class); /** @var CategoryRepositoryInterface $categoryRepository */ $categoryRepository = app(CategoryRepositoryInterface::class); - $category = $categoryRepository->find((int) $attributes['categoryId']); + $category = $categoryRepository->find((int)$attributes['categoryId']); $journals = $popupHelper->byCategory($category, $attributes); try { @@ -237,15 +237,15 @@ trait RenderPartialViews $accountRepository = app(AccountRepositoryInterface::class); /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); + $popupHelper = app(PopupReportInterface::class); - $account = $accountRepository->find((int) $attributes['accountId']); + $account = $accountRepository->find((int)$attributes['accountId']); if (null === $account) { return 'This is an unknown account. Apologies.'; } - $journals = $popupHelper->byExpenses($account, $attributes); + $journals = $popupHelper->byExpenses($account, $attributes); try { $view = view('popup.report.expense-entry', compact('journals', 'account'))->render(); @@ -266,8 +266,8 @@ trait RenderPartialViews */ protected function getCurrentActions(Rule $rule): array // get info from object and present. { - $index = 0; - $actions = []; + $index = 0; + $actions = []; // must be repos $currentActions = $rule->ruleActions()->orderBy('order', 'ASC')->get(); @@ -306,11 +306,11 @@ trait RenderPartialViews protected function getCurrentTriggers(Rule $rule): array // get info from object and present. { // TODO duplicated code. - $operators = config('search.operators'); - $triggers = []; + $operators = config('search.operators'); + $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); @@ -325,7 +325,7 @@ trait RenderPartialViews $count = ($index + 1); try { - $rootOperator = OperatorQuerySearch::getRootOperator((string) $entry->trigger_type); + $rootOperator = OperatorQuerySearch::getRootOperator((string)$entry->trigger_type); if (str_starts_with($rootOperator, '-')) { $rootOperator = substr($rootOperator, 1); } @@ -335,7 +335,7 @@ trait RenderPartialViews 'oldTrigger' => $rootOperator, 'oldValue' => $entry->trigger_value, 'oldChecked' => $entry->stop_processing, - 'oldProhibited' => str_starts_with((string) $entry->trigger_type, '-'), + 'oldProhibited' => str_starts_with((string)$entry->trigger_type, '-'), 'count' => $count, 'triggers' => $triggers, ] @@ -365,14 +365,14 @@ trait RenderPartialViews $accountRepository = app(AccountRepositoryInterface::class); /** @var PopupReportInterface $popupHelper */ - $popupHelper = app(PopupReportInterface::class); - $account = $accountRepository->find((int) $attributes['accountId']); + $popupHelper = app(PopupReportInterface::class); + $account = $accountRepository->find((int)$attributes['accountId']); if (null === $account) { return 'This is an unknown category. Apologies.'; } - $journals = $popupHelper->byIncome($account, $attributes); + $journals = $popupHelper->byIncome($account, $attributes); try { $view = view('popup.report.income-entry', compact('journals', 'account'))->render(); diff --git a/app/Support/Http/Controllers/RequestInformation.php b/app/Support/Http/Controllers/RequestInformation.php index 6c7731b68f..73a39655e6 100644 --- a/app/Support/Http/Controllers/RequestInformation.php +++ b/app/Support/Http/Controllers/RequestInformation.php @@ -32,10 +32,9 @@ use FireflyIII\Support\Binder\AccountList; use FireflyIII\User; use Illuminate\Contracts\Validation\Validator as ValidatorContract; use Illuminate\Routing\Route; -use Illuminate\Support\Facades\Validator; -use Illuminate\Support\Facades\Route as RouteFacade; use Illuminate\Support\Facades\Hash; - +use Illuminate\Support\Facades\Route as RouteFacade; +use Illuminate\Support\Facades\Validator; use function Safe\parse_url; /** @@ -67,7 +66,7 @@ trait RequestInformation 'type' => $triggerInfo['type'] ?? '', 'value' => $triggerInfo['value'] ?? '', 'prohibited' => $triggerInfo['prohibited'] ?? false, - 'stop_processing' => 1 === (int) ($triggerInfo['stop_processing'] ?? '0'), + 'stop_processing' => 1 === (int)($triggerInfo['stop_processing'] ?? '0'), ]; $current = RuleFormRequest::replaceAmountTrigger($current); $triggers[] = $current; @@ -85,13 +84,13 @@ trait RequestInformation $page = $this->getPageName(); $specificPage = $this->getSpecificPageName(); // indicator if user has seen the help for this page ( + special page): - $key = sprintf('shown_demo_%s%s', $page, $specificPage); + $key = sprintf('shown_demo_%s%s', $page, $specificPage); // is there an intro for this route? $intro = config(sprintf('intro.%s', $page)) ?? []; $specialIntro = config(sprintf('intro.%s%s', $page, $specificPage)) ?? []; // some routes have a "what" parameter, which indicates a special page: - $shownDemo = true; + $shownDemo = true; // both must be array and either must be > 0 if (count($intro) > 0 || count($specialIntro) > 0) { $shownDemo = app('preferences')->get($key, false)->data; @@ -128,7 +127,7 @@ trait RequestInformation $start = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); + $end = session('end', today(config('app.timezone'))->endOfMonth()); if ($start->greaterThanOrEqualTo($date) && $end->greaterThanOrEqualTo($date)) { return true; } @@ -146,20 +145,20 @@ trait RequestInformation final protected function parseAttributes(array $attributes): array // parse input + return result { $attributes['location'] ??= ''; - $attributes['accounts'] = AccountList::routeBinder($attributes['accounts'] ?? '', new Route('get', '', [])); - $date = Carbon::createFromFormat('Ymd', $attributes['startDate']); + $attributes['accounts'] = AccountList::routeBinder($attributes['accounts'] ?? '', new Route('get', '', [])); + $date = Carbon::createFromFormat('Ymd', $attributes['startDate']); if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } $date->startOfMonth(); $attributes['startDate'] = $date; - $date2 = Carbon::createFromFormat('Ymd', $attributes['endDate']); + $date2 = Carbon::createFromFormat('Ymd', $attributes['endDate']); if (!$date2 instanceof Carbon) { $date2 = today(config('app.timezone')); } $date2->endOfDay(); - $attributes['endDate'] = $date2; + $attributes['endDate'] = $date2; return $attributes; } @@ -172,11 +171,11 @@ trait RequestInformation final protected function validatePassword(User $user, string $current, string $new): bool // get request info { if (!Hash::check($current, $user->password)) { - throw new ValidationException((string) trans('firefly.invalid_current_password')); + throw new ValidationException((string)trans('firefly.invalid_current_password')); } if ($current === $new) { - throw new ValidationException((string) trans('firefly.should_change')); + throw new ValidationException((string)trans('firefly.should_change')); } return true; diff --git a/app/Support/Http/Controllers/RuleManagement.php b/app/Support/Http/Controllers/RuleManagement.php index 6b88c3524c..9903873484 100644 --- a/app/Support/Http/Controllers/RuleManagement.php +++ b/app/Support/Http/Controllers/RuleManagement.php @@ -51,7 +51,7 @@ trait RuleManagement [ 'oldAction' => $oldAction['type'], 'oldValue' => $oldAction['value'] ?? '', - 'oldChecked' => 1 === (int) ($oldAction['stop_processing'] ?? '0'), + 'oldChecked' => 1 === (int)($oldAction['stop_processing'] ?? '0'), 'count' => $index + 1, ] )->render(); @@ -74,11 +74,11 @@ trait RuleManagement protected function getPreviousTriggers(Request $request): array { // TODO duplicated code. - $operators = config('search.operators'); - $triggers = []; + $operators = config('search.operators'); + $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); @@ -94,8 +94,8 @@ trait RuleManagement [ 'oldTrigger' => OperatorQuerySearch::getRootOperator($oldTrigger['type']), 'oldValue' => $oldTrigger['value'] ?? '', - 'oldChecked' => 1 === (int) ($oldTrigger['stop_processing'] ?? '0'), - 'oldProhibited' => 1 === (int) ($oldTrigger['prohibited'] ?? '0'), + 'oldChecked' => 1 === (int)($oldTrigger['stop_processing'] ?? '0'), + 'oldProhibited' => 1 === (int)($oldTrigger['prohibited'] ?? '0'), 'count' => $index + 1, 'triggers' => $triggers, ] @@ -124,15 +124,15 @@ trait RuleManagement $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); - $index = 0; + $index = 0; foreach ($submittedOperators as $operator) { $rootOperator = OperatorQuerySearch::getRootOperator($operator['type']); - $needsContext = (bool) config(sprintf('search.operators.%s.needs_context', $rootOperator)); + $needsContext = (bool)config(sprintf('search.operators.%s.needs_context', $rootOperator)); try { $renderedEntries[] = view( @@ -164,8 +164,8 @@ trait RuleManagement $repository = app(RuleGroupRepositoryInterface::class); if (0 === $repository->count()) { $data = [ - 'title' => (string) trans('firefly.default_rule_group_name'), - 'description' => (string) trans('firefly.default_rule_group_description'), + 'title' => (string)trans('firefly.default_rule_group_name'), + 'description' => (string)trans('firefly.default_rule_group_description'), 'active' => true, ]; diff --git a/app/Support/Http/Controllers/TransactionCalculation.php b/app/Support/Http/Controllers/TransactionCalculation.php index 17df264ce8..a872b53807 100644 --- a/app/Support/Http/Controllers/TransactionCalculation.php +++ b/app/Support/Http/Controllers/TransactionCalculation.php @@ -39,15 +39,14 @@ trait TransactionCalculation */ protected function getExpensesForOpposing(Collection $accounts, Collection $opposing, Carbon $start, Carbon $end): array { - $total = $accounts->merge($opposing); + $total = $accounts->merge($opposing); /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setAccounts($total) - ->setRange($start, $end) - ->withAccountInformation() - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ; + ->setRange($start, $end) + ->withAccountInformation() + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); return $collector->getExtractedJournals(); } @@ -61,8 +60,7 @@ trait TransactionCalculation $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) - ->setTags($tags)->withAccountInformation() - ; + ->setTags($tags)->withAccountInformation(); return $collector->getExtractedJournals(); } @@ -75,8 +73,7 @@ trait TransactionCalculation /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) - ->setBudgets($budgets)->withAccountInformation() - ; + ->setBudgets($budgets)->withAccountInformation(); return $collector->getExtractedJournals(); } @@ -93,8 +90,7 @@ trait TransactionCalculation ->setRange($start, $end) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) ->setCategories($categories) - ->withAccountInformation() - ; + ->withAccountInformation(); return $collector->getExtractedJournals(); } @@ -107,8 +103,7 @@ trait TransactionCalculation /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) - ->setCategories($categories)->withAccountInformation() - ; + ->setCategories($categories)->withAccountInformation(); return $collector->getExtractedJournals(); } @@ -118,7 +113,7 @@ trait TransactionCalculation */ protected function getIncomeForOpposing(Collection $accounts, Collection $opposing, Carbon $start, Carbon $end): array { - $total = $accounts->merge($opposing); + $total = $accounts->merge($opposing); /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -135,8 +130,7 @@ trait TransactionCalculation /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) - ->setTags($tags)->withAccountInformation() - ; + ->setTags($tags)->withAccountInformation(); return $collector->getExtractedJournals(); } diff --git a/app/Support/Http/Controllers/UserNavigation.php b/app/Support/Http/Controllers/UserNavigation.php index 8fac232ad0..fc34201443 100644 --- a/app/Support/Http/Controllers/UserNavigation.php +++ b/app/Support/Http/Controllers/UserNavigation.php @@ -49,7 +49,7 @@ trait UserNavigation final protected function getPreviousUrl(string $identifier): string { app('log')->debug(sprintf('Trying to retrieve URL stored under "%s"', $identifier)); - $url = (string) session($identifier); + $url = (string)session($identifier); app('log')->debug(sprintf('The URL is %s', $url)); return app('steam')->getSafeUrl($url, route('index')); @@ -69,7 +69,7 @@ trait UserNavigation final protected function isEditableGroup(TransactionGroup $group): bool { /** @var null|TransactionJournal $journal */ - $journal = $group->transactionJournals()->first(); + $journal = $group->transactionJournals()->first(); if (null === $journal) { return false; } @@ -96,10 +96,10 @@ trait UserNavigation return redirect(route('index')); } - $journal = $transaction->transactionJournal; + $journal = $transaction->transactionJournal; /** @var null|Transaction $other */ - $other = $journal->transactions()->where('id', '!=', $transaction->id)->first(); + $other = $journal->transactions()->where('id', '!=', $transaction->id)->first(); if (null === $other) { app('log')->error(sprintf('Account #%d has no valid journals. Dont know where it belongs.', $account->id)); session()->flash('error', trans('firefly.cant_find_redirect_account')); @@ -119,7 +119,7 @@ trait UserNavigation final protected function redirectGroupToAccount(TransactionGroup $group) { /** @var null|TransactionJournal $journal */ - $journal = $group->transactionJournals()->first(); + $journal = $group->transactionJournals()->first(); if (null === $journal) { app('log')->error(sprintf('No journals in group #%d', $group->id));